profileevaluator.cpp 95.4 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
    enum StrState { NeverStarted, NotStarted, Started, PutSpace };
158

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
    int parens = 0;
    bool inQuote = false;
292
293
    while (!ts->atEnd()) {
        QString line = ts->readLine();
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
294
        const ushort *cur = (const ushort *)line.unicode(),
295
296
                     *end = cur + line.length(),
                     *cmtptr = 0;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
297
298
        m_proitem.reserve(line.length());
        m_proitemPtr = (ushort *)m_proitem.unicode();
299
300
301
        enum { NotEscaped, Escaped, PostEscaped } escaped = NotEscaped;
        StrState sts = NeverStarted;
        goto startItem;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
302
      nextItem:
303
304
305
306
        escaped = NotEscaped;
      nextItem1:
        sts = NotStarted;
      startItem:
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
307
308
309
310
        ushort *ptr = m_proitemPtr;
        while (cur < end) {
            ushort c = *cur++;
            if (c == '#') { // Yep - no escaping possible
311
312
                cmtptr = cur;
                break;
con's avatar
con committed
313
            }
314
            if (escaped != Escaped) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
315
                if (c == '\\') {
316
                    escaped = Escaped;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
317
318
319
                    goto putch;
                } else if (c == '"') {
                    inQuote = !inQuote;
320
                    goto putch1;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
321
322
323
324
325
326
327
328
329
330
331
332
                }
            }
            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();
333
334
335
                            if (escaped == Escaped)
                                escaped = PostEscaped;
                            goto nextItem1;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
                        }
                    } 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;
                        }
363
                    }
364
                }
con's avatar
con committed
365
366
            }

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
367
            if (c == ' ' || c == '\t') {
368
                if (sts == Started) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
369
                    sts = PutSpace;
370
371
372
                    if (escaped == Escaped)
                        escaped = PostEscaped;
                }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
373
            } else {
374
375
              putch1:
                escaped = NotEscaped;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
376
377
378
379
380
381
382
              putch:
                if (sts == PutSpace)
                    *ptr++ = ' ';
                *ptr++ = c;
                sts = Started;
            }
        }
383
384
385
386
387
        if (escaped != NotEscaped) {
            --ptr;
            if (ptr != (ushort *)m_proitem.unicode() && *(ptr - 1) == ' ')
                --ptr;
        }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
388
        m_proitemPtr = ptr;
389
390
391
392
        updateItem();
        if (cmtptr)
            insertComment(line.right(end - cmtptr).simplified());
        if (sts != NeverStarted && escaped == NotEscaped)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
393
394
            finalizeBlock();
        ++m_lineNo;
con's avatar
con committed
395
    }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
396
    return true;
con's avatar
con committed
397
398
399
400
}

void ProFileEvaluator::Private::finalizeBlock()
{
401
402
403
404
    if (m_blockstack.top()->blockKind() & ProBlock::SingleLine)
        leaveScope();
    m_block = 0;
    m_commentItem = 0;
con's avatar
con committed
405
406
}

407
void ProFileEvaluator::Private::insertVariable(const ushort **pCur, const ushort *end)
con's avatar
con committed
408
409
{
    ProVariable::VariableOperator opkind;
410
411
    ushort *uc = (ushort *)m_proitem.unicode();
    ushort *ptr = m_proitemPtr;
con's avatar
con committed
412

413
    if (ptr == uc) // Line starting with '=', like a conflict marker
414
415
        return;

416
    switch (*(ptr - 1)) {
con's avatar
con committed
417
        case '+':
418
            --ptr;
con's avatar
con committed
419
420
421
            opkind = ProVariable::AddOperator;
            break;
        case '-':
422
            --ptr;
con's avatar
con committed
423
424
425
            opkind = ProVariable::RemoveOperator;
            break;
        case '*':
426
            --ptr;
con's avatar
con committed
427
428
429
            opkind = ProVariable::UniqueAddOperator;
            break;
        case '~':
430
            --ptr;
con's avatar
con committed
431
432
433
434
435
436
            opkind = ProVariable::ReplaceOperator;
            break;
        default:
            opkind = ProVariable::SetOperator;
    }

437
438
439
440
441
442
    while (ptr != uc && *(ptr - 1) == ' ')
        --ptr;
    m_proitem.resize(ptr - uc);
    QString proVar = m_proitem;
    proVar.detach();

con's avatar
con committed
443
    ProBlock *block = m_blockstack.top();
444
    ProVariable *variable = new ProVariable(proVar, block);
con's avatar
con committed
445
446
447
448
449
450
451
452
453
454
455
456
457
    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
458
459
460
461
462
463
        StrState sts = NotStarted;
        ptr = uc;
        const ushort *cur = *pCur;
        while (cur < end) {
            ushort c = *cur;
            if (c == '#') // comment?
con's avatar
con committed
464
                break;
465
466
467
468
469
470
471
472
473
474
            ++cur;

            if (c == ' ' || c == '\t') {
                if (sts == Started)
                    sts = PutSpace;
            } else {
                if (sts == PutSpace)
                    *ptr++ = ' ';
                *ptr++ = c;
                sts = Started;
con's avatar
con committed
475
476
            }
        }
477
478
479
480
        *pCur = cur;
        m_proitemPtr = ptr;
    } else {
        m_proitemPtr = uc;
con's avatar
con committed
481
482
483
484
485
486
487
488
    }
}

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

    ProOperator::OperatorKind opkind;
hjk's avatar
hjk committed
489
    switch (op) {
con's avatar
con committed
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
543
544
545
546
547
548
549
550
551
552
        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)
{
    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();
553
554
555
556
    if (m_blockstack.count() == 1)
        q->errorMessage(format("Excess closing brace."));
    else
        m_blockstack.pop();
con's avatar
con committed
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
    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()
{
582
583
584
585
    ushort *uc = (ushort *)m_proitem.unicode();
    ushort *ptr = m_proitemPtr;

    if (ptr == uc)
con's avatar
con committed
586
587
        return;

588
589
590
591
592
    m_proitem.resize(ptr - uc);
    m_proitemPtr = uc;
    QString proItem = m_proitem;
    proItem.detach();

con's avatar
con committed
593
594
    ProBlock *block = currentBlock();
    if (block->blockKind() & ProBlock::VariableKind) {
595
596
597
        m_commentItem = new ProValue(proItem, static_cast<ProVariable*>(block));
    } else if (proItem.endsWith(QLatin1Char(')'))) {
        m_commentItem = new ProFunction(proItem);
con's avatar
con committed
598
    } else {
599
        m_commentItem = new ProCondition(proItem);
con's avatar
con committed
600
601
602
603
604
605
    }
    m_commentItem->setLineNumber(m_lineNo);
    block->appendItem(m_commentItem);
}


606
ProItem::ProItemReturn ProFileEvaluator::Private::visitBeginProBlock(ProBlock *block)
con's avatar
con committed
607
{
608
    if (block->blockKind() & ProBlock::ScopeContentsKind) {
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
        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);
        }
627
628
629
630
631
632
633
634
635
    } 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
636
    }
637
    return ProItem::ReturnTrue;
con's avatar
con committed
638
639
}

640
void ProFileEvaluator::Private::visitEndProBlock(ProBlock *block)
con's avatar
con committed
641
{
642
643
    if ((block->blockKind() & ProBlock::ScopeContentsKind)
        && !(block->blockKind() & ProBlock::FunctionBodyKind)) {
644
        if (m_skipLevel) {
645
            Q_ASSERT(!m_sts.condition);
646
            --m_skipLevel;
647
        } else if (!(block->blockKind() & ProBlock::SingleLine)) {
648
649
            // 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.
650
            m_sts.condition = true;
651
        }
652
    }
con's avatar
con committed
653
654
}

655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
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();
}

685
void ProFileEvaluator::Private::visitBeginProVariable(ProVariable *)
con's avatar
con committed
686
{
687
    m_sts.varVal.clear();
con's avatar
con committed
688
689
}

690
void ProFileEvaluator::Private::visitEndProVariable(ProVariable *variable)
con's avatar
con committed
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
759
760
761
762
763
764
765
766
767
768
    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
769
770
}

771
void ProFileEvaluator::Private::visitProOperator(ProOperator *oper)
con's avatar
con committed
772
773
774
775
{
    m_invertNext = (oper->operatorKind() == ProOperator::NotOperator);
}

776
void ProFileEvaluator::Private::visitProCondition(ProCondition *cond)
con's avatar
con committed
777
{
778
    if (!m_skipLevel) {
779
        if (!cond->text().compare(QLatin1String("else"), Qt::CaseInsensitive)) {
780
781
782
783
784
            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;
785
        }
con's avatar
con committed
786
    }
787
    m_invertNext = false;
con's avatar
con committed
788
789
}

790
ProItem::ProItemReturn ProFileEvaluator::Private::visitBeginProFile(ProFile * pro)
con's avatar
con committed
791
792
793
794
795
796
797
798
799
800
801
802
803
804
{
    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);

805
806
807
808
809
810
811
812
813
        if (m_parsePreAndPostFiles) {
            const QString mkspecDirectory = propertyValue(QLatin1String("QMAKE_MKSPECS"));
            if (!mkspecDirectory.isEmpty()) {
                bool cumulative = m_cumulative;
                m_cumulative = false;
                evaluateFile(mkspecDirectory + QLatin1String("/default/qmake.conf"));
                m_cumulative = cumulative;
            }
            evaluateFeatureFile(QLatin1String("default_pre.prf"));
814

815
816
817
818
            QStringList &tgt = m_valuemap[QLatin1String("TARGET")];
            if (tgt.isEmpty())
                tgt.append(QFileInfo(pro->fileName()).baseName());

819
            QStringList tmp = m_valuemap.value(QLatin1String("CONFIG"));
820
            tmp.append(m_addUserConfigCmdArgs);
821
            foreach (const QString &remove, m_removeUserConfigCmdArgs)
822
                tmp.removeAll(remove);
823
            m_valuemap.insert(QLatin1String("CONFIG"), tmp);
con's avatar
con committed
824
825
        }

826
        return returnBool(QDir::setCurrent(pro->directoryName()));
con's avatar
con committed
827
828
    }

829
    return ProItem::ReturnTrue;
con's avatar
con committed
830
831
}

832
ProItem::ProItemReturn ProFileEvaluator::Private::visitEndProFile(ProFile * pro)
con's avatar
con committed
833
834
835
836
{
    PRE(pro);
    m_lineNo = pro->lineNumber();
    if (m_profileStack.count() == 1 && !m_oldPath.isEmpty()) {
837
838
839
840
841
842
843
844
845
846
847
848
849
850
        if (m_parsePreAndPostFiles) {
            evaluateFeatureFile(QLatin1String("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 (evaluateFeatureFile(config)) {
                            finished = false;
                            break;
con's avatar
con committed
851
852
853
                        }
                    }
                }
854
855
                if (finished)
                    break;
con's avatar
con committed
856
857
858
            }
        }

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
859
860
861
862
863
864
865
        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
866
        m_profileStack.pop();
867
        return returnBool(QDir::setCurrent(m_oldPath));
con's avatar
con committed
868
    }
869
870

    return ProItem::ReturnTrue;
con's avatar
con committed
871
872
}

873
void ProFileEvaluator::Private::visitProValue(ProValue *value)
con's avatar
con committed
874
875
876
{
    PRE(value);
    m_lineNo = value->lineNumber();
877
    m_sts.varVal += expandVariableReferences(value->value());
con's avatar
con committed
878
879
}

880
ProItem::ProItemReturn ProFileEvaluator::Private::visitProFunction(ProFunction *func)
con's avatar
con committed
881
{
882
883
884
    // Make sure that called subblocks don't inherit & destroy the state
    bool invertThis = m_invertNext;
    m_invertNext = false;
885
886
887
    if (!m_skipLevel)
        m_sts.prevCondition = false;
    if (m_cumulative || !m_sts.condition) {
888
889
890
        QString text = func->text();
        int lparen = text.indexOf(QLatin1Char('('));
        int rparen = text.lastIndexOf(QLatin1Char(')'));
891
        Q_ASSERT(lparen < rparen);
892
893
894
        QString arguments = text.mid(lparen + 1, rparen - lparen - 1);
        QString funcName = text.left(lparen);
        m_lineNo = func->lineNumber();
895
896
897
898
        ProItem::ProItemReturn result = evaluateConditionalFunction(funcName.trimmed(), arguments);
        if (result != ProItem::ReturnFalse && result != ProItem::ReturnTrue)
            return result;
        if (!m_skipLevel && ((result == ProItem::ReturnTrue) ^ invertThis))
899
            m_sts.condition = true;
900
    }
901
    return ProItem::ReturnTrue;
con's avatar
con committed
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
}


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)
        return m_profileStack.top();
    return 0;
}

QString ProFileEvaluator::Private::currentFileName() const
{
    ProFile *pro = currentProFile();
    if (pro)
        return pro->fileName();
    return QString();
}

1021
QString ProFileEvaluator::Private::currentDirectory() const
con's avatar
con committed
1022
1023
{
    ProFile *cur = m_profileStack.top();
1024
    return cur->directoryName();
con's avatar
con committed
1025
1026
}

1027
1028
1029
1030
1031
void ProFileEvaluator::Private::doVariableReplace(QString *str)
{
    *str = expandVariableReferences(*str).join(QString(Option::field_sep));
}

con's avatar
con committed
1032
1033
1034
QStringList ProFileEvaluator::Private::expandVariableReferences(const QString &str)
{
    QStringList ret;
1035
1036
//    if (ok)
//        *ok = true;
con's avatar
con committed
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
    if (str.isEmpty())
        return ret;

    const ushort LSQUARE = '[';
    const ushort RSQUARE = ']';
    const ushort LCURLY = '{';
    const ushort RCURLY = '}';
    const ushort LPAREN = '(';
    const ushort RPAREN = ')';
    const ushort DOLLAR = '$';
    const ushort BACKSLASH = '\\';
    const ushort UNDERSCORE = '_';
    const ushort DOT = '.';
    const ushort SPACE = ' ';
    const ushort TAB = '\t';
1052
1053
    const ushort SINGLEQUOTE = '\'';
    const ushort DOUBLEQUOTE = '"';
con's avatar
con committed
1054

1055
    ushort unicode, quote = 0;
con's avatar
con committed
1056
1057
1058
1059
1060
1061
1062
1063
1064
    const QChar *str_data = str.data();
    const int str_len = str.length();

    ushort term;
    QString var, args;

    int replaced = 0;
    QString current;
    for (int i = 0; i < str_len; ++i) {
1065
        unicode = str_data[i].unicode();
con's avatar
con committed
1066
        const int start_var = i;
1067
1068
1069
        if (unicode == DOLLAR && str_len > i+2) {
            unicode = str_data[++i].unicode();
            if (unicode == DOLLAR) {
con's avatar
con committed
1070
1071
1072
1073
                term = 0;
                var.clear();
                args.clear();
                enum { VAR, ENVIRON, FUNCTION, PROPERTY } var_type = VAR;
1074
1075
1076
                unicode = str_data[++i].unicode();
                if (unicode == LSQUARE) {
                    unicode = str_data[++i].unicode();
con's avatar
con committed
1077
1078
                    term = RSQUARE;
                    var_type = PROPERTY;
1079
1080
                } else if (unicode == LCURLY) {
                    unicode = str_data[++i].unicode();
con's avatar
con committed
1081
1082
                    var_type = VAR;
                    term = RCURLY;
1083
1084
                } else if (unicode == LPAREN) {
                    unicode = str_data[++i].unicode();
con's avatar
con committed
1085
1086
1087
                    var_type = ENVIRON;
                    term = RPAREN;
                }
1088
1089
1090
1091
1092
1093
                forever {
                    if (!(unicode & (0xFF<<8)) &&
                       unicode != DOT && unicode != UNDERSCORE &&
                       //unicode != SINGLEQUOTE && unicode != DOUBLEQUOTE &&
                       (unicode < 'a' || unicode > 'z') && (unicode < 'A' || unicode > 'Z') &&
                       (unicode < '0' || unicode > '9'))
con's avatar
con committed
1094
                        break;
1095
                    var.append(QChar(unicode));
con's avatar
con committed
1096
1097
                    if (++i == str_len)
                        break;
1098
1099
                    unicode = str_data[i].unicode();
                    // at this point, i points to either the 'term' or 'next' character (which is in unicode)
con's avatar
con committed
1100
                }
1101
                if (var_type == VAR && unicode == LPAREN) {
con's avatar
con committed
1102
1103
                    var_type = FUNCTION;
                    int depth = 0;
1104
                    forever {
con's avatar
con committed
1105
1106
                        if (++i == str_len)
                            break;
1107
1108
                        unicode = str_data[i].unicode();
                        if (unicode == LPAREN) {
con's avatar
con committed
1109
                            depth++;
1110
                        } else if (unicode == RPAREN) {
con's avatar
con committed
1111
1112
1113
1114
                            if (!depth)
                                break;
                            --depth;
                        }
1115
                        args.append(QChar(unicode));
con's avatar
con committed
1116
                    }
1117
1118
                    if (++i < str_len)
                        unicode = str_data[i].unicode();
con's avatar
con committed
1119
                    else
1120
1121
1122
                        unicode = 0;
                    // at this point i is pointing to the 'next' character (which is in unicode)
                    // this might actually be a term character since you can do $${func()}
con's avatar
con committed
1123
1124
                }
                if (term) {
1125
                    if (unicode != term) {
con's avatar
con committed
1126
                        q->logMessage(format("Missing %1 terminator [found %2]")
1127
1128
1129
1130
                            .arg(QChar(term))
                            .arg(unicode ? QString(unicode) : QString::fromLatin1(("end-of-line"))));
//                        if (ok)
//                            *ok = false;
con's avatar
con committed
1131
1132
                        return QStringList();
                    }
1133
1134
1135
                } else {
                    // move the 'cursor' back to the last char of the thing we were looking at
                    --i;
con's avatar
con committed
1136
                }
1137
1138
                // since i never points to the 'next' character, there is no reason for this to be set
                unicode = 0;
con's avatar
con committed
1139
1140
1141

                QStringList replacement;
                if (var_type == ENVIRON) {
1142
                    replacement = split_value_list(QString::fromLocal8Bit(qgetenv(var.toLatin1().constData())));
con's avatar
con committed
1143
1144
1145
1146
1147
                } else if (var_type == PROPERTY) {
                    replacement << propertyValue(var);
                } else if (var_type == FUNCTION) {
                    replacement << evaluateExpandFunction(var, args);
                } else if (var_type == VAR) {
1148
                    replacement = values(var);
con's avatar
con committed
1149
1150
1151
1152
                }
                if (!(replaced++) && start_var)
                    current = str.left(start_var);
                if (!replacement.isEmpty()) {
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
                    if (quote) {
                        current += replacement.join(QString(Option::field_sep));
                    } else {
                        current += replacement.takeFirst();
                        if (!replacement.isEmpty()) {
                            if (!current.isEmpty())
                                ret.append(current);
                            current = replacement.takeLast();
                            if (!replacement.isEmpty())
                                ret += replacement;
                        }
con's avatar
con committed
1164
1165
1166
1167
1168
1169
1170
                    }
                }
            } else {
                if (replaced)
                    current.append(QLatin1Char('$'));
            }
        }
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
        if (quote && unicode == quote) {
            unicode = 0;
            quote = 0;
        } else if (unicode == BACKSLASH) {
            bool escape = false;
            const char *symbols = "[]{}()$\\'\"";
            for (const char *s = symbols; *s; ++s) {
                if (str_data[i+1].unicode() == (ushort)*s) {
                    i++;
                    escape = true;
                    if (!(replaced++))
                        current = str.left(start_var);
                    current.append(str.at(i));
                    break;
                }
            }
            if (escape || !replaced)
                unicode =0;
        } else if (!quote && (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE)) {
            quote = unicode;
            unicode = 0;
            if (!(replaced++) && i)
                current = str.left(i);
        } else if (!quote && (unicode == SPACE || unicode == TAB)) {
            unicode = 0;
            if (!current.isEmpty()) {
                ret.append(current);
                current.clear();
            }
        }
        if (replaced && unicode)
            current.append(QChar(unicode));
con's avatar
con committed
1203
    }
1204
1205
1206
    if (!replaced)
        ret = QStringList(str);
    else if (!current.isEmpty())
con's avatar
con committed
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
        ret.append(current);
    return ret;
}

bool ProFileEvaluator::Private::isActiveConfig(const QString &config, bool regex)
{
    // magic types for easy flipping
    if (config == QLatin1String("true"))
        return true;
    if (config == QLatin1String("false"))
        return false;

    // mkspecs
    if ((Option::target_mode == Option::TARG_MACX_MODE
            || Option::target_mode == Option::TARG_QNX6_MODE
            || Option::target_mode == Option::TARG_UNIX_MODE)
          && config == QLatin1String("unix"))
        return true;
    if (Option::target_mode == Option::TARG_MACX_MODE && config == QLatin1String("macx"))
        return true;
    if (Option::target_mode == Option::TARG_QNX6_MODE && config == QLatin1String("qnx6"))
        return true;
    if (Option::target_mode == Option::TARG_MAC9_MODE && config == QLatin1String("mac9"))
        return true;
    if ((Option::target_mode == Option::TARG_MAC9_MODE
            || Option::target_mode == Option::TARG_MACX_MODE)
          && config == QLatin1String("mac"))
        return true;
    if (Option::target_mode == Option::TARG_WIN_MODE && config == QLatin1String("win32"))
        return true;

1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
    if (regex) {
        QRegExp re(config, Qt::CaseSensitive, QRegExp::Wildcard);

        if (re.exactMatch(Option::qmakespec))
            return true;

        // CONFIG variable
        foreach (const QString &configValue, m_valuemap.value(QLatin1String("CONFIG"))) {
            if (re.exactMatch(configValue))
                return true;
        }
    } else {
        // mkspecs
        if (Option::qmakespec == config)
            return true;

        // CONFIG variable
        foreach (const QString &configValue, m_valuemap.value(QLatin1String("CONFIG"))) {
            if (configValue == config)
                return true;
        }
    }
con's avatar
con committed
1260
1261
1262
1263

    return false;
}

1264
1265
1266
1267
1268
1269
1270
1271
QStringList ProFileEvaluator::Private::evaluateFunction(
        ProBlock *funcPtr, const QStringList &argumentsList, bool *ok)
{
    bool oki;
    QStringList ret;

    if (m_valuemapStack.count() >= 100) {
        q->errorMessage(format("ran into infinite recursion (depth > 100)."));
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1272
        oki = false;
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
    } else {
        State sts = m_sts;
        m_valuemapStack.push(m_valuemap);
        m_filevaluemapStack.push(m_filevaluemap);

        QStringList args;
        for (int i = 0; i < argumentsList.count(); ++i) {
            QStringList theArgs = expandVariableReferences(argumentsList[i]);
            args += theArgs;
            m_valuemap[QString::number(i+1)] = theArgs;
        }
        m_valuemap[QLatin1String("ARGS")] = args;
        oki = (funcPtr->Accept(this) != ProItem::ReturnFalse); // True || Return
        ret = m_returnValue;
        m_returnValue.clear();

        m_valuemap = m_valuemapStack.pop();
        m_filevaluemap = m_filevaluemapStack.pop();
        m_sts = sts;
    }
    if (ok)
        *ok = oki;
    if (oki)
        return ret;
    return QStringList();
}

con's avatar
con committed
1300
1301
1302
QStringList ProFileEvaluator::Private::evaluateExpandFunction(const QString &func, const QString &arguments)
{
    QStringList argumentsList = split_arg_list(arguments);
1303

1304
1305
1306
    if (ProBlock *funcPtr = m_replaceFunctions.value(func, 0))
        return evaluateFunction(funcPtr, argumentsList, 0);

con's avatar
con committed
1307
1308
    QStringList args;
    for (int i = 0; i < argumentsList.count(); ++i)
1309
        args += expandVariableReferences(argumentsList[i]).join(Option::field_sep);
con's avatar
con committed
1310
1311
1312
1313
1314
1315
1316

    enum ExpandFunc { E_MEMBER=1, E_FIRST, E_LAST, E_CAT, E_FROMFILE, E_EVAL, E_LIST,
                      E_SPRINTF, E_JOIN, E_SPLIT, E_BASENAME, E_DIRNAME, E_SECTION,
                      E_FIND, E_SYSTEM, E_UNIQUE, E_QUOTE, E_ESCAPE_EXPAND,
                      E_UPPER, E_LOWER, E_FILES, E_PROMPT, E_RE_ESCAPE,
                      E_REPLACE };

1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
    static QHash<QString, int> expands;
    if (expands.isEmpty()) {
        expands.insert(QLatin1String("member"), E_MEMBER);
        expands.insert(QLatin1String("first"), E_FIRST);
        expands.insert(QLatin1String("last"), E_LAST);
        expands.insert(QLatin1String("cat"), E_CAT);
        expands.insert(QLatin1String("fromfile"), E_FROMFILE); // implementation disabled (see comment below)
        expands.insert(QLatin1String("eval"), E_EVAL);
        expands.insert(QLatin1String("list"), E_LIST);
        expands.insert(QLatin1String("sprintf"), E_SPRINTF);
        expands.insert(QLatin1String("join"), E_JOIN);
        expands.insert(QLatin1String("split"), E_SPLIT);
        expands.insert(QLatin1String("basename"), E_BASENAME);
        expands.insert(QLatin1String("dirname"), E_DIRNAME);
        expands.insert(QLatin1String("section"), E_SECTION);
        expands.insert(QLatin1String("find"), E_FIND);
        expands.insert(QLatin1String("system"), E_SYSTEM);
        expands.insert(QLatin1String("unique"), E_UNIQUE);
        expands.insert(QLatin1String("quote"), E_QUOTE);
        expands.insert(QLatin1String("escape_expand"), E_ESCAPE_EXPAND);
        expands.insert(QLatin1String("upper"), E_UPPER);
        expands.insert(QLatin1String("lower"), E_LOWER);
        expands.insert(QLatin1String("re_escape"), E_RE_ESCAPE);
        expands.insert(QLatin1String("files"), E_FILES);
        expands.insert(QLatin1String("prompt"), E_PROMPT); // interactive, so cannot be implemented
        expands.insert(QLatin1String("replace"), E_REPLACE);
con's avatar
con committed
1343
    }
1344
    ExpandFunc func_t = ExpandFunc(expands.value(func.toLower()));
con's avatar
con committed
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358

    QStringList ret;

    switch (func_t) {
        case E_BASENAME:
        case E_DIRNAME:
        case E_SECTION: {
            bool regexp = false;
            QString sep, var;
            int beg = 0;
            int end = -1;
            if (func_t == E_SECTION) {
                if (args.count() != 3 && args.count() != 4) {
                    q->logMessage(format("%1(var) section(var, sep, begin, end) "
1359
                        "requires three or four arguments.").arg(func));
con's avatar
con committed
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
                } else {
                    var = args[0];
                    sep = args[1];
                    beg = args[2].toInt();
                    if (args.count() == 4)
                        end = args[3].toInt();
                }
            } else {
                if (args.count() != 1) {
                    q->logMessage(format("%1(var) requires one argument.").arg(func));