profileevaluator.cpp 113 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
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
con's avatar
con committed
27
**
28
**************************************************************************/
29

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

#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
#endif

65
66
using namespace ProFileEvaluatorInternal;

con's avatar
con committed
67
68
QT_BEGIN_NAMESPACE

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
static void refFunctions(QHash<QString, ProBlock *> *defs)
{
    foreach (ProBlock *itm, *defs)
        itm->ref();
}

static void clearFunctions(QHash<QString, ProBlock *> *defs)
{
    foreach (ProBlock *itm, *defs)
        itm->deref();
    defs->clear();
}

static void clearFunctions(ProFileEvaluator::FunctionDefs *defs)
{
    clearFunctions(&defs->replaceFunctions);
    clearFunctions(&defs->testFunctions);
}

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
88

89
90
///////////////////////////////////////////////////////////////////////
//
91
// ProFileCache
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
ProFileCache::~ProFileCache()
{
    foreach (ProFile *pro, parsed_files)
        pro->deref();
}

void ProFileCache::discardFile(const QString &fileName)
{
    QHash<QString, ProFile *>::Iterator it = parsed_files.find(fileName);
    if (it != parsed_files.end()) {
        it.value()->deref();
        parsed_files.erase(it);
    }
}

void ProFileCache::discardFiles(const QString &prefix)
{
    QHash<QString, ProFile *>::Iterator
            it = parsed_files.begin(),
            end = parsed_files.end();
    while (it != end)
        if (it.key().startsWith(prefix)) {
            it.value()->deref();
            it = parsed_files.erase(it);
        } else {
            ++it;
        }
}

void ProFileCache::addFile(ProFile *pro)
{
    parsed_files[pro->fileName()] = pro;
    pro->ref();
}

ProFile *ProFileCache::getFile(const QString &fileName)
{
    ProFile *pro = parsed_files.value(fileName);
    if (pro)
        pro->ref();
    return pro;
}

///////////////////////////////////////////////////////////////////////
//
140
// ProFileOption
141
142
143
//
///////////////////////////////////////////////////////////////////////

144
ProFileOption::ProFileOption()
145
146
147
148
149
150
151
152
153
154
{
#ifdef Q_OS_WIN
    dirlist_sep = QLatin1Char(';');
    dir_sep = QLatin1Char('\\');
#else
    dirlist_sep = QLatin1Char(':');
    dir_sep = QLatin1Char('/');
#endif
    qmakespec = QString::fromLatin1(qgetenv("QMAKESPEC").data());

155
#if defined(Q_OS_WIN32)
156
    target_mode = TARG_WIN_MODE;
157
#elif defined(Q_OS_MAC)
158
    target_mode = TARG_MACX_MODE;
159
#elif defined(Q_OS_QNX6)
160
    target_mode = TARG_QNX6_MODE;
161
#else
162
    target_mode = TARG_UNIX_MODE;
163
164
#endif

165
    field_sep = QLatin1String(" ");
166
167

    cache = 0;
168
169
}

170
ProFileOption::~ProFileOption()
171
172
173
174
{
    clearFunctions(&base_functions);
}

175
QString ProFileOption::field_sep;
176

con's avatar
con committed
177
178
179
180
181
182
///////////////////////////////////////////////////////////////////////
//
// ProFileEvaluator::Private
//
///////////////////////////////////////////////////////////////////////

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
183
class ProFileEvaluator::Private
con's avatar
con committed
184
185
{
public:
186
    Private(ProFileEvaluator *q_, ProFileOption *option);
187
    ~Private();
con's avatar
con committed
188

189
190
191
192
193
194
    ProFileEvaluator *q;
    int m_lineNo;                                   // Error reporting
    bool m_verbose;

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

195
196
197
198
199
200
201
202
203
204
205
206
    struct BlockCursor {
        BlockCursor() : cursor(0) {}
        BlockCursor(ProBlock *blk) : block(blk), cursor(blk->itemsRef()) {}
        ~BlockCursor() { if (cursor) *cursor = 0; }
        void set(ProBlock *blk) { if (cursor) *cursor = 0; block = blk; cursor = blk->itemsRef(); }
        void reset() { if (cursor) { *cursor = 0; cursor = 0; } }
        void append(ProItem *item) { *cursor = item; cursor = item->nextRef(); }
        bool isValid() const { return cursor != 0; }
        ProBlock *block;
        ProItem **cursor;
    };

con's avatar
con committed
207
    bool read(ProFile *pro);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
208
    bool read(ProBlock *pro, const QString &content);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
209
    bool readInternal(ProBlock *pro, const QString &content, ushort *buf);
con's avatar
con committed
210

211
    BlockCursor &currentBlock();
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
212
213
214
    void updateItem(ushort *uc, ushort *ptr);
    ProVariable *startVariable(ushort *uc, ushort *ptr);
    void finalizeVariable(ProVariable *var, ushort *uc, ushort *ptr);
con's avatar
con committed
215
216
217
218
219
    void insertOperator(const char op);
    void enterScope(bool multiLine);
    void leaveScope();
    void finalizeBlock();

220
221
    QStack<BlockCursor> m_blockstack;
    BlockCursor m_block;
222
223
224

    /////////////// Evaluating pro file contents

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
225
226
227
    ProItem::ProItemReturn visitProFile(ProFile *pro);
    ProItem::ProItemReturn visitProBlock(ProBlock *block);
    ProItem::ProItemReturn visitProItem(ProItem *item);
228
229
    ProItem::ProItemReturn visitProLoopIteration();
    void visitProLoopCleanup();
230
    void visitProVariable(ProVariable *variable);
231
    ProItem::ProItemReturn visitProFunction(ProFunction *function);
232
233
    void visitProOperator(ProOperator *oper);
    void visitProCondition(ProCondition *condition);
con's avatar
con committed
234

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
235
    QStringList valuesDirect(const QString &variableName) const { return m_valuemap[variableName]; }
con's avatar
con committed
236
237
    QStringList values(const QString &variableName) const;
    QStringList values(const QString &variableName, const ProFile *pro) const;
238
239
    QStringList values(const QString &variableName, const QHash<QString, QStringList> &place,
                       const ProFile *pro) const;
240
    QString propertyValue(const QString &val, bool complain = true) const;
con's avatar
con committed
241

242
    static QStringList split_value_list(const QString &vals);
con's avatar
con committed
243
    bool isActiveConfig(const QString &config, bool regex = false);
244
245
    QStringList expandVariableReferences(const QString &value, bool do_semicolon = false,
                                         int *pos = 0);
246
    void doVariableReplace(QString *str);
con's avatar
con committed
247
248
    QStringList evaluateExpandFunction(const QString &function, const QString &arguments);
    QString format(const char *format) const;
249
250
251
    void logMessage(const QString &msg) const;
    void errorMessage(const QString &msg) const;
    void fileMessage(const QString &msg) const;
con's avatar
con committed
252
253

    QString currentFileName() const;
254
    QString currentDirectory() const;
con's avatar
con committed
255
    ProFile *currentProFile() const;
256
257
    QString resolvePath(const QString &fileName) const
        { return IoUtils::resolvePath(currentDirectory(), fileName); }
con's avatar
con committed
258

259
    ProItem::ProItemReturn evaluateConditionalFunction(const QString &function, const QString &arguments);
260
261
    ProFile *parsedProFile(const QString &fileName, bool cache,
                           const QString &contents = QString());
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
262
    bool evaluateFile(const QString &fileName);
263
264
265
266
    bool evaluateFeatureFile(const QString &fileName,
                             QHash<QString, QStringList> *values = 0, FunctionDefs *defs = 0);
    bool evaluateFileInto(const QString &fileName,
                          QHash<QString, QStringList> *values, FunctionDefs *defs);
con's avatar
con committed
267

268
269
270
    static inline ProItem::ProItemReturn returnBool(bool b)
        { return b ? ProItem::ReturnTrue : ProItem::ReturnFalse; }

271
272
    QList<QStringList> prepareFunctionArgs(const QString &arguments);
    QStringList evaluateFunction(ProBlock *funcPtr, const QList<QStringList> &argumentsList, bool *ok);
273

274
275
    QStringList qmakeMkspecPaths() const;
    QStringList qmakeFeaturePaths() const;
con's avatar
con committed
276

277
    struct State {
278
279
        bool condition;
        bool prevCondition;
280
281
    } m_sts;
    bool m_invertNext; // Short-lived, so not in State
282
    bool m_hadCondition; // Nested calls set it on return, so no need for it to be in State
283
284
    int m_skipLevel;
    bool m_cumulative;
con's avatar
con committed
285
    QStack<ProFile*> m_profileStack;                // To handle 'include(a.pri), so we can track back to 'a.pro' when finished with 'a.pri'
286
287
288
289
290
291
292
293
    struct ProLoop {
        QString variable;
        QStringList oldVarVal;
        QStringList list;
        int index;
        bool infinite;
    };
    QStack<ProLoop> m_loopStack;
con's avatar
con committed
294
295
296

    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
297
    QString m_outputDir;
con's avatar
con committed
298

299
    int m_listCount;
300
301
    bool m_definingTest;
    QString m_definingFunc;
302
    FunctionDefs m_functionDefs;
303
304
305
306
    QStringList m_returnValue;
    QStack<QHash<QString, QStringList> > m_valuemapStack;
    QStack<QHash<const ProFile*, QHash<QString, QStringList> > > m_filevaluemapStack;

307
308
    QStringList m_addUserConfigCmdArgs;
    QStringList m_removeUserConfigCmdArgs;
309
    bool m_parsePreAndPostFiles;
310

311
    ProFileOption *m_option;
con's avatar
con committed
312
313
};

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
314
#if !defined(__GNUC__) || __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3)
315
Q_DECLARE_TYPEINFO(ProFileEvaluator::Private::State, Q_PRIMITIVE_TYPE);
316
Q_DECLARE_TYPEINFO(ProFileEvaluator::Private::ProLoop, Q_MOVABLE_TYPE);
317
Q_DECLARE_TYPEINFO(ProFileEvaluator::Private::BlockCursor, Q_MOVABLE_TYPE);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
318
#endif
319

320
ProFileEvaluator::Private::Private(ProFileEvaluator *q_, ProFileOption *option)
321
  : q(q_), m_option(option)
con's avatar
con committed
322
{
323
    // Configuration, more or less
con's avatar
con committed
324
    m_verbose = true;
325
    m_cumulative = true;
326
    m_parsePreAndPostFiles = true;
327
328

    // Evaluator state
329
330
    m_sts.condition = false;
    m_sts.prevCondition = false;
331
332
    m_invertNext = false;
    m_skipLevel = 0;
333
    m_definingFunc.clear();
334
    m_listCount = 0;
con's avatar
con committed
335
336
}

337
338
339
340
341
ProFileEvaluator::Private::~Private()
{
    clearFunctions(&m_functionDefs);
}

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
342
343
////////// Parser ///////////

con's avatar
con committed
344
345
346
bool ProFileEvaluator::Private::read(ProFile *pro)
{
    QFile file(pro->fileName());
347
    if (!file.open(QIODevice::ReadOnly)) {
348
349
        if (IoUtils::exists(pro->fileName()))
            errorMessage(format("%1 not readable.").arg(pro->fileName()));
con's avatar
con committed
350
351
352
        return false;
    }

353
354
    QString content(QString::fromLatin1(file.readAll())); // yes, really latin1
    file.close();
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
355
    m_lineNo = 1;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
356
    return readInternal(pro, content, (ushort*)content.data());
357
358
}

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
359
bool ProFileEvaluator::Private::read(ProBlock *pro, const QString &content)
360
{
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
361
362
    QString buf;
    buf.reserve(content.size());
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
363
    m_lineNo = 1;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
364
    return readInternal(pro, content, (ushort*)buf.data());
365
366
}

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
367
368
369
// We know that the buffer cannot grow larger than the input string,
// and the read() functions rely on it.
bool ProFileEvaluator::Private::readInternal(ProBlock *pro, const QString &in, ushort *buf)
370
{
371
    // Parser state
372
    m_blockstack.push(BlockCursor(pro));
con's avatar
con committed
373

374
375
    // We rely on QStrings being null-terminated, so don't maintain a global end pointer.
    const ushort *cur = (const ushort *)in.unicode();
376
  freshLine:
377
    ProVariable *currAssignment = 0;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
378
    ushort *ptr = buf;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
379
    int parens = 0;
380
381
382
    bool inError = false;
    bool putSpace = false;
    ushort quote = 0;
383
    forever {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
384
        ushort c;
385
386

        // First, skip leading whitespace
387
388
389
        for (;; ++cur) {
            c = *cur;
            if (c == '\n' || !c) { // Entirely empty line (sans whitespace)
390
                if (currAssignment) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
391
                    finalizeVariable(currAssignment, buf, ptr);
392
393
                    currAssignment = 0;
                } else {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
394
                    updateItem(buf, ptr);
395
                }
396
                finalizeBlock();
397
398
399
400
401
                if (c) {
                    ++cur;
                    ++m_lineNo;
                    goto freshLine;
                }
402
403
                m_block.reset();
                m_blockstack.clear(); // FIXME: should actually check the state here
404
                return true;
con's avatar
con committed
405
            }
406
            if (c != ' ' && c != '\t' && c != '\r')
407
408
409
410
                break;
        }

        // Then strip comments. Yep - no escaping is possible.
411
412
413
414
415
416
417
418
419
420
421
422
        const ushort *end; // End of this line
        const ushort *cptr; // Start of next line
        for (cptr = cur;; ++cptr) {
            c = *cptr;
            if (c == '#') {
                for (end = cptr; (c = *++cptr);) {
                    if (c == '\n') {
                        ++cptr;
                        break;
                    }
                }
                if (end == cur) { // Line with only a comment (sans whitespace)
423
424
                    // Qmake bizarreness: such lines do not affect line continuations
                    goto ignore;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
425
                }
426
427
428
                break;
            }
            if (!c) {
429
430
                end = cptr;
                break;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
431
            }
432
433
434
435
436
            if (c == '\n') {
                end = cptr++;
                break;
            }
        }
437

438
        // Then look for line continuations. Yep - no escaping here as well.
439
440
441
442
443
444
445
446
447
448
        bool lineCont;
        forever {
            // We don't have to check for underrun here, as we already determined
            // that the line is non-empty.
            ushort ec = *(end - 1);
            if (ec == '\\') {
                --end;
                lineCont = true;
                break;
            }
449
            if (ec != ' ' && ec != '\t' && ec != '\r') {
450
451
452
453
454
455
456
457
                lineCont = false;
                break;
            }
            --end;
        }

        if (!inError) {
            // Finally, do the tokenization
458
            if (!currAssignment) {
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
              newItem:
                do {
                    if (cur == end)
                        goto lineEnd;
                    c = *cur++;
                } while (c == ' ' || c == '\t');
                forever {
                    if (c == '"') {
                        quote = '"' - quote;
                    } else if (!quote) {
                        if (c == '(') {
                            ++parens;
                        } else if (c == ')') {
                            --parens;
                        } else if (!parens) {
                            if (c == ':') {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
475
                                updateItem(buf, ptr);
476
477
                                enterScope(false);
                              nextItem:
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
478
                                ptr = buf;
479
480
481
482
                                putSpace = false;
                                goto newItem;
                            }
                            if (c == '{') {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
483
                                updateItem(buf, ptr);
484
485
486
487
                                enterScope(true);
                                goto nextItem;
                            }
                            if (c == '}') {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
488
                                updateItem(buf, ptr);
489
490
491
492
                                leaveScope();
                                goto nextItem;
                            }
                            if (c == '=') {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
493
494
                                if ((currAssignment = startVariable(buf, ptr))) {
                                    ptr = buf;
495
496
497
                                    putSpace = false;
                                    break;
                                }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
498
                                ptr = buf;
499
500
501
502
                                inError = true;
                                goto skip;
                            }
                            if (c == '|' || c == '!') {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
503
                                updateItem(buf, ptr);
504
505
506
                                insertOperator(c);
                                goto nextItem;
                            }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
507
                        }
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
                    }

                    if (putSpace) {
                        putSpace = false;
                        *ptr++ = ' ';
                    }
                    *ptr++ = c;

                    forever {
                        if (cur == end)
                            goto lineEnd;
                        c = *cur++;
                        if (c != ' ' && c != '\t')
                            break;
                        putSpace = true;
                    }
                }
525
            } // !currAssignment
526
527
528
529
530
531

            do {
                if (cur == end)
                    goto lineEnd;
                c = *cur++;
            } while (c == ' ' || c == '\t');
532
533
534
535
            forever {
                if (putSpace) {
                    putSpace = false;
                    *ptr++ = ' ';
536
                }
537
                *ptr++ = c;
538

539
540
541
542
543
544
545
                forever {
                    if (cur == end)
                        goto lineEnd;
                    c = *cur++;
                    if (c != ' ' && c != '\t')
                        break;
                    putSpace = true;
546
547
548
549
                }
            }
          lineEnd:
            if (lineCont) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
550
                putSpace = (ptr != buf);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
551
            } else {
552
                if (currAssignment) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
553
                    finalizeVariable(currAssignment, buf, ptr);
554
555
                    currAssignment = 0;
                } else {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
556
                    updateItem(buf, ptr);
557
                }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
558
                ptr = buf;
559
                putSpace = false;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
560
            }
561
562
563
        } // !inError
      skip:
        if (!lineCont) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
564
            finalizeBlock();
565
            cur = cptr;
566
567
568
569
            ++m_lineNo;
            goto freshLine;
        }
      ignore:
570
        cur = cptr;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
571
        ++m_lineNo;
con's avatar
con committed
572
573
574
575
576
    }
}

void ProFileEvaluator::Private::finalizeBlock()
{
577
    if (m_blockstack.top().block->blockKind() & ProBlock::SingleLine)
578
        leaveScope();
579
    m_block.reset();
con's avatar
con committed
580
581
}

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
582
ProVariable *ProFileEvaluator::Private::startVariable(ushort *uc, ushort *ptr)
con's avatar
con committed
583
584
585
{
    ProVariable::VariableOperator opkind;

586
    if (ptr == uc) // Line starting with '=', like a conflict marker
587
        return 0;
588

589
    switch (*(ptr - 1)) {
con's avatar
con committed
590
        case '+':
591
            --ptr;
con's avatar
con committed
592
593
594
            opkind = ProVariable::AddOperator;
            break;
        case '-':
595
            --ptr;
con's avatar
con committed
596
597
598
            opkind = ProVariable::RemoveOperator;
            break;
        case '*':
599
            --ptr;
con's avatar
con committed
600
601
602
            opkind = ProVariable::UniqueAddOperator;
            break;
        case '~':
603
            --ptr;
con's avatar
con committed
604
605
606
607
            opkind = ProVariable::ReplaceOperator;
            break;
        default:
            opkind = ProVariable::SetOperator;
608
            goto skipTrunc;
con's avatar
con committed
609
610
    }

611
    if (ptr == uc) // Line starting with manipulation operator
612
        return 0;
613
    if (*(ptr - 1) == ' ')
614
        --ptr;
615
616

  skipTrunc:
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
617
    ProVariable *variable = new ProVariable(QString((QChar*)uc, ptr - uc));
con's avatar
con committed
618
619
    variable->setLineNumber(m_lineNo);
    variable->setVariableOperator(opkind);
620
621
    return variable;
}
con's avatar
con committed
622

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
623
void ProFileEvaluator::Private::finalizeVariable(ProVariable *variable, ushort *uc, ushort *ptr)
624
{
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
625
    variable->setValue(QString((QChar*)uc, ptr - uc));
626

627
    m_blockstack.top().append(variable);
con's avatar
con committed
628
629
630
631
632
}

void ProFileEvaluator::Private::insertOperator(const char op)
{
    ProOperator::OperatorKind opkind;
hjk's avatar
hjk committed
633
    switch (op) {
con's avatar
con committed
634
635
636
637
638
639
640
641
642
643
644
645
        case '!':
            opkind = ProOperator::NotOperator;
            break;
        case '|':
            opkind = ProOperator::OrOperator;
            break;
        default:
            opkind = ProOperator::OrOperator;
    }

    ProOperator * const proOp = new ProOperator(opkind);
    proOp->setLineNumber(m_lineNo);
646
    currentBlock().append(proOp);
con's avatar
con committed
647
648
649
650
}

void ProFileEvaluator::Private::enterScope(bool multiLine)
{
651
652
    BlockCursor &parent = currentBlock();

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
653
    ProBlock *block = new ProBlock();
con's avatar
con committed
654
655
656
657
658
    block->setLineNumber(m_lineNo);
    if (multiLine)
        block->setBlockKind(ProBlock::ScopeContentsKind);
    else
        block->setBlockKind(ProBlock::ScopeContentsKind|ProBlock::SingleLine);
659
    m_blockstack.push(BlockCursor(block));
con's avatar
con committed
660

661
662
663
664
    parent.block->setBlockKind(ProBlock::ScopeKind);
    parent.append(block);

    m_block.reset();
con's avatar
con committed
665
666
667
668
}

void ProFileEvaluator::Private::leaveScope()
{
669
    if (m_blockstack.count() == 1)
670
        errorMessage(format("Excess closing brace."));
671
672
    else
        m_blockstack.pop();
con's avatar
con committed
673
674
675
    finalizeBlock();
}

676
ProFileEvaluator::Private::BlockCursor &ProFileEvaluator::Private::currentBlock()
con's avatar
con committed
677
{
678
679
680
681
682
683
    if (!m_block.isValid()) {
        ProBlock *blk = new ProBlock();
        blk->setLineNumber(m_lineNo);
        m_blockstack.top().append(blk);
        m_block.set(blk);
    }
con's avatar
con committed
684
685
686
    return m_block;
}

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
687
void ProFileEvaluator::Private::updateItem(ushort *uc, ushort *ptr)
con's avatar
con committed
688
{
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
689
    if (ptr == uc)
con's avatar
con committed
690
691
        return;

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
692
    QString proItem = QString((QChar*)uc, ptr - uc);
693

694
    ProItem *item;
695
    if (proItem.endsWith(QLatin1Char(')'))) {
696
        item = new ProFunction(proItem);
con's avatar
con committed
697
    } else {
698
        item = new ProCondition(proItem);
con's avatar
con committed
699
    }
700
    item->setLineNumber(m_lineNo);
701
    currentBlock().append(item);
con's avatar
con committed
702
703
}

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
704
705
//////// Evaluator tools /////////

706
QStringList ProFileEvaluator::Private::split_value_list(const QString &vals)
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
707
708
709
710
711
{
    QString build;
    QStringList ret;
    QStack<char> quote;

712
    const ushort SPACE = ' ';
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
    const ushort LPAREN = '(';
    const ushort RPAREN = ')';
    const ushort SINGLEQUOTE = '\'';
    const ushort DOUBLEQUOTE = '"';
    const ushort BACKSLASH = '\\';

    ushort unicode;
    const QChar *vals_data = vals.data();
    const int vals_len = vals.length();
    for (int x = 0, parens = 0; x < vals_len; x++) {
        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;
        }

737
        if (!parens && quote.isEmpty() && vals_data[x] == SPACE) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
            ret << build;
            build.clear();
        } else {
            build += vals_data[x];
        }
    }
    if (!build.isEmpty())
        ret << build;
    return ret;
}

static void insertUnique(QHash<QString, QStringList> *map,
    const QString &key, const QStringList &value)
{
    QStringList &sl = (*map)[key];
    foreach (const QString &str, value)
        if (!sl.contains(str))
            sl.append(str);
}

static void removeEach(QHash<QString, QStringList> *map,
    const QString &key, const QStringList &value)
{
    QStringList &sl = (*map)[key];
    foreach (const QString &str, value)
        sl.removeAll(str);
}

static void replaceInList(QStringList *varlist,
        const QRegExp &regexp, const QString &replace, bool global)
{
    for (QStringList::Iterator varit = varlist->begin(); varit != varlist->end(); ) {
        if ((*varit).contains(regexp)) {
            (*varit).replace(regexp, replace);
            if ((*varit).isEmpty())
                varit = varlist->erase(varit);
            else
                ++varit;
            if (!global)
                break;
        } else {
            ++varit;
        }
    }
}

784
785
786
787
788
789
790
791
792
793
794
795
static QString expandEnvVars(const QString &str)
{
    QString string = str;
    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()));
    return string;
}

796
797
798
799
800
801
802
803
static QStringList expandEnvVars(const QStringList &x)
{
    QStringList ret;
    foreach (const QString &str, x)
        ret << expandEnvVars(str);
    return ret;
}

804
805
806
807
808
// This is braindead, but we want qmake compat
static QString fixPathToLocalOS(const QString &str)
{
    QString string = str;

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
809
    if (string.length() > 2 && string.at(0).isLetter() && string.at(1) == QLatin1Char(':'))
810
811
812
813
814
815
816
817
818
819
        string[0] = string[0].toLower();

#if defined(Q_OS_WIN32)
    string.replace(QLatin1Char('/'), QLatin1Char('\\'));
#else
    string.replace(QLatin1Char('\\'), QLatin1Char('/'));
#endif
    return string;
}

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
820
//////// Evaluator /////////
con's avatar
con committed
821

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
ProItem::ProItemReturn ProFileEvaluator::Private::visitProItem(ProItem *item)
{
    switch (item->kind()) {
    case ProItem::BlockKind: // This is never a ProFile
        return visitProBlock(static_cast<ProBlock*>(item));
    case ProItem::VariableKind:
        visitProVariable(static_cast<ProVariable*>(item));
        break;
    case ProItem::ConditionKind:
        visitProCondition(static_cast<ProCondition*>(item));
        break;
    case ProItem::FunctionKind:
        return visitProFunction(static_cast<ProFunction*>(item));
    case ProItem::OperatorKind:
        visitProOperator(static_cast<ProOperator*>(item));
        break;
    }
    return ProItem::ReturnTrue;
}

ProItem::ProItemReturn ProFileEvaluator::Private::visitProBlock(ProBlock *block)
con's avatar
con committed
843
{
844
    if (block->blockKind() & ProBlock::ScopeContentsKind) {
845
846
847
        if (!m_definingFunc.isEmpty()) {
            if (!m_skipLevel || m_cumulative) {
                QHash<QString, ProBlock *> *hash =
848
849
                        (m_definingTest ? &m_functionDefs.testFunctions
                                        : &m_functionDefs.replaceFunctions);
850
851
852
853
854
855
856
                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();
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
857
            return ProItem::ReturnTrue;
858
        } else if (!(block->blockKind() & ProBlock::FunctionBodyKind)) {
859
860
861
862
            if (!m_sts.condition) {
                if (m_skipLevel || m_hadCondition)
                    ++m_skipLevel;
            } else {
863
                Q_ASSERT(!m_skipLevel);
864
            }
865
        }
866
    } else {
867
        m_hadCondition = false;
868
869
870
871
872
873
874
875
        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
876
    }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
877
    ProItem::ProItemReturn rt = ProItem::ReturnTrue;
878
879
    for (ProItem *item = block->items(); item; item = item->next()) {
        rt = visitProItem(item);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
880
881
882
883
        if (rt != ProItem::ReturnTrue && rt != ProItem::ReturnFalse) {
            if (rt == ProItem::ReturnLoop) {
                rt = ProItem::ReturnTrue;
                while (visitProLoopIteration())
884
885
                    for (ProItem *lItem = item; (lItem = lItem->next()); ) {
                        rt = visitProItem(lItem);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
                        if (rt != ProItem::ReturnTrue && rt != ProItem::ReturnFalse) {
                            if (rt == ProItem::ReturnNext) {
                                rt = ProItem::ReturnTrue;
                                break;
                            }
                            if (rt == ProItem::ReturnBreak)
                                rt = ProItem::ReturnTrue;
                            goto do_break;
                        }
                    }
              do_break:
                visitProLoopCleanup();
            }
            break;
        }
    }
902
903
    if ((block->blockKind() & ProBlock::ScopeContentsKind)
        && !(block->blockKind() & ProBlock::FunctionBodyKind)) {
904
        if (m_skipLevel) {
905
            Q_ASSERT(!m_sts.condition);
906
            --m_skipLevel;
907
        } else if (!(block->blockKind() & ProBlock::SingleLine)) {
908
909
            // 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.
910
            m_sts.condition = true;
911
        }
912
    }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
913
    return rt;
con's avatar
con committed
914
915
}

916
917
918
919
920
921
922
923
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) {
924
            errorMessage(format("ran into infinite loop (> 1000 iterations)."));
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
            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();
}

946
void ProFileEvaluator::Private::visitProVariable(ProVariable *var)
con's avatar
con committed
947
{
948
949
    m_lineNo = var->lineNumber();
    const QString &varName = var->variable();
con's avatar
con committed
950

951
952
    if (var->variableOperator() == ProVariable::ReplaceOperator) {      // ~=
        // DEFINES ~= s/a/b/?[gqi]
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
        QString val = var->value();
        doVariableReplace(&val);
        if (val.length() < 4 || val.at(0) != QLatin1Char('s')) {
            logMessage(format("the ~= operator can handle only the s/// function."));
            return;
        }
        QChar sep = val.at(1);
        QStringList func = val.split(sep);
        if (func.count() < 3 || func.count() > 4) {
            logMessage(format("the s/// function expects 3 or 4 arguments."));
            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);

        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);
        }
    } else {
        static const QString deppath(QLatin1String("DEPENDPATH"));
        static const QString incpath(QLatin1String("INCLUDEPATH"));
        bool doSemicolon = (varName == deppath || varName == incpath);
990
        QStringList varVal = expandVariableReferences(var->value(), doSemicolon);
991
992
993

        switch (var->variableOperator()) {
        default: // ReplaceOperator - cannot happen
994
995
996
        case ProVariable::SetOperator:          // =
            if (!m_cumulative) {
                if (!m_skipLevel) {
997
998
                    m_valuemap[varName] = varVal;
                    m_filevaluemap[currentProFile()][varName] = varVal;
999
1000
1001
                }
            } else {
                // We are greedy for values.
1002
1003
                m_valuemap[varName] += varVal;
                m_filevaluemap[currentProFile()][varName] += varVal;
1004
1005
1006
1007
            }
            break;
        case ProVariable::UniqueAddOperator:    // *=
            if (!m_skipLevel || m_cumulative) {
1008
1009
                insertUnique(&m_valuemap, varName, varVal);
                insertUnique(&m_filevaluemap[currentProFile()], varName, varVal);
1010
1011
1012
1013
            }
            break;
        case ProVariable::AddOperator:          // +=
            if (!m_skipLevel || m_cumulative) {
1014
1015
                m_valuemap[varName] += varVal;
                m_filevaluemap[currentProFile()][varName] += varVal;
1016
1017
1018
1019
1020
            }
            break;
        case ProVariable::RemoveOperator:       // -=
            if (!m_cumulative) {
                if (!m_skipLevel) {
1021
1022
                    removeEach(&m_valuemap, varName, varVal);
                    removeEach(&m_filevaluemap[currentProFile()], varName, varVal);
1023
1024
1025
1026
1027
                }
            } else {
                // We are stingy with our values, too.
            }
            break;
1028
        }
1029
    }
con's avatar
con committed
1030
1031
}

1032
void ProFileEvaluator::Private::visitProOperator(ProOperator *oper)
con's avatar
con committed
1033
1034
1035
1036
{
    m_invertNext = (oper->operatorKind() == ProOperator::NotOperator);
}

1037
void ProFileEvaluator::Private::visitProCondition(ProCondition *cond)
con's avatar
con committed
1038
{
1039
    if (!m_skipLevel) {
1040
        m_hadCondition = true;
1041
        if (!cond->text().compare(QLatin1String("else"), Qt::CaseInsensitive)) {
1042
1043
1044
1045
1046
            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;
1047
        }
con's avatar
con committed
1048
    }
1049
    m_invertNext = false;
con's avatar
con committed
1050
1051
}

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1052
ProItem::ProItemReturn ProFileEvaluator::Private::visitProFile(ProFile *pro)
con's avatar
con committed
1053
1054
{
    m_lineNo = pro->lineNumber();
1055

1056
1057
    m_profileStack.push(pro);
    if (m_profileStack.count() == 1) {
1058
        // Do this only for the initial profile we visit, since
con's avatar
con committed
1059
1060
1061
        // that is *the* profile. All the other times we reach this function will be due to
        // include(file) or load(file)

1062
        if (m_parsePreAndPostFiles) {
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072

            if (m_option->base_valuemap.isEmpty()) {
                // ### init QMAKE_QMAKE, QMAKE_SH