profileevaluator.cpp 95.2 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
8
**
9
** Commercial Usage
10
**
11
12
13
14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18
19
20
21
22
23
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
**
25
** If you are unsure which license is appropriate for your use, please
26
** contact the sales department at http://www.qtsoftware.com/contact.
con's avatar
con committed
27
**
28
**************************************************************************/
29

con's avatar
con committed
30
31
32
33
34
#include "profileevaluator.h"
#include "proparserutils.h"
#include "proitems.h"

#include <QtCore/QByteArray>
35
#include <QtCore/QDateTime>
con's avatar
con committed
36
37
38
39
40
41
42
43
44
45
46
47
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QList>
#include <QtCore/QRegExp>
#include <QtCore/QSet>
#include <QtCore/QStack>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QTextStream>

48
49
50
#ifdef Q_OS_UNIX
#include <unistd.h>
#include <sys/utsname.h>
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
51
#else
52
53
54
55
56
#include <Windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>

con's avatar
con committed
57
58
#ifdef Q_OS_WIN32
#define QT_POPEN _popen
59
#define QT_PCLOSE _pclose
con's avatar
con committed
60
61
#else
#define QT_POPEN popen
62
#define QT_PCLOSE pclose
con's avatar
con committed
63
64
65
66
#endif

QT_BEGIN_NAMESPACE

67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
///////////////////////////////////////////////////////////////////////
//
// Option
//
///////////////////////////////////////////////////////////////////////

QString
Option::fixString(QString string, uchar flags)
{
    // XXX Ripped out caching, so this will be slow. Should not matter for current uses.

    //fix the environment variables
    if (flags & Option::FixEnvVars) {
        int rep;
        QRegExp reg_variableName(QLatin1String("\\$\\(.*\\)"));
        reg_variableName.setMinimal(true);
        while ((rep = reg_variableName.indexIn(string)) != -1)
            string.replace(rep, reg_variableName.matchedLength(),
                           QString::fromLocal8Bit(qgetenv(string.mid(rep + 2, reg_variableName.matchedLength() - 3).toLatin1().constData()).constData()));
    }

    //canonicalize it (and treat as a path)
    if (flags & Option::FixPathCanonicalize) {
#if 0
        string = QFileInfo(string).canonicalFilePath();
#endif
        string = QDir::cleanPath(string);
    }

    if (string.length() > 2 && string[0].isLetter() && string[1] == QLatin1Char(':'))
        string[0] = string[0].toLower();

    //fix separators
    Q_ASSERT(!((flags & Option::FixPathToLocalSeparators) && (flags & Option::FixPathToTargetSeparators)));
    if (flags & Option::FixPathToLocalSeparators) {
#if defined(Q_OS_WIN32)
        string = string.replace(QLatin1Char('/'), QLatin1Char('\\'));
#else
        string = string.replace(QLatin1Char('\\'), QLatin1Char('/'));
#endif
    } else if (flags & Option::FixPathToTargetSeparators) {
        string = string.replace(QLatin1Char('/'), Option::dir_sep)
                       .replace(QLatin1Char('\\'), Option::dir_sep);
    }

    if ((string.startsWith(QLatin1Char('"')) && string.endsWith(QLatin1Char('"'))) ||
        (string.startsWith(QLatin1Char('\'')) && string.endsWith(QLatin1Char('\''))))
        string = string.mid(1, string.length() - 2);

    return string;
}

con's avatar
con committed
119
120
121
122
123
124
125
126
127
128
129
///////////////////////////////////////////////////////////////////////
//
// ProFileEvaluator::Private
//
///////////////////////////////////////////////////////////////////////

class ProFileEvaluator::Private : public AbstractProItemVisitor
{
public:
    Private(ProFileEvaluator *q_);

130
131
132
133
134
135
    ProFileEvaluator *q;
    int m_lineNo;                                   // Error reporting
    bool m_verbose;

    /////////////// Reading pro file

con's avatar
con committed
136
    bool read(ProFile *pro);
137
138
    bool read(ProFile *pro, const QString &content);
    bool read(ProFile *pro, QTextStream *ts);
con's avatar
con committed
139
140
141

    ProBlock *currentBlock();
    void updateItem();
142
    void insertVariable(const ushort **pCur, const ushort *end);
con's avatar
con committed
143
144
145
146
147
148
    void insertOperator(const char op);
    void insertComment(const QString &comment);
    void enterScope(bool multiLine);
    void leaveScope();
    void finalizeBlock();

149
150
151
152
153
154
    QStack<ProBlock *> m_blockstack;
    ProBlock *m_block;

    ProItem *m_commentItem;
    QString m_proitem;
    QString m_pendingComment;
155
    ushort *m_proitemPtr;
156

157
158
    enum StrState { NotStarted, Started, PutSpace };

159
160
    /////////////// Evaluating pro file contents

con's avatar
con committed
161
    // implementation of AbstractProItemVisitor
162
    ProItem::ProItemReturn visitBeginProBlock(ProBlock *block);
163
    void visitEndProBlock(ProBlock *block);
164
165
    ProItem::ProItemReturn visitProLoopIteration();
    void visitProLoopCleanup();
166
167
    void visitBeginProVariable(ProVariable *variable);
    void visitEndProVariable(ProVariable *variable);
168
169
    ProItem::ProItemReturn visitBeginProFile(ProFile *value);
    ProItem::ProItemReturn visitEndProFile(ProFile *value);
170
    void visitProValue(ProValue *value);
171
    ProItem::ProItemReturn visitProFunction(ProFunction *function);
172
173
    void visitProOperator(ProOperator *oper);
    void visitProCondition(ProCondition *condition);
con's avatar
con committed
174

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
175
    QStringList valuesDirect(const QString &variableName) const { return m_valuemap[variableName]; }
con's avatar
con committed
176
177
    QStringList values(const QString &variableName) const;
    QStringList values(const QString &variableName, const ProFile *pro) const;
178
179
    QStringList values(const QString &variableName, const QHash<QString, QStringList> &place,
                       const ProFile *pro) const;
con's avatar
con committed
180
181
182
183
    QString propertyValue(const QString &val) const;

    bool isActiveConfig(const QString &config, bool regex = false);
    QStringList expandVariableReferences(const QString &value);
184
    void doVariableReplace(QString *str);
con's avatar
con committed
185
186
187
188
    QStringList evaluateExpandFunction(const QString &function, const QString &arguments);
    QString format(const char *format) const;

    QString currentFileName() const;
189
    QString currentDirectory() const;
con's avatar
con committed
190
191
    ProFile *currentProFile() const;

192
    ProItem::ProItemReturn evaluateConditionalFunction(const QString &function, const QString &arguments);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
193
194
    bool evaluateFile(const QString &fileName);
    bool evaluateFeatureFile(const QString &fileName);
con's avatar
con committed
195

196
197
198
199
200
    static inline ProItem::ProItemReturn returnBool(bool b)
        { return b ? ProItem::ReturnTrue : ProItem::ReturnFalse; }

    QStringList evaluateFunction(ProBlock *funcPtr, const QStringList &argumentsList, bool *ok);

con's avatar
con committed
201
202
    QStringList qmakeFeaturePaths();

203
    struct State {
204
205
        bool condition;
        bool prevCondition;
206
        QStringList varVal;
207
208
    } m_sts;
    bool m_invertNext; // Short-lived, so not in State
209
210
211
    int m_skipLevel;
    bool m_cumulative;
    QString m_origfile;
con's avatar
con committed
212
213
    QString m_oldPath;                              // To restore the current path to the path
    QStack<ProFile*> m_profileStack;                // To handle 'include(a.pri), so we can track back to 'a.pro' when finished with 'a.pri'
214
215
216
217
218
219
220
221
    struct ProLoop {
        QString variable;
        QStringList oldVarVal;
        QStringList list;
        int index;
        bool infinite;
    };
    QStack<ProLoop> m_loopStack;
con's avatar
con committed
222
223
224
225

    QHash<QString, QStringList> m_valuemap;         // VariableName must be us-ascii, the content however can be non-us-ascii.
    QHash<const ProFile*, QHash<QString, QStringList> > m_filevaluemap; // Variables per include file
    QHash<QString, QString> m_properties;
226
    QString m_outputDir;
con's avatar
con committed
227

228
229
230
231
232
233
234
235
    bool m_definingTest;
    QString m_definingFunc;
    QHash<QString, ProBlock *> m_testFunctions;
    QHash<QString, ProBlock *> m_replaceFunctions;
    QStringList m_returnValue;
    QStack<QHash<QString, QStringList> > m_valuemapStack;
    QStack<QHash<const ProFile*, QHash<QString, QStringList> > > m_filevaluemapStack;

236
237
    QStringList m_addUserConfigCmdArgs;
    QStringList m_removeUserConfigCmdArgs;
238
    bool m_parsePreAndPostFiles;
con's avatar
con committed
239
240
};

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
241
#if !defined(__GNUC__) || __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3)
242
Q_DECLARE_TYPEINFO(ProFileEvaluator::Private::State, Q_PRIMITIVE_TYPE);
243
Q_DECLARE_TYPEINFO(ProFileEvaluator::Private::ProLoop, Q_MOVABLE_TYPE);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
244
#endif
245

con's avatar
con committed
246
247
248
ProFileEvaluator::Private::Private(ProFileEvaluator *q_)
  : q(q_)
{
249
    // Configuration, more or less
con's avatar
con committed
250
    m_verbose = true;
251
    m_cumulative = true;
252
    m_parsePreAndPostFiles = true;
253
254

    // Evaluator state
255
256
    m_sts.condition = false;
    m_sts.prevCondition = false;
257
258
    m_invertNext = false;
    m_skipLevel = 0;
259
    m_definingFunc.clear();
con's avatar
con committed
260
261
262
263
264
265
266
267
268
269
}

bool ProFileEvaluator::Private::read(ProFile *pro)
{
    QFile file(pro->fileName());
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        q->errorMessage(format("%1 not readable.").arg(pro->fileName()));
        return false;
    }

270
271
272
273
274
275
276
277
278
279
280
281
282
    QTextStream ts(&file);
    return read(pro, &ts);
}

bool ProFileEvaluator::Private::read(ProFile *pro, const QString &content)
{
    QString str(content);
    QTextStream ts(&str, QIODevice::ReadOnly | QIODevice::Text);
    return read(pro, &ts);
}

bool ProFileEvaluator::Private::read(ProFile *pro, QTextStream *ts)
{
283
284
285
    // Parser state
    m_block = 0;
    m_commentItem = 0;
con's avatar
con committed
286
    m_lineNo = 1;
287
    m_blockstack.clear();
con's avatar
con committed
288
289
    m_blockstack.push(pro);

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
290
291
292
    int parens = 0;
    bool inQuote = false;
    bool escaped = false;
293
294
    while (!ts->atEnd()) {
        QString line = ts->readLine();
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
295
296
297
298
299
300
301
302
303
304
305
306
307
        const ushort *cur = (const ushort *)line.unicode(),
                     *end = cur + line.length();
        m_proitem.reserve(line.length());
        m_proitemPtr = (ushort *)m_proitem.unicode();
      nextItem:
        ushort *ptr = m_proitemPtr;
        StrState sts = NotStarted;
        while (cur < end) {
            ushort c = *cur++;
            if (c == '#') { // Yep - no escaping possible
                m_proitemPtr = ptr;
                insertComment(line.right(end - cur).simplified());
                goto done;
con's avatar
con committed
308
            }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
            if (!escaped) {
                if (c == '\\') {
                    escaped = true;
                    goto putch;
                } else if (c == '"') {
                    inQuote = !inQuote;
                    goto putch;
                }
            } else {
                escaped = false;
            }
            if (!inQuote) {
                if (c == '(') {
                    ++parens;
                } else if (c == ')') {
                    --parens;
                } else if (!parens) {
                    if (m_block && (m_block->blockKind() & ProBlock::VariableKind)) {
                        if (c == ' ' || c == '\t') {
                            m_proitemPtr = ptr;
                            updateItem();
                            goto nextItem;
                        }
                    } else {
                        if (c == ':') {
                            m_proitemPtr = ptr;
                            enterScope(false);
                            goto nextItem;
                        }
                        if (c == '{') {
                            m_proitemPtr = ptr;
                            enterScope(true);
                            goto nextItem;
                        }
                        if (c == '}') {
                            m_proitemPtr = ptr;
                            leaveScope();
                            goto nextItem;
                        }
                        if (c == '=') {
                            m_proitemPtr = ptr;
                            insertVariable(&cur, end);
                            goto nextItem;
                        }
                        if (c == '|' || c == '!') {
                            m_proitemPtr = ptr;
                            insertOperator(c);
                            goto nextItem;
                        }
358
                    }
359
                }
con's avatar
con committed
360
361
            }

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
            if (c == ' ' || c == '\t') {
                if (sts == Started)
                    sts = PutSpace;
            } else {
              putch:
                if (sts == PutSpace)
                    *ptr++ = ' ';
                *ptr++ = c;
                sts = Started;
            }
        }
        m_proitemPtr = ptr;
      done:
        if (escaped) {
            --m_proitemPtr;
            updateItem();
378
        } else {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
379
380
            updateItem();
            finalizeBlock();
381
        }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
382
        ++m_lineNo;
con's avatar
con committed
383
    }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
384
    return true;
con's avatar
con committed
385
386
387
388
}

void ProFileEvaluator::Private::finalizeBlock()
{
389
390
391
392
    if (m_blockstack.top()->blockKind() & ProBlock::SingleLine)
        leaveScope();
    m_block = 0;
    m_commentItem = 0;
con's avatar
con committed
393
394
}

395
void ProFileEvaluator::Private::insertVariable(const ushort **pCur, const ushort *end)
con's avatar
con committed
396
397
{
    ProVariable::VariableOperator opkind;
398
399
    ushort *uc = (ushort *)m_proitem.unicode();
    ushort *ptr = m_proitemPtr;
con's avatar
con committed
400

401
    if (ptr == uc) // Line starting with '=', like a conflict marker
402
403
        return;

404
    switch (*(ptr - 1)) {
con's avatar
con committed
405
        case '+':
406
            --ptr;
con's avatar
con committed
407
408
409
            opkind = ProVariable::AddOperator;
            break;
        case '-':
410
            --ptr;
con's avatar
con committed
411
412
413
            opkind = ProVariable::RemoveOperator;
            break;
        case '*':
414
            --ptr;
con's avatar
con committed
415
416
417
            opkind = ProVariable::UniqueAddOperator;
            break;
        case '~':
418
            --ptr;
con's avatar
con committed
419
420
421
422
423
424
            opkind = ProVariable::ReplaceOperator;
            break;
        default:
            opkind = ProVariable::SetOperator;
    }

425
426
427
428
429
430
    while (ptr != uc && *(ptr - 1) == ' ')
        --ptr;
    m_proitem.resize(ptr - uc);
    QString proVar = m_proitem;
    proVar.detach();

con's avatar
con committed
431
    ProBlock *block = m_blockstack.top();
432
    ProVariable *variable = new ProVariable(proVar, block);
con's avatar
con committed
433
434
435
436
437
438
439
440
441
442
443
444
445
    variable->setLineNumber(m_lineNo);
    variable->setVariableOperator(opkind);
    block->appendItem(variable);
    m_block = variable;

    if (!m_pendingComment.isEmpty()) {
        m_block->setComment(m_pendingComment);
        m_pendingComment.clear();
    }
    m_commentItem = variable;

    if (opkind == ProVariable::ReplaceOperator) {
        // skip util end of line or comment
446
447
448
449
450
451
        StrState sts = NotStarted;
        ptr = uc;
        const ushort *cur = *pCur;
        while (cur < end) {
            ushort c = *cur;
            if (c == '#') // comment?
con's avatar
con committed
452
                break;
453
454
455
456
457
458
459
460
461
462
            ++cur;

            if (c == ' ' || c == '\t') {
                if (sts == Started)
                    sts = PutSpace;
            } else {
                if (sts == PutSpace)
                    *ptr++ = ' ';
                *ptr++ = c;
                sts = Started;
con's avatar
con committed
463
464
            }
        }
465
466
467
468
        *pCur = cur;
        m_proitemPtr = ptr;
    } else {
        m_proitemPtr = uc;
con's avatar
con committed
469
470
471
472
473
474
475
476
    }
}

void ProFileEvaluator::Private::insertOperator(const char op)
{
    updateItem();

    ProOperator::OperatorKind opkind;
hjk's avatar
hjk committed
477
    switch (op) {
con's avatar
con committed
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
        case '!':
            opkind = ProOperator::NotOperator;
            break;
        case '|':
            opkind = ProOperator::OrOperator;
            break;
        default:
            opkind = ProOperator::OrOperator;
    }

    ProBlock * const block = currentBlock();
    ProOperator * const proOp = new ProOperator(opkind);
    proOp->setLineNumber(m_lineNo);
    block->appendItem(proOp);
    m_commentItem = proOp;
}

void ProFileEvaluator::Private::insertComment(const QString &comment)
{
    updateItem();

    QString strComment;
    if (!m_commentItem)
        strComment = m_pendingComment;
    else
        strComment = m_commentItem->comment();

    if (strComment.isEmpty())
        strComment = comment;
    else {
        strComment += QLatin1Char('\n');
        strComment += comment.trimmed();
    }

    strComment = strComment.trimmed();

    if (!m_commentItem)
        m_pendingComment = strComment;
    else
        m_commentItem->setComment(strComment);
}

void ProFileEvaluator::Private::enterScope(bool multiLine)
{
    updateItem();

    ProBlock *parent = currentBlock();
    ProBlock *block = new ProBlock(parent);
    block->setLineNumber(m_lineNo);
    parent->setBlockKind(ProBlock::ScopeKind);

    parent->appendItem(block);

    if (multiLine)
        block->setBlockKind(ProBlock::ScopeContentsKind);
    else
        block->setBlockKind(ProBlock::ScopeContentsKind|ProBlock::SingleLine);

    m_blockstack.push(block);
    m_block = 0;
}

void ProFileEvaluator::Private::leaveScope()
{
    updateItem();
543
544
545
546
    if (m_blockstack.count() == 1)
        q->errorMessage(format("Excess closing brace."));
    else
        m_blockstack.pop();
con's avatar
con committed
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
    finalizeBlock();
}

ProBlock *ProFileEvaluator::Private::currentBlock()
{
    if (m_block)
        return m_block;

    ProBlock *parent = m_blockstack.top();
    m_block = new ProBlock(parent);
    m_block->setLineNumber(m_lineNo);
    parent->appendItem(m_block);

    if (!m_pendingComment.isEmpty()) {
        m_block->setComment(m_pendingComment);
        m_pendingComment.clear();
    }

    m_commentItem = m_block;

    return m_block;
}

void ProFileEvaluator::Private::updateItem()
{
572
573
574
575
    ushort *uc = (ushort *)m_proitem.unicode();
    ushort *ptr = m_proitemPtr;

    if (ptr == uc)
con's avatar
con committed
576
577
        return;

578
579
580
581
582
    m_proitem.resize(ptr - uc);
    m_proitemPtr = uc;
    QString proItem = m_proitem;
    proItem.detach();

con's avatar
con committed
583
584
    ProBlock *block = currentBlock();
    if (block->blockKind() & ProBlock::VariableKind) {
585
586
587
        m_commentItem = new ProValue(proItem, static_cast<ProVariable*>(block));
    } else if (proItem.endsWith(QLatin1Char(')'))) {
        m_commentItem = new ProFunction(proItem);
con's avatar
con committed
588
    } else {
589
        m_commentItem = new ProCondition(proItem);
con's avatar
con committed
590
591
592
593
594
595
    }
    m_commentItem->setLineNumber(m_lineNo);
    block->appendItem(m_commentItem);
}


596
ProItem::ProItemReturn ProFileEvaluator::Private::visitBeginProBlock(ProBlock *block)
con's avatar
con committed
597
{
598
    if (block->blockKind() & ProBlock::ScopeContentsKind) {
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
        if (!m_definingFunc.isEmpty()) {
            if (!m_skipLevel || m_cumulative) {
                QHash<QString, ProBlock *> *hash =
                        (m_definingTest ? &m_testFunctions : &m_replaceFunctions);
                if (ProBlock *def = hash->value(m_definingFunc))
                    def->deref();
                hash->insert(m_definingFunc, block);
                block->ref();
                block->setBlockKind(block->blockKind() | ProBlock::FunctionBodyKind);
            }
            m_definingFunc.clear();
            return ProItem::ReturnSkip;
        } else if (!(block->blockKind() & ProBlock::FunctionBodyKind)) {
            if (!m_sts.condition)
                ++m_skipLevel;
            else
                Q_ASSERT(!m_skipLevel);
        }
617
618
619
620
621
622
623
624
625
    } else {
        if (!m_skipLevel) {
            if (m_sts.condition) {
                m_sts.prevCondition = true;
                m_sts.condition = false;
            }
        } else {
            Q_ASSERT(!m_sts.condition);
        }
con's avatar
con committed
626
    }
627
    return ProItem::ReturnTrue;
con's avatar
con committed
628
629
}

630
void ProFileEvaluator::Private::visitEndProBlock(ProBlock *block)
con's avatar
con committed
631
{
632
633
    if ((block->blockKind() & ProBlock::ScopeContentsKind)
        && !(block->blockKind() & ProBlock::FunctionBodyKind)) {
634
        if (m_skipLevel) {
635
            Q_ASSERT(!m_sts.condition);
636
            --m_skipLevel;
637
        } else if (!(block->blockKind() & ProBlock::SingleLine)) {
638
639
            // Conditionals contained inside this block may have changed the state.
            // So we reset it here to make an else following us do the right thing.
640
            m_sts.condition = true;
641
        }
642
    }
con's avatar
con committed
643
644
}

645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
ProItem::ProItemReturn ProFileEvaluator::Private::visitProLoopIteration()
{
    ProLoop &loop = m_loopStack.top();

    if (loop.infinite) {
        if (!loop.variable.isEmpty())
            m_valuemap[loop.variable] = QStringList(QString::number(loop.index++));
        if (loop.index > 1000) {
            q->errorMessage(format("ran into infinite loop (> 1000 iterations)."));
            return ProItem::ReturnFalse;
        }
    } else {
        QString val;
        do {
            if (loop.index >= loop.list.count())
                return ProItem::ReturnFalse;
            val = loop.list.at(loop.index++);
        } while (val.isEmpty()); // stupid, but qmake is like that
        m_valuemap[loop.variable] = QStringList(val);
    }
    return ProItem::ReturnTrue;
}

void ProFileEvaluator::Private::visitProLoopCleanup()
{
    ProLoop &loop = m_loopStack.top();
    m_valuemap[loop.variable] = loop.oldVarVal;
    m_loopStack.pop_back();
}

675
void ProFileEvaluator::Private::visitBeginProVariable(ProVariable *)
con's avatar
con committed
676
{
677
    m_sts.varVal.clear();
con's avatar
con committed
678
679
}

680
void ProFileEvaluator::Private::visitEndProVariable(ProVariable *variable)
con's avatar
con committed
681
{
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
    QString varName = variable->variable();

    switch (variable->variableOperator()) {
        case ProVariable::SetOperator:          // =
            if (!m_cumulative) {
                if (!m_skipLevel) {
                    m_valuemap[varName] = m_sts.varVal;
                    m_filevaluemap[currentProFile()][varName] = m_sts.varVal;
                }
            } else {
                // We are greedy for values.
                m_valuemap[varName] += m_sts.varVal;
                m_filevaluemap[currentProFile()][varName] += m_sts.varVal;
            }
            break;
        case ProVariable::UniqueAddOperator:    // *=
            if (!m_skipLevel || m_cumulative) {
                insertUnique(&m_valuemap, varName, m_sts.varVal);
                insertUnique(&m_filevaluemap[currentProFile()], varName, m_sts.varVal);
            }
            break;
        case ProVariable::AddOperator:          // +=
            if (!m_skipLevel || m_cumulative) {
                m_valuemap[varName] += m_sts.varVal;
                m_filevaluemap[currentProFile()][varName] += m_sts.varVal;
            }
            break;
        case ProVariable::RemoveOperator:       // -=
            if (!m_cumulative) {
                if (!m_skipLevel) {
                    removeEach(&m_valuemap, varName, m_sts.varVal);
                    removeEach(&m_filevaluemap[currentProFile()], varName, m_sts.varVal);
                }
            } else {
                // We are stingy with our values, too.
            }
            break;
        case ProVariable::ReplaceOperator:      // ~=
            {
                // DEFINES ~= s/a/b/?[gqi]

                QString val = m_sts.varVal.first();
                doVariableReplace(&val);
                if (val.length() < 4 || val[0] != QLatin1Char('s')) {
                    q->logMessage(format("the ~= operator can handle only the s/// function."));
                    break;
                }
                QChar sep = val.at(1);
                QStringList func = val.split(sep);
                if (func.count() < 3 || func.count() > 4) {
                    q->logMessage(format("the s/// function expects 3 or 4 arguments."));
                    break;
                }

                bool global = false, quote = false, case_sense = false;
                if (func.count() == 4) {
                    global = func[3].indexOf(QLatin1Char('g')) != -1;
                    case_sense = func[3].indexOf(QLatin1Char('i')) == -1;
                    quote = func[3].indexOf(QLatin1Char('q')) != -1;
                }
                QString pattern = func[1];
                QString replace = func[2];
                if (quote)
                    pattern = QRegExp::escape(pattern);

                QRegExp regexp(pattern, case_sense ? Qt::CaseSensitive : Qt::CaseInsensitive);

                if (!m_skipLevel || m_cumulative) {
                    // We could make a union of modified and unmodified values,
                    // but this will break just as much as it fixes, so leave it as is.
                    replaceInList(&m_valuemap[varName], regexp, replace, global);
                    replaceInList(&m_filevaluemap[currentProFile()][varName], regexp, replace, global);

                }
            }
            break;
    }
con's avatar
con committed
759
760
}

761
void ProFileEvaluator::Private::visitProOperator(ProOperator *oper)
con's avatar
con committed
762
763
764
765
{
    m_invertNext = (oper->operatorKind() == ProOperator::NotOperator);
}

766
void ProFileEvaluator::Private::visitProCondition(ProCondition *cond)
con's avatar
con committed
767
{
768
    if (!m_skipLevel) {
769
        if (!cond->text().compare(QLatin1String("else"), Qt::CaseInsensitive)) {
770
771
772
773
774
            m_sts.condition = !m_sts.prevCondition;
        } else {
            m_sts.prevCondition = false;
            if (!m_sts.condition && isActiveConfig(cond->text(), true) ^ m_invertNext)
                m_sts.condition = true;
775
        }
con's avatar
con committed
776
    }
777
    m_invertNext = false;
con's avatar
con committed
778
779
}

780
ProItem::ProItemReturn ProFileEvaluator::Private::visitBeginProFile(ProFile * pro)
con's avatar
con committed
781
782
783
784
785
786
787
788
789
790
791
792
793
794
{
    PRE(pro);
    m_lineNo = pro->lineNumber();
    if (m_origfile.isEmpty())
        m_origfile = pro->fileName();
    if (m_oldPath.isEmpty()) {
        // change the working directory for the initial profile we visit, since
        // that is *the* profile. All the other times we reach this function will be due to
        // include(file) or load(file)

        m_oldPath = QDir::currentPath();

        m_profileStack.push(pro);

795
        const QString mkspecDirectory = propertyValue(QLatin1String("QMAKE_MKSPECS"));
796
        if (!mkspecDirectory.isEmpty() && m_parsePreAndPostFiles) {
797
798
            bool cumulative = m_cumulative;
            m_cumulative = false;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
799
800
            evaluateFile(mkspecDirectory + QLatin1String("/default/qmake.conf"));
            evaluateFile(mkspecDirectory + QLatin1String("/features/default_pre.prf"));
801

802
            QStringList tmp = m_valuemap.value(QLatin1String("CONFIG"));
803
804
805
            tmp.append(m_addUserConfigCmdArgs);
            foreach(const QString &remove, m_removeUserConfigCmdArgs)
                tmp.removeAll(remove);
806
            m_valuemap.insert(QLatin1String("CONFIG"), tmp);
807
            m_cumulative = cumulative;
con's avatar
con committed
808
809
        }

810
        return returnBool(QDir::setCurrent(pro->directoryName()));
con's avatar
con committed
811
812
    }

813
    return ProItem::ReturnTrue;
con's avatar
con committed
814
815
}

816
ProItem::ProItemReturn ProFileEvaluator::Private::visitEndProFile(ProFile * pro)
con's avatar
con committed
817
818
819
820
{
    PRE(pro);
    m_lineNo = pro->lineNumber();
    if (m_profileStack.count() == 1 && !m_oldPath.isEmpty()) {
821
        const QString &mkspecDirectory = propertyValue(QLatin1String("QMAKE_MKSPECS"));
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
        if (!mkspecDirectory.isEmpty()) {
            if (m_parsePreAndPostFiles) {
                bool cumulative = m_cumulative;
                m_cumulative = false;

                evaluateFile(mkspecDirectory + QLatin1String("/features/default_post.prf"));

                QSet<QString> processed;
                forever {
                    bool finished = true;
                    QStringList configs = valuesDirect(QLatin1String("CONFIG"));
                    for (int i = configs.size() - 1; i >= 0; --i) {
                        const QString config = configs[i].toLower();
                        if (!processed.contains(config)) {
                            processed.insert(config);
                            if (evaluateFile(mkspecDirectory + QLatin1String("/features/")
                                + config + QLatin1String(".prf"))) {
                                finished = false;
                                break;
                            }
con's avatar
con committed
842
843
                        }
                    }
844
845
                    if (finished)
                        break;
con's avatar
con committed
846
                }
847
                m_cumulative = cumulative;
con's avatar
con committed
848
            }
849

850
851
852
853
854
855
            foreach (ProBlock *itm, m_replaceFunctions)
                itm->deref();
            m_replaceFunctions.clear();
            foreach (ProBlock *itm, m_testFunctions)
                itm->deref();
            m_testFunctions.clear();
con's avatar
con committed
856
857
858
        }

        m_profileStack.pop();
859
        return returnBool(QDir::setCurrent(m_oldPath));
con's avatar
con committed
860
    }
861
862

    return ProItem::ReturnTrue;
con's avatar
con committed
863
864
}

865
void ProFileEvaluator::Private::visitProValue(ProValue *value)
con's avatar
con committed
866
867
868
{
    PRE(value);
    m_lineNo = value->lineNumber();
869
    m_sts.varVal += expandVariableReferences(value->value());
con's avatar
con committed
870
871
}

872
ProItem::ProItemReturn ProFileEvaluator::Private::visitProFunction(ProFunction *func)
con's avatar
con committed
873
{
874
875
876
    // Make sure that called subblocks don't inherit & destroy the state
    bool invertThis = m_invertNext;
    m_invertNext = false;
877
878
879
    if (!m_skipLevel)
        m_sts.prevCondition = false;
    if (m_cumulative || !m_sts.condition) {
880
881
882
        QString text = func->text();
        int lparen = text.indexOf(QLatin1Char('('));
        int rparen = text.lastIndexOf(QLatin1Char(')'));
883
        Q_ASSERT(lparen < rparen);
884
885
886
        QString arguments = text.mid(lparen + 1, rparen - lparen - 1);
        QString funcName = text.left(lparen);
        m_lineNo = func->lineNumber();
887
888
889
890
        ProItem::ProItemReturn result = evaluateConditionalFunction(funcName.trimmed(), arguments);
        if (result != ProItem::ReturnFalse && result != ProItem::ReturnTrue)
            return result;
        if (!m_skipLevel && ((result == ProItem::ReturnTrue) ^ invertThis))
891
            m_sts.condition = true;
892
    }
893
    return ProItem::ReturnTrue;
con's avatar
con committed
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
}


QStringList ProFileEvaluator::Private::qmakeFeaturePaths()
{
    QStringList concat;
    {
        const QString base_concat = QDir::separator() + QString(QLatin1String("features"));
        concat << base_concat + QDir::separator() + QLatin1String("mac");
        concat << base_concat + QDir::separator() + QLatin1String("macx");
        concat << base_concat + QDir::separator() + QLatin1String("unix");
        concat << base_concat + QDir::separator() + QLatin1String("win32");
        concat << base_concat + QDir::separator() + QLatin1String("mac9");
        concat << base_concat + QDir::separator() + QLatin1String("qnx6");
        concat << base_concat;
    }
    const QString mkspecs_concat = QDir::separator() + QString(QLatin1String("mkspecs"));
    QStringList feature_roots;
    QByteArray mkspec_path = qgetenv("QMAKEFEATURES");
    if (!mkspec_path.isNull())
        feature_roots += splitPathList(QString::fromLocal8Bit(mkspec_path));
    /*
    if (prop)
        feature_roots += splitPathList(prop->value("QMAKEFEATURES"));
    if (!Option::mkfile::cachefile.isEmpty()) {
        QString path;
        int last_slash = Option::mkfile::cachefile.lastIndexOf(Option::dir_sep);
        if (last_slash != -1)
            path = Option::fixPathToLocalOS(Option::mkfile::cachefile.left(last_slash));
        foreach (const QString &concat_it, concat)
            feature_roots << (path + concat_it);
    }
    */

    QByteArray qmakepath = qgetenv("QMAKEPATH");
    if (!qmakepath.isNull()) {
        const QStringList lst = splitPathList(QString::fromLocal8Bit(qmakepath));
        foreach (const QString &item, lst) {
            foreach (const QString &concat_it, concat)
                feature_roots << (item + mkspecs_concat + concat_it);
        }
    }
    //if (!Option::mkfile::qmakespec.isEmpty())
    //    feature_roots << Option::mkfile::qmakespec + QDir::separator() + "features";
    //if (!Option::mkfile::qmakespec.isEmpty()) {
    //    QFileInfo specfi(Option::mkfile::qmakespec);
    //    QDir specdir(specfi.absoluteFilePath());
    //    while (!specdir.isRoot()) {
    //        if (!specdir.cdUp() || specdir.isRoot())
    //            break;
    //        if (QFile::exists(specdir.path() + QDir::separator() + "features")) {
    //            foreach (const QString &concat_it, concat) 
    //                feature_roots << (specdir.path() + concat_it);
    //            break;
    //        }
    //    }
    //}
    foreach (const QString &concat_it, concat)
        feature_roots << (propertyValue(QLatin1String("QT_INSTALL_PREFIX")) +
                          mkspecs_concat + concat_it);
    foreach (const QString &concat_it, concat)
        feature_roots << (propertyValue(QLatin1String("QT_INSTALL_DATA")) +
                          mkspecs_concat + concat_it);
    return feature_roots;
}

QString ProFileEvaluator::Private::propertyValue(const QString &name) const
{
    if (m_properties.contains(name))
        return m_properties.value(name);
    if (name == QLatin1String("QT_INSTALL_PREFIX"))
        return QLibraryInfo::location(QLibraryInfo::PrefixPath);
    if (name == QLatin1String("QT_INSTALL_DATA"))
        return QLibraryInfo::location(QLibraryInfo::DataPath);
    if (name == QLatin1String("QT_INSTALL_DOCS"))
        return QLibraryInfo::location(QLibraryInfo::DocumentationPath);
    if (name == QLatin1String("QT_INSTALL_HEADERS"))
        return QLibraryInfo::location(QLibraryInfo::HeadersPath);
    if (name == QLatin1String("QT_INSTALL_LIBS"))
        return QLibraryInfo::location(QLibraryInfo::LibrariesPath);
    if (name == QLatin1String("QT_INSTALL_BINS"))
        return QLibraryInfo::location(QLibraryInfo::BinariesPath);
    if (name == QLatin1String("QT_INSTALL_PLUGINS"))
        return QLibraryInfo::location(QLibraryInfo::PluginsPath);
    if (name == QLatin1String("QT_INSTALL_TRANSLATIONS"))
        return QLibraryInfo::location(QLibraryInfo::TranslationsPath);
    if (name == QLatin1String("QT_INSTALL_CONFIGURATION"))
        return QLibraryInfo::location(QLibraryInfo::SettingsPath);
    if (name == QLatin1String("QT_INSTALL_EXAMPLES"))
        return QLibraryInfo::location(QLibraryInfo::ExamplesPath);
    if (name == QLatin1String("QT_INSTALL_DEMOS"))
        return QLibraryInfo::location(QLibraryInfo::DemosPath);
    if (name == QLatin1String("QMAKE_MKSPECS"))
        return qmake_mkspec_paths().join(Option::dirlist_sep);
    if (name == QLatin1String("QMAKE_VERSION"))
        return QLatin1String("1.0");        //### FIXME
        //return qmake_version();
#ifdef QT_VERSION_STR
    if (name == QLatin1String("QT_VERSION"))
        return QLatin1String(QT_VERSION_STR);
#endif
    return QLatin1String("UNKNOWN");        //###
}

ProFile *ProFileEvaluator::Private::currentProFile() const
{
    if (m_profileStack.count() > 0)