qmakeevaluator.cpp 55.4 KB
Newer Older
1
2
3
4
5
6
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
Eike Ziller's avatar
Eike Ziller committed
7
** Contact: http://www.qt-project.org/
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**************************************************************************/

#include "qmakeevaluator.h"

#include "qmakeglobals.h"
#include "qmakeparser.h"
#include "qmakeevaluator_p.h"
#include "ioutils.h"

#include <QByteArray>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QList>
#include <QRegExp>
#include <QSet>
#include <QStack>
#include <QString>
#include <QStringList>
#ifdef PROEVALUATOR_THREAD_SAFE
# include <QThreadPool>
#endif

#ifdef Q_OS_UNIX
#include <unistd.h>
#include <sys/utsname.h>
#else
#include <Windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>

using namespace ProFileEvaluatorInternal;

QT_BEGIN_NAMESPACE

using namespace ProStringConstants;

#define fL1S(s) QString::fromLatin1(s)

71

72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
QMakeBaseKey::QMakeBaseKey(const QString &_root, bool _hostBuild)
    : root(_root), hostBuild(_hostBuild)
{
}

uint qHash(const QMakeBaseKey &key)
{
    return qHash(key.root) ^ key.hostBuild;
}

bool operator==(const QMakeBaseKey &one, const QMakeBaseKey &two)
{
    return one.root == two.root && one.hostBuild == two.hostBuild;
}

87
88
89
90
91
92
93
94
95
96
97
98
99
QMakeBaseEnv::QMakeBaseEnv()
    : evaluator(0)
{
#ifdef PROEVALUATOR_THREAD_SAFE
    inProgress = false;
#endif
}

QMakeBaseEnv::~QMakeBaseEnv()
{
    delete evaluator;
}

100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
namespace ProFileEvaluatorInternal {
QMakeStatics statics;
}

void QMakeEvaluator::initStatics()
{
    if (!statics.field_sep.isNull())
        return;

    statics.field_sep = QLatin1String(" ");
    statics.strtrue = QLatin1String("true");
    statics.strfalse = QLatin1String("false");
    statics.strCONFIG = ProString("CONFIG");
    statics.strARGS = ProString("ARGS");
    statics.strDot = QLatin1String(".");
    statics.strDotDot = QLatin1String("..");
    statics.strever = QLatin1String("ever");
    statics.strforever = QLatin1String("forever");
118
    statics.strhost_build = QLatin1String("host_build");
119
    statics.strTEMPLATE = ProString("TEMPLATE");
120
121
122
#ifdef PROEVALUATOR_FULL
    statics.strREQUIRES = ProString("REQUIRES");
#endif
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148

    statics.fakeValue = ProStringList(ProString("_FAKE_")); // It has to have a unique begin() value

    initFunctionStatics();

    static const struct {
        const char * const oldname, * const newname;
    } mapInits[] = {
        { "INTERFACES", "FORMS" },
        { "QMAKE_POST_BUILD", "QMAKE_POST_LINK" },
        { "TARGETDEPS", "POST_TARGETDEPS" },
        { "LIBPATH", "QMAKE_LIBDIR" },
        { "QMAKE_EXT_MOC", "QMAKE_EXT_CPP_MOC" },
        { "QMAKE_MOD_MOC", "QMAKE_H_MOD_MOC" },
        { "QMAKE_LFLAGS_SHAPP", "QMAKE_LFLAGS_APP" },
        { "PRECOMPH", "PRECOMPILED_HEADER" },
        { "PRECOMPCPP", "PRECOMPILED_SOURCE" },
        { "INCPATH", "INCLUDEPATH" },
        { "QMAKE_EXTRA_WIN_COMPILERS", "QMAKE_EXTRA_COMPILERS" },
        { "QMAKE_EXTRA_UNIX_COMPILERS", "QMAKE_EXTRA_COMPILERS" },
        { "QMAKE_EXTRA_WIN_TARGETS", "QMAKE_EXTRA_TARGETS" },
        { "QMAKE_EXTRA_UNIX_TARGETS", "QMAKE_EXTRA_TARGETS" },
        { "QMAKE_EXTRA_UNIX_INCLUDES", "QMAKE_EXTRA_INCLUDES" },
        { "QMAKE_EXTRA_UNIX_VARIABLES", "QMAKE_EXTRA_VARIABLES" },
        { "QMAKE_RPATH", "QMAKE_LFLAGS_RPATH" },
        { "QMAKE_FRAMEWORKDIR", "QMAKE_FRAMEWORKPATH" },
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
149
150
        { "QMAKE_FRAMEWORKDIR_FLAGS", "QMAKE_FRAMEWORKPATH_FLAGS" },
        { "IN_PWD", "PWD" }
151
152
153
154
155
156
157
158
159
    };
    for (unsigned i = 0; i < sizeof(mapInits)/sizeof(mapInits[0]); ++i)
        statics.varMap.insert(ProString(mapInits[i].oldname),
                              ProString(mapInits[i].newname));
}

const ProString &QMakeEvaluator::map(const ProString &var)
{
    QHash<ProString, ProString>::ConstIterator it = statics.varMap.constFind(var);
160
161
    if (it == statics.varMap.constEnd())
        return var;
Robert Loehning's avatar
Robert Loehning committed
162
    deprecationWarning(fL1S("Variable %1 is deprecated; use %2 instead.")
163
164
                       .arg(var.toQString(), it.value().toQString()));
    return it.value();
165
166
167
168
}


QMakeEvaluator::QMakeEvaluator(QMakeGlobals *option,
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
169
                               QMakeParser *parser, QMakeHandler *handler)
170
171
172
173
174
175
176
  : m_option(option), m_parser(parser), m_handler(handler)
{
    // So that single-threaded apps don't have to call initialize() for now.
    initStatics();

    // Configuration, more or less
#ifdef PROEVALUATOR_CUMULATIVE
177
    m_cumulative = false;
178
#endif
179
    m_hostBuild = false;
180
181

    // Evaluator state
182
#ifdef PROEVALUATOR_CUMULATIVE
183
    m_skipLevel = 0;
184
#endif
185
186
    m_loopLevel = 0;
    m_listCount = 0;
187
    m_valuemapStack.push(ProValueMap());
188
189
190
191
192
193
}

QMakeEvaluator::~QMakeEvaluator()
{
}

194
195
196
197
198
void QMakeEvaluator::initFrom(const QMakeEvaluator &other)
{
    Q_ASSERT_X(&other, "QMakeEvaluator::visitProFile", "Project not prepared");
    m_functionDefs = other.m_functionDefs;
    m_valuemapStack = other.m_valuemapStack;
199
    m_qmakespec = other.m_qmakespec;
200
    m_qmakespecFull = other.m_qmakespecFull;
201
    m_qmakespecName = other.m_qmakespecName;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
202
    m_mkspecPaths = other.m_mkspecPaths;
203
    m_featureRoots = other.m_featureRoots;
204
205
}

206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
//////// Evaluator tools /////////

uint QMakeEvaluator::getBlockLen(const ushort *&tokPtr)
{
    uint len = *tokPtr++;
    len |= (uint)*tokPtr++ << 16;
    return len;
}

ProString QMakeEvaluator::getStr(const ushort *&tokPtr)
{
    uint len = *tokPtr++;
    ProString ret(m_current.pro->items(), tokPtr - m_current.pro->tokPtr(), len, NoHash);
    ret.setSource(m_current.pro);
    tokPtr += len;
    return ret;
}

ProString QMakeEvaluator::getHashStr(const ushort *&tokPtr)
{
    uint hash = getBlockLen(tokPtr);
    uint len = *tokPtr++;
    ProString ret(m_current.pro->items(), tokPtr - m_current.pro->tokPtr(), len, hash);
    tokPtr += len;
    return ret;
}

void QMakeEvaluator::skipStr(const ushort *&tokPtr)
{
    uint len = *tokPtr++;
    tokPtr += len;
}

void QMakeEvaluator::skipHashStr(const ushort *&tokPtr)
{
    tokPtr += 2;
    uint len = *tokPtr++;
    tokPtr += len;
}

// FIXME: this should not build new strings for direct sections.
// Note that the E_SPRINTF and E_LIST implementations rely on the deep copy.
ProStringList QMakeEvaluator::split_value_list(const QString &vals, const ProFile *source)
{
    QString build;
    ProStringList ret;
    QStack<char> quote;

    const ushort SPACE = ' ';
    const ushort LPAREN = '(';
    const ushort RPAREN = ')';
    const ushort SINGLEQUOTE = '\'';
    const ushort DOUBLEQUOTE = '"';
    const ushort BACKSLASH = '\\';

    if (!source)
        source = currentProFile();

    ushort unicode;
    const QChar *vals_data = vals.data();
    const int vals_len = vals.length();
267
268
    int parens = 0;
    for (int x = 0; x < vals_len; x++) {
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
        unicode = vals_data[x].unicode();
        if (x != (int)vals_len-1 && unicode == BACKSLASH &&
            (vals_data[x+1].unicode() == SINGLEQUOTE || vals_data[x+1].unicode() == DOUBLEQUOTE)) {
            build += vals_data[x++]; //get that 'escape'
        } else if (!quote.isEmpty() && unicode == quote.top()) {
            quote.pop();
        } else if (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE) {
            quote.push(unicode);
        } else if (unicode == RPAREN) {
            --parens;
        } else if (unicode == LPAREN) {
            ++parens;
        }

        if (!parens && quote.isEmpty() && vals_data[x] == SPACE) {
            ret << ProString(build, NoHash).setSource(source);
            build.clear();
        } else {
            build += vals_data[x];
        }
    }
    if (!build.isEmpty())
        ret << ProString(build, NoHash).setSource(source);
292
293
    if (parens)
        deprecationWarning(fL1S("Unmatched parentheses are deprecated."));
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
    return ret;
}

static void zipEmpty(ProStringList *value)
{
    for (int i = value->size(); --i >= 0;)
        if (value->at(i).isEmpty())
            value->remove(i);
}

static void insertUnique(ProStringList *varlist, const ProStringList &value)
{
    foreach (const ProString &str, value)
        if (!str.isEmpty() && !varlist->contains(str))
            varlist->append(str);
}

static void removeAll(ProStringList *varlist, const ProString &value)
{
    for (int i = varlist->size(); --i >= 0; )
        if (varlist->at(i) == value)
            varlist->remove(i);
}

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
318
void QMakeEvaluator::removeEach(ProStringList *varlist, const ProStringList &value)
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
{
    foreach (const ProString &str, value)
        if (!str.isEmpty())
            removeAll(varlist, str);
}

static void replaceInList(ProStringList *varlist,
        const QRegExp &regexp, const QString &replace, bool global, QString &tmp)
{
    for (ProStringList::Iterator varit = varlist->begin(); varit != varlist->end(); ) {
        QString val = varit->toQString(tmp);
        QString copy = val; // Force detach and have a reference value
        val.replace(regexp, replace);
        if (!val.isSharedWith(copy)) {
            if (val.isEmpty()) {
                varit = varlist->erase(varit);
            } else {
                (*varit).setValue(val, NoHash);
                ++varit;
            }
            if (!global)
                break;
        } else {
            ++varit;
        }
    }
}

//////// Evaluator /////////

static ALWAYS_INLINE void addStr(
        const ProString &str, ProStringList *ret, bool &pending, bool joined)
{
    if (joined) {
        ret->last().append(str, &pending);
    } else {
        if (!pending) {
            pending = true;
            *ret << str;
        } else {
            ret->last().append(str);
        }
    }
}

static ALWAYS_INLINE void addStrList(
        const ProStringList &list, ushort tok, ProStringList *ret, bool &pending, bool joined)
{
    if (!list.isEmpty()) {
        if (joined) {
            ret->last().append(list, &pending, !(tok & TokQuoted));
        } else {
            if (tok & TokQuoted) {
                if (!pending) {
                    pending = true;
                    *ret << ProString();
                }
                ret->last().append(list);
            } else {
                if (!pending) {
                    // Another qmake bizzarity: if nothing is pending and the
                    // first element is empty, it will be eaten
                    if (!list.at(0).isEmpty()) {
                        // The common case
                        pending = true;
                        *ret += list;
                        return;
                    }
                } else {
                    ret->last().append(list.at(0));
                }
                // This is somewhat slow, but a corner case
                for (int j = 1; j < list.size(); ++j) {
                    pending = true;
                    *ret << list.at(j);
                }
            }
        }
    }
}

void QMakeEvaluator::evaluateExpression(
        const ushort *&tokPtr, ProStringList *ret, bool joined)
{
    if (joined)
        *ret << ProString();
    bool pending = false;
    forever {
        ushort tok = *tokPtr++;
        if (tok & TokNewStr)
            pending = false;
        ushort maskedTok = tok & TokMask;
        switch (maskedTok) {
        case TokLine:
            m_current.line = *tokPtr++;
            break;
        case TokLiteral:
            addStr(getStr(tokPtr), ret, pending, joined);
            break;
        case TokHashLiteral:
            addStr(getHashStr(tokPtr), ret, pending, joined);
            break;
        case TokVariable:
            addStrList(values(map(getHashStr(tokPtr))), tok, ret, pending, joined);
            break;
        case TokProperty:
425
            addStr(propertyValue(getHashStr(tokPtr)).setSource(currentProFile()),
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
                   ret, pending, joined);
            break;
        case TokEnvVar:
            addStrList(split_value_list(m_option->getEnv(getStr(tokPtr).toQString(m_tmp1))),
                       tok, ret, pending, joined);
            break;
        case TokFuncName: {
            ProString func = getHashStr(tokPtr);
            addStrList(evaluateExpandFunction(func, tokPtr), tok, ret, pending, joined);
            break; }
        default:
            tokPtr--;
            return;
        }
    }
}

void QMakeEvaluator::skipExpression(const ushort *&pTokPtr)
{
    const ushort *tokPtr = pTokPtr;
    forever {
        ushort tok = *tokPtr++;
        switch (tok) {
        case TokLine:
            m_current.line = *tokPtr++;
            break;
        case TokValueTerminator:
        case TokFuncTerminator:
            pTokPtr = tokPtr;
            return;
        case TokArgSeparator:
            break;
        default:
            switch (tok & TokMask) {
            case TokLiteral:
            case TokEnvVar:
                skipStr(tokPtr);
                break;
            case TokHashLiteral:
            case TokVariable:
466
            case TokProperty:
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
                skipHashStr(tokPtr);
                break;
            case TokFuncName:
                skipHashStr(tokPtr);
                pTokPtr = tokPtr;
                skipExpression(pTokPtr);
                tokPtr = pTokPtr;
                break;
            default:
                Q_ASSERT_X(false, "skipExpression", "Unrecognized token");
                break;
            }
        }
    }
}

QMakeEvaluator::VisitReturn QMakeEvaluator::visitProBlock(
        ProFile *pro, const ushort *tokPtr)
{
    m_current.pro = pro;
    m_current.line = 0;
    return visitProBlock(tokPtr);
}

QMakeEvaluator::VisitReturn QMakeEvaluator::visitProBlock(
        const ushort *tokPtr)
{
    ProStringList curr;
    bool okey = true, or_op = false, invert = false;
    uint blockLen;
    while (ushort tok = *tokPtr++) {
498
        VisitReturn ret;
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
        switch (tok) {
        case TokLine:
            m_current.line = *tokPtr++;
            continue;
        case TokAssign:
        case TokAppend:
        case TokAppendUnique:
        case TokRemove:
        case TokReplace:
            visitProVariable(tok, curr, tokPtr);
            curr.clear();
            continue;
        case TokBranch:
            blockLen = getBlockLen(tokPtr);
            if (m_cumulative) {
514
#ifdef PROEVALUATOR_CUMULATIVE
515
516
517
518
519
520
521
522
523
524
525
526
527
                if (!okey)
                    m_skipLevel++;
                ret = blockLen ? visitProBlock(tokPtr) : ReturnTrue;
                tokPtr += blockLen;
                blockLen = getBlockLen(tokPtr);
                if (!okey)
                    m_skipLevel--;
                else
                    m_skipLevel++;
                if ((ret == ReturnTrue || ret == ReturnFalse) && blockLen)
                    ret = visitProBlock(tokPtr);
                if (okey)
                    m_skipLevel--;
528
#endif
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
            } else {
                if (okey)
                    ret = blockLen ? visitProBlock(tokPtr) : ReturnTrue;
                tokPtr += blockLen;
                blockLen = getBlockLen(tokPtr);
                if (!okey)
                    ret = blockLen ? visitProBlock(tokPtr) : ReturnTrue;
            }
            tokPtr += blockLen;
            okey = true, or_op = false; // force next evaluation
            break;
        case TokForLoop:
            if (m_cumulative) { // This is a no-win situation, so just pretend it's no loop
                skipHashStr(tokPtr);
                uint exprLen = getBlockLen(tokPtr);
                tokPtr += exprLen;
                blockLen = getBlockLen(tokPtr);
                ret = visitProBlock(tokPtr);
            } else if (okey != or_op) {
                const ProString &variable = getHashStr(tokPtr);
                uint exprLen = getBlockLen(tokPtr);
                const ushort *exprPtr = tokPtr;
                tokPtr += exprLen;
                blockLen = getBlockLen(tokPtr);
                ret = visitProLoop(variable, exprPtr, tokPtr);
            } else {
                skipHashStr(tokPtr);
                uint exprLen = getBlockLen(tokPtr);
                tokPtr += exprLen;
                blockLen = getBlockLen(tokPtr);
                ret = ReturnTrue;
            }
            tokPtr += blockLen;
            okey = true, or_op = false; // force next evaluation
            break;
        case TokTestDef:
        case TokReplaceDef:
            if (m_cumulative || okey != or_op) {
                const ProString &name = getHashStr(tokPtr);
                blockLen = getBlockLen(tokPtr);
                visitProFunctionDef(tok, name, tokPtr);
            } else {
                skipHashStr(tokPtr);
                blockLen = getBlockLen(tokPtr);
            }
            tokPtr += blockLen;
            okey = true, or_op = false; // force next evaluation
            continue;
        case TokNot:
            invert ^= true;
            continue;
        case TokAnd:
            or_op = false;
            continue;
        case TokOr:
            or_op = true;
            continue;
        case TokCondition:
            if (!m_skipLevel && okey != or_op) {
                if (curr.size() != 1) {
                    if (!m_cumulative || !curr.isEmpty())
                        evalError(fL1S("Conditional must expand to exactly one word."));
                    okey = false;
                } else {
                    okey = isActiveConfig(curr.at(0).toQString(m_tmp2), true) ^ invert;
                }
            }
            or_op = !okey; // tentatively force next evaluation
            invert = false;
            curr.clear();
            continue;
        case TokTestCall:
            if (!m_skipLevel && okey != or_op) {
                if (curr.size() != 1) {
                    if (!m_cumulative || !curr.isEmpty())
                        evalError(fL1S("Test name must expand to exactly one word."));
                    skipExpression(tokPtr);
                    okey = false;
                } else {
                    ret = evaluateConditionalFunction(curr.at(0), tokPtr);
                    switch (ret) {
                    case ReturnTrue: okey = true; break;
                    case ReturnFalse: okey = false; break;
                    default: return ret;
                    }
                    okey ^= invert;
                }
            } else if (m_cumulative) {
617
#ifdef PROEVALUATOR_CUMULATIVE
618
619
620
621
622
623
                m_skipLevel++;
                if (curr.size() != 1)
                    skipExpression(tokPtr);
                else
                    evaluateConditionalFunction(curr.at(0), tokPtr);
                m_skipLevel--;
624
#endif
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
            } else {
                skipExpression(tokPtr);
            }
            or_op = !okey; // tentatively force next evaluation
            invert = false;
            curr.clear();
            continue;
        default: {
                const ushort *oTokPtr = --tokPtr;
                evaluateExpression(tokPtr, &curr, false);
                if (tokPtr != oTokPtr)
                    continue;
            }
            Q_ASSERT_X(false, "visitProBlock", "unexpected item type");
        }
        if (ret != ReturnTrue && ret != ReturnFalse)
641
            return ret;
642
    }
643
    return returnBool(okey);
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
}


void QMakeEvaluator::visitProFunctionDef(
        ushort tok, const ProString &name, const ushort *tokPtr)
{
    QHash<ProString, ProFunctionDef> *hash =
            (tok == TokTestDef
             ? &m_functionDefs.testFunctions
             : &m_functionDefs.replaceFunctions);
    hash->insert(name, ProFunctionDef(m_current.pro, tokPtr - m_current.pro->tokPtr()));
}

QMakeEvaluator::VisitReturn QMakeEvaluator::visitProLoop(
        const ProString &_variable, const ushort *exprPtr, const ushort *tokPtr)
{
    VisitReturn ret = ReturnTrue;
    bool infinite = false;
    int index = 0;
    ProString variable;
    ProStringList oldVarVal;
    ProString it_list = expandVariableReferences(exprPtr, 0, true).at(0);
    if (_variable.isEmpty()) {
        if (it_list != statics.strever) {
            evalError(fL1S("Invalid loop expression."));
            return ReturnFalse;
        }
        it_list = ProString(statics.strforever);
    } else {
        variable = map(_variable);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
674
        oldVarVal = values(variable);
675
    }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
676
    ProStringList list = values(it_list);
677
678
679
680
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
    if (list.isEmpty()) {
        if (it_list == statics.strforever) {
            infinite = true;
        } else {
            const QString &itl = it_list.toQString(m_tmp1);
            int dotdot = itl.indexOf(statics.strDotDot);
            if (dotdot != -1) {
                bool ok;
                int start = itl.left(dotdot).toInt(&ok);
                if (ok) {
                    int end = itl.mid(dotdot+2).toInt(&ok);
                    if (ok) {
                        if (start < end) {
                            for (int i = start; i <= end; i++)
                                list << ProString(QString::number(i), NoHash);
                        } else {
                            for (int i = start; i >= end; i--)
                                list << ProString(QString::number(i), NoHash);
                        }
                    }
                }
            }
        }
    }

    m_loopLevel++;
    forever {
        if (infinite) {
            if (!variable.isEmpty())
                m_valuemapStack.top()[variable] = ProStringList(ProString(QString::number(index++), NoHash));
            if (index > 1000) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
708
                evalError(fL1S("Ran into infinite loop (> 1000 iterations)."));
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
                break;
            }
        } else {
            ProString val;
            do {
                if (index >= list.count())
                    goto do_break;
                val = list.at(index++);
            } while (val.isEmpty()); // stupid, but qmake is like that
            m_valuemapStack.top()[variable] = ProStringList(val);
        }

        ret = visitProBlock(tokPtr);
        switch (ret) {
        case ReturnTrue:
        case ReturnFalse:
            break;
        case ReturnNext:
            ret = ReturnTrue;
            break;
        case ReturnBreak:
            ret = ReturnTrue;
            goto do_break;
        default:
            goto do_break;
        }
    }
  do_break:
    m_loopLevel--;

    if (!variable.isEmpty())
        m_valuemapStack.top()[variable] = oldVarVal;
    return ret;
}

void QMakeEvaluator::visitProVariable(
        ushort tok, const ProStringList &curr, const ushort *&tokPtr)
{
    int sizeHint = *tokPtr++;

    if (curr.size() != 1) {
        skipExpression(tokPtr);
        if (!m_cumulative || !curr.isEmpty())
            evalError(fL1S("Left hand side of assignment must expand to exactly one word."));
        return;
    }
    const ProString &varName = map(curr.first());

    if (tok == TokReplace) {      // ~=
        // DEFINES ~= s/a/b/?[gqi]

        const ProStringList &varVal = expandVariableReferences(tokPtr, sizeHint, true);
        const QString &val = varVal.at(0).toQString(m_tmp1);
        if (val.length() < 4 || val.at(0) != QLatin1Char('s')) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
763
            evalError(fL1S("The ~= operator can handle only the s/// function."));
764
765
766
767
768
            return;
        }
        QChar sep = val.at(1);
        QStringList func = val.split(sep);
        if (func.count() < 3 || func.count() > 4) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
769
            evalError(fL1S("The s/// function expects 3 or 4 arguments."));
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
            return;
        }

        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);

786
787
788
        // 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(&valuesRef(varName), regexp, replace, global, m_tmp2);
789
790
791
792
793
    } else {
        ProStringList varVal = expandVariableReferences(tokPtr, sizeHint);
        switch (tok) {
        default: // whatever - cannot happen
        case TokAssign:          // =
794
            zipEmpty(&varVal);
795
            if (!m_cumulative) {
796
797
798
                // FIXME: add check+warning about accidental value removal.
                // This may be a bit too noisy, though.
                m_valuemapStack.top()[varName] = varVal;
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
            } else {
                if (!varVal.isEmpty()) {
                    // We are greedy for values. But avoid exponential growth.
                    ProStringList &v = valuesRef(varName);
                    if (v.isEmpty()) {
                        v = varVal;
                    } else {
                        ProStringList old = v;
                        v = varVal;
                        QSet<ProString> has;
                        has.reserve(v.size());
                        foreach (const ProString &s, v)
                            has.insert(s);
                        v.reserve(v.size() + old.size());
                        foreach (const ProString &s, old)
                            if (!has.contains(s))
                                v << s;
                    }
                }
            }
            break;
        case TokAppendUnique:    // *=
821
            insertUnique(&valuesRef(varName), varVal);
822
823
            break;
        case TokAppend:          // +=
824
825
            zipEmpty(&varVal);
            valuesRef(varName) += varVal;
826
827
828
            break;
        case TokRemove:       // -=
            if (!m_cumulative) {
829
                removeEach(&valuesRef(varName), varVal);
830
831
832
833
834
835
            } else {
                // We are stingy with our values, too.
            }
            break;
        }
    }
836
837
838

    if (varName == statics.strTEMPLATE)
        setTemplate();
839
840
841
842
#ifdef PROEVALUATOR_FULL
    else if (varName == statics.strREQUIRES)
        checkRequirements(values(varName));
#endif
843
844
845
846
847
}

void QMakeEvaluator::setTemplate()
{
    ProStringList &values = valuesRef(statics.strTEMPLATE);
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
    if (!m_option->user_template.isEmpty()) {
        // Don't allow override
        values = ProStringList(ProString(m_option->user_template, NoHash));
    } else {
        if (values.isEmpty())
            values.append(ProString("app", NoHash));
        else
            values.erase(values.begin() + 1, values.end());
    }
    if (!m_option->user_template_prefix.isEmpty()) {
        QString val = values.first().toQString(m_tmp1);
        if (!val.startsWith(m_option->user_template_prefix)) {
            val.prepend(m_option->user_template_prefix);
            values = ProStringList(ProString(val, NoHash));
        }
    }
864
865
}

866
867
868
869
870
871
872
void QMakeEvaluator::loadDefaults()
{
    ProValueMap &vars = m_valuemapStack.top();

    vars[ProString("DIR_SEPARATOR")] << ProString(m_option->dir_sep, NoHash);
    vars[ProString("DIRLIST_SEPARATOR")] << ProString(m_option->dirlist_sep, NoHash);
    vars[ProString("_DATE_")] << ProString(QDateTime::currentDateTime().toString(), NoHash);
873
874
    if (!m_option->qmake_abslocation.isEmpty())
        vars[ProString("QMAKE_QMAKE")] << ProString(m_option->qmake_abslocation, NoHash);
875
876
877
878
879
880
#if defined(Q_OS_WIN32)
    vars[ProString("QMAKE_HOST.os")] << ProString("Windows", NoHash);

    DWORD name_length = 1024;
    wchar_t name[1024];
    if (GetComputerName(name, &name_length))
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
881
        vars[ProString("QMAKE_HOST.name")] << ProString(QString::fromWCharArray(name), NoHash);
882
883
884
885
886
887
888
889
890
891
892
893
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

    QSysInfo::WinVersion ver = QSysInfo::WindowsVersion;
    vars[ProString("QMAKE_HOST.version")] << ProString(QString::number(ver), NoHash);
    ProString verStr;
    switch (ver) {
    case QSysInfo::WV_Me: verStr = ProString("WinMe", NoHash); break;
    case QSysInfo::WV_95: verStr = ProString("Win95", NoHash); break;
    case QSysInfo::WV_98: verStr = ProString("Win98", NoHash); break;
    case QSysInfo::WV_NT: verStr = ProString("WinNT", NoHash); break;
    case QSysInfo::WV_2000: verStr = ProString("Win2000", NoHash); break;
    case QSysInfo::WV_2003: verStr = ProString("Win2003", NoHash); break;
    case QSysInfo::WV_XP: verStr = ProString("WinXP", NoHash); break;
    case QSysInfo::WV_VISTA: verStr = ProString("WinVista", NoHash); break;
    default: verStr = ProString("Unknown", NoHash); break;
    }
    vars[ProString("QMAKE_HOST.version_string")] << verStr;

    SYSTEM_INFO info;
    GetSystemInfo(&info);
    ProString archStr;
    switch (info.wProcessorArchitecture) {
# ifdef PROCESSOR_ARCHITECTURE_AMD64
    case PROCESSOR_ARCHITECTURE_AMD64:
        archStr = ProString("x86_64", NoHash);
        break;
# endif
    case PROCESSOR_ARCHITECTURE_INTEL:
        archStr = ProString("x86", NoHash);
        break;
    case PROCESSOR_ARCHITECTURE_IA64:
# ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64
    case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
# endif
        archStr = ProString("IA64", NoHash);
        break;
    default:
        archStr = ProString("Unknown", NoHash);
        break;
    }
    vars[ProString("QMAKE_HOST.arch")] << archStr;
922
923

# if defined(Q_CC_MSVC) // ### bogus condition, but nobody x-builds for msvc with a different qmake
924
925
926
927
928
929
930
931
932
933
    QLatin1Char backslash('\\');
    QString paths = m_option->getEnv(QLatin1String("PATH"));
    QString vcBin64 = m_option->getEnv(QLatin1String("VCINSTALLDIR"));
    if (!vcBin64.endsWith(backslash))
        vcBin64.append(backslash);
    vcBin64.append(QLatin1String("bin\\amd64"));
    QString vcBinX86_64 = m_option->getEnv(QLatin1String("VCINSTALLDIR"));
    if (!vcBinX86_64.endsWith(backslash))
        vcBinX86_64.append(backslash);
    vcBinX86_64.append(QLatin1String("bin\\x86_amd64"));
934
935
936
937
938
939
    if (paths.contains(vcBin64, Qt::CaseInsensitive)
            || paths.contains(vcBinX86_64, Qt::CaseInsensitive))
        vars[ProString("QMAKE_TARGET.arch")] << ProString("x86_64", NoHash);
    else
        vars[ProString("QMAKE_TARGET.arch")] << ProString("x86", NoHash);
# endif
940
941
942
943
944
945
946
947
948
949
950
951
#elif defined(Q_OS_UNIX)
    struct utsname name;
    if (!uname(&name)) {
        vars[ProString("QMAKE_HOST.os")] << ProString(name.sysname, NoHash);
        vars[ProString("QMAKE_HOST.name")] << ProString(QString::fromLocal8Bit(name.nodename), NoHash);
        vars[ProString("QMAKE_HOST.version")] << ProString(name.release, NoHash);
        vars[ProString("QMAKE_HOST.version_string")] << ProString(name.version, NoHash);
        vars[ProString("QMAKE_HOST.arch")] << ProString(name.machine, NoHash);
    }
#endif
}

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
952
bool QMakeEvaluator::prepareProject(const QString &inDir)
953
{
954
    QString superdir;
955
    if (m_option->do_cache) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
956
        QString conffile;
957
958
959
960
        QString cachefile = m_option->cachefile;
        if (cachefile.isEmpty())  { //find it as it has not been specified
            if (m_outputDir.isEmpty())
                goto no_cache;
961
            superdir = m_outputDir;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
962
963
964
965
966
967
968
969
970
971
972
973
974
            forever {
                QString superfile = superdir + QLatin1String("/.qmake.super");
                if (IoUtils::exists(superfile)) {
                    m_superfile = superfile;
                    break;
                }
                QFileInfo qdfi(superdir);
                if (qdfi.isRoot()) {
                    superdir.clear();
                    break;
                }
                superdir = qdfi.path();
            }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
975
            QString sdir = inDir;
976
            QString dir = m_outputDir;
977
            forever {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
978
979
980
                conffile = sdir + QLatin1String("/.qmake.conf");
                if (!IoUtils::exists(conffile))
                    conffile.clear();
981
                cachefile = dir + QLatin1String("/.qmake.cache");
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
982
983
984
                if (!IoUtils::exists(cachefile))
                    cachefile.clear();
                if (!conffile.isEmpty() || !cachefile.isEmpty()) {
985
986
                    if (dir != sdir)
                        m_sourceRoot = sdir;
987
                    m_buildRoot = dir;
988
989
                    break;
                }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
990
991
                if (dir == superdir)
                    goto no_cache;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
992
                QFileInfo qsdfi(sdir);
993
                QFileInfo qdfi(dir);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
994
                if (qsdfi.isRoot() || qdfi.isRoot())
995
                    goto no_cache;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
996
                sdir = qsdfi.path();
997
                dir = qdfi.path();
998
            }
999
1000
        } else {
            m_buildRoot = QFileInfo(cachefile).path();
1001
        }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1002
        m_conffile = conffile;
1003
        m_cachefile = cachefile;
1004
    }
1005
  no_cache:
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027

    // Look for mkspecs/ in source and build. First to win determines the root.
    QString sdir = inDir;
    QString dir = m_outputDir;
    while (dir != m_buildRoot) {
        if ((dir != sdir && QFileInfo(sdir, QLatin1String("mkspecs")).isDir())
                || QFileInfo(dir, QLatin1String("mkspecs")).isDir()) {
            if (dir != sdir)
                m_sourceRoot = sdir;
            m_buildRoot = dir;
            break;
        }
        if (dir == superdir)
            break;
        QFileInfo qsdfi(sdir);
        QFileInfo qdfi(dir);
        if (qsdfi.isRoot() || qdfi.isRoot())
            break;
        sdir = qsdfi.path();
        dir = qdfi.path();
    }

1028
    return true;
1029
1030
}

1031
bool QMakeEvaluator::loadSpec()
1032
{
1033
1034
    QString qmakespec = m_option->expandEnvVars(
                m_hostBuild ? m_option->qmakespec : m_option->xqmakespec);
1035
1036
1037

    {
        QMakeEvaluator evaluator(m_option, m_parser, m_handler);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1038
1039
1040
1041
1042
        if (!m_superfile.isEmpty()) {
            valuesRef(ProString("_QMAKE_SUPER_CACHE_")) << ProString(m_superfile, NoHash);
            if (!evaluator.evaluateFileDirect(m_superfile, QMakeHandler::EvalConfigFile, LoadProOnly))
                return false;
        }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1043
1044
1045
1046
1047
        if (!m_conffile.isEmpty()) {
            valuesRef(ProString("_QMAKE_CONF_")) << ProString(m_conffile, NoHash);
            if (!evaluator.evaluateFileDirect(m_conffile, QMakeHandler::EvalConfigFile, LoadProOnly))
                return false;
        }
1048
1049
1050
1051
1052
        if (!m_cachefile.isEmpty()) {
            valuesRef(ProString("_QMAKE_CACHE_")) << ProString(m_cachefile, NoHash);
            if (!evaluator.evaluateFileDirect(m_cachefile, QMakeHandler::EvalConfigFile, LoadProOnly))
                return false;
        }
1053
1054
1055
1056
1057
1058
        if (qmakespec.isEmpty()) {
            if (!m_hostBuild)
                qmakespec = evaluator.first(ProString("XQMAKESPEC")).toQString();
            if (qmakespec.isEmpty())
                qmakespec = evaluator.first(ProString("QMAKESPEC")).toQString();
        }
1059
1060
        m_qmakepath = evaluator.values(ProString("QMAKEPATH")).toQStringList();
        m_qmakefeatures = evaluator.values(ProString("QMAKEFEATURES")).toQStringList();
1061
1062
    }

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1063
    updateMkspecPaths();
1064
    if (qmakespec.isEmpty())
1065
        qmakespec = m_hostBuild ? QLatin1String("default-host") : QLatin1String("default");
1066
    if (IoUtils::isRelativePath(qmakespec)) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1067
        foreach (const QString &root, m_mkspecPaths) {
1068
1069
1070
1071
1072
1073
            QString mkspec = root + QLatin1Char('/') + qmakespec;
            if (IoUtils::exists(mkspec)) {
                qmakespec = mkspec;
                goto cool;
            }
        }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1074
        evalError(fL1S("Could not find qmake configuration file %1.").arg(qmakespec));
1075
        return false;
1076
1077
    }
  cool:
1078
    m_qmakespec = QDir::cleanPath(qmakespec);
1079

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1080
1081
1082
1083
    if (!m_superfile.isEmpty()
        && !evaluateFileDirect(m_superfile, QMakeHandler::EvalConfigFile, LoadProOnly)) {
        return false;
    }
1084
1085
    if (!evaluateFeatureFile(QLatin1String("spec_pre.prf")))
        return false;
1086
    QString spec = m_qmakespec + QLatin1String("/qmake.conf");
1087
    if (!evaluateFileDirect(spec, QMakeHandler::EvalConfigFile, LoadProOnly)) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1088
        evalError(fL1S("Could not read qmake configuration file %1.").arg(spec));
1089
        return false;
1090
1091
    }
#ifdef Q_OS_UNIX
1092
    m_qmakespecFull = QFileInfo(m_qmakespec).canonicalFilePath();
1093
#else
1094
1095
1096
1097
    // We can't resolve symlinks as they do on Unix, so configure.exe puts
    // the source of the qmake.conf at the end of the default/qmake.conf in
    // the QMAKESPEC_ORIGINAL variable.
    const ProString &orig_spec = first(ProString("QMAKESPEC_ORIGINAL"));
1098
    m_qmakespecFull = orig_spec.isEmpty() ? m_qmakespec : orig_spec.toQString();
1099
#endif
1100
    valuesRef(ProString("QMAKESPEC")) << ProString(m_qmakespecFull, NoHash);
1101
    m_qmakespecName = IoUtils::fileName(m_qmakespecFull).toString();
1102
1103
    if (!evaluateFeatureFile(QLatin1String("spec_post.prf")))
        return false;
1104
    updateFeaturePaths(); // The spec extends the feature search path, so rebuild the cache.
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1105
1106
1107
1108
    if (!m_conffile.isEmpty()
        && !evaluateFileDirect(m_conffile, QMakeHandler::EvalConfigFile, LoadProOnly)) {
        return false;
    }
1109
1110
    if (!m_cachefile.isEmpty()
        && !evaluateFileDirect(m_cachefile, QMakeHandler::EvalConfigFile, LoadProOnly)) {
1111
1112
1113
        return false;
    }
    return true;
1114
1115
}

1116
1117
1118
void QMakeEvaluator::setupProject()
{
    setTemplate();
1119
1120
    ProValueMap &vars = m_valuemapStack.top();
    vars[ProString("TARGET")] << ProString(QFileInfo(currentFileName()).baseName(), NoHash);
1121
1122
1123
    vars[ProString("_PRO_FILE_")] << ProString(currentFileName(), NoHash);
    vars[ProString("_PRO_FILE_PWD_")] << ProString(currentDirectory(), NoHash);
    vars[ProString("OUT_PWD")] << ProString(m_outputDir, NoHash);
1124
1125
}

1126
1127
1128
1129
void QMakeEvaluator::visitCmdLine(const QString &cmds)
{
    if (!cmds.isEmpty()) {
        if (ProFile *pro = m_parser->parsedProBlock(fL1S("(command line)"), cmds)) {
1130
1131
1132
1133
1134
            if (pro->isOk()) {
                m_locationStack.push(m_current);
                visitProBlock(pro, pro->tokPtr());
                m_current = m_locationStack.pop();
            }
1135
1136
1137
1138
1139
1140
            pro->deref();
        }
    }
}

QMakeEvaluator::VisitReturn QMakeEvaluator::visitProFile(
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1141
        ProFile *pro, QMakeHandler::EvalFileType type, LoadFlags flags)
1142
1143
1144
1145
{
    if (!m_cumulative && !pro->isOk())
        return ReturnFalse;

1146
    if (flags & LoadPreFiles) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1147
        if (!prepareProject(pro->directoryName()))
1148
1149
            return ReturnFalse;

1150
1151
        m_hostBuild = pro->isHostBuild();

1152
1153
1154
#ifdef PROEVALUATOR_THREAD_SAFE
        m_option->mutex.lock();
#endif
1155
        QMakeBaseEnv **baseEnvPtr = &m_option->baseEnvs[QMakeBaseKey(m_buildRoot, m_hostBuild)];
1156
1157
1158
1159
        if (!*baseEnvPtr)
            *baseEnvPtr = new QMakeBaseEnv;
        QMakeBaseEnv *baseEnv = *baseEnvPtr;

1160
1161
#ifdef PROEVALUATOR_THREAD_SAFE
        {
1162
1163
1164
            QMutexLocker locker(&baseEnv->mutex);
            m_option->mutex.unlock();
            if (baseEnv->inProgress) {
1165
                QThreadPool::globalInstance()->releaseThread();
1166
                baseEnv->cond.wait(&baseEnv->mutex);
1167
                QThreadPool::globalInstance()->reserveThread();
1168
                if (!baseEnv->isOk)
1169
                    return ReturnFalse;
1170
1171
            } else
#endif
1172
            if (!baseEnv->evaluator) {
1173
#ifdef PROEVALUATOR_THREAD_SAFE
1174
                baseEnv->inProgress = true;
1175
1176
1177
                locker.unlock();
#endif

1178
1179
                QMakeEvaluator *baseEval = new QMakeEvaluator(m_option, m_parser, m_handler);
                baseEnv->evaluator = baseEval;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1180
                baseEval->m_superfile = m_superfile;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1181
                baseEval->m_conffile = m_conffile;
1182
                baseEval->m_cachefile = m_cachefile;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1183
                baseEval->m_sourceRoot = m_sourceRoot;
1184
                baseEval->m_buildRoot = m_buildRoot;
1185
                baseEval->m_hostBuild = m_hostBuild;
1186
                bool ok = baseEval->loadSpec();
1187
1188
1189

#ifdef PROEVALUATOR_THREAD_SAFE
                locker.relock();
1190
1191
1192
                baseEnv->isOk = ok;
                baseEnv->inProgress = false;
                baseEnv->cond.wakeAll();
1193
#endif
1194
1195
1196

                if (!ok)
                    return ReturnFalse;
1197
1198
1199
1200
1201
            }
#ifdef PROEVALUATOR_THREAD_SAFE
        }
#endif

1202
        initFrom(*baseEnv->evaluator);
1203
1204
1205
    } else {
        if (m_valuemapStack.at(0).isEmpty())
            loadDefaults();
1206
1207
1208
1209
    }

    m_handler->aboutToEval(currentProFile(), pro, type);
    m_profileStack.push(pro);
1210
    valuesRef(ProString("PWD")) = ProStringList(ProString(currentDirectory(), NoHash));
1211
    if (flags & LoadPreFiles) {
1212
1213
        setupProject();

1214
1215
1216
1217
1218
1219
1220
        evaluateFeatureFile(QLatin1String("default_pre.prf"));

        visitCmdLine(m_option->precmds);
    }

    visitProBlock(pro, pro->tokPtr());

1221
    if (flags & LoadPostFiles) {
1222
1223
1224
1225
1226
1227
1228
        visitCmdLine(m_option->postcmds);

        evaluateFeatureFile(QLatin1String("default_post.prf"));

        QSet<QString> processed;
        forever {
            bool finished = true;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1229
            ProStringList configs = values(statics.strCONFIG);
1230
1231
1232
1233
1234
            for (int i = configs.size() - 1; i >= 0; --i) {
                QString config = configs.at(i).toQString(m_tmp1).toLower();
                if (!processed.contains(config)) {
                    config.detach();
                    processed.insert(config);
1235
                    if (evaluateFeatureFile(config, true)) {
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
                        finished = false;
                        break;
                    }
                }
            }
            if (finished)
                break;
        }
    }
    m_profileStack.pop();
1246
    valuesRef(ProString("PWD")) = ProStringList(ProString(currentDirectory(), NoHash));
1247
1248
1249
1250
1251
1252
    m_handler->doneWithEval(currentProFile());

    return ReturnTrue;
}


Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1253
void QMakeEvaluator::updateMkspecPaths()
1254
1255
1256
1257
{
    QStringList ret;
    const QString concat = QLatin1String("/mkspecs");

1258
1259
    foreach (const QString &it, m_option->getPathListEnv(QLatin1String("QMAKEPATH")))
        ret << it + concat;
1260

1261
1262
1263
    foreach (const QString &it, m_qmakepath)
        ret << it + concat;

1264
1265
1266
1267
    if (!m_buildRoot.isEmpty())
        ret << m_buildRoot + concat;
    if (!m_sourceRoot.isEmpty())
        ret << m_sourceRoot + concat;
1268

1269
    ret << m_option->propertyValue(ProString("QT_HOST_DATA/get")) + concat;
1270
1271

    ret.removeDuplicates();
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1272
    m_mkspecPaths = ret;
1273
1274
}

1275
void QMakeEvaluator::updateFeaturePaths()
1276
1277
{
    QString mkspecs_concat = QLatin1String("/mkspecs");
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1278
    QString features_concat = QLatin1String("/features/");
1279
1280
1281

    QStringList feature_roots;

1282
    foreach (const QString &f, m_option->getPathListEnv(QLatin1String("QMAKEFEATURES")))
1283
        feature_roots += f;
1284

1285
1286
    feature_roots += m_qmakefeatures;

1287
    feature_roots += m_option->propertyValue(ProString("QMAKEFEATURES")).toQString(m_mtmp).split(
1288
1289
            m_option->dirlist_sep, QString::SkipEmptyParts);

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1290
    QStringList feature_bases;
1291
1292
1293
1294
    if (!m_buildRoot.isEmpty())
        feature_bases << m_buildRoot;
    if (!m_sourceRoot.isEmpty())
        feature_bases << m_sourceRoot;
1295

1296
    foreach (const QString &item, m_option->getPathListEnv(QLatin1String("QMAKEPATH")))
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1297
        feature_bases << (item + mkspecs_concat);
1298

1299
1300
1301
    foreach (const QString &item, m_qmakepath)
        feature_bases << (item + mkspecs_concat);

1302
    if (!m_qmakespecFull.isEmpty()) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1303
        // The spec is already platform-dependent, so no subdirs here.
1304
        feature_roots << (m_qmakespecFull + features_concat);
1305

1306
        // Also check directly under the root directory of the mkspecs collection
1307
        QDir specdir(m_qmakespecFull);
1308
1309
1310
1311
        while (!specdir.isRoot() && specdir.cdUp()) {
            const QString specpath = specdir.path();
            if (specpath.endsWith(mkspecs_concat)) {
                if (IoUtils::exists(specpath + features_concat))
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1312
                    feature_bases << specpath;
1313
1314
1315
1316
1317
                break;
            }
        }
    }

1318
    feature_bases << (m_option->propertyValue(ProString("QT_HOST_DATA/get")).toQString(m_mtmp)
1319
                      + mkspecs_concat);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1320
1321
1322
1323
1324
1325

    foreach (const QString &fb, feature_bases) {
        foreach (const ProString &sfx, values(ProString("QMAKE_PLATFORM")))
            feature_roots << (fb + features_concat + sfx + QLatin1Char('/'));
        feature_roots << (fb + features_concat);
    }
1326
1327
1328
1329
1330
1331
1332

    for (int i = 0; i < feature_roots.count(); ++i)
        if (!feature_roots.at(i).endsWith((ushort)'/'))
            feature_roots[i].append((ushort)'/');

    feature_roots.removeDuplicates();

1333
1334
1335
1336
    QStringList ret;
    foreach (const QString &root, feature_roots)
        if (IoUtils::exists(root))
            ret << root;
1337
    m_featureRoots = ret;
1338
1339
}

1340
ProString QMakeEvaluator::propertyValue(const ProString &name) const
1341
1342
{
    if (name == QLatin1String("QMAKE_MKSPECS"))
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1343
        return ProString(m_mkspecPaths.join(m_option->dirlist_sep), NoHash);
1344
    ProString ret = m_option->propertyValue(name);
1345
1346
//    if (ret.isNull())
//        evalError(fL1S("Querying unknown property %1").arg(name.toQString(m_mtmp)));
1347
    return ret;
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
}

ProFile *QMakeEvaluator::currentProFile() const
{
    if (m_profileStack.count() > 0)
        return m_profileStack.top();
    return 0;
}

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

QString QMakeEvaluator::currentDirectory() const
{
1367
1368
1369
1370
    ProFile *pro = currentProFile();
    if (pro)
        return pro->directoryName();
    return QString();
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
}

bool QMakeEvaluator::isActiveConfig(const QString &config, bool regex)
{
    // magic types for easy flipping
    if (config == statics.strtrue)
        return true;
    if (config == statics.strfalse)
        return false;

1381
1382
1383
    if (config == statics.strhost_build)
        return m_hostBuild;

1384
1385
1386
1387
1388
1389
    if (regex && (config.contains(QLatin1Char('*')) || config.contains(QLatin1Char('?')))) {
        QString cfg = config;
        cfg.detach(); // Keep m_tmp out of QRegExp's cache
        QRegExp re(cfg, Qt::CaseSensitive, QRegExp::Wildcard);

        // mkspecs
1390
        if (re.exactMatch(m_qmakespecName))
1391
1392
1393
1394
            return true;

        // CONFIG variable
        int t = 0;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1395
        foreach (const ProString &configValue, values(statics.strCONFIG)) {
1396
1397
1398
1399
1400
1401
            if (re.exactMatch(configValue.toQString(m_tmp[t])))
                return true;
            t ^= 1;
        }
    } else {
        // mkspecs
1402
        if (m_qmakespecName == config)
1403
1404
1405
            return true;

        // CONFIG variable
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1406
        if (values(statics.strCONFIG).contains(ProString(config, NoHash)))
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
            return true;
    }

    return false;
}

ProStringList QMakeEvaluator::expandVariableReferences(
        const ushort *&tokPtr, int sizeHint, bool joined)
{
    ProStringList ret;
    ret.reserve(sizeHint);
    forever {
        evaluateExpression(tokPtr, &ret, joined);
        switch (*tokPtr) {
        case TokValueTerminator:
        case TokFuncTerminator:
            tokPtr++;
            return ret;
        case TokArgSeparator:
            if (joined) {
                tokPtr++;
                continue;
            }
            // fallthrough
        default:
            Q_ASSERT_X(false, "expandVariableReferences", "Unrecognized token");
            break;
        }
    }
}

QList<ProStringList> QMakeEvaluator::prepareFunctionArgs(const ushort *&tokPtr)
{
    QList<ProStringList> args_list;
    if (*tokPtr != TokFuncTerminator) {
        for (;; tokPtr++) {
            ProStringList arg;
            evaluateExpression(tokPtr, &arg, false);
            args_list << arg;
            if (*tokPtr == TokFuncTerminator)
                break;
            Q_ASSERT(*tokPtr == TokArgSeparator);
        }
    }
    tokPtr++;
    return args_list;
}

ProStringList QMakeEvaluator::evaluateFunction(
        const ProFunctionDef &func, const QList<ProStringList> &argumentsList, bool *ok)
{
    bool oki;
    ProStringList ret;

    if (m_valuemapStack.count() >= 100) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1462
        evalError(fL1S("Ran into infinite recursion (depth > 100)."));
1463
1464
        oki = false;
    } else {
1465
        m_valuemapStack.push(ProValueMap());
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
        m_locationStack.push(m_current);
        int loopLevel = m_loopLevel;
        m_loopLevel = 0;

        ProStringList args;
        for (int i = 0; i < argumentsList.count(); ++i) {
            args += argumentsList[i];
            m_valuemapStack.top()[ProString(QString::number(i+1))] = argumentsList[i];
        }
        m_valuemapStack.top()[statics.strARGS] = args;
1476
1477
        VisitReturn vr = visitProBlock(func.pro(), func.tokPtr());
        oki = (vr != ReturnFalse && vr != ReturnError); // True || Return
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
        ret = m_returnValue;
        m_returnValue.clear();

        m_loopLevel = loopLevel;
        m_current = m_locationStack.pop();
        m_valuemapStack.pop();
    }
    if (ok)
        *ok = oki;
    if (oki)
        return ret;
    return ProStringList();
}

QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateBoolFunction(
        const ProFunctionDef &func, const QList<ProStringList> &argumentsList,
        const ProString &function)
{
    bool ok;
    ProStringList ret = evaluateFunction(func, argumentsList, &ok);
    if (ok) {
        if (ret.isEmpty())
            return ReturnTrue;
        if (ret.at(0) != statics.strfalse) {
            if (ret.at(0) == statics.strtrue)
                return ReturnTrue;
            int val = ret.at(0).toQString(m_tmp1