profileevaluator.cpp 76.2 KB
Newer Older
con's avatar
con committed
1
2
3
4
5
6
7
8
/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
9
10
11
**
** Non-Open Source Usage
**
con's avatar
con committed
12
13
14
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
15
16
17
18
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
con's avatar
con committed
19
20
21
22
23
24
25
26
27
28
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
29
30
31
32
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.2, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
33

con's avatar
con committed
34
35
36
37
#include "profileevaluator.h"
#include "proparserutils.h"
#include "proitems.h"

hjk's avatar
hjk committed
38
39
#include <utils/qtcassert.h>

con's avatar
con committed
40
#include <QtCore/QByteArray>
41
#include <QtCore/QDateTime>
con's avatar
con committed
42
43
44
45
46
47
48
49
50
51
52
53
#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>

54
55
56
57
58
59
60
61
62
#ifdef Q_OS_UNIX
#include <unistd.h>
#include <sys/utsname.h>
#elif defined(Q_OS_WIN32)
#include <Windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>

con's avatar
con committed
63
64
65
66
67
68
69
70
#ifdef Q_OS_WIN32
#define QT_POPEN _popen
#else
#define QT_POPEN popen
#endif

QT_BEGIN_NAMESPACE

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

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

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

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

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

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

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

    return string;
}

con's avatar
con committed
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
149
150
151
152
153
154
155
156
157
///////////////////////////////////////////////////////////////////////
//
// ProFileEvaluator::Private
//
///////////////////////////////////////////////////////////////////////

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

    bool read(ProFile *pro);

    ProBlock *currentBlock();
    void updateItem();
    bool parseLine(const QString &line);
    void insertVariable(const QString &line, int *i);
    void insertOperator(const char op);
    void insertComment(const QString &comment);
    void enterScope(bool multiLine);
    void leaveScope();
    void finalizeBlock();

    // implementation of AbstractProItemVisitor
    bool visitBeginProBlock(ProBlock *block);
    bool visitEndProBlock(ProBlock *block);
    bool visitBeginProVariable(ProVariable *variable);
    bool visitEndProVariable(ProVariable *variable);
    bool visitBeginProFile(ProFile *value);
    bool visitEndProFile(ProFile *value);
    bool visitProValue(ProValue *value);
    bool visitProFunction(ProFunction *function);
    bool visitProOperator(ProOperator *oper);
    bool visitProCondition(ProCondition *condition);

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
158
    QStringList valuesDirect(const QString &variableName) const { return m_valuemap[variableName]; }
con's avatar
con committed
159
160
    QStringList values(const QString &variableName) const;
    QStringList values(const QString &variableName, const ProFile *pro) const;
161
162
    QStringList values(const QString &variableName, const QHash<QString, QStringList> &place,
                       const ProFile *pro) const;
con's avatar
con committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
    QString propertyValue(const QString &val) const;

    bool isActiveConfig(const QString &config, bool regex = false);
    QStringList expandPattern(const QString &pattern);
    void expandPatternHelper(const QString &relName, const QString &absName,
        QStringList &sources_out);
    QStringList expandVariableReferences(const QString &value);
    QStringList evaluateExpandFunction(const QString &function, const QString &arguments);
    QString format(const char *format) const;

    QString currentFileName() const;
    QString getcwd() const;
    ProFile *currentProFile() const;

    bool evaluateConditionalFunction(const QString &function, const QString &arguments, bool *result);
    bool evaluateFile(const QString &fileName, bool *result);
    bool evaluateFeatureFile(const QString &fileName, bool *result);

    QStringList qmakeFeaturePaths();

    ProFileEvaluator *q;

    QStack<ProBlock *> m_blockstack;
    ProBlock *m_block;

    ProItem *m_commentItem;
    QString m_proitem;
    QString m_pendingComment;
    bool m_syntaxError;
    bool m_contNextLine;
    bool m_condition;
    bool m_invertNext;
    QString m_lastVarName;
    ProVariable::VariableOperator m_variableOperator;
    int m_lineNo;                                   // Error reporting
    QString m_oldPath;                              // To restore the current path to the path
    QStack<ProFile*> m_profileStack;                // To handle 'include(a.pri), so we can track back to 'a.pro' when finished with 'a.pri'

    QHash<QString, QStringList> m_valuemap;         // VariableName must be us-ascii, the content however can be non-us-ascii.
    QHash<const ProFile*, QHash<QString, QStringList> > m_filevaluemap; // Variables per include file
    QHash<QString, QString> m_properties;
204
    QString m_outputDir;
con's avatar
con committed
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
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
    QString m_origfile;

    int m_prevLineNo;                               // Checking whether we're assigning the same TARGET
    ProFile *m_prevProFile;                         // See m_prevLineNo

    bool m_verbose;
};

ProFileEvaluator::Private::Private(ProFileEvaluator *q_)
  : q(q_)
{
    m_prevLineNo = 0;
    m_prevProFile = 0;
    m_verbose = true;
    m_block = 0;
    m_commentItem = 0;
    m_syntaxError = 0;
    m_lineNo = 0;
    m_contNextLine = false;
}

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

    m_syntaxError = false;
    m_lineNo = 1;
    m_blockstack.push(pro);

    QTextStream ts(&file);
    while (!ts.atEnd()) {
        QString line = ts.readLine();
        if (!parseLine(line)) {
            q->errorMessage(format(".pro parse failure."));
            return false;
        }
        ++m_lineNo;
    }
    return true;
}

bool ProFileEvaluator::Private::parseLine(const QString &line0)
{
    if (m_blockstack.isEmpty())
        return false;

    ushort quote = 0;
    int parens = 0;
    bool contNextLine = false;
    QString line = line0.simplified();

    for (int i = 0; !m_syntaxError && i < line.length(); ++i) {
        ushort c = line.at(i).unicode();
        if (quote && c == quote)
            quote = 0;
        else if (c == '(')
            ++parens;
        else if (c == ')')
            --parens;
        else if (c == '"' && (i == 0 || line.at(i - 1).unicode() != '\\'))
            quote = c;
        else if (!parens && !quote) {
            if (c == '#') {
                insertComment(line.mid(i + 1));
                contNextLine = m_contNextLine;
                break;
            }
            if (c == '\\' && i >= line.count() - 1) {
                updateItem();
                contNextLine = true;
                continue;
            }
            if (m_block && (m_block->blockKind() & ProBlock::VariableKind)) {
                if (c == ' ')
                    updateItem();
                else
                    m_proitem += c;
                continue;
            }
            if (c == ':') {
                enterScope(false);
                continue;
            }
            if (c == '{') {
                enterScope(true);
                continue;
            }
            if (c == '}') {
                leaveScope();
                continue;
            }
            if (c == '=') {
                insertVariable(line, &i);
                continue;
            }
            if (c == '|' || c == '!') {
                insertOperator(c);
                continue;
            }
        }

        m_proitem += c;
    }
    m_contNextLine = contNextLine;

    if (!m_syntaxError) {
        updateItem();
        if (!m_contNextLine)
            finalizeBlock();
    }
    return !m_syntaxError;
}

void ProFileEvaluator::Private::finalizeBlock()
{
    if (m_blockstack.isEmpty()) {
        m_syntaxError = true;
    } else {
        if (m_blockstack.top()->blockKind() & ProBlock::SingleLine)
            leaveScope();
        m_block = 0;
        m_commentItem = 0;
    }
}

void ProFileEvaluator::Private::insertVariable(const QString &line, int *i)
{
    ProVariable::VariableOperator opkind;

    switch (m_proitem.at(m_proitem.length() - 1).unicode()) {
        case '+':
            m_proitem.chop(1);
            opkind = ProVariable::AddOperator;
            break;
        case '-':
            m_proitem.chop(1);
            opkind = ProVariable::RemoveOperator;
            break;
        case '*':
            m_proitem.chop(1);
            opkind = ProVariable::UniqueAddOperator;
            break;
        case '~':
            m_proitem.chop(1);
            opkind = ProVariable::ReplaceOperator;
            break;
        default:
            opkind = ProVariable::SetOperator;
    }

    ProBlock *block = m_blockstack.top();
    m_proitem = m_proitem.trimmed();
    ProVariable *variable = new ProVariable(m_proitem, block);
    variable->setLineNumber(m_lineNo);
    variable->setVariableOperator(opkind);
    block->appendItem(variable);
    m_block = variable;

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

    m_proitem.clear();

    if (opkind == ProVariable::ReplaceOperator) {
        // skip util end of line or comment
        while (1) {
            ++(*i);

            // end of line?
            if (*i >= line.count())
                break;

            // comment?
            if (line.at(*i).unicode() == '#') {
                --(*i);
                break;
            }

            m_proitem += line.at(*i);
        }
        m_proitem = m_proitem.trimmed();
    }
}

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

    ProOperator::OperatorKind opkind;
hjk's avatar
hjk committed
401
    switch (op) {
con's avatar
con committed
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
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
466
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
        case '!':
            opkind = ProOperator::NotOperator;
            break;
        case '|':
            opkind = ProOperator::OrOperator;
            break;
        default:
            opkind = ProOperator::OrOperator;
    }

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

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

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

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

    strComment = strComment.trimmed();

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

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

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

    parent->appendItem(block);

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

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

void ProFileEvaluator::Private::leaveScope()
{
    updateItem();
    m_blockstack.pop();
    finalizeBlock();
}

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

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

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

    m_commentItem = m_block;

    return m_block;
}

void ProFileEvaluator::Private::updateItem()
{
    m_proitem = m_proitem.trimmed();
    if (m_proitem.isEmpty())
        return;

    ProBlock *block = currentBlock();
    if (block->blockKind() & ProBlock::VariableKind) {
        m_commentItem = new ProValue(m_proitem, static_cast<ProVariable*>(block));
    } else if (m_proitem.endsWith(QLatin1Char(')'))) {
        m_commentItem = new ProFunction(m_proitem);
    } else {
        m_commentItem = new ProCondition(m_proitem);
    }
    m_commentItem->setLineNumber(m_lineNo);
    block->appendItem(m_commentItem);

    m_proitem.clear();
}


bool ProFileEvaluator::Private::visitBeginProBlock(ProBlock *block)
{
    if (block->blockKind() == ProBlock::ScopeKind) {
        m_invertNext = false;
        m_condition = false;
    }
    return true;
}

bool ProFileEvaluator::Private::visitEndProBlock(ProBlock *block)
{
    Q_UNUSED(block);
    return true;
}

bool ProFileEvaluator::Private::visitBeginProVariable(ProVariable *variable)
{
    m_lastVarName = variable->variable();
    m_variableOperator = variable->variableOperator();
    return true;
}

bool ProFileEvaluator::Private::visitEndProVariable(ProVariable *variable)
{
    Q_UNUSED(variable);
    m_lastVarName.clear();
    return true;
}

bool ProFileEvaluator::Private::visitProOperator(ProOperator *oper)
{
    m_invertNext = (oper->operatorKind() == ProOperator::NotOperator);
    return true;
}

bool ProFileEvaluator::Private::visitProCondition(ProCondition *cond)
{
    if (!m_condition) {
        if (m_invertNext)
            m_condition |= !isActiveConfig(cond->text(), true);
        else
            m_condition |= isActiveConfig(cond->text(), true);
    }
    return true;
}

bool ProFileEvaluator::Private::visitBeginProFile(ProFile * pro)
{
    PRE(pro);
    bool ok = true;
    m_lineNo = pro->lineNumber();

    if (m_origfile.isEmpty())
        m_origfile = pro->fileName();
    if (m_oldPath.isEmpty()) {
        // change the working directory for the initial profile we visit, since
        // that is *the* profile. All the other times we reach this function will be due to
        // include(file) or load(file)

        m_oldPath = QDir::currentPath();

        m_profileStack.push(pro);

575
        const QString mkspecDirectory = propertyValue(QLatin1String("QMAKE_MKSPECS"));
con's avatar
con committed
576
577
578
        if (!mkspecDirectory.isEmpty()) {
            // This is what qmake does, everything set in the mkspec is also set
            // But this also creates a lot of problems
579
580
            evaluateFile(mkspecDirectory + QLatin1String("/default/qmake.conf"), &ok);
            evaluateFile(mkspecDirectory + QLatin1String("/features/default_pre.prf"), &ok);
con's avatar
con committed
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
        }

        QString fn = pro->fileName();
        ok = QDir::setCurrent(QFileInfo(fn).absolutePath());
    }

    return ok;
}

bool ProFileEvaluator::Private::visitEndProFile(ProFile * pro)
{
    PRE(pro);
    bool ok = true;
    m_lineNo = pro->lineNumber();
    if (m_profileStack.count() == 1 && !m_oldPath.isEmpty()) {
596
        const QString &mkspecDirectory = propertyValue(QLatin1String("QMAKE_MKSPECS"));
con's avatar
con committed
597
        if (!mkspecDirectory.isEmpty()) {
598
            evaluateFile(mkspecDirectory + QLatin1String("/features/default_post.prf"), &ok);
con's avatar
con committed
599

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
600
            QSet<QString> processed;
601
            forever {
con's avatar
con committed
602
                bool finished = true;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
603
                QStringList configs = valuesDirect(QLatin1String("CONFIG"));
604
                for (int i = configs.size() - 1; i >= 0; --i) {
con's avatar
con committed
605
                    const QString config = configs[i].toLower();
hjk's avatar
hjk committed
606
                    if (!processed.contains(config)) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
607
                        processed.insert(config);
608
609
                        evaluateFile(mkspecDirectory + QLatin1String("/features/")
                                     + config + QLatin1String(".prf"), &ok);
hjk's avatar
hjk committed
610
                        if (ok) {
con's avatar
con committed
611
612
613
614
615
                            finished = false;
                            break;
                        }
                    }
                }
hjk's avatar
hjk committed
616
                if (finished)
con's avatar
con committed
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
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
708
709
710
711
                    break;
            }
        }

        m_profileStack.pop();
        ok = QDir::setCurrent(m_oldPath);
    }
    return ok;
}

bool ProFileEvaluator::Private::visitProValue(ProValue *value)
{
    PRE(value);
    m_lineNo = value->lineNumber();
    QString val = value->value();

    QString varName = m_lastVarName;

    QStringList v = expandVariableReferences(val);

    // Since qmake combines different values for the TARGET variable, we join
    // TARGET values that are on the same line. We can't do this later with all
    // values because this parser isn't scope-aware, so we'd risk joining
    // scope-specific targets together.
    if (varName == QLatin1String("TARGET")
            && m_lineNo == m_prevLineNo
            && currentProFile() == m_prevProFile) {
        QStringList targets = m_valuemap.value(QLatin1String("TARGET"));
        m_valuemap.remove(QLatin1String("TARGET"));
        QStringList lastTarget(targets.takeLast());
        lastTarget << v.join(QLatin1String(" "));
        targets.push_back(lastTarget.join(QLatin1String(" ")));
        v = targets;
    }
    m_prevLineNo = m_lineNo;
    m_prevProFile = currentProFile();

    // The following two blocks fix bug 180128 by making all "interesting"
    // file name absolute in each .pro file, not just the top most one
    if (varName == QLatin1String("SOURCES")
            || varName == QLatin1String("HEADERS")
            || varName == QLatin1String("INTERFACES")
            || varName == QLatin1String("FORMS")
            || varName == QLatin1String("FORMS3")
            || varName == QLatin1String("RESOURCES")) {
        // matches only existent files, expand certain(?) patterns
        QStringList vv;
        for (int i = v.count(); --i >= 0; )
            vv << expandPattern(v[i]);
        v = vv;
    }

    if (varName == QLatin1String("TRANSLATIONS")) {
        // also matches non-existent files, but does not expand pattern
        QString dir = QFileInfo(currentFileName()).absolutePath();
        dir += QLatin1Char('/');
        for (int i = v.count(); --i >= 0; )
            v[i] = QFileInfo(dir, v[i]).absoluteFilePath();
    }

    switch (m_variableOperator) {
        case ProVariable::UniqueAddOperator:    // *
            insertUnique(&m_valuemap, varName, v, true);
            insertUnique(&m_filevaluemap[currentProFile()], varName, v, true);
            break;
        case ProVariable::SetOperator:          // =
        case ProVariable::AddOperator:          // +
            insertUnique(&m_valuemap, varName, v, false);
            insertUnique(&m_filevaluemap[currentProFile()], varName, v, false);
            break;
        case ProVariable::RemoveOperator:       // -
            // fix me: interaction between AddOperator and RemoveOperator
            insertUnique(&m_valuemap, varName.prepend(QLatin1Char('-')), v, false);
            insertUnique(&m_filevaluemap[currentProFile()],
                         varName.prepend(QLatin1Char('-')), v, false);
            break;
        case ProVariable::ReplaceOperator:      // ~
            {
                // DEFINES ~= s/a/b/?[gqi]

/*              Create a superset by executing replacement + adding items that have changed
                to original list. We're not sure if this is really the right approach, so for
                the time being we will just do nothing ...

                QChar sep = val.at(1);
                QStringList func = val.split(sep);
                if (func.count() < 3 || func.count() > 4) {
                    q->logMessage(format("'~= operator '(function s///) expects 3 or 4 arguments."));
                    return false;
                }
                if (func[0] != QLatin1String("s")) {
                    q->logMessage(format("~= operator can only handle s/// function."));
                    return false;
                }

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
712
                bool global = false, quote = false, case_sense = false;
con's avatar
con 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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
                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);

                QStringList replaceList = replaceInList(m_valuemap.value(varName), regexp, replace,
                                                        global);
                // Add changed entries to list
                foreach (const QString &entry, replaceList)
                    if (!m_valuemap.value(varName).contains(entry))
                        insertUnique(&m_valuemap, varName, QStringList() << entry, false);

                replaceList = replaceInList(m_filevaluemap[currentProFile()].value(varName), regexp,
                                      replace, global);
                foreach (const QString &entry, replaceList)
                    if (!m_filevaluemap[currentProFile()].value(varName).contains(entry))
                        insertUnique(&m_filevaluemap[currentProFile()], varName,
                                     QStringList() << entry, false); */
            }
            break;

    }
    return true;
}

bool ProFileEvaluator::Private::visitProFunction(ProFunction *func)
{
    m_lineNo = func->lineNumber();
    bool result = true;
    bool ok = true;
    QString text = func->text();
    int lparen = text.indexOf(QLatin1Char('('));
    int rparen = text.lastIndexOf(QLatin1Char(')'));
hjk's avatar
hjk committed
753
    QTC_ASSERT(lparen < rparen, return false);
con's avatar
con committed
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108

    QString arguments = text.mid(lparen + 1, rparen - lparen - 1);
    QString funcName = text.left(lparen);
    ok &= evaluateConditionalFunction(funcName.trimmed(), arguments, &result);
    return ok;
}


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

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

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

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

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

QString ProFileEvaluator::Private::getcwd() const
{
    ProFile *cur = m_profileStack.top();
    QFileInfo fi(cur->fileName());
    return fi.absolutePath();
}

QStringList ProFileEvaluator::Private::expandVariableReferences(const QString &str)
{
    bool fOK;
    bool *ok = &fOK;
    QStringList ret;
    if (ok)
        *ok = true;
    if (str.isEmpty())
        return ret;

    const ushort LSQUARE = '[';
    const ushort RSQUARE = ']';
    const ushort LCURLY = '{';
    const ushort RCURLY = '}';
    const ushort LPAREN = '(';
    const ushort RPAREN = ')';
    const ushort DOLLAR = '$';
    const ushort BACKSLASH = '\\';
    const ushort UNDERSCORE = '_';
    const ushort DOT = '.';
    const ushort SPACE = ' ';
    const ushort TAB = '\t';

    const QChar *str_data = str.data();
    const int str_len = str.length();

    ushort term;
    QString var, args;

    int replaced = 0;
    QString current;
    for (int i = 0; i < str_len; ++i) {
        ushort c = str_data[i].unicode();
        const int start_var = i;
        if (c == BACKSLASH) {
            bool escape = false;
            const char *symbols = "[]{}()$\\";
            for (const char *s = symbols; *s; ++s) {
                if (str_data[i+1] == (ushort)*s) {
                    i++;
                    escape = true;
                    if (!(replaced++))
                        current = str.left(start_var);
                    current.append(str.at(i));
                    break;
                }
            }
            if (!escape && replaced)
                current.append(QChar(c));
            continue;
        }
        if (c == SPACE || c == TAB) {
            c = 0;
            if (!current.isEmpty()) {
                unquote(&current);
                ret.append(current);
                current.clear();
            }
        } else if (c == DOLLAR && str_len > i+2) {
            c = str_data[++i].unicode();
            if (c == DOLLAR) {
                term = 0;
                var.clear();
                args.clear();
                enum { VAR, ENVIRON, FUNCTION, PROPERTY } var_type = VAR;
                c = str_data[++i].unicode();
                if (c == LSQUARE) {
                    c = str_data[++i].unicode();
                    term = RSQUARE;
                    var_type = PROPERTY;
                } else if (c == LCURLY) {
                    c = str_data[++i].unicode();
                    var_type = VAR;
                    term = RCURLY;
                } else if (c == LPAREN) {
                    c = str_data[++i].unicode();
                    var_type = ENVIRON;
                    term = RPAREN;
                }
                while (1) {
                    if (!(c & (0xFF<<8)) &&
                       c != DOT && c != UNDERSCORE &&
                       (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9'))
                        break;
                    var.append(QChar(c));
                    if (++i == str_len)
                        break;
                    c = str_data[i].unicode();
                }
                if (var_type == VAR && c == LPAREN) {
                    var_type = FUNCTION;
                    int depth = 0;
                    while (1) {
                        if (++i == str_len)
                            break;
                        c = str_data[i].unicode();
                        if (c == LPAREN) {
                            depth++;
                        } else if (c == RPAREN) {
                            if (!depth)
                                break;
                            --depth;
                        }
                        args.append(QChar(c));
                    }
                    if (i < str_len-1)
                        c = str_data[++i].unicode();
                    else
                        c = 0;
                }
                if (term) {
                    if (c != term) {
                        q->logMessage(format("Missing %1 terminator [found %2]")
                            .arg(QChar(term)).arg(QChar(c)));
                        if (ok)
                            *ok = false;
                        return QStringList();
                    }
                    c = 0;
                } else if (i > str_len-1) {
                    c = 0;
                }

                QStringList replacement;
                if (var_type == ENVIRON) {
                    replacement << QString::fromLocal8Bit(qgetenv(var.toLocal8Bit().constData()));
                } else if (var_type == PROPERTY) {
                    replacement << propertyValue(var);
                    //if (prop)
                    //    replacement = QStringList(prop->value(var));
                } else if (var_type == FUNCTION) {
                    replacement << evaluateExpandFunction(var, args);
                } else if (var_type == VAR) {
                    replacement += values(var);
                }
                if (!(replaced++) && start_var)
                    current = str.left(start_var);
                if (!replacement.isEmpty()) {
                    /* If a list is beteen two strings make sure it expands in such a way
                     * that the string to the left is prepended to the first string and
                     * the string to the right is appended to the last string, example:
                     *  LIST = a b c
                     *  V3 = x/$$LIST/f.cpp
                     *  message($$member(V3,0))     # Outputs "x/a"
                     *  message($$member(V3,1))     # Outputs "b"
                     *  message($$member(V3,2))     # Outputs "c/f.cpp"
                     */
                    current.append(replacement.at(0));
                    for (int i = 1; i < replacement.count(); ++i) {
                        unquote(&current);
                        ret.append(current);
                        current = replacement.at(i);
                    }
                }
            } else {
                if (replaced)
                    current.append(QLatin1Char('$'));
            }
        }
        if (replaced && c != 0)
            current.append(QChar(c));
    }
    if (!replaced) {
        current = str;
        unquote(&current);
        ret.append(current);
    } else if (!current.isEmpty()) {
        unquote(&current);
        ret.append(current);
    }
    return ret;
}

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

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

    QRegExp re(config, Qt::CaseSensitive, QRegExp::Wildcard);
    QString spec = Option::qmakespec;
    if ((regex && re.exactMatch(spec)) || (!regex && spec == config))
        return true;

    return false;
}

QStringList ProFileEvaluator::Private::evaluateExpandFunction(const QString &func, const QString &arguments)
{
    QStringList argumentsList = split_arg_list(arguments);
    QStringList args;
    for (int i = 0; i < argumentsList.count(); ++i)
        args += expandVariableReferences(argumentsList[i]);

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

    static QHash<QString, int> *expands = 0;
    if (!expands) {
        expands = new QHash<QString, int>;
1109
1110
1111
        expands->insert(QLatin1String("member"), E_MEMBER);
        expands->insert(QLatin1String("first"), E_FIRST);
        expands->insert(QLatin1String("last"), E_LAST);
con's avatar
con committed
1112
        expands->insert(QLatin1String("cat"), E_CAT);
1113
        expands->insert(QLatin1String("fromfile"), E_FROMFILE); // implementation disabled (see comment below)
con's avatar
con committed
1114
1115
1116
        expands->insert(QLatin1String("eval"), E_EVAL);
        expands->insert(QLatin1String("list"), E_LIST);
        expands->insert(QLatin1String("sprintf"), E_SPRINTF);
1117
1118
1119
1120
        expands->insert(QLatin1String("join"), E_JOIN);
        expands->insert(QLatin1String("split"), E_SPLIT);
        expands->insert(QLatin1String("basename"), E_BASENAME);
        expands->insert(QLatin1String("dirname"), E_DIRNAME);
con's avatar
con committed
1121
1122
        expands->insert(QLatin1String("section"), E_SECTION);
        expands->insert(QLatin1String("find"), E_FIND);
1123
        expands->insert(QLatin1String("system"), E_SYSTEM);
con's avatar
con committed
1124
        expands->insert(QLatin1String("unique"), E_UNIQUE);
1125
        expands->insert(QLatin1String("quote"), E_QUOTE);
con's avatar
con committed
1126
1127
1128
1129
1130
        expands->insert(QLatin1String("escape_expand"), E_ESCAPE_EXPAND);
        expands->insert(QLatin1String("upper"), E_UPPER);
        expands->insert(QLatin1String("lower"), E_LOWER);
        expands->insert(QLatin1String("re_escape"), E_RE_ESCAPE);
        expands->insert(QLatin1String("files"), E_FILES);
1131
        expands->insert(QLatin1String("prompt"), E_PROMPT); // interactive, so cannot be implemented
con's avatar
con committed
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
        expands->insert(QLatin1String("replace"), E_REPLACE);
    }
    ExpandFunc func_t = ExpandFunc(expands->value(func.toLower()));

    QStringList ret;

    switch (func_t) {
        case E_BASENAME:
        case E_DIRNAME:
        case E_SECTION: {
            bool regexp = false;
            QString sep, var;
            int beg = 0;
            int end = -1;
            if (func_t == E_SECTION) {
                if (args.count() != 3 && args.count() != 4) {
                    q->logMessage(format("%1(var) section(var, sep, begin, end) "
1149
                        "requires three or four arguments.").arg(func));
con's avatar
con committed
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
                } else {
                    var = args[0];
                    sep = args[1];
                    beg = args[2].toInt();
                    if (args.count() == 4)
                        end = args[3].toInt();
                }
            } else {
                if (args.count() != 1) {
                    q->logMessage(format("%1(var) requires one argument.").arg(func));
                } else {
                    var = args[0];
                    regexp = true;
                    sep = QLatin1String("[\\\\/]");
                    if (func_t == E_DIRNAME)
                        end = -2;
                    else
                        beg = -1;
                }
            }
            if (!var.isNull()) {
                foreach (const QString str, values(var)) {
                    if (regexp)
                        ret += str.section(QRegExp(sep), beg, end);
                    else
                        ret += str.section(sep, beg, end);
                }
            }
            break;
        }
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
        case E_SPRINTF:
            if(args.count() < 1) {
                q->logMessage(format("sprintf(format, ...) requires at least one argument"));
            } else {
                QString tmp = args.at(0);
                for (int i = 1; i < args.count(); ++i)
                    tmp = tmp.arg(args.at(i));
                ret = split_value_list(tmp);
            }
            break;
con's avatar
con committed
1190
1191
        case E_JOIN: {
            if (args.count() < 1 || args.count() > 4) {
1192
                q->logMessage(format("join(var, glue, before, after) requires one to four arguments."));
con's avatar
con committed
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
            } else {
                QString glue, before, after;
                if (args.count() >= 2)
                    glue = args[1];
                if (args.count() >= 3)
                    before = args[2];
                if (args.count() == 4)
                    after = args[3];
                const QStringList &var = values(args.first());
                if (!var.isEmpty())
                    ret.append(before + var.join(glue) + after);
            }
            break;
        }
        case E_SPLIT: {
1208
            if (args.count() != 2) {
1209
                q->logMessage(format("split(var, sep) requires one or two arguments"));
con's avatar
con committed
1210
            } else {
1211
                const QString &sep = (args.count() == 2) ? args[1] : QString(Option::field_sep);
con's avatar
con committed
1212
1213
1214
1215
1216
1217
1218
1219
                foreach (const QString &var, values(args.first()))
                    foreach (const QString &splt, var.split(sep))
                        ret.append(splt);
            }
            break;
        }
        case E_MEMBER: {
            if (args.count() < 1 || args.count() > 3) {
1220
                q->logMessage(format("member(var, start, end) requires one to three arguments."));
con's avatar
con committed
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
            } else {
                bool ok = true;
                const QStringList var = values(args.first());
                int start = 0, end = 0;
                if (args.count() >= 2) {
                    QString start_str = args[1];
                    start = start_str.toInt(&ok);
                    if (!ok) {
                        if (args.count() == 2) {
                            int dotdot = start_str.indexOf(QLatin1String(".."));
                            if (dotdot != -1) {
                                start = start_str.left(dotdot).toInt(&ok);
                                if (ok)
                                    end = start_str.mid(dotdot+2).toInt(&ok);
                            }
                        }
                        if (!ok)
                            q->logMessage(format("member() argument 2 (start) '%2' invalid.")
                                .arg(start_str));
                    } else {
                        end = start;
                        if (args.count() == 3)
                            end = args[2].toInt(&ok);
                        if (!ok)
                            q->logMessage(format("member() argument 3 (end) '%2' invalid.\n")
                                .arg(args[2]));
                    }
                }
                if (ok) {
                    if (start < 0)
                        start += var.count();
                    if (end < 0)
                        end += var.count();
                    if (start < 0 || start >= var.count() || end < 0 || end >= var.count()) {
                        //nothing
                    } else if (start < end) {
                        for (int i = start; i <= end && var.count() >= i; i++)
                            ret.append(var[i]);
                    } else {
                        for (int i = start; i >= end && var.count() >= i && i >= 0; i--)
                            ret += var[i];
                    }
                }
            }
            break;
        }
        case E_FIRST:
        case E_LAST: {
            if (args.count() != 1) {
                q->logMessage(format("%1(var) requires one argument.").arg(func));
            } else {
                const QStringList var = values(args.first());
                if (!var.isEmpty()) {
                    if (func_t == E_FIRST)
                        ret.append(var[0]);
                    else
                        ret.append(var.last());
                }
            }
            break;
        }
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
        case E_CAT:
            if (args.count() < 1 || args.count() > 2) {
                q->logMessage(format("cat(file, singleline=true) requires one or two arguments."));
            } else {
                QString file = args[0];
                file = Option::fixPathToLocalOS(file);

                bool singleLine = true;
                if (args.count() > 1)
                    singleLine = (args[1].toLower() == QLatin1String("true"));

                QFile qfile(file);
                if (qfile.open(QIODevice::ReadOnly)) {
                    QTextStream stream(&qfile);
                    while (!stream.atEnd()) {
                        ret += split_value_list(stream.readLine().trimmed());
                        if (!singleLine)
                            ret += QLatin1String("\n");
                    }
                    qfile.close();
                }
            }
            break;
#if 0 // Used only by Qt's configure for caching
        case E_FROMFILE:
            if (args.count() != 2) {
                q->logMessage(format("fromfile(file, variable) requires two arguments."));
            } else {
                QString file = args[0], seek_variableName = args[1];

                ProFile pro(Option::fixPathToLocalOS(file));

                ProFileEvaluator visitor;
                visitor.setVerbose(m_verbose);
                visitor.setCumulative(m_cumulative);

                if (!visitor.queryProFile(&pro))
                    break;

                if (!visitor.accept(&pro))
                    break;

                ret = visitor.values(seek_variableName);
            }
            break;
#endif
        case E_EVAL: {
            if (args.count() != 1) {
                q->logMessage(format("eval(variable) requires one argument"));

            } else {
                ret += values(args.at(0));
            }
            break; }
        case E_LIST: {
            static int x = 0;
            QString tmp;
            tmp.sprintf(".QMAKE_INTERNAL_TMP_variableName_%d", x++);
            ret = QStringList(tmp);
            QStringList lst;
            foreach (const QString &arg, args)
                lst += split_value_list(arg);
            m_valuemap[tmp] = lst;
            break; }
        case E_FIND:
            if (args.count() != 2) {
                q->logMessage(format("find(var, str) requires two arguments."));
            } else {
                QRegExp regx(args[1]);
                foreach (const QString &val, values(args.first()))
                    if (regx.indexIn(val) != -1)
                        ret += val;
            }
            break;
#if 0 // Disabled, as it is relatively useless, too slow and dangerous.
        case E_SYSTEM:
            if (!m_skipLevel) { // FIXME: should exec only if the result is being used
                                // (i.e., if this is nested into an assignment) - these
                                // are less likely to have side effects
con's avatar
con committed
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
                if (args.count() < 1 || args.count() > 2) {
                    q->logMessage(format("system(execute) requires one or two arguments."));
                } else {
                    char buff[256];
                    FILE *proc = QT_POPEN(args[0].toLatin1(), "r");
                    bool singleLine = true;
                    if (args.count() > 1)
                        singleLine = (args[1].toLower() == QLatin1String("true"));
                    QString output;
                    while (proc && !feof(proc)) {
                        int read_in = int(fread(buff, 1, 255, proc));
                        if (!read_in)
                            break;
                        for (int i = 0; i < read_in; i++) {
                            if ((singleLine && buff[i] == '\n') || buff[i] == '\t')
                                buff[i] = ' ';
                        }
                        buff[read_in] = '\0';
                        output += QLatin1String(buff);
                    }
                    ret += split_value_list(output);
                }
            }
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
            break;
#endif
        case E_UNIQUE:
            if(args.count() != 1) {
                q->logMessage(format("unique(var) requires one argument."));
            } else {
                foreach (const QString &var, values(args.first()))
                    if (!ret.contains(var))
                        ret.append(var);
            }
            break;
con's avatar
con committed
1395
1396
1397
1398
        case E_QUOTE:
            for (int i = 0; i < args.count(); ++i)
                ret += QStringList(args.at(i));
            break;
1399
1400
1401
1402
1403
1404
1405
1406
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
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
        case E_ESCAPE_EXPAND:
            for (int i = 0; i < args.size(); ++i) {
                QChar *i_data = args[i].data();
                int i_len = args[i].length();
                for (int x = 0; x < i_len; ++x) {
                    if (*(i_data+x) == QLatin1Char('\\') && x < i_len-1) {
                        if (*(i_data+x+1) == QLatin1Char('\\')) {
                            ++x;
                        } else {
                            struct {
                                char in, out;
                            } mapped_quotes[] = {
                                { 'n', '\n' },
                                { 't', '\t' },
                                { 'r', '\r' },
                                { 0, 0 }
                            };
                            for (int i = 0; mapped_quotes[i].in; ++i) {
                                if (*(i_data+x+1) == QLatin1Char(mapped_quotes[i].in)) {
                                    *(i_data+x) = QLatin1Char(mapped_quotes[i].out);
                                    if (x < i_len-2)
                                        memmove(i_data+x+1, i_data+x+2, (i_len-x-2)*sizeof(QChar));
                                    --i_len;
                                    break;
                                }
                            }
                        }
                    }
                }
                ret.append(QString(i_data, i_len));
            }
            break;
        case E_RE_ESCAPE:
            for (int i = 0; i < args.size(); ++i)
                ret += QRegExp::escape(args[i]);
            break;
        case E_UPPER:
        case E_LOWER:
            for (int i = 0; i < args.count(); ++i)
                if (func_t == E_UPPER)
                    ret += args[i].toUpper();
                else
                    ret += args[i].toLower();
            break;
        case E_FILES:
            if (args.count() != 1 && args.count() != 2) {
                q->logMessage(format("files(pattern, recursive=false) requires one or two arguments"));
            } else {
                bool recursive = false;
                if (args.count() == 2)
                    recursive = (args[1].toLower() == QLatin1String("true") || args[1].toInt());
                QStringList dirs;
                QString r = Option::fixPathToLocalOS(args[0]);
                int slash = r.lastIndexOf(QDir::separator());
                if (slash != -1) {
                    dirs.append(r.left(slash));
                    r = r.mid(slash+1);
                } else {
                    dirs.append(QString());
                }

                const QRegExp regex(r, Qt::CaseSensitive, QRegExp::Wildcard);
                for (int d = 0; d < dirs.count(); d++) {
                    QString dir = dirs[d];
                    if (!dir.isEmpty() && !dir.endsWith(Option::dir_sep))
                        dir += QLatin1Char('/');

                    QDir qdir(dir);
                    for (int i = 0; i < (int)qdir.count(); ++i) {
                        if (qdir[i] == QLatin1String(".") || qdir[i] == QLatin1String(".."))
                            continue;
                        QString fname = dir + qdir[i];
                        if (QFileInfo(fname).isDir()) {
                            if (recursive)
                                dirs.append(fname);
                        }
                        if (regex.exactMatch(qdir[i]))
                            ret += fname;
                    }
                }
            }
            break;
        case E_REPLACE:
            if(args.count() != 3 ) {
                q->logMessage(format("replace(var, before, after) requires three arguments"));
            } else {
                const QRegExp before(args[1]);
                const QString after(args[2]);
                foreach (QString val, values(args.first()))
                    ret += val.replace(before, after);
            }
            break;
con's avatar
con committed
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
        case 0:
            q->logMessage(format("'%1' is not a function").arg(func));
            break;
        default:
            q->logMessage(format("Function '%1' is not implemented").arg(func));
            break;
    }

    return ret;
}

bool ProFileEvaluator::Private::evaluateConditionalFunction(const QString &function,
    const QString &arguments, bool *result)
{
    QStringList argumentsList = split_arg_list(arguments);
    QString sep;
    sep.append(Option::field_sep);

    QStringList args;
    for (int i = 0; i < argumentsList.count(); ++i)
        args += expandVariableReferences(argumentsList[i]).join(sep);

    enum ConditionFunc { CF_CONFIG = 1, CF_CONTAINS, CF_COUNT, CF_EXISTS, CF_INCLUDE,
        CF_LOAD, CF_ISEMPTY, CF_SYSTEM, CF_MESSAGE};

    static QHash<QString, int> *functions = 0;
    if (!functions) {
        functions = new QHash<QString, int>;
        functions->insert(QLatin1String("load"), CF_LOAD);         //v
        functions->insert(QLatin1String("include"), CF_INCLUDE);   //v
        functions->insert(QLatin1String("message"), CF_MESSAGE);   //v
        functions->insert(QLatin1String("warning"), CF_MESSAGE);   //v
        functions->insert(QLatin1String("error"), CF_MESSAGE);     //v
    }

    bool cond = false;
    bool ok = true;

    ConditionFunc func_t = (ConditionFunc)functions->value(function);

    switch (func_t) {
        case CF_CONFIG: {
            if (args.count() < 1 || args.count() > 2) {
                q->logMessage(format("CONFIG(config) requires one or two arguments."));
                ok = false;
                break;
            }
            if (args.count() == 1) {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1539
                //cond = isActiveConfig(args.first()); XXX
con's avatar
con committed
1540
1541
1542
                break;
            }
            const QStringList mutuals = args[1].split(QLatin1Char('|'));
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
1543
            const QStringList &configs = valuesDirect(QLatin1String("CONFIG"));
con's avatar
con committed
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
            for (int i = configs.size() - 1 && ok; i >= 0; i--) {
                for (int mut = 0; mut < mutuals.count(); mut++) {
                    if (configs[i] == mutuals[mut].trimmed()) {
                        cond = (configs[i] == args[0]);
                        break;
                    }
                }
            }
            break;
        }
        case CF_CONTAINS: {
            if (args.count() < 2 || args.count() > 3) {
1556
                q->logMessage(format("contains(var, val) requires two or three arguments."));
con's avatar
con committed
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
                ok = false;
                break;
            }

            QRegExp regx(args[1]);
            const QStringList &l = values(args.first());
            if (args.count() == 2) {
                for (int i = 0; i < l.size(); ++i) {
                    const QString val = l[i];
                    if (regx.exactMatch(val) || val == args[1]) {
                        cond = true;
                        break;
                    }
                }
            } else {
                const QStringList mutuals = args[2].split(QLatin1Char('|'));
                for (int i = l.size() - 1; i >= 0; i--) {
                    const QString val = l[i];
                    for (int mut = 0; mut < mutuals.count(); mut++) {
                        if (val == mutuals[mut].trimmed()) {
                            cond = (regx.exactMatch(val) || val == args[1]);
                            break;
                        }
                    }
                }
            }

            break;
        }
        case CF_COUNT: {
            if (args.count() != 2 && args.count() != 3) {
1588
                q->logMessage(format("count(var, count) requires two or three arguments."));
con's avatar
con committed
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
                ok = false;
                break;
            }
            if (args.count() == 3) {
                QString comp = args[2];
                if (comp == QLatin1String(">") || comp == QLatin1String("greaterThan")) {
                    cond = values(args.first()).count() > args[1].toInt();
                } else if (comp == QLatin1String(">=")) {
                    cond = values(args.first()).count() >= args[1].toInt();
                } else if (comp == QLatin1String("<") || comp == QLatin1String("lessThan")) {
                    cond = values(args.first()).count() < args[1].toInt();
                } else if (comp == QLatin1String("<=")) {
                    cond = values(args.first()).count() <= args[1].toInt();
                } else if (comp == QLatin1String("equals") || comp == QLatin1String("isEqual") || comp == QLatin1String("=") || comp == QLatin1String("==")) {
                    cond = values(args.first()).count() == args[1].toInt();
                } else {
                    ok = false;
                    q->logMessage(format("unexpected modifier to count(%2)").arg(comp));
                }
                break;
            }
            cond = values(args.first()).count() == args[1].toInt();
            break;
        }
        case CF_INCLUDE: {
            QString parseInto;
            if (args.count() == 2) {
                parseInto = args[1];
            } else if (args.count() != 1) {
1618
                q->logMessage(format("include(file) requires one or two arguments."));
con's avatar
con committed
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
                ok = false;
                break;
            }
            QString fileName = args.first();
            // ### this breaks if we have include(c:/reallystupid.pri) but IMHO that's really bad style.
            QDir currentProPath(getcwd());
            fileName = QDir::cleanPath(currentProPath.absoluteFilePath(fileName));
            ok = evaluateFile(fileName, &ok);
            break;
        }
        case CF_LOAD: {
            QString parseInto;
            bool ignore_error = false;
            if (args.count() == 2) {
                QString sarg = args[1];
                ignore_error = (sarg.toLower() == QLatin1String("true") || sarg.toInt());
            } else if (args.count() != 1) {
1636
                q->logMessage(format("load(feature) requires one or two arguments."));
con's avatar
con committed
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
                ok = false;
                break;
            }
            ok = evaluateFeatureFile( args.first(), &cond);
            break;
        }
        case CF_MESSAGE: {
            if (args.count() != 1) {
                q->logMessage(format("%1(message) requires one argument.").arg(function));
                ok = false;
                break;
            }
            QString msg = args.first();
            if (function == QLatin1String("error")) {
                QStringList parents;
                foreach (ProFile *proFile, m_profileStack)
                    parents.append(proFile->fileName());
                if (!parents.isEmpty())
                    parents.takeLast();
                if (parents.isEmpty()) 
                    q->fileMessage(format("Project ERROR: %1").arg(msg));
                else
                    q->fileMessage(format("Project ERROR: %1. File was included from: '%2'")
                        .arg(msg).arg(parents.join(QLatin1String("', '"))));
            } else {
                q->fileMessage(format("Project MESSAGE: %1").arg(msg));
            }
            break;
        }
        case CF_SYSTEM: {
            if (args.count() != 1) {
                q->logMessage(format("system(exec) requires one argument."));
                ok = false;
                break;
            }
            ok = system(args.first().toLatin1().constData()) == 0;
            break;
        }
        case CF_ISEMPTY: {
            if (args.count() != 1) {
                q->logMessage(format("isEmpty(var) requires one argument."));
                ok = false;
                break;
            }
            QStringList sl = values(args.first());
            if (sl.count() == 0) {
                cond = true;
            } else if (sl.count() > 0) {
                QString var = sl.first();
                cond = (var.isEmpty());
            }
            break;
        }
        case CF_EXISTS: {
            if (args.count() != 1) {
                q->logMessage(format("exists(file) requires one argument."));
                ok = false;
                break;
            }
            QString file = args.first();
1697
            file = Option::fixPathToLocalOS(file);
con's avatar
con committed
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721

            if (QFile::exists(file)) {
                cond = true;
                break;
            }
            //regular expression I guess
            QString dirstr = getcwd();
            int slsh = file.lastIndexOf(Option::dir_sep);
            if (slsh != -1) {
                dirstr = file.left(slsh+1);
                file = file.right(file.length() - slsh - 1);
            }
            cond = QDir(dirstr).entryList(QStringList(file)).count();

            break;
        }
    }

    if (result)
        *result = cond;

    return ok;
}

1722
1723
1724
QStringList ProFileEvaluator::Private::values(const QString &variableName,
                                              const QHash<QString, QStringList> &place,
                                              const ProFile *pro) const
con's avatar
con committed
1725
{
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
    if (variableName == QLatin1String("LITERAL_WHITESPACE")) //a real space in a token
        return QStringList(QLatin1String("\t"));
    if (variableName == QLatin1String("LITERAL_DOLLAR")) //a real $
        return QStringList(QLatin1String("$"));
    if (variableName == QLatin1String("LITERAL_HASH")) //a real #
        return QStringList(QLatin1String("#"));
    if (variableName == QLatin1String("OUT_PWD")) //the out going dir
        return QStringList(m_outputDir);
    if (variableName == QLatin1String("PWD") ||  //current working dir (of _FILE_)
        variableName == QLatin1String("IN_PWD"))
con's avatar
con committed
1736
        return QStringList(getcwd());
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
    if (variableName == QLatin1String("DIR_SEPARATOR"))
        return QStringList(Option::dir_sep);
    if (variableName == QLatin1String("DIRLIST_SEPARATOR"))
        return QStringList(Option::dirlist_sep);
    if (variableName == QLatin1String("_LINE_")) //parser line number
        return QStringList(QString::number(m_lineNo));
    if (variableName == QLatin1String("_FILE_")) //parser file; qmake is a bit weird here
        return QStringList(m_profileStack.size() == 1 ? pro->fileName() : QFileInfo(pro->fileName()).fileName());
    if (variableName == QLatin1String("_DATE_")) //current date/time
        return QStringList(QDateTime::currentDateTime().toString());
    if (variableName == QLatin1String("_PRO_FILE_"))
        return QStringList(m_origfile);
    if (variableName == QLatin1String("_PRO_FILE_PWD_"))
        return  QStringList(QFileInfo(m_origfile).absolutePath());
    if (variableName == QLatin1String("_QMAKE_CACHE_"))
        return QStringList(); // FIXME?
    if (variableName.startsWith(QLatin1String("QMAKE_HOST."))) {
        QString ret, type = variableName.mid(11);
#if defined(Q_OS_WIN32)
        if (type == QLatin1String("os")) {
            ret = QLatin1String("Windows");
        } else if (type == QLatin1String("name")) {
            DWORD name_length = 1024;
            TCHAR name[1024];
            if (GetComputerName(name, &name_length))
                ret = QString::fromUtf16((ushort*)name, name_length);
        } else if (type == QLatin1String("version") || type == QLatin1String("version_string")) {
            QSysInfo::WinVersion ver = QSysInfo::WindowsVersion;
            if (type == QLatin1String("version"))
                ret = QString::number(ver);
            else if (ver == QSysInfo::WV_Me)
                ret = QLatin1String("WinMe");
            else if (ver == QSysInfo::WV_95)
                ret = QLatin1String("Win95");
            else if (ver == QSysInfo::WV_98)
                ret = QLatin1String("Win98");
            else if (ver == QSysInfo::WV_NT)
                ret = QLatin1String("WinNT");
            else if (ver == QSysInfo::WV_2000)
                ret = QLatin1String("Win2000");
            else if (ver == QSysInfo::WV_2000)
                ret = QLatin1String("Win2003");
            else if (ver == QSysInfo::WV_XP)
                ret = QLatin1String("WinXP");
            else if (ver == QSysInfo::WV_VISTA)
                ret = QLatin1String("WinVista");
            else
                ret = QLatin1String("Unknown");
        } else if (type == QLatin1String("arch")) {
            SYSTEM_INFO info;
            GetSystemInfo(&info);
            switch(info.wProcessorArchitecture) {
#ifdef PROCESSOR_ARCHITECTURE_AMD64
            case PROCESSOR_ARCHITECTURE_AMD64:
                ret = QLatin1String("x86_64");
                break;
#endif
            case PROCESSOR_ARCHITECTURE_INTEL:
                ret = QLatin1String("x86");
                break;
            case PROCESSOR_ARCHITECTURE_IA64:
#ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64
            case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
#endif
                ret = QLatin1String("IA64");
                break;
            default:
                ret = QLatin1String("Unknown");
                break;
            }
        }
#elif defined(Q_OS_UNIX)
        struct utsname name;
        if (!uname(&name)) {
            if (type == QLatin1String("os"))
                ret = QString::fromLatin1(name.sysname);
            else if (type == QLatin1String("name"))
                ret = QString::fromLatin1(name.nodename);
            else if (type == QLatin1String("version"))
                ret = QString::fromLatin1(name.release);
            else if (type == QLatin1String("version_string"))
                ret = QString::fromLatin1(name.version);
            else if (type == QLatin1String("arch"))
                ret = QString::fromLatin1(name.machine);
        }
#endif
        return QStringList(ret);
    }

    QStringList result = place[variableName];
    if (result.isEmpty()) {
        if (variableName == QLatin1String("TARGET")) {
            result.append(QFileInfo(m_origfile).baseName());
        } else if (variableName == QLatin1String("TEMPLATE")) {
            result.append(QLatin1String("app"));
        } else if (variableName == QLatin1String("QMAKE_DIR_SEP")) {
            result.append(Option::dirlist_sep);
        }
con's avatar
con committed
1835
    }
1836
1837
1838
1839
1840
1841
    return result;
}

QStringList ProFileEvaluator::Private::values(const QString &variableName) const
{
    return values(variableName, m_valuemap, currentProFile());
con's avatar
con committed
1842
1843
1844
1845
}

QStringList ProFileEvaluator::Private::values(const QString &variableName, const ProFile *pro) const
{
1846
    return values(variableName, m_filevaluemap[pro], pro);
con's avatar
con committed
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
}

ProFile *ProFileEvaluator::parsedProFile(const QString &fileName)
{
    QFileInfo fi(fileName);
    if (fi.exists()) {
        ProFile *pro = new ProFile(fi.absoluteFilePath());
        if (d->read(pro))
            return pro;
        delete pro;
    }
    return 0;
}

void ProFileEvaluator::releaseParsedProFile(ProFile *proFile)
{
    delete proFile;
}

bool ProFileEvaluator::Private::evaluateFile(const QString &fileName, bool *result)
{
    bool ok = true;
    ProFile *pro = q->parsedProFile(fileName);
    if (pro) {
        m_profileStack.push(pro);
        ok = (currentProFile() ? pro->Accept(this) : false);
dt's avatar
dt committed
1873
1874
1875
        m_profileStack.pop();
        q->releaseParsedProFile(pro);

con's avatar
con committed
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
        if (result)
            *result = true;
    } else {
        if (result)
            *result = false;
    }
/*    if (ok && readFeatures) {
        QStringList configs = values("CONFIG");
        QSet<QString> processed;
        foreach (const QString &fn, configs) {
            if (!processed.contains(fn)) {
                processed.insert(fn);
                evaluateFeatureFile(fn, 0);
            }
        }
    } */

    return ok;
}

bool ProFileEvaluator::Private::evaluateFeatureFile(const QString &fileName, bool *result)
{
    QString fn;
    foreach (const QString &path, qmakeFeaturePaths()) {
        QString fname = path + QLatin1Char('/') + fileName;
        if (QFileInfo(fname).exists()) {
            fn = fname;
            break;
        }
        fname += QLatin1String(".prf");
        if (QFileInfo(fname).exists()) {
            fn = fname;
            break;
        }
    }
    return fn.isEmpty() ? false : evaluateFile(fn, result);
}

void ProFileEvaluator::Private::expandPatternHelper(const QString &relName, const QString &absName,
        QStringList &sources_out)
{
    const QStringList vpaths = values(QLatin1String("VPATH"))
        + values(QLatin1String("QMAKE_ABSOLUTE_SOURCE_PATH"))
        + values(QLatin1String("DEPENDPATH"))
        + values(QLatin1String("VPATH_SOURCES"));

    QFileInfo fi(absName);
    bool found = fi.exists();
    // Search in all vpaths
    if (!found) {
        foreach (const QString &vpath, vpaths) {
            fi.setFile(vpath + QDir::separator() + relName);
            if (fi.exists()) {
                found = true;
                break;
            }
        }
    }

    if (found) {
        sources_out += fi.absoluteFilePath(); // Not resolving symlinks
    } else {
        QString val = relName;
        QString dir;
        QString wildcard = val;
        QString real_dir;
        if (wildcard.lastIndexOf(QLatin1Char('/')) != -1) {
            dir = wildcard.left(wildcard.lastIndexOf(QLatin1Char('/')) + 1);
            real_dir = dir;
            wildcard = wildcard.right(wildcard.length() - dir.length());
        }

        if (real_dir.isEmpty() || QFileInfo(real_dir).exists()) {
            QStringList files = QDir(real_dir).entryList(QStringList(wildcard));
            if (files.isEmpty()) {
                q->logMessage(format("Failure to find %1").arg(val));
            } else {
                QString a;
                for (int i = files.count() - 1; i >= 0; --i) {
                    if (files[i] == QLatin1String(".") || files[i] == QLatin1String(".."))
                        continue;
                    a = dir + files[i];
                    sources_out += a;
                }
            }
        } else {
            q->logMessage(format("Cannot match %1/%2, as %3 does not exist.")
                .arg(real_dir).arg(wildcard).arg(real_dir));
        }
    }
}


/*
 * Lookup of files are done in this order:
 *  1. look in pwd
 *  2. look in vpaths
 *  3. expand wild card files relative from the profiles folder
 **/

// FIXME: This code supports something that I'd consider a flaw in .pro file syntax
// which is not even documented. So arguably this can be ditched completely...
QStringList ProFileEvaluator::Private::expandPattern(const QString& pattern)
{
    if (!currentProFile())
        return QStringList();

    QStringList sources_out;
    const QString absName = QDir::cleanPath(QDir::current().absoluteFilePath(pattern));

    expandPatternHelper(pattern, absName, sources_out);
    return sources_out;
}

QString ProFileEvaluator::Private::format(const char *fmt) const
{
    ProFile *pro = currentProFile();
    QString fileName = pro ? pro->fileName() : QLatin1String("Not a file");
    int lineNumber = pro ? m_lineNo : 0;
    return QString::fromLatin1("%1(%2):").arg(fileName).arg(lineNumber) + QString::fromAscii(fmt);
}


///////////////////////////////////////////////////////////////////////
//
// ProFileEvaluator
//
///////////////////////////////////////////////////////////////////////

ProFileEvaluator::ProFileEvaluator()
  : d(new Private(this))
{
    Option::init();
}

ProFileEvaluator::~ProFileEvaluator()
{
    delete d;
}

bool ProFileEvaluator::contains(const QString &variableName) const
{
    return d->m_valuemap.contains(variableName);
}

QStringList ProFileEvaluator::values(const QString &variableName) const
{
    return d->values(variableName);
}

QStringList ProFileEvaluator::values(const QString &variableName, const ProFile *pro) const
{
    return d->values(variableName, pro);
}

ProFileEvaluator::TemplateType ProFileEvaluator::templateType()
{
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
2033
    QStringList templ = values(QLatin1String("TEMPLATE"));
con's avatar
con committed
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
    if (templ.count() >= 1) {
        QString t = templ.last().toLower();
        if (t == QLatin1String("app"))
            return TT_Application;
        if (t == QLatin1String("lib"))
            return TT_Library;
        if (t == QLatin1String("script"))
            return TT_Script;
        if (t == QLatin1String("subdirs"))
            return TT_Subdirs;
    }
    return TT_Unknown;
}

bool ProFileEvaluator::queryProFile(ProFile *pro)
{
    return d->read(pro);
}

bool ProFileEvaluator::accept(ProFile *pro)
{
    return pro->Accept(d);
}

QString ProFileEvaluator::propertyValue(const QString &name) const
{
    return d->propertyValue(name);
}

namespace {
    template<class K, class T> void insert(QHash<K,T> *out, const QHash<K,T> &in)
    {
        typename QHash<K,T>::const_iterator i = in.begin();
        while (i != in.end()) {
            out->insert(i.key(), i.value());
            ++i;
        }
    }
} // anon namespace

void ProFileEvaluator::addVariables(const QHash<QString, QStringList> &variables)
{
    insert(&(d->m_valuemap), variables);
}

void ProFileEvaluator::addProperties(const QHash<QString, QString> &properties)
{
    insert(&(d->m_properties), properties);
}

void ProFileEvaluator::logMessage(const QString &message)
{
    if (d->m_verbose)
        qWarning("%s", qPrintable(message));
}

void ProFileEvaluator::fileMessage(const QString &message)
{
    qWarning("%s", qPrintable(message));
}

void ProFileEvaluator::errorMessage(const QString &message)
{
    qWarning("%s", qPrintable(message));
}

// This function is unneeded and still retained. See log message for reason.
QStringList ProFileEvaluator::absFileNames(const QString &variableName)
{
    QStringList sources_out;
    QFileInfo fi(d->m_origfile);
    QDir dir(fi.absoluteDir());
    foreach (const QString &fn, values(variableName)) {
        const QString absName = QDir::cleanPath(dir.absoluteFilePath(fn));
        d->expandPatternHelper(fn, absName, sources_out);
    }

    return sources_out;
}

void ProFileEvaluator::setVerbose(bool on)
{
    d->m_verbose = on;
}

2119
2120
2121
2122
2123
void ProFileEvaluator::setOutputDir(const QString &dir)
{
    d->m_outputDir = dir;
}

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
2124
void evaluateProFile(const ProFileEvaluator &visitor, QHash<QByteArray, QStringList> *varMap)
con's avatar
con committed
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
{
    QStringList sourceFiles;
    QString codecForTr;
    QString codecForSource;
    QStringList tsFileNames;

    // app/lib template
    sourceFiles += visitor.values(QLatin1String("SOURCES"));
    sourceFiles += visitor.values(QLatin1String("HEADERS"));
    tsFileNames = visitor.values(QLatin1String("TRANSLATIONS"));
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
2135

con's avatar
con committed
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
    QStringList trcodec = visitor.values(QLatin1String("CODEC"))
        + visitor.values(QLatin1String("DEFAULTCODEC"))
        + visitor.values(QLatin1String("CODECFORTR"));
    if (!trcodec.isEmpty())
        codecForTr = trcodec.last();

    QStringList srccodec = visitor.values(QLatin1String("CODECFORSRC"));
    if (!srccodec.isEmpty())
        codecForSource = srccodec.last();

    QStringList forms = visitor.values(QLatin1String("INTERFACES"))
        + visitor.values(QLatin1String("FORMS"))
        + visitor.values(QLatin1String("FORMS3"));
    sourceFiles << forms;

#if QT_VERSION >= 0x040500
    sourceFiles.sort();
    sourceFiles.removeDuplicates();
    tsFileNames.sort();
    tsFileNames.removeDuplicates();
#else
    sourceFiles = sourceFiles.toSet().toList();
    sourceFiles.sort();
    tsFileNames = tsFileNames.toSet().toList();
    tsFileNames.sort();
#endif

    varMap->insert("SOURCES", sourceFiles);
    varMap->insert("CODECFORTR", QStringList() << codecForTr);
    varMap->insert("CODECFORSRC", QStringList() << codecForSource);
    varMap->insert("TRANSLATIONS", tsFileNames);
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
}

bool evaluateProFile(const QString &fileName, bool verbose, QHash<QByteArray, QStringList> *varMap)
{
    QFileInfo fi(fileName);
    if (!fi.exists())
        return false;

    ProFile pro(fi.absoluteFilePath());

    ProFileEvaluator visitor;
    visitor.setVerbose(verbose);

    if (!visitor.queryProFile(&pro))
        return false;

    if (!visitor.accept(&pro))
        return false;

    evaluateProFile(visitor, varMap);

con's avatar
con committed
2188
2189
2190
2191
    return true;
}

QT_END_NAMESPACE