1
/****************************************************************************
2
**
3
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4
** Contact: Nokia Corporation (qt-info@nokia.com)
5
**
6
** This file is part of the qmake application of the Qt Toolkit.
7
**
8
** $QT_BEGIN_LICENSE:LGPL$
9
** No Commercial Usage
10
** This file contains pre-release code and may not be distributed.
11
** You may use this file in accordance with the terms and conditions
12
** contained in the either Technology Preview License Agreement or the
13
** Beta Release License Agreement.
14
**
15
** GNU Lesser General Public License Usage
16
** Alternatively, this file may be used under the terms of the GNU Lesser
17
** General Public License version 2.1 as published by the Free Software
18
** Foundation and appearing in the file LICENSE.LGPL included in the
19
** packaging of this file.  Please review the following information to
20
** ensure the GNU Lesser General Public License version 2.1 requirements
21
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22
**
23
** In addition, as a special exception, Nokia gives you certain
24
** additional rights. These rights are described in the Nokia Qt LGPL
25
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26
** package.
27
**
28
** GNU General Public License Usage
29
** Alternatively, this file may be used under the terms of the GNU
30
** General Public License version 3.0 as published by the Free Software
31
** Foundation and appearing in the file LICENSE.GPL included in the
32
** packaging of this file.  Please review the following information to
33
** ensure the GNU General Public License version 3.0 requirements will be
34
** met: http://www.gnu.org/copyleft/gpl.html.
35
**
36
** If you are unsure which license is appropriate for your use, please
37
** contact the sales department at http://www.qtsoftware.com/contact.
38
** $QT_END_LICENSE$
39
**
40
****************************************************************************/
41
42
#include "project.h"
43
#include "property.h"
44
#include "option.h"
45
#include "cachekeys.h"
46
47
#include <qdatetime.h>
48
#include <qfile.h>
49
#include <qfileinfo.h>
50
#include <qdir.h>
51
#include <qregexp.h>
52
#include <qtextstream.h>
53
#include <qstack.h>
54
#include <qhash.h>
55
#include <qdebug.h>
56
#ifdef Q_OS_UNIX
57
#include <unistd.h>
58
#include <sys/utsname.h>
59
#elif defined(Q_OS_WIN32)
60
#include <windows.h>
61
#endif
62
#include <stdio.h>
63
#include <stdlib.h>
64
65
#ifdef Q_OS_WIN32
66
#define QT_POPEN _popen
67
#define QT_PCLOSE _pclose
68
#else
69
#define QT_POPEN popen
70
#define QT_PCLOSE pclose
71
#endif
72
73
QT_BEGIN_NAMESPACE
74
75
//expand fucntions
76
enum ExpandFunc { E_MEMBER=1, E_FIRST, E_LAST, E_CAT, E_FROMFILE, E_EVAL, E_LIST,
77
                  E_SPRINTF, E_JOIN, E_SPLIT, E_BASENAME, E_DIRNAME, E_SECTION,
78
                  E_FIND, E_SYSTEM, E_UNIQUE, E_QUOTE, E_ESCAPE_EXPAND,
79
                  E_UPPER, E_LOWER, E_FILES, E_PROMPT, E_RE_ESCAPE, E_REPLACE };
80
QMap<QString, ExpandFunc> qmake_expandFunctions()
81
{
82
    static QMap<QString, ExpandFunc> *qmake_expand_functions = 0;
83
    if(!qmake_expand_functions) {
84
        qmake_expand_functions = new QMap<QString, ExpandFunc>;
85
        qmakeAddCacheClear(qmakeDeleteCacheClear_QMapStringInt, (void**)&qmake_expand_functions);
86
        qmake_expand_functions->insert("member", E_MEMBER);
87
        qmake_expand_functions->insert("first", E_FIRST);
88
        qmake_expand_functions->insert("last", E_LAST);
89
        qmake_expand_functions->insert("cat", E_CAT);
90
        qmake_expand_functions->insert("fromfile", E_FROMFILE);
91
        qmake_expand_functions->insert("eval", E_EVAL);
92
        qmake_expand_functions->insert("list", E_LIST);
93
        qmake_expand_functions->insert("sprintf", E_SPRINTF);
94
        qmake_expand_functions->insert("join", E_JOIN);
95
        qmake_expand_functions->insert("split", E_SPLIT);
96
        qmake_expand_functions->insert("basename", E_BASENAME);
97
        qmake_expand_functions->insert("dirname", E_DIRNAME);
98
        qmake_expand_functions->insert("section", E_SECTION);
99
        qmake_expand_functions->insert("find", E_FIND);
100
        qmake_expand_functions->insert("system", E_SYSTEM);
101
        qmake_expand_functions->insert("unique", E_UNIQUE);
102
        qmake_expand_functions->insert("quote", E_QUOTE);
103
        qmake_expand_functions->insert("escape_expand", E_ESCAPE_EXPAND);
104
        qmake_expand_functions->insert("upper", E_UPPER);
105
        qmake_expand_functions->insert("lower", E_LOWER);
106
        qmake_expand_functions->insert("re_escape", E_RE_ESCAPE);
107
        qmake_expand_functions->insert("files", E_FILES);
108
        qmake_expand_functions->insert("prompt", E_PROMPT);
109
        qmake_expand_functions->insert("replace", E_REPLACE);
110
    }
111
    return *qmake_expand_functions;
112
}
113
//replace functions
114
enum TestFunc { T_REQUIRES=1, T_GREATERTHAN, T_LESSTHAN, T_EQUALS,
115
                T_EXISTS, T_EXPORT, T_CLEAR, T_UNSET, T_EVAL, T_CONFIG, T_SYSTEM,
116
                T_RETURN, T_BREAK, T_NEXT, T_DEFINED, T_CONTAINS, T_INFILE,
117
                T_COUNT, T_ISEMPTY, T_INCLUDE, T_LOAD, T_DEBUG, T_ERROR,
118
                T_MESSAGE, T_WARNING, T_IF };
119
QMap<QString, TestFunc> qmake_testFunctions()
120
{
121
    static QMap<QString, TestFunc> *qmake_test_functions = 0;
122
    if(!qmake_test_functions) {
123
        qmake_test_functions = new QMap<QString, TestFunc>;
124
        qmake_test_functions->insert("requires", T_REQUIRES);
125
        qmake_test_functions->insert("greaterThan", T_GREATERTHAN);
126
        qmake_test_functions->insert("lessThan", T_LESSTHAN);
127
        qmake_test_functions->insert("equals", T_EQUALS);
128
        qmake_test_functions->insert("isEqual", T_EQUALS);
129
        qmake_test_functions->insert("exists", T_EXISTS);
130
        qmake_test_functions->insert("export", T_EXPORT);
131
        qmake_test_functions->insert("clear", T_CLEAR);
132
        qmake_test_functions->insert("unset", T_UNSET);
133
        qmake_test_functions->insert("eval", T_EVAL);
134
        qmake_test_functions->insert("CONFIG", T_CONFIG);
135
        qmake_test_functions->insert("if", T_IF);
136
        qmake_test_functions->insert("isActiveConfig", T_CONFIG);
137
        qmake_test_functions->insert("system", T_SYSTEM);
138
        qmake_test_functions->insert("return", T_RETURN);
139
        qmake_test_functions->insert("break", T_BREAK);
140
        qmake_test_functions->insert("next", T_NEXT);
141
        qmake_test_functions->insert("defined", T_DEFINED);
142
        qmake_test_functions->insert("contains", T_CONTAINS);
143
        qmake_test_functions->insert("infile", T_INFILE);
144
        qmake_test_functions->insert("count", T_COUNT);
145
        qmake_test_functions->insert("isEmpty", T_ISEMPTY);
146
        qmake_test_functions->insert("include", T_INCLUDE);
147
        qmake_test_functions->insert("load", T_LOAD);
148
        qmake_test_functions->insert("debug", T_DEBUG);
149
        qmake_test_functions->insert("error", T_ERROR);
150
        qmake_test_functions->insert("message", T_MESSAGE);
151
        qmake_test_functions->insert("warning", T_WARNING);
152
    }
153
    return *qmake_test_functions;
154
}
155
156
QT_END_NAMESPACE
157
158
#ifdef QTSCRIPT_SUPPORT
159
#include "qscriptvalue.h"
160
#include "qscriptengine.h"
161
#include "qscriptvalueiterator.h"
162
163
QT_BEGIN_NAMESPACE
164
165
static QScriptValue qscript_projectWrapper(QScriptEngine *eng, QMakeProject *project,
166
                                    const QMap<QString, QStringList> &place);
167
168
static bool qscript_createQMakeProjectMap(QMap<QString, QStringList> &vars, QScriptValue js)
169
{
170
    QScriptValueIterator it(js);
171
    while(it.hasNext()) {
172
        it.next();
173
        vars[it.name()] = qscriptvalue_cast<QStringList>(it.value());
174
    }
175
    return true;
176
}
177
178
static QScriptValue qscript_call_testfunction(QScriptContext *context, QScriptEngine *engine)
179
{
180
    QMakeProject *self = qscriptvalue_cast<QMakeProject*>(context->callee().property("qmakeProject"));
181
    QString func = context->callee().property("functionName").toString();
182
    QStringList args;
183
    for(int i = 0; i < context->argumentCount(); ++i)
184
        args += context->argument(i).toString();
185
    QMap<QString, QStringList> place = self->variables();
186
    qscript_createQMakeProjectMap(place, engine->globalObject().property("qmake"));
187
    QScriptValue ret(engine, self->doProjectTest(func, args, place));
188
    engine->globalObject().setProperty("qmake", qscript_projectWrapper(engine, self, place));
189
    return ret;
190
}
191
192
static QScriptValue qscript_call_expandfunction(QScriptContext *context, QScriptEngine *engine)
193
{
194
    QMakeProject *self = qscriptvalue_cast<QMakeProject*>(context->callee().property("qmakeProject"));
195
    QString func = context->callee().property("functionName").toString();
196
    QStringList args;
197
    for(int i = 0; i < context->argumentCount(); ++i)
198
        args += context->argument(i).toString();
199
    QMap<QString, QStringList> place = self->variables();
200
    qscript_createQMakeProjectMap(place, engine->globalObject().property("qmake"));
201
    QScriptValue ret = qScriptValueFromValue(engine, self->doProjectExpand(func, args, place));
202
    engine->globalObject().setProperty("qmake", qscript_projectWrapper(engine, self, place));
203
    return ret;
204
}
205
206
static QScriptValue qscript_projectWrapper(QScriptEngine *eng, QMakeProject *project,
207
                                           const QMap<QString, QStringList> &place)
208
{
209
    QScriptValue ret = eng->newObject();
210
    {
211
        QStringList testFuncs = qmake_testFunctions().keys() + project->userTestFunctions();
212
        for(int i = 0; i < testFuncs.size(); ++i) {
213
            QString funcName = testFuncs.at(i);
214
            QScriptValue fun = eng->newFunction(qscript_call_testfunction);
215
            fun.setProperty("qmakeProject", eng->newVariant(qVariantFromValue(project)));
216
            fun.setProperty("functionName", QScriptValue(eng, funcName));
217
            eng->globalObject().setProperty(funcName, fun);
218
        }
219
    }
220
    {
221
        QStringList testFuncs = qmake_expandFunctions().keys() + project->userExpandFunctions();
222
        for(int i = 0; i < testFuncs.size(); ++i) {
223
            QString funcName = testFuncs.at(i);
224
            QScriptValue fun = eng->newFunction(qscript_call_expandfunction);
225
            fun.setProperty("qmakeProject", eng->newVariant(qVariantFromValue(project)));
226
            fun.setProperty("functionName", QScriptValue(eng, funcName));
227
            eng->globalObject().setProperty(funcName, fun);
228
        }
229
    }
230
    for(QMap<QString, QStringList>::ConstIterator it = place.begin(); it != place.end(); ++it)
231
        ret.setProperty(it.key(), qScriptValueFromValue(eng, it.value()));
232
    return ret;
233
}
234
235
QT_END_NAMESPACE
236
237
#endif
238
239
QT_BEGIN_NAMESPACE
240
241
struct parser_info {
242
    QString file;
243
    int line_no;
244
    bool from_file;
245
} parser;
246
247
static QString remove_quotes(const QString &arg)
248
{
249
    const ushort SINGLEQUOTE = '\'';
250
    const ushort DOUBLEQUOTE = '"';
251
252
    const QChar *arg_data = arg.data();
253
    const ushort first = arg_data->unicode();
254
    const int arg_len = arg.length();
255
    if(first == SINGLEQUOTE || first == DOUBLEQUOTE) {
256
        const ushort last = (arg_data+arg_len-1)->unicode();
257
        if(last == first)
258
            return arg.mid(1, arg_len-2);
259
    }
260
    return arg;
261
}
262
263
static QString varMap(const QString &x)
264
{
265
    QString ret(x);
266
    if(ret.startsWith("TMAKE")) //tmake no more!
267
        ret = "QMAKE" + ret.mid(5);
268
    else if(ret == "INTERFACES")
269
        ret = "FORMS";
270
    else if(ret == "QMAKE_POST_BUILD")
271
        ret = "QMAKE_POST_LINK";
272
    else if(ret == "TARGETDEPS")
273
        ret = "POST_TARGETDEPS";
274
    else if(ret == "LIBPATH")
275
        ret = "QMAKE_LIBDIR";
276
    else if(ret == "QMAKE_EXT_MOC")
277
        ret = "QMAKE_EXT_CPP_MOC";
278
    else if(ret == "QMAKE_MOD_MOC")
279
        ret = "QMAKE_H_MOD_MOC";
280
    else if(ret == "QMAKE_LFLAGS_SHAPP")
281
        ret = "QMAKE_LFLAGS_APP";
282
    else if(ret == "PRECOMPH")
283
        ret = "PRECOMPILED_HEADER";
284
    else if(ret == "PRECOMPCPP")
285
        ret = "PRECOMPILED_SOURCE";
286
    else if(ret == "INCPATH")
287
        ret = "INCLUDEPATH";
288
    else if(ret == "QMAKE_EXTRA_WIN_COMPILERS" || ret == "QMAKE_EXTRA_UNIX_COMPILERS")
289
        ret = "QMAKE_EXTRA_COMPILERS";
290
    else if(ret == "QMAKE_EXTRA_WIN_TARGETS" || ret == "QMAKE_EXTRA_UNIX_TARGETS")
291
        ret = "QMAKE_EXTRA_TARGETS";
292
    else if(ret == "QMAKE_EXTRA_UNIX_INCLUDES")
293
        ret = "QMAKE_EXTRA_INCLUDES";
294
    else if(ret == "QMAKE_EXTRA_UNIX_VARIABLES")
295
        ret = "QMAKE_EXTRA_VARIABLES";
296
    else if(ret == "QMAKE_RPATH")
297
        ret = "QMAKE_LFLAGS_RPATH";
298
    else if(ret == "QMAKE_FRAMEWORKDIR")
299
        ret = "QMAKE_FRAMEWORKPATH";
300
    else if(ret == "QMAKE_FRAMEWORKDIR_FLAGS")
301
        ret = "QMAKE_FRAMEWORKPATH_FLAGS";
302
    return ret;
303
}
304
305
static QStringList split_arg_list(QString params)
306
{
307
    int quote = 0;
308
    QStringList args;
309
310
    const ushort LPAREN = '(';
311
    const ushort RPAREN = ')';
312
    const ushort SINGLEQUOTE = '\'';
313
    const ushort DOUBLEQUOTE = '"';
314
    const ushort COMMA = ',';
315
    const ushort SPACE = ' ';
316
    //const ushort TAB = '\t';
317
318
    ushort unicode;
319
    const QChar *params_data = params.data();
320
    const int params_len = params.length();
321
    int last = 0;
322
    while(last < params_len && (params_data[last].unicode() == SPACE
323
                                /*|| params_data[last].unicode() == TAB*/))
324
        ++last;
325
    for(int x = last, parens = 0; x <= params_len; x++) {
326
        unicode = params_data[x].unicode();
327
        if(x == params_len) {
328
            while(x && params_data[x-1].unicode() == SPACE)
329
                --x;
330
            QString mid(params_data+last, x-last);
331
            if(quote) {
332
                if(mid[0] == quote && mid[(int)mid.length()-1] == quote)
333
                    mid = mid.mid(1, mid.length()-2);
334
                quote = 0;
335
            }
336
            args << mid;
337
            break;
338
        }
339
        if(unicode == LPAREN) {
340
            --parens;
341
        } else if(unicode == RPAREN) {
342
            ++parens;
343
        } else if(quote && unicode == quote) {
344
            quote = 0;
345
        } else if(!quote && (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE)) {
346
            quote = unicode;
347
        }
348
        if(!parens && !quote && unicode == COMMA) {
349
            QString mid = params.mid(last, x - last).trimmed();
350
            args << mid;
351
            last = x+1;
352
            while(last < params_len && (params_data[last].unicode() == SPACE
353
                                        /*|| params_data[last].unicode() == TAB*/))
354
                ++last;
355
        }
356
    }
357
    return args;
358
}
359
360
static QStringList split_value_list(const QString &vals, bool do_semicolon=false)
361
{
362
    QString build;
363
    QStringList ret;
364
    QStack<char> quote;
365
366
    const ushort LPAREN = '(';
367
    const ushort RPAREN = ')';
368
    const ushort SINGLEQUOTE = '\'';
369
    const ushort DOUBLEQUOTE = '"';
370
    const ushort BACKSLASH = '\\';
371
    const ushort SEMICOLON = ';';
372
373
    ushort unicode;
374
    const QChar *vals_data = vals.data();
375
    const int vals_len = vals.length();
376
    for(int x = 0, parens = 0; x < vals_len; x++) {
377
        unicode = vals_data[x].unicode();
378
        if(x != (int)vals_len-1 && unicode == BACKSLASH &&
379
            (vals_data[x+1].unicode() == SINGLEQUOTE || vals_data[x+1].unicode() == DOUBLEQUOTE)) {
380
            build += vals_data[x++]; //get that 'escape'
381
        } else if(!quote.isEmpty() && unicode == quote.top()) {
382
            quote.pop();
383
        } else if(unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE) {
384
            quote.push(unicode);
385
        } else if(unicode == RPAREN) {
386
            --parens;
387
        } else if(unicode == LPAREN) {
388
            ++parens;
389
        }
390
391
        if(!parens && quote.isEmpty() && ((do_semicolon && unicode == SEMICOLON) ||
392
                                           vals_data[x] == Option::field_sep)) {
393
            ret << build;
394
            build.clear();
395
        } else {
396
            build += vals_data[x];
397
        }
398
    }
399
    if(!build.isEmpty())
400
        ret << build;
401
    return ret;
402
}
403
404
//just a parsable entity
405
struct ParsableBlock
406
{
407
    ParsableBlock() : ref_cnt(1) { }
408
    virtual ~ParsableBlock() { }
409
410
    struct Parse {
411
        QString text;
412
        parser_info pi;
413
        Parse(const QString &t) : text(t){ pi = parser; }
414
    };
415
    QList<Parse> parselist;
416
417
    inline int ref() { return ++ref_cnt; }
418
    inline int deref() { return --ref_cnt; }
419
420
protected:
421
    int ref_cnt;
422
    virtual bool continueBlock() = 0;
423
    bool eval(QMakeProject *p, QMap<QString, QStringList> &place);
424
};
425
426
bool ParsableBlock::eval(QMakeProject *p, QMap<QString, QStringList> &place)
427
{
428
    //save state
429
    parser_info pi = parser;
430
    const int block_count = p->scope_blocks.count();
431
432
    //execute
433
    bool ret = true;
434
    for(int i = 0; i < parselist.count(); i++) {
435
        parser = parselist.at(i).pi;
436
        if(!(ret = p->parse(parselist.at(i).text, place)) || !continueBlock())
437
            break;
438
    }
439
440
    //restore state
441
    parser = pi;
442
    while(p->scope_blocks.count() > block_count)
443
        p->scope_blocks.pop();
444
    return ret;
445
}
446
447
//defined functions
448
struct FunctionBlock : public ParsableBlock
449
{
450
    FunctionBlock() : calling_place(0), scope_level(1), cause_return(false) { }
451
452
    QMap<QString, QStringList> vars;
453
    QMap<QString, QStringList> *calling_place;
454
    QStringList return_value;
455
    int scope_level;
456
    bool cause_return;
457
458
    bool exec(const QList<QStringList> &args,
459
              QMakeProject *p, QMap<QString, QStringList> &place, QStringList &functionReturn);
460
    virtual bool continueBlock() { return !cause_return; }
461
};
462
463
bool FunctionBlock::exec(const QList<QStringList> &args,
464
                         QMakeProject *proj, QMap<QString, QStringList> &place,
465
                         QStringList &functionReturn)
466
{
467
    //save state
468
#if 1
469
    calling_place = &place;
470
#else
471
    calling_place = &proj->variables();
472
#endif
473
    return_value.clear();
474
    cause_return = false;
475
476
    //execute
477
#if 0
478
    vars = proj->variables(); // should be place so that local variables can be inherited
479
#else
480
    vars = place;
481
#endif
482
    vars["ARGS"].clear();
483
    for(int i = 0; i < args.count(); i++) {
484
        vars["ARGS"] += args[i];
485
        vars[QString::number(i+1)] = args[i];
486
    }
487
    bool ret = ParsableBlock::eval(proj, vars);
488
    functionReturn = return_value;
489
490
    //restore state
491
    calling_place = 0;
492
    return_value.clear();
493
    vars.clear();
494
    return ret;
495
}
496
497
//loops
498
struct IteratorBlock : public ParsableBlock
499
{
500
    IteratorBlock() : scope_level(1), loop_forever(false), cause_break(false), cause_next(false) { }
501
502
    int scope_level;
503
504
    struct Test {
505
        QString func;
506
        QStringList args;
507
        bool invert;
508
        parser_info pi;
509
        Test(const QString &f, QStringList &a, bool i) : func(f), args(a), invert(i) { pi = parser; }
510
    };
511
    QList<Test> test;
512
513
    QString variable;
514
515
    bool loop_forever, cause_break, cause_next;
516
    QStringList list;
517
518
    bool exec(QMakeProject *p, QMap<QString, QStringList> &place);
519
    virtual bool continueBlock() { return !cause_next && !cause_break; }
520
};
521
bool IteratorBlock::exec(QMakeProject *p, QMap<QString, QStringList> &place)
522
{
523
    bool ret = true;
524
    QStringList::Iterator it;
525
    if(!loop_forever)
526
        it = list.begin();
527
    int iterate_count = 0;
528
    //save state
529
    IteratorBlock *saved_iterator = p->iterator;
530
    p->iterator = this;
531
532
    //do the loop
533
    while(loop_forever || it != list.end()) {
534
        cause_next = cause_break = false;
535
        if(!loop_forever && (*it).isEmpty()) { //ignore empty items
536
            ++it;
537
            continue;
538
        }
539
540
        //set up the loop variable
541
        QStringList va;
542
        if(!variable.isEmpty()) {
543
            va = place[variable];
544
            if(loop_forever)
545
                place[variable] = QStringList(QString::number(iterate_count));
546
            else
547
                place[variable] = QStringList(*it);
548
        }
549
        //do the iterations
550
        bool succeed = true;
551
        for(QList<Test>::Iterator test_it = test.begin(); test_it != test.end(); ++test_it) {
552
            parser = (*test_it).pi;
553
            succeed = p->doProjectTest((*test_it).func, (*test_it).args, place);
554
            if((*test_it).invert)
555
                succeed = !succeed;
556
            if(!succeed)
557
                break;
558
        }
559
        if(succeed)
560
            ret = ParsableBlock::eval(p, place);
561
        //restore the variable in the map
562
        if(!variable.isEmpty())
563
            place[variable] = va;
564
        //loop counters
565
        if(!loop_forever)
566
            ++it;
567
        iterate_count++;
568
        if(!ret || cause_break)
569
            break;
570
    }
571
572
    //restore state
573
    p->iterator = saved_iterator;
574
    return ret;
575
}
576
577
QMakeProject::ScopeBlock::~ScopeBlock()
578
{
579
#if 0
580
    if(iterate)
581
        delete iterate;
582
#endif
583
}
584
585
static void qmake_error_msg(const QString &msg)
586
{
587
    fprintf(stderr, "%s:%d: %s\n", parser.file.toLatin1().constData(), parser.line_no,
588
            msg.toLatin1().constData());
589
}
590
591
/*
592
   1) environment variable QMAKEFEATURES (as separated by colons)
593
   2) property variable QMAKEFEATURES (as separated by colons)
594
   3) <project_root> (where .qmake.cache lives) + FEATURES_DIR
595
   4) environment variable QMAKEPATH (as separated by colons) + /mkspecs/FEATURES_DIR
596
   5) your QMAKESPEC/features dir
597
   6) your data_install/mkspecs/FEATURES_DIR
598
   7) your QMAKESPEC/../FEATURES_DIR dir
599
600
   FEATURES_DIR is defined as:
601
602
   1) features/(unix|win32|macx)/
603
   2) features/
604
*/
605
QStringList qmake_feature_paths(QMakeProperty *prop=0)
606
{
607
    QStringList concat;
608
    {
609
        const QString base_concat = QDir::separator() + QString("features");
610
        switch(Option::target_mode) {
611
        case Option::TARG_MACX_MODE:                     //also a unix
612
            concat << base_concat + QDir::separator() + "mac";
613
            concat << base_concat + QDir::separator() + "macx";
614
            concat << base_concat + QDir::separator() + "unix";
615
            break;
616
        case Option::TARG_UNIX_MODE:
617
            concat << base_concat + QDir::separator() + "unix";
618
            break;
619
        case Option::TARG_WIN_MODE:
620
            concat << base_concat + QDir::separator() + "win32";
621
            break;
622
        case Option::TARG_MAC9_MODE:
623
            concat << base_concat + QDir::separator() + "mac";
624
            concat << base_concat + QDir::separator() + "mac9";
625
            break;
626
        case Option::TARG_QNX6_MODE: //also a unix
627
            concat << base_concat + QDir::separator() + "qnx6";
628
            concat << base_concat + QDir::separator() + "unix";
629
            break;
630
        }
631
        concat << base_concat;
632
    }
633
    const QString mkspecs_concat = QDir::separator() + QString("mkspecs");
634
    QStringList feature_roots;
635
    QByteArray mkspec_path = qgetenv("QMAKEFEATURES");
636
    if(!mkspec_path.isNull())
637
        feature_roots += splitPathList(QString::fromLocal8Bit(mkspec_path));
638
    if(prop)
639
        feature_roots += splitPathList(prop->value("QMAKEFEATURES"));
640
    if(!Option::mkfile::cachefile.isEmpty()) {
641
        QString path;
642
        int last_slash = Option::mkfile::cachefile.lastIndexOf(Option::dir_sep);
643
        if(last_slash != -1)
644
            path = Option::fixPathToLocalOS(Option::mkfile::cachefile.left(last_slash));
645
        for(QStringList::Iterator concat_it = concat.begin();
646
            concat_it != concat.end(); ++concat_it)
647
            feature_roots << (path + (*concat_it));
648
    }
649
    QByteArray qmakepath = qgetenv("QMAKEPATH");
650
    if (!qmakepath.isNull()) {
651
        const QStringList lst = splitPathList(QString::fromLocal8Bit(qmakepath));
652
        for(QStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it) {
653
            for(QStringList::Iterator concat_it = concat.begin();
654
                concat_it != concat.end(); ++concat_it)
655
                    feature_roots << ((*it) + mkspecs_concat + (*concat_it));
656
        }
657
    }
658
    if(!Option::mkfile::qmakespec.isEmpty())
659
        feature_roots << Option::mkfile::qmakespec + QDir::separator() + "features";
660
    if(!Option::mkfile::qmakespec.isEmpty()) {
661
        QFileInfo specfi(Option::mkfile::qmakespec);
662
        QDir specdir(specfi.absoluteFilePath());
663
        while(!specdir.isRoot()) {
664
            if(!specdir.cdUp() || specdir.isRoot())
665
                break;
666
            if(QFile::exists(specdir.path() + QDir::separator() + "features")) {
667
                for(QStringList::Iterator concat_it = concat.begin();
668
                    concat_it != concat.end(); ++concat_it)
669
                    feature_roots << (specdir.path() + (*concat_it));
670
                break;
671
            }
672
        }
673
    }
674
    for(QStringList::Iterator concat_it = concat.begin();
675
        concat_it != concat.end(); ++concat_it)
676
        feature_roots << (QLibraryInfo::location(QLibraryInfo::PrefixPath) +
677
                          mkspecs_concat + (*concat_it));
678
    for(QStringList::Iterator concat_it = concat.begin();
679
        concat_it != concat.end(); ++concat_it)
680
        feature_roots << (QLibraryInfo::location(QLibraryInfo::DataPath) +
681
                          mkspecs_concat + (*concat_it));
682
    return feature_roots;
683
}
684
685
QStringList qmake_mkspec_paths()
686
{
687
    QStringList ret;
688
    const QString concat = QDir::separator() + QString("mkspecs");
689
    QByteArray qmakepath = qgetenv("QMAKEPATH");
690
    if (!qmakepath.isEmpty()) {
691
        const QStringList lst = splitPathList(QString::fromLocal8Bit(qmakepath));
692
        for(QStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it)
693
            ret << ((*it) + concat);
694
    }
695
    ret << QLibraryInfo::location(QLibraryInfo::DataPath) + concat;
696
697
    return ret;
698
}
699
700
class QMakeProjectEnv
701
{
702
    QStringList envs;
703
public:
704
    QMakeProjectEnv() { }
705
    QMakeProjectEnv(QMakeProject *p) { execute(p->variables()); }
706
    QMakeProjectEnv(const QMap<QString, QStringList> &values) { execute(values); }
707
708
    void execute(QMakeProject *p) { execute(p->variables()); }
709
    void execute(const QMap<QString, QStringList> &values) {
710
#ifdef Q_OS_UNIX
711
        for(QMap<QString, QStringList>::ConstIterator it = values.begin(); it != values.end(); ++it) {
712
            const QString var = it.key(), val = it.value().join(" ");
713
            if(!var.startsWith(".")) {
714
                const QString env_var = Option::sysenv_mod + var;
715
                if(!putenv(strdup(QString(env_var + "=" + val).toAscii().data())))
716
                    envs.append(env_var);
717
            }
718
        }
719
#else
720
        Q_UNUSED(values);
721
#endif
722
    }
723
    ~QMakeProjectEnv() {
724
#ifdef Q_OS_UNIX
725
        for(QStringList::ConstIterator it = envs.begin();it != envs.end(); ++it) {
726
            putenv(strdup(QString(*it + "=").toAscii().data()));
727
        }
728
#endif
729
    }
730
};
731
732
QMakeProject::~QMakeProject()
733
{
734
    if(own_prop)
735
        delete prop;
736
    for(QMap<QString, FunctionBlock*>::iterator it = replaceFunctions.begin(); it != replaceFunctions.end(); ++it) {
737
        if(!it.value()->deref())
738
            delete it.value();
739
    }
740
    replaceFunctions.clear();
741
    for(QMap<QString, FunctionBlock*>::iterator it = testFunctions.begin(); it != testFunctions.end(); ++it) {
742
        if(!it.value()->deref())
743
            delete it.value();
744
    }
745
    testFunctions.clear();
746
}
747
748
749
void
750
QMakeProject::init(QMakeProperty *p, const QMap<QString, QStringList> *vars)
751
{
752
    if(vars)
753
        base_vars = *vars;
754
    if(!p) {
755
        prop = new QMakeProperty;
756
        own_prop = true;
757
    } else {
758
        prop = p;
759
        own_prop = false;
760
    }
761
    reset();
762
}
763
764
QMakeProject::QMakeProject(QMakeProject *p, const QMap<QString, QStringList> *vars)
765
{
766
    init(p->properties(), vars ? vars : &p->variables());
767
    for(QMap<QString, FunctionBlock*>::iterator it = p->replaceFunctions.begin(); it != p->replaceFunctions.end(); ++it) {
768
        it.value()->ref();
769
        replaceFunctions.insert(it.key(), it.value());
770
    }
771
    for(QMap<QString, FunctionBlock*>::iterator it = p->testFunctions.begin(); it != p->testFunctions.end(); ++it) {
772
        it.value()->ref();
773
        testFunctions.insert(it.key(), it.value());
774
    }
775
}
776
777
void
778
QMakeProject::reset()
779
{
780
    // scope_blocks starts with one non-ignoring entity
781
    scope_blocks.clear();
782
    scope_blocks.push(ScopeBlock());
783
    iterator = 0;
784
    function = 0;
785
}
786
787
bool
788
QMakeProject::parse(const QString &t, QMap<QString, QStringList> &place, int numLines)
789
{
790
    QString s = t.simplified();
791
    int hash_mark = s.indexOf("#");
792
    if(hash_mark != -1) //good bye comments
793
        s = s.left(hash_mark);
794
    if(s.isEmpty()) // blank_line
795
        return true;
796
797
    if(scope_blocks.top().ignore) {
798
        bool continue_parsing = false;
799
        // adjust scope for each block which appears on a single line
800
        for(int i = 0; i < s.length(); i++) {
801
            if(s[i] == '{') {
802
                scope_blocks.push(ScopeBlock(true));
803
            } else if(s[i] == '}') {
804
                if(scope_blocks.count() == 1) {
805
                    fprintf(stderr, "Braces mismatch %s:%d\n", parser.file.toLatin1().constData(), parser.line_no);
806
                    return false;
807
                }
808
                ScopeBlock sb = scope_blocks.pop();
809
                if(sb.iterate) {
810
                    sb.iterate->exec(this, place);
811
                    delete sb.iterate;
812
                    sb.iterate = 0;
813
                }
814
                if(!scope_blocks.top().ignore) {
815
                    debug_msg(1, "Project Parser: %s:%d : Leaving block %d", parser.file.toLatin1().constData(),
816
                              parser.line_no, scope_blocks.count()+1);
817
                    s = s.mid(i+1).trimmed();
818
                    continue_parsing = !s.isEmpty();
819
                    break;
820
                }
821
            }
822
        }
823
        if(!continue_parsing) {
824
            debug_msg(1, "Project Parser: %s:%d : Ignored due to block being false.",
825
                      parser.file.toLatin1().constData(), parser.line_no);
826
            return true;
827
        }
828
    }
829
830
    if(function) {
831
        QString append;
832
        int d_off = 0;
833
        const QChar *d = s.unicode();
834
        bool function_finished = false;
835
        while(d_off < s.length()) {
836
            if(*(d+d_off) == QLatin1Char('}')) {
837
                function->scope_level--;
838
                if(!function->scope_level) {
839
                    function_finished = true;
840
                    break;
841
                }
842
            } else if(*(d+d_off) == QLatin1Char('{')) {
843
                function->scope_level++;
844
            }
845
            append += *(d+d_off);
846
            ++d_off;
847
        }
848
        if(!append.isEmpty())
849
            function->parselist.append(IteratorBlock::Parse(append));
850
        if(function_finished) {
851
            function = 0;
852
            s = QString(d+d_off, s.length()-d_off);
853
        } else {
854
            return true;
855
        }
856
    } else if(IteratorBlock *it = scope_blocks.top().iterate) {
857
        QString append;
858
        int d_off = 0;
859
        const QChar *d = s.unicode();
860
        bool iterate_finished = false;
861
        while(d_off < s.length()) {
862
            if(*(d+d_off) == QLatin1Char('}')) {
863
                it->scope_level--;
864
                if(!it->scope_level) {
865
                    iterate_finished = true;
866
                    break;
867
                }
868
            } else if(*(d+d_off) == QLatin1Char('{')) {
869
                it->scope_level++;
870
            }
871
            append += *(d+d_off);
872
            ++d_off;
873
        }
874
        if(!append.isEmpty())
875
            scope_blocks.top().iterate->parselist.append(IteratorBlock::Parse(append));
876
        if(iterate_finished) {
877
            scope_blocks.top().iterate = 0;
878
            bool ret = it->exec(this, place);
879
            delete it;
880
            if(!ret)
881
                return false;
882
            s = s.mid(d_off);
883
        } else {
884
            return true;
885
        }
886
    }
887
888
    QString scope, var, op;
889
    QStringList val;
890
#define SKIP_WS(d, o, l) while(o < l && (*(d+o) == QLatin1Char(' ') || *(d+o) == QLatin1Char('\t'))) ++o
891
    const QChar *d = s.unicode();
892
    int d_off = 0;
893
    SKIP_WS(d, d_off, s.length());
894
    IteratorBlock *iterator = 0;
895
    bool scope_failed = false, else_line = false, or_op=false;
896
    QChar quote = 0;
897
    int parens = 0, scope_count=0, start_block = 0;
898
    while(d_off < s.length()) {
899
        if(!parens) {
900
            if(*(d+d_off) == QLatin1Char('='))
901
                break;
902
            if(*(d+d_off) == QLatin1Char('+') || *(d+d_off) == QLatin1Char('-') ||
903
               *(d+d_off) == QLatin1Char('*') || *(d+d_off) == QLatin1Char('~')) {
904
                if(*(d+d_off+1) == QLatin1Char('=')) {
905
                    break;
906
                } else if(*(d+d_off+1) == QLatin1Char(' ')) {
907
                    const QChar *k = d+d_off+1;
908
                    int k_off = 0;
909
                    SKIP_WS(k, k_off, s.length()-d_off);
910
                    if(*(k+k_off) == QLatin1Char('=')) {
911
                        QString msg;
912
                        qmake_error_msg(QString(d+d_off, 1) + "must be followed immediately by =");
913
                        return false;
914
                    }
915
                }
916
            }
917
        }
918
919
        if(!quote.isNull()) {
920
            if(*(d+d_off) == quote)
921
                quote = QChar();
922
        } else if(*(d+d_off) == '(') {
923
            ++parens;
924
        } else if(*(d+d_off) == ')') {
925
            --parens;
926
        } else if(*(d+d_off) == '"' /*|| *(d+d_off) == '\''*/) {
927
            quote = *(d+d_off);
928
        }
929
930
        if(!parens && quote.isNull() &&
931
           (*(d+d_off) == QLatin1Char(':') || *(d+d_off) == QLatin1Char('{') ||
932
            *(d+d_off) == QLatin1Char(')') || *(d+d_off) == QLatin1Char('|'))) {
933
            scope_count++;
934
            scope = var.trimmed();
935
            if(*(d+d_off) == QLatin1Char(')'))
936
                scope += *(d+d_off); // need this
937
            var = "";
938
939
            bool test = scope_failed;
940
            if(scope.isEmpty()) {
941
                test = true;
942
            } else if(scope.toLower() == "else") { //else is a builtin scope here as it modifies state
943
                if(scope_count != 1 || scope_blocks.top().else_status == ScopeBlock::TestNone) {
944
                    qmake_error_msg(("Unexpected " + scope + " ('" + s + "')").toLatin1());
945
                    return false;
946
                }
947
                else_line = true;
948
                test = (scope_blocks.top().else_status == ScopeBlock::TestSeek);
949
                debug_msg(1, "Project Parser: %s:%d : Else%s %s.", parser.file.toLatin1().constData(), parser.line_no,
950
                          scope == "else" ? "" : QString(" (" + scope + ")").toLatin1().constData(),
951
                          test ? "considered" : "excluded");
952
            } else {
953
                QString comp_scope = scope;
954
                bool invert_test = (comp_scope.at(0) == QLatin1Char('!'));
955
                if(invert_test)
956
                    comp_scope = comp_scope.mid(1);
957
                int lparen = comp_scope.indexOf('(');
958
                if(or_op == scope_failed) {
959
                    if(lparen != -1) { // if there is an lparen in the scope, it IS a function
960
                        int rparen = comp_scope.lastIndexOf(')');
961
                        if(rparen == -1) {
962
                            qmake_error_msg("Function missing right paren: " + comp_scope);
963
                            return false;
964
                        }
965
                        QString func = comp_scope.left(lparen);
966
                        QStringList args = split_arg_list(comp_scope.mid(lparen+1, rparen - lparen - 1));
967
                        if(function) {
968
                            fprintf(stderr, "%s:%d: No tests can come after a function definition!\n",
969
                                    parser.file.toLatin1().constData(), parser.line_no);
970
                            return false;
971
                        } else if(func == "for") { //for is a builtin function here, as it modifies state
972
                            if(args.count() > 2 || args.count() < 1) {
973
                                fprintf(stderr, "%s:%d: for(iterate, list) requires two arguments.\n",
974
                                        parser.file.toLatin1().constData(), parser.line_no);
975
                                return false;
976
                            } else if(iterator) {
977
                                fprintf(stderr, "%s:%d unexpected nested for()\n",
978
                                        parser.file.toLatin1().constData(), parser.line_no);
979
                                return false;
980
                            }
981
982
                            iterator = new IteratorBlock;
983
                            QString it_list;
984
                            if(args.count() == 1) {
985
                                doVariableReplace(args[0], place);
986
                                it_list = args[0];
987
                                if(args[0] != "ever") {
988
                                    delete iterator;
989
                                    iterator = 0;
990
                                    fprintf(stderr, "%s:%d: for(iterate, list) requires two arguments.\n",
991
                                            parser.file.toLatin1().constData(), parser.line_no);
992
                                    return false;
993
                                }
994
                                it_list = "forever";
995
                            } else if(args.count() == 2) {
996
                                iterator->variable = args[0];
997
                                doVariableReplace(args[1], place);
998
                                it_list = args[1];
999
                            }
1000
                            QStringList list = place[it_list];
1001
                            if(list.isEmpty()) {
1002
                                if(it_list == "forever") {
1003
                                    iterator->loop_forever = true;
1004
                                } else {
1005
                                    int dotdot = it_list.indexOf("..");
1006
                                    if(dotdot != -1) {
1007
                                        bool ok;
1008
                                        int start = it_list.left(dotdot).toInt(&ok);
1009
                                        if(ok) {
1010
                                            int end = it_list.mid(dotdot+2).toInt(&ok);
1011
                                            if(ok) {
1012
                                                if(start < end) {
1013
                                                    for(int i = start; i <= end; i++)
1014
                                                        list << QString::number(i);
1015
                                                } else {
1016
                                                    for(int i = start; i >= end; i--)
1017
                                                        list << QString::number(i);
1018
                                                }
1019
                                            }
1020
                                        }
1021
                                    }
1022
                                }
1023
                            }
1024
                            iterator->list = list;
1025
                            test = !invert_test;
1026
                        } else if(iterator) {
1027
                            iterator->test.append(IteratorBlock::Test(func, args, invert_test));
1028
                            test = !invert_test;
1029
                        } else if(func == "defineTest" || func == "defineReplace") {
1030
                            if(!function_blocks.isEmpty()) {
1031
                                fprintf(stderr,
1032
                                        "%s:%d: cannot define a function within another definition.\n",
1033
                                        parser.file.toLatin1().constData(), parser.line_no);
1034
                                return false;
1035
                            }
1036
                            if(args.count() != 1) {
1037
                                fprintf(stderr, "%s:%d: %s(function_name) requires one argument.\n",
1038
                                        parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
1039
                                return false;
1040
                            }
1041
                            QMap<QString, FunctionBlock*> *map = 0;
1042
                            if(func == "defineTest")
1043
                                map = &testFunctions;
1044
                            else
1045
                                map = &replaceFunctions;
1046
#if 0
1047
                            if(!map || map->contains(args[0])) {
1048
                                fprintf(stderr, "%s:%d: Function[%s] multiply defined.\n",
1049
                                        parser.file.toLatin1().constData(), parser.line_no, args[0].toLatin1().constData());
1050
                                return false;
1051
                            }
1052
#endif
1053
                            function = new FunctionBlock;
1054
                            map->insert(args[0], function);
1055
                            test = true;
1056
                        } else {
1057
                            test = doProjectTest(func, args, place);
1058
                            if(*(d+d_off) == QLatin1Char(')') && d_off == s.length()-1) {
1059
                                if(invert_test)
1060
                                    test = !test;
1061
                                scope_blocks.top().else_status =
1062
                                    (test ? ScopeBlock::TestFound : ScopeBlock::TestSeek);
1063
                                return true;  // assume we are done
1064
                            }
1065
                        }
1066
                    } else {
1067
                        QString cscope = comp_scope.trimmed();
1068
                        doVariableReplace(cscope, place);
1069
                        test = isActiveConfig(cscope.trimmed(), true, &place);
1070
                    }
1071
                    if(invert_test)
1072
                        test = !test;
1073
                }
1074
            }
1075
            if(!test && !scope_failed)
1076
                debug_msg(1, "Project Parser: %s:%d : Test (%s) failed.", parser.file.toLatin1().constData(),
1077
                          parser.line_no, scope.toLatin1().constData());
1078
            if(test == or_op)
1079
                scope_failed = !test;
1080
            or_op = (*(d+d_off) == QLatin1Char('|'));
1081
1082
            if(*(d+d_off) == QLatin1Char('{')) { // scoping block
1083
                start_block++;
1084
                if(iterator) {
1085
                    for(int off = 0, braces = 0; true; ++off) {
1086
                        if(*(d+d_off+off) == QLatin1Char('{'))
1087
                            ++braces;
1088
                        else if(*(d+d_off+off) == QLatin1Char('}') && braces)
1089
                            --braces;
1090
                        if(!braces || d_off+off == s.length()) {
1091
                            iterator->parselist.append(s.mid(d_off, off-1));
1092
                            if(braces > 1)
1093
                                iterator->scope_level += braces-1;
1094
                            d_off += off-1;
1095
                            break;
1096
                        }
1097
                    }
1098
                }
1099
            }
1100
        } else if(!parens && *(d+d_off) == QLatin1Char('}')) {
1101
            if(start_block) {
1102
                --start_block;
1103
            } else if(!scope_blocks.count()) {
1104
                warn_msg(WarnParser, "Possible braces mismatch %s:%d", parser.file.toLatin1().constData(), parser.line_no);
1105
            } else {
1106
                if(scope_blocks.count() == 1) {
1107
                    fprintf(stderr, "Braces mismatch %s:%d\n", parser.file.toLatin1().constData(), parser.line_no);
1108
                    return false;
1109
                }
1110
                debug_msg(1, "Project Parser: %s:%d : Leaving block %d", parser.file.toLatin1().constData(),
1111
                          parser.line_no, scope_blocks.count());
1112
                ScopeBlock sb = scope_blocks.pop();
1113
                if(sb.iterate)
1114
                    sb.iterate->exec(this, place);
1115
            }
1116
        } else {
1117
            var += *(d+d_off);
1118
        }
1119
        ++d_off;
1120
    }
1121
    var = var.trimmed();
1122
1123
    if(!else_line || (else_line && !scope_failed))
1124
        scope_blocks.top().else_status = (!scope_failed ? ScopeBlock::TestFound : ScopeBlock::TestSeek);
1125
    if(start_block) {
1126
        ScopeBlock next_block(scope_failed);
1127
        next_block.iterate = iterator;
1128
        if(iterator)
1129
            next_block.else_status = ScopeBlock::TestNone;
1130
        else if(scope_failed)
1131
            next_block.else_status = ScopeBlock::TestSeek;
1132
        else
1133
            next_block.else_status = ScopeBlock::TestFound;
1134
        scope_blocks.push(next_block);
1135
        debug_msg(1, "Project Parser: %s:%d : Entering block %d (%d). [%s]", parser.file.toLatin1().constData(),
1136
                  parser.line_no, scope_blocks.count(), scope_failed, s.toLatin1().constData());
1137
    } else if(iterator) {
1138
        iterator->parselist.append(var+s.mid(d_off));
1139
        bool ret = iterator->exec(this, place);
1140
        delete iterator;
1141
        return ret;
1142
    }
1143
1144
    if((!scope_count && !var.isEmpty()) || (scope_count == 1 && else_line))
1145
        scope_blocks.top().else_status = ScopeBlock::TestNone;
1146
    if(d_off == s.length()) {
1147
        if(!var.trimmed().isEmpty())
1148
            qmake_error_msg(("Parse Error ('" + s + "')").toLatin1());
1149
        return var.isEmpty(); // allow just a scope
1150
    }
1151
1152
    SKIP_WS(d, d_off, s.length());
1153
    for(; d_off < s.length() && op.indexOf('=') == -1; op += *(d+(d_off++)))
1154
        ;
1155
    op.replace(QRegExp("\\s"), "");
1156
1157
    SKIP_WS(d, d_off, s.length());
1158
    QString vals = s.mid(d_off); // vals now contains the space separated list of values
1159
    int rbraces = vals.count('}'), lbraces = vals.count('{');
1160
    if(scope_blocks.count() > 1 && rbraces - lbraces == 1) {
1161
        debug_msg(1, "Project Parser: %s:%d : Leaving block %d", parser.file.toLatin1().constData(),
1162
                  parser.line_no, scope_blocks.count());
1163
        ScopeBlock sb = scope_blocks.pop();
1164
        if(sb.iterate)
1165
            sb.iterate->exec(this, place);
1166
        vals.truncate(vals.length()-1);
1167
    } else if(rbraces != lbraces) {
1168
        warn_msg(WarnParser, "Possible braces mismatch {%s} %s:%d",
1169
                 vals.toLatin1().constData(), parser.file.toLatin1().constData(), parser.line_no);
1170
    }
1171
    if(scope_failed)
1172
        return true; // oh well
1173
#undef SKIP_WS
1174
1175
    doVariableReplace(var, place);
1176
    var = varMap(var); //backwards compatability
1177
    if(!var.isEmpty() && Option::mkfile::do_preprocess) {
1178
        static QString last_file("*none*");
1179
        if(parser.file != last_file) {
1180
            fprintf(stdout, "#file %s:%d\n", parser.file.toLatin1().constData(), parser.line_no);
1181
            last_file = parser.file;
1182
        }
1183
        fprintf(stdout, "%s %s %s\n", var.toLatin1().constData(), op.toLatin1().constData(), vals.toLatin1().constData());
1184
    }
1185
1186
    if(vals.contains('=') && numLines > 1)
1187
        warn_msg(WarnParser, "Detected possible line continuation: {%s} %s:%d",
1188
                 var.toLatin1().constData(), parser.file.toLatin1().constData(), parser.line_no);
1189
1190
    QStringList &varlist = place[var]; // varlist is the list in the symbol table
1191
1192
    if(Option::debug_level >= 1) {
1193
        QString tmp_vals = vals;
1194
        doVariableReplace(tmp_vals, place);
1195
        debug_msg(1, "Project Parser: %s:%d :%s: :%s: (%s)", parser.file.toLatin1().constData(), parser.line_no,
1196
                  var.toLatin1().constData(), op.toLatin1().constData(), tmp_vals.toLatin1().constData());
1197
    }
1198
1199
    // now do the operation
1200
    if(op == "~=") {
1201
        doVariableReplace(vals, place);
1202
        if(vals.length() < 4 || vals.at(0) != 's') {
1203
            qmake_error_msg(("~= operator only can handle s/// function ('" +
1204
                            s + "')").toLatin1());
1205
            return false;
1206
        }
1207
        QChar sep = vals.at(1);
1208
        QStringList func = vals.split(sep);
1209
        if(func.count() < 3 || func.count() > 4) {
1210
            qmake_error_msg(("~= operator only can handle s/// function ('" +
1211
                s + "')").toLatin1());
1212
            return false;
1213
        }
1214
        bool global = false, case_sense = true, quote = false;
1215
        if(func.count() == 4) {
1216
            global = func[3].indexOf('g') != -1;
1217
            case_sense = func[3].indexOf('i') == -1;
1218
            quote = func[3].indexOf('q') != -1;
1219
        }
1220
        QString from = func[1], to = func[2];
1221
        if(quote)
1222
            from = QRegExp::escape(from);
1223
        QRegExp regexp(from, case_sense ? Qt::CaseSensitive : Qt::CaseInsensitive);
1224
        for(QStringList::Iterator varit = varlist.begin(); varit != varlist.end();) {
1225
            if((*varit).contains(regexp)) {
1226
                (*varit) = (*varit).replace(regexp, to);
1227
                if ((*varit).isEmpty())
1228
                    varit = varlist.erase(varit);
1229
                else
1230
                    ++varit;
1231
                if(!global)
1232
                    break;
1233
            } else
1234
                ++varit;
1235
        }
1236
    } else {
1237
        QStringList vallist;
1238
        {
1239
            //doVariableReplace(vals, place);
1240
            QStringList tmp = split_value_list(vals, (var == "DEPENDPATH" || var == "INCLUDEPATH"));
1241
            for(int i = 0; i < tmp.size(); ++i)
1242
                vallist += doVariableReplaceExpand(tmp[i], place);
1243
        }
1244
1245
        if(op == "=") {
1246
            if(!varlist.isEmpty()) {
1247
                bool send_warning = false;
1248
                if(var != "TEMPLATE" && var != "TARGET") {
1249
                    QSet<QString> incoming_vals = vallist.toSet();
1250
                    for(int i = 0; i < varlist.size(); ++i) {
1251
                        const QString var = varlist.at(i).trimmed();
1252
                        if(!var.isEmpty() && !incoming_vals.contains(var)) {
1253
                            send_warning = true;
1254
                            break;
1255
                        }
1256
                    }
1257
                }
1258
                if(send_warning)
1259
                    warn_msg(WarnParser, "Operator=(%s) clears variables previously set: %s:%d",
1260
                             var.toLatin1().constData(), parser.file.toLatin1().constData(), parser.line_no);
1261
            }
1262
            varlist.clear();
1263
        }
1264
        for(QStringList::ConstIterator valit = vallist.begin();
1265
            valit != vallist.end(); ++valit) {
1266
            if((*valit).isEmpty())
1267
                continue;
1268
            if((op == "*=" && !varlist.contains((*valit))) ||
1269
               op == "=" || op == "+=")
1270
                varlist.append((*valit));
1271
            else if(op == "-=")
1272
                varlist.removeAll((*valit));
1273
        }
1274
        if(var == "REQUIRES") // special case to get communicated to backends!
1275
            doProjectCheckReqs(vallist, place);
1276
    }
1277
    return true;
1278
}
1279
1280
bool
1281
QMakeProject::read(QTextStream &file, QMap<QString, QStringList> &place)
1282
{
1283
    int numLines = 0;
1284
    bool ret = true;
1285
    QString s;
1286
    while(!file.atEnd()) {
1287
        parser.line_no++;
1288
        QString line = file.readLine().trimmed();
1289
        int prelen = line.length();
1290
1291
        int hash_mark = line.indexOf("#");
1292
        if(hash_mark != -1) //good bye comments
1293
            line = line.left(hash_mark).trimmed();
1294
        if(!line.isEmpty() && line.right(1) == "\\") {
1295
            if(!line.startsWith("#")) {
1296
                line.truncate(line.length() - 1);
1297
                s += line + Option::field_sep;
1298
                ++numLines;
1299
            }
1300
        } else if(!line.isEmpty() || (line.isEmpty() && !prelen)) {
1301
            if(s.isEmpty() && line.isEmpty())
1302
                continue;
1303
            if(!line.isEmpty()) {
1304
                s += line;
1305
                ++numLines;
1306
            }
1307
            if(!s.isEmpty()) {
1308
                if(!(ret = parse(s, place, numLines))) {
1309
                    s = "";
1310
                    numLines = 0;
1311
                    break;
1312
                }
1313
                s = "";
1314
                numLines = 0;
1315
            }
1316
        }
1317
    }
1318
    if (!s.isEmpty())
1319
        ret = parse(s, place, numLines);
1320
    return ret;
1321
}
1322
1323
bool
1324
QMakeProject::read(const QString &file, QMap<QString, QStringList> &place)
1325
{
1326
    parser_info pi = parser;
1327
    reset();
1328
1329
    const QString oldpwd = qmake_getpwd();
1330
    QString filename = Option::fixPathToLocalOS(file);
1331
    doVariableReplace(filename, place);
1332
    bool ret = false, using_stdin = false;
1333
    QFile qfile;
1334
    if(!strcmp(filename.toLatin1(), "-")) {
1335
        qfile.setFileName("");
1336
        ret = qfile.open(stdin, QIODevice::ReadOnly);
1337
        using_stdin = true;
1338
    } else if(QFileInfo(file).isDir()) {
1339
        return false;
1340
    } else {
1341
        qfile.setFileName(filename);
1342
        ret = qfile.open(QIODevice::ReadOnly);
1343
        qmake_setpwd(QFileInfo(filename).absolutePath());
1344
    }
1345
    if(ret) {
1346
        parser_info pi = parser;
1347
        parser.from_file = true;
1348
        parser.file = filename;
1349
        parser.line_no = 0;
1350
        QTextStream t(&qfile);
1351
        ret = read(t, place);
1352
        if(!using_stdin)
1353
            qfile.close();
1354
    }
1355
    if(scope_blocks.count() != 1) {
1356
        qmake_error_msg("Unterminated conditional block at end of file");
1357
        ret = false;
1358
    }
1359
    parser = pi;
1360
    qmake_setpwd(oldpwd);
1361
    return ret;
1362
}
1363
1364
bool
1365
QMakeProject::read(const QString &project, uchar cmd)
1366
{
1367
    pfile = QFileInfo(project).absoluteFilePath();
1368
    return read(cmd);
1369
}
1370
1371
bool
1372
QMakeProject::read(uchar cmd)
1373
{
1374
    if(cfile.isEmpty()) {
1375
        //find out where qmake (myself) lives
1376
        if (!base_vars.contains("QMAKE_QMAKE")) {
1377
            if (!Option::qmake_abslocation.isNull())
1378
                base_vars["QMAKE_QMAKE"] = QStringList(Option::qmake_abslocation);
1379
            else
1380
                base_vars["QMAKE_QMAKE"] = QStringList("qmake");
1381
        }
1382
1383
        // hack to get the Option stuff in there
1384
        base_vars["QMAKE_EXT_OBJ"] = QStringList(Option::obj_ext);
1385
        base_vars["QMAKE_EXT_CPP"] = Option::cpp_ext;
1386
        base_vars["QMAKE_EXT_C"] = Option::c_ext;
1387
        base_vars["QMAKE_EXT_H"] = Option::h_ext;
1388
        base_vars["QMAKE_SH"] = Option::shellPath;
1389
        if(!Option::user_template_prefix.isEmpty())
1390
            base_vars["TEMPLATE_PREFIX"] = QStringList(Option::user_template_prefix);
1391
1392
        if(cmd & ReadCache && Option::mkfile::do_cache) {        // parse the cache
1393
            int cache_depth = -1;
1394
            QString qmake_cache = Option::mkfile::cachefile;
1395
            if(qmake_cache.isEmpty())  { //find it as it has not been specified
1396
                QString dir = QDir::toNativeSeparators(Option::output_dir);
1397
                while(!QFile::exists((qmake_cache = dir + QDir::separator() + ".qmake.cache"))) {
1398
                    dir = dir.left(dir.lastIndexOf(QDir::separator()));
1399
                    if(dir.isEmpty() || dir.indexOf(QDir::separator()) == -1) {
1400
                        qmake_cache = "";
1401
                        break;
1402
                    }
1403
                    if(cache_depth == -1)
1404
                        cache_depth = 1;
1405
                    else
1406
                        cache_depth++;
1407
                }
1408
            } else {
1409
                QString abs_cache = QFileInfo(Option::mkfile::cachefile).absoluteDir().path();
1410
                if(Option::output_dir.startsWith(abs_cache))
1411
                    cache_depth = Option::output_dir.mid(abs_cache.length()).count('/');
1412
            }
1413
            if(!qmake_cache.isEmpty()) {
1414
                if(read(qmake_cache, cache)) {
1415
                    Option::mkfile::cachefile_depth = cache_depth;
1416
                    Option::mkfile::cachefile = qmake_cache;
1417
                    if(Option::mkfile::qmakespec.isEmpty() && !cache["QMAKESPEC"].isEmpty())
1418
                        Option::mkfile::qmakespec = cache["QMAKESPEC"].first();
1419
                }
1420
            }
1421
        }
1422
        if(cmd & ReadConf) {             // parse mkspec
1423
            QString qmakespec = fixEnvVariables(Option::mkfile::qmakespec);
1424
            QStringList mkspec_roots = qmake_mkspec_paths();
1425
            debug_msg(2, "Looking for mkspec %s in (%s)", qmakespec.toLatin1().constData(),
1426
                      mkspec_roots.join("::").toLatin1().constData());
1427
            if(qmakespec.isEmpty()) {
1428
                for(QStringList::ConstIterator it = mkspec_roots.begin(); it != mkspec_roots.end(); ++it) {
1429
                    QString mkspec = (*it) + QDir::separator() + "default";
1430
                    QFileInfo default_info(mkspec);
1431
                    if(default_info.exists() && default_info.isDir()) {
1432
                        qmakespec = mkspec;
1433
                        break;
1434
                    }
1435
                }
1436
                if(qmakespec.isEmpty()) {
1437
                    fprintf(stderr, "QMAKESPEC has not been set, so configuration cannot be deduced.\n");
1438
                    return false;
1439
                }
1440
                Option::mkfile::qmakespec = qmakespec;
1441
            }
1442
1443
            if(QDir::isRelativePath(qmakespec)) {
1444
                if (QFile::exists(qmakespec+"/qmake.conf")) {
1445
                    Option::mkfile::qmakespec = QFileInfo(Option::mkfile::qmakespec).absoluteFilePath();
1446
                } else if (QFile::exists(Option::output_dir+"/"+qmakespec+"/qmake.conf")) {
1447
                    qmakespec = Option::mkfile::qmakespec = QFileInfo(Option::output_dir+"/"+qmakespec).absoluteFilePath();
1448
                } else {
1449
                    bool found_mkspec = false;
1450
                    for(QStringList::ConstIterator it = mkspec_roots.begin(); it != mkspec_roots.end(); ++it) {
1451
                        QString mkspec = (*it) + QDir::separator() + qmakespec;
1452
                        if(QFile::exists(mkspec)) {
1453
                            found_mkspec = true;
1454
                            Option::mkfile::qmakespec = qmakespec = mkspec;
1455
                            break;
1456
                        }
1457
                    }
1458
                    if(!found_mkspec) {
1459
                        fprintf(stderr, "Could not find mkspecs for your QMAKESPEC(%s) after trying:\n\t%s\n",
1460
                                qmakespec.toLatin1().constData(), mkspec_roots.join("\n\t").toLatin1().constData());
1461
                        return false;
1462
                    }
1463
                }
1464
            }
1465
1466
            // parse qmake configuration
1467
            while(qmakespec.endsWith(QString(QChar(QDir::separator()))))
1468
                qmakespec.truncate(qmakespec.length()-1);
1469
            QString spec = qmakespec + QDir::separator() + "qmake.conf";
1470
            if(!QFile::exists(spec) &&
1471
               QFile::exists(qmakespec + QDir::separator() + "tmake.conf"))
1472
                spec = qmakespec + QDir::separator() + "tmake.conf";
1473
            debug_msg(1, "QMAKESPEC conf: reading %s", spec.toLatin1().constData());
1474
            if(!read(spec, base_vars)) {
1475
                fprintf(stderr, "Failure to read QMAKESPEC conf file %s.\n", spec.toLatin1().constData());
1476
                return false;
1477
            }
1478
            if(Option::mkfile::do_cache && !Option::mkfile::cachefile.isEmpty()) {
1479
                debug_msg(1, "QMAKECACHE file: reading %s", Option::mkfile::cachefile.toLatin1().constData());
1480
                read(Option::mkfile::cachefile, base_vars);
1481
            }
1482
        }
1483
1484
        if(cmd & ReadFeatures) {
1485
            debug_msg(1, "Processing default_pre: %s", vars["CONFIG"].join("::").toLatin1().constData());
1486
            if(doProjectInclude("default_pre", IncludeFlagFeature, base_vars) == IncludeNoExist)
1487
                doProjectInclude("default", IncludeFlagFeature, base_vars);
1488
        }
1489
    }
1490
1491
    vars = base_vars; // start with the base
1492
1493
    //get a default
1494
    if(pfile != "-" && vars["TARGET"].isEmpty())
1495
        vars["TARGET"].append(QFileInfo(pfile).baseName());
1496
1497
    //before commandline
1498
    if(cmd & ReadCmdLine) {
1499
        cfile = pfile;
1500
        parser.file = "(internal)";
1501
        parser.from_file = false;
1502
        parser.line_no = 1; //really arg count now.. duh
1503
        reset();
1504
        for(QStringList::ConstIterator it = Option::before_user_vars.begin();
1505
            it != Option::before_user_vars.end(); ++it) {
1506
            if(!parse((*it), vars)) {
1507
                fprintf(stderr, "Argument failed to parse: %s\n", (*it).toLatin1().constData());
1508
                return false;
1509
            }
1510
            parser.line_no++;
1511
        }
1512
    }
1513
1514
    //commandline configs
1515
    if(cmd & ReadConfigs && !Option::user_configs.isEmpty()) {
1516
        parser.file = "(configs)";
1517
        parser.from_file = false;
1518
        parser.line_no = 1; //really arg count now.. duh
1519
        parse("CONFIG += " + Option::user_configs.join(" "), vars);
1520
    }
1521
1522
    if(cmd & ReadProFile) { // parse project file
1523
        debug_msg(1, "Project file: reading %s", pfile.toLatin1().constData());
1524
        if(pfile != "-" && !QFile::exists(pfile) && !pfile.endsWith(".pro"))
1525
            pfile += ".pro";
1526
        if(!read(pfile, vars))
1527
            return false;
1528
    }
1529
1530
    if(cmd & ReadPostFiles) { // parse post files
1531
        const QStringList l = vars["QMAKE_POST_INCLUDE_FILES"];
1532
        for(QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
1533
            if(read((*it), vars)) {
1534
                if(vars["QMAKE_INTERNAL_INCLUDED_FILES"].indexOf((*it)) == -1)
1535
                    vars["QMAKE_INTERNAL_INCLUDED_FILES"].append((*it));
1536
            }
1537
        }
1538
    }
1539
1540
    if(cmd & ReadCmdLine) {
1541
        parser.file = "(internal)";
1542
        parser.from_file = false;
1543
        parser.line_no = 1; //really arg count now.. duh
1544
        reset();
1545
        for(QStringList::ConstIterator it = Option::after_user_vars.begin();
1546
            it != Option::after_user_vars.end(); ++it) {
1547
            if(!parse((*it), vars)) {
1548
                fprintf(stderr, "Argument failed to parse: %s\n", (*it).toLatin1().constData());
1549
                return false;
1550
            }
1551
            parser.line_no++;
1552
        }
1553
    }
1554
1555
    //after configs (set in BUILDS)
1556
    if(cmd & ReadConfigs && !Option::after_user_configs.isEmpty()) {
1557
        parser.file = "(configs)";
1558
        parser.from_file = false;
1559
        parser.line_no = 1; //really arg count now.. duh
1560
        parse("CONFIG += " + Option::after_user_configs.join(" "), vars);
1561
    }
1562
1563
    if(pfile != "-" && vars["TARGET"].isEmpty())
1564
        vars["TARGET"].append(QFileInfo(pfile).baseName());
1565
1566
    if(cmd & ReadConfigs && !Option::user_configs.isEmpty()) {
1567
        parser.file = "(configs)";
1568
        parser.from_file = false;
1569
        parser.line_no = 1; //really arg count now.. duh
1570
        parse("CONFIG += " + Option::user_configs.join(" "), base_vars);
1571
    }
1572
1573
    if(cmd & ReadFeatures) {
1574
        debug_msg(1, "Processing default_post: %s", vars["CONFIG"].join("::").toLatin1().constData());
1575
        doProjectInclude("default_post", IncludeFlagFeature, vars);
1576
1577
        QHash<QString, bool> processed;
1578
        const QStringList &configs = vars["CONFIG"];
1579
        debug_msg(1, "Processing CONFIG features: %s", configs.join("::").toLatin1().constData());
1580
        while(1) {
1581
            bool finished = true;
1582
            for(int i = configs.size()-1; i >= 0; --i) {
1583
		const QString config = configs[i].toLower();
1584
                if(!processed.contains(config)) {
1585
                    processed.insert(config, true);
1586
                    if(doProjectInclude(config, IncludeFlagFeature, vars) == IncludeSuccess) {
1587
                        finished = false;
1588
                        break;
1589
                    }
1590
                }
1591
            }
1592
            if(finished)
1593
                break;
1594
        }
1595
    }
1596
    Option::postProcessProject(this);   // let Option post-process
1597
    return true;
1598
}
1599
1600
bool
1601
QMakeProject::isActiveConfig(const QString &x, bool regex, QMap<QString, QStringList> *place)
1602
{
1603
    if(x.isEmpty())
1604
        return true;
1605
1606
    //magic types for easy flipping
1607
    if(x == "true")
1608
        return true;
1609
    else if(x == "false")
1610
        return false;
1611
1612
    //mkspecs
1613
    if((Option::target_mode == Option::TARG_MACX_MODE || Option::target_mode == Option::TARG_QNX6_MODE ||
1614
        Option::target_mode == Option::TARG_UNIX_MODE) && x == "unix")
1615
        return true;
1616
    else if(Option::target_mode == Option::TARG_MACX_MODE && x == "macx")
1617
        return true;
1618
    else if(Option::target_mode == Option::TARG_QNX6_MODE && x == "qnx6")
1619
        return true;
1620
    else if(Option::target_mode == Option::TARG_MAC9_MODE && x == "mac9")
1621
        return true;
1622
    else if((Option::target_mode == Option::TARG_MAC9_MODE || Option::target_mode == Option::TARG_MACX_MODE) &&
1623
            x == "mac")
1624
        return true;
1625
    else if(Option::target_mode == Option::TARG_WIN_MODE && x == "win32")
1626
        return true;
1627
    QRegExp re(x, Qt::CaseSensitive, QRegExp::Wildcard);
1628
    static QString spec;
1629
    if(spec.isEmpty())
1630
        spec = QFileInfo(Option::mkfile::qmakespec).fileName();
1631
    if((regex && re.exactMatch(spec)) || (!regex && spec == x))
1632
        return true;
1633
#ifdef Q_OS_UNIX
1634
    else if(spec == "default") {
1635
        static char *buffer = NULL;
1636
        if(!buffer) {
1637
            buffer = (char *)malloc(1024);
1638
            qmakeAddCacheClear(qmakeFreeCacheClear, (void**)&buffer);
1639
        }
1640
        int l = readlink(Option::mkfile::qmakespec.toLatin1(), buffer, 1024);
1641
        if(l != -1) {
1642
            buffer[l] = '\0';
1643
            QString r = buffer;
1644
            if(r.lastIndexOf('/') != -1)
1645
                r = r.mid(r.lastIndexOf('/') + 1);
1646
            if((regex && re.exactMatch(r)) || (!regex && r == x))
1647
                return true;
1648
        }
1649
    }
1650
#elif defined(Q_OS_WIN)
1651
    else if(spec == "default") {
1652
        // We can't resolve symlinks as they do on Unix, so configure.exe puts the source of the
1653
        // qmake.conf at the end of the default/qmake.conf in the QMAKESPEC_ORG variable.
1654
        const QStringList &spec_org = (place ? (*place)["QMAKESPEC_ORIGINAL"]
1655
                                             : vars["QMAKESPEC_ORIGINAL"]);
1656
        if (!spec_org.isEmpty()) {
1657
            spec = spec_org.at(0);
1658
            int lastSlash = spec.lastIndexOf('/');
1659
            if(lastSlash != -1)
1660
                spec = spec.mid(lastSlash + 1);
1661
            if((regex && re.exactMatch(spec)) || (!regex && spec == x))
1662
                return true;
1663
        }
1664
    }
1665
#endif
1666
1667
    //simple matching
1668
    const QStringList &configs = (place ? (*place)["CONFIG"] : vars["CONFIG"]);
1669
    for(QStringList::ConstIterator it = configs.begin(); it != configs.end(); ++it) {
1670
        if(((regex && re.exactMatch((*it))) || (!regex && (*it) == x)) && re.exactMatch((*it)))
1671
            return true;
1672
    }
1673
    return false;
1674
}
1675
1676
bool
1677
QMakeProject::doProjectTest(QString str, QMap<QString, QStringList> &place)
1678
{
1679
    QString chk = remove_quotes(str);
1680
    if(chk.isEmpty())
1681
        return true;
1682
    bool invert_test = (chk.left(1) == "!");
1683
    if(invert_test)
1684
        chk = chk.mid(1);
1685
1686
    bool test=false;
1687
    int lparen = chk.indexOf('(');
1688
    if(lparen != -1) { // if there is an lparen in the chk, it IS a function
1689
        int rparen = chk.indexOf(')', lparen);
1690
        if(rparen == -1) {
1691
            qmake_error_msg("Function missing right paren: " + chk);
1692
        } else {
1693
            QString func = chk.left(lparen);
1694
            test = doProjectTest(func, chk.mid(lparen+1, rparen - lparen - 1), place);
1695
        }
1696
    } else {
1697
        test = isActiveConfig(chk, true, &place);
1698
    }
1699
    if(invert_test)
1700
        return !test;
1701
    return test;
1702
}
1703
1704
bool
1705
QMakeProject::doProjectTest(QString func, const QString &params,
1706
                            QMap<QString, QStringList> &place)
1707
{
1708
    return doProjectTest(func, split_arg_list(params), place);
1709
}
1710
1711
QMakeProject::IncludeStatus
1712
QMakeProject::doProjectInclude(QString file, uchar flags, QMap<QString, QStringList> &place)
1713
{
1714
    enum { UnknownFormat, ProFormat, JSFormat } format = UnknownFormat;
1715
    if(flags & IncludeFlagFeature) {
1716
        if(!file.endsWith(Option::prf_ext))
1717
            file += Option::prf_ext;
1718
        if(file.indexOf(Option::dir_sep) == -1 || !QFile::exists(file)) {
1719
            static QStringList *feature_roots = 0;
1720
            if(!feature_roots) {
1721
                feature_roots = new QStringList(qmake_feature_paths(prop));
1722
                qmakeAddCacheClear(qmakeDeleteCacheClear_QStringList, (void**)&feature_roots);
1723
            }
1724
            debug_msg(2, "Looking for feature '%s' in (%s)", file.toLatin1().constData(),
1725
			feature_roots->join("::").toLatin1().constData());
1726
            int start_root = 0;
1727
            if(parser.from_file) {
1728
                QFileInfo currFile(parser.file), prfFile(file);
1729
                if(currFile.fileName() == prfFile.fileName()) {
1730
                    currFile = QFileInfo(currFile.canonicalFilePath());
1731
                    for(int root = 0; root < feature_roots->size(); ++root) {
1732
                        prfFile = QFileInfo(feature_roots->at(root) +
1733
                                            QDir::separator() + file).canonicalFilePath();
1734
                        if(prfFile == currFile) {
1735
                            start_root = root+1;
1736
                            break;
1737
                        }
1738
                    }
1739
                }
1740
            }
1741
            for(int root = start_root; root < feature_roots->size(); ++root) {
1742
                QString prf(feature_roots->at(root) + QDir::separator() + file);
1743
                if(QFile::exists(prf + Option::js_ext)) {
1744
                    format = JSFormat;
1745
                    file = prf + Option::js_ext;
1746
                    break;
1747
                } else if(QFile::exists(prf)) {
1748
                    format = ProFormat;
1749
                    file = prf;
1750
                    break;
1751
                }
1752
            }
1753
            if(format == UnknownFormat)
1754
                return IncludeNoExist;
1755
            if(place["QMAKE_INTERNAL_INCLUDED_FEATURES"].indexOf(file) != -1)
1756
                return IncludeFeatureAlreadyLoaded;
1757
            place["QMAKE_INTERNAL_INCLUDED_FEATURES"].append(file);
1758
        }
1759
    }
1760
    if(QDir::isRelativePath(file)) {
1761
        QStringList include_roots;
1762
        if(Option::output_dir != qmake_getpwd())
1763
            include_roots << qmake_getpwd();
1764
        include_roots << Option::output_dir;
1765
        for(int root = 0; root < include_roots.size(); ++root) {
1766
            QString testName = QDir::toNativeSeparators(include_roots[root]);
1767
            if (!testName.endsWith(QString(QDir::separator())))
1768
                testName += QDir::separator();
1769
            testName += file;
1770
            if(QFile::exists(testName)) {
1771
                file = testName;
1772
                break;
1773
            }
1774
        }
1775
    }
1776
    if(format == UnknownFormat) {
1777
        if(QFile::exists(file)) {
1778
            if(file.endsWith(Option::js_ext))
1779
                format = JSFormat;
1780
            else
1781
                format = ProFormat;
1782
        } else {
1783
            return IncludeNoExist;
1784
        }
1785
    }
1786
    if(Option::mkfile::do_preprocess) //nice to see this first..
1787
        fprintf(stderr, "#switching file %s(%s) - %s:%d\n", (flags & IncludeFlagFeature) ? "load" : "include",
1788
                file.toLatin1().constData(),
1789
                parser.file.toLatin1().constData(), parser.line_no);
1790
    debug_msg(1, "Project Parser: %s'ing file %s.", (flags & IncludeFlagFeature) ? "load" : "include",
1791
              file.toLatin1().constData());
1792
1793
    QString orig_file = file;
1794
    int di = file.lastIndexOf(QDir::separator());
1795
    QString oldpwd = qmake_getpwd();
1796
    if(di != -1) {
1797
        if(!qmake_setpwd(file.left(file.lastIndexOf(QDir::separator())))) {
1798
            fprintf(stderr, "Cannot find directory: %s\n", file.left(di).toLatin1().constData());
1799
            return IncludeFailure;
1800
        }
1801
        file = file.right(file.length() - di - 1);
1802
    }
1803
    bool parsed = false;
1804
    parser_info pi = parser;
1805
    if(format == JSFormat) {
1806
#ifdef QTSCRIPT_SUPPORT
1807
        eng.globalObject().setProperty("qmake", qscript_projectWrapper(&eng, this, place));
1808
        QFile f(file);
1809
        if (f.open(QFile::ReadOnly)) {
1810
            QString code = f.readAll();
1811
            QScriptValue r = eng.evaluate(code);
1812
            if(eng.hasUncaughtException()) {
1813
                const int lineNo = eng.uncaughtExceptionLineNumber();
1814
                fprintf(stderr, "%s:%d: %s\n", file.toLatin1().constData(), lineNo,
1815
                        r.toString().toLatin1().constData());
1816
            } else {
1817
                parsed = true;
1818
                QScriptValue variables = eng.globalObject().property("qmake");
1819
                if (variables.isValid() && variables.isObject())
1820
                    qscript_createQMakeProjectMap(place, variables);
1821
            }
1822
        }
1823
#else
1824
        warn_msg(WarnParser, "%s:%d: QtScript support disabled for %s.",
1825
                 pi.file.toLatin1().constData(), pi.line_no, orig_file.toLatin1().constData());
1826
#endif
1827
    } else {
1828
        QStack<ScopeBlock> sc = scope_blocks;
1829
        IteratorBlock *it = iterator;
1830
        FunctionBlock *fu = function;
1831
        if(flags & (IncludeFlagNewProject|IncludeFlagNewParser)) {
1832
            // The "project's variables" are used in other places (eg. export()) so it's not
1833
            // possible to use "place" everywhere. Instead just set variables and grab them later
1834
            QMakeProject proj(this, &place);
1835
            if(flags & IncludeFlagNewParser) {
1836
#if 1
1837
                if(proj.doProjectInclude("default_pre", IncludeFlagFeature, proj.variables()) == IncludeNoExist)
1838
                    proj.doProjectInclude("default", IncludeFlagFeature, proj.variables());
1839
#endif
1840
                parsed = proj.read(file, proj.variables());
1841
            } else {
1842
                parsed = proj.read(file);
1843
            }
1844
            place = proj.variables();
1845
        } else {
1846
            parsed = read(file, place);
1847
        }
1848
        iterator = it;
1849
        function = fu;
1850
        scope_blocks = sc;
1851
    }
1852
    if(parsed) {
1853
        if(place["QMAKE_INTERNAL_INCLUDED_FILES"].indexOf(orig_file) == -1)
1854
            place["QMAKE_INTERNAL_INCLUDED_FILES"].append(orig_file);
1855
    } else {
1856
        warn_msg(WarnParser, "%s:%d: Failure to include file %s.",
1857
                 pi.file.toLatin1().constData(), pi.line_no, orig_file.toLatin1().constData());
1858
    }
1859
    parser = pi;
1860
    qmake_setpwd(oldpwd);
1861
    if(!parsed)
1862
        return IncludeParseFailure;
1863
    return IncludeSuccess;
1864
}
1865
1866
QStringList
1867
QMakeProject::doProjectExpand(QString func, const QString &params,
1868
                              QMap<QString, QStringList> &place)
1869
{
1870
    return doProjectExpand(func, split_arg_list(params), place);
1871
}
1872
1873
QStringList
1874
QMakeProject::doProjectExpand(QString func, QStringList args,
1875
                              QMap<QString, QStringList> &place)
1876
{
1877
    QList<QStringList> args_list;
1878
    for(int i = 0; i < args.size(); ++i) {
1879
        QStringList arg = split_value_list(args[i]), tmp;
1880
        for(int i = 0; i < arg.size(); ++i)
1881
            tmp += doVariableReplaceExpand(arg[i], place);;
1882
        args_list += tmp;
1883
    }
1884
    return doProjectExpand(func, args_list, place);
1885
}
1886
1887
QStringList
1888
QMakeProject::doProjectExpand(QString func, QList<QStringList> args_list,
1889
                              QMap<QString, QStringList> &place)
1890
{
1891
    func = func.trimmed();
1892
    if(replaceFunctions.contains(func)) {
1893
        FunctionBlock *defined = replaceFunctions[func];
1894
        function_blocks.push(defined);
1895
        QStringList ret;
1896
        defined->exec(args_list, this, place, ret);
1897
        Q_ASSERT(function_blocks.pop() == defined);
1898
        return ret;
1899
    }
1900
1901
    QStringList args; //why don't the builtin functions just use args_list? --Sam
1902
    for(int i = 0; i < args_list.size(); ++i)
1903
        args += args_list[i].join(QString(Option::field_sep));
1904
1905
    ExpandFunc func_t = qmake_expandFunctions().value(func.toLower());
1906
    debug_msg(1, "Running project expand: %s(%s) [%d]",
1907
              func.toLatin1().constData(), args.join("::").toLatin1().constData(), func_t);
1908
1909
    QStringList ret;
1910
    switch(func_t) {
1911
    case E_MEMBER: {
1912
        if(args.count() < 1 || args.count() > 3) {
1913
            fprintf(stderr, "%s:%d: member(var, start, end) requires three arguments.\n",
1914
                    parser.file.toLatin1().constData(), parser.line_no);
1915
        } else {
1916
            bool ok = true;
1917
            const QStringList &var = values(args.first(), place);
1918
            int start = 0, end = 0;
1919
            if(args.count() >= 2) {
1920
                QString start_str = args[1];
1921
                start = start_str.toInt(&ok);
1922
                if(!ok) {
1923
                    if(args.count() == 2) {
1924
                        int dotdot = start_str.indexOf("..");
1925
                        if(dotdot != -1) {
1926
                            start = start_str.left(dotdot).toInt(&ok);
1927
                            if(ok)
1928
                                end = start_str.mid(dotdot+2).toInt(&ok);
1929
                        }
1930
                    }
1931
                    if(!ok)
1932
                        fprintf(stderr, "%s:%d: member() argument 2 (start) '%s' invalid.\n",
1933
                                parser.file.toLatin1().constData(), parser.line_no,
1934
                                start_str.toLatin1().constData());
1935
                } else {
1936
                    end = start;
1937
                    if(args.count() == 3)
1938
                        end = args[2].toInt(&ok);
1939
                    if(!ok)
1940
                        fprintf(stderr, "%s:%d: member() argument 3 (end) '%s' invalid.\n",
1941
                                parser.file.toLatin1().constData(), parser.line_no,
1942
                                args[2].toLatin1().constData());
1943
                }
1944
            }
1945
            if(ok) {
1946
                if(start < 0)
1947
                    start += var.count();
1948
                if(end < 0)
1949
                    end += var.count();
1950
                if(start < 0 || start >= var.count() || end < 0 || end >= var.count()) {
1951
                    //nothing
1952
                } else if(start < end) {
1953
                    for(int i = start; i <= end && (int)var.count() >= i; i++)
1954
                        ret += var[i];
1955
                } else {
1956
                    for(int i = start; i >= end && (int)var.count() >= i && i >= 0; i--)
1957
                        ret += var[i];
1958
                }
1959
            }
1960
        }
1961
        break; }
1962
    case E_FIRST:
1963
    case E_LAST: {
1964
        if(args.count() != 1) {
1965
            fprintf(stderr, "%s:%d: %s(var) requires one argument.\n",
1966
                    parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
1967
        } else {
1968
            const QStringList &var = values(args.first(), place);
1969
            if(!var.isEmpty()) {
1970
                if(func_t == E_FIRST)
1971
                    ret = QStringList(var[0]);
1972
                else
1973
                    ret = QStringList(var[var.size()-1]);
1974
            }
1975
        }
1976
        break; }
1977
    case E_CAT: {
1978
        if(args.count() < 1 || args.count() > 2) {
1979
            fprintf(stderr, "%s:%d: cat(file) requires one argument.\n",
1980
                    parser.file.toLatin1().constData(), parser.line_no);
1981
        } else {
1982
            QString file = args[0];
1983
            file = Option::fixPathToLocalOS(file);
1984
1985
            bool singleLine = true;
1986
            if(args.count() > 1)
1987
                singleLine = (args[1].toLower() == "true");
1988
1989
            QFile qfile(file);
1990
            if(qfile.open(QIODevice::ReadOnly)) {
1991
                QTextStream stream(&qfile);
1992
                while(!stream.atEnd()) {
1993
                    ret += split_value_list(stream.readLine().trimmed());
1994
                    if(!singleLine)
1995
                        ret += "\n";
1996
                }
1997
                qfile.close();
1998
            }
1999
        }
2000
        break; }
2001
    case E_FROMFILE: {
2002
        if(args.count() != 2) {
2003
            fprintf(stderr, "%s:%d: fromfile(file, variable) requires two arguments.\n",
2004
                    parser.file.toLatin1().constData(), parser.line_no);
2005
        } else {
2006
            QString file = args[0], seek_var = args[1];
2007
            file = Option::fixPathToLocalOS(file);
2008
2009
            QMap<QString, QStringList> tmp;
2010
            if(doProjectInclude(file, IncludeFlagNewParser, tmp) == IncludeSuccess) {
2011
                if(tmp.contains("QMAKE_INTERNAL_INCLUDED_FILES")) {
2012
                    QStringList &out = place["QMAKE_INTERNAL_INCLUDED_FILES"];
2013
                    const QStringList &in = tmp["QMAKE_INTERNAL_INCLUDED_FILES"];
2014
                    for(int i = 0; i < in.size(); ++i) {
2015
                        if(out.indexOf(in[i]) == -1)
2016
                            out += in[i];
2017
                    }
2018
                }
2019
                ret = tmp[seek_var];
2020
            }
2021
        }
2022
        break; }
2023
    case E_EVAL: {
2024
        if(args.count() < 1 || args.count() > 2) {
2025
            fprintf(stderr, "%s:%d: eval(variable) requires one argument.\n",
2026
                    parser.file.toLatin1().constData(), parser.line_no);
2027
2028
        } else {
2029
            const QMap<QString, QStringList> *source = &place;
2030
            if(args.count() == 2) {
2031
                if(args.at(1) == "Global") {
2032
                    source = &vars;
2033
                } else if(args.at(1) == "Local") {
2034
                    source = &place;
2035
                } else {
2036
                    fprintf(stderr, "%s:%d: unexpected source to eval.\n", parser.file.toLatin1().constData(),
2037
                            parser.line_no);
2038
                }
2039
            }
2040
            ret += source->value(args.at(0));
2041
        }
2042
        break; }
2043
    case E_LIST: {
2044
        static int x = 0;
2045
        QString tmp;
2046
        tmp.sprintf(".QMAKE_INTERNAL_TMP_VAR_%d", x++);
2047
        ret = QStringList(tmp);
2048
        QStringList &lst = (*((QMap<QString, QStringList>*)&place))[tmp];
2049
        lst.clear();
2050
        for(QStringList::ConstIterator arg_it = args.begin();
2051
            arg_it != args.end(); ++arg_it)
2052
            lst += split_value_list((*arg_it));
2053
        break; }
2054
    case E_SPRINTF: {
2055
        if(args.count() < 1) {
2056
            fprintf(stderr, "%s:%d: sprintf(format, ...) requires one argument.\n",
2057
                    parser.file.toLatin1().constData(), parser.line_no);
2058
        } else {
2059
            QString tmp = args.at(0);
2060
            for(int i = 1; i < args.count(); ++i)
2061
                tmp = tmp.arg(args.at(i));
2062
            ret = split_value_list(tmp);
2063
        }
2064
        break; }
2065
    case E_JOIN: {
2066
        if(args.count() < 1 || args.count() > 4) {
2067
            fprintf(stderr, "%s:%d: join(var, glue, before, after) requires four"
2068
                    "arguments.\n", parser.file.toLatin1().constData(), parser.line_no);
2069
        } else {
2070
            QString glue, before, after;
2071
            if(args.count() >= 2)
2072
                glue = args[1];
2073
            if(args.count() >= 3)
2074
                before = args[2];
2075
            if(args.count() == 4)
2076
                after = args[3];
2077
            const QStringList &var = values(args.first(), place);
2078
            if(!var.isEmpty())
2079
                ret = split_value_list(before + var.join(glue) + after);
2080
        }
2081
        break; }
2082
    case E_SPLIT: {
2083
        if(args.count() < 1 || args.count() > 2) {
2084
            fprintf(stderr, "%s:%d split(var, sep) requires one or two arguments\n",
2085
                    parser.file.toLatin1().constData(), parser.line_no);
2086
        } else {
2087
            QString sep = QString(Option::field_sep);
2088
            if(args.count() >= 2)
2089
                sep = args[1];
2090
            QStringList var = values(args.first(), place);
2091
            for(QStringList::ConstIterator vit = var.begin(); vit != var.end(); ++vit) {
2092
                QStringList lst = (*vit).split(sep);
2093
                for(QStringList::ConstIterator spltit = lst.begin(); spltit != lst.end(); ++spltit)
2094
                    ret += (*spltit);
2095
            }
2096
        }
2097
        break; }
2098
    case E_BASENAME:
2099
    case E_DIRNAME:
2100
    case E_SECTION: {
2101
        bool regexp = false;
2102
        QString sep, var;
2103
        int beg=0, end=-1;
2104
        if(func_t == E_SECTION) {
2105
            if(args.count() != 3 && args.count() != 4) {
2106
                fprintf(stderr, "%s:%d section(var, sep, begin, end) requires three argument\n",
2107
                        parser.file.toLatin1().constData(), parser.line_no);
2108
            } else {
2109
                var = args[0];
2110
                sep = args[1];
2111
                beg = args[2].toInt();
2112
                if(args.count() == 4)
2113
                    end = args[3].toInt();
2114
            }
2115
        } else {
2116
            if(args.count() != 1) {
2117
                fprintf(stderr, "%s:%d %s(var) requires one argument.\n",
2118
                        parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
2119
            } else {
2120
                var = args[0];
2121
                regexp = true;
2122
                sep = "[" + QRegExp::escape(Option::dir_sep) + "/]";
2123
                if(func_t == E_DIRNAME)
2124
                    end = -2;
2125
                else
2126
                    beg = -1;
2127
            }
2128
        }
2129
        if(!var.isNull()) {
2130
            const QStringList &l = values(var, place);
2131
            for(QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
2132
                QString separator = sep;
2133
                if(regexp)
2134
                    ret += (*it).section(QRegExp(separator), beg, end);
2135
                else
2136
                    ret += (*it).section(separator, beg, end);
2137
            }
2138
        }
2139
        break; }
2140
    case E_FIND: {
2141
        if(args.count() != 2) {
2142
            fprintf(stderr, "%s:%d find(var, str) requires two arguments\n",
2143
                    parser.file.toLatin1().constData(), parser.line_no);
2144
        } else {
2145
            QRegExp regx(args[1]);
2146
            const QStringList &var = values(args.first(), place);
2147
            for(QStringList::ConstIterator vit = var.begin();
2148
                vit != var.end(); ++vit) {
2149
                if(regx.indexIn(*vit) != -1)
2150
                    ret += (*vit);
2151
            }
2152
        }
2153
        break;  }
2154
    case E_SYSTEM: {
2155
        if(args.count() < 1 || args.count() > 2) {
2156
            fprintf(stderr, "%s:%d system(execut) requires one argument.\n",
2157
                    parser.file.toLatin1().constData(), parser.line_no);
2158
        } else {
2159
            QMakeProjectEnv env(place);
2160
            char buff[256];
2161
            FILE *proc = QT_POPEN(args[0].toLatin1(), "r");
2162
            bool singleLine = true;
2163
            if(args.count() > 1)
2164
                singleLine = (args[1].toLower() == "true");
2165
            QString output;
2166
            while(proc && !feof(proc)) {
2167
                int read_in = int(fread(buff, 1, 255, proc));
2168
                if(!read_in)
2169
                    break;
2170
                for(int i = 0; i < read_in; i++) {
2171
                    if((singleLine && buff[i] == '\n') || buff[i] == '\t')
2172
                        buff[i] = ' ';
2173
                }
2174
                buff[read_in] = '\0';
2175
                output += buff;
2176
            }
2177
            ret += split_value_list(output);
2178
            if(proc)
2179
                QT_PCLOSE(proc);
2180
        }
2181
        break; }
2182
    case E_UNIQUE: {
2183
        if(args.count() != 1) {
2184
            fprintf(stderr, "%s:%d unique(var) requires one argument.\n",
2185
                    parser.file.toLatin1().constData(), parser.line_no);
2186
        } else {
2187
            const QStringList &var = values(args.first(), place);
2188
            for(int i = 0; i < var.count(); i++) {
2189
                if(!ret.contains(var[i]))
2190
                    ret.append(var[i]);
2191
            }
2192
        }
2193
        break; }
2194
    case E_QUOTE:
2195
        ret = args;
2196
        break;
2197
    case E_ESCAPE_EXPAND: {
2198
        for(int i = 0; i < args.size(); ++i) {
2199
            QChar *i_data = args[i].data();
2200
            int i_len = args[i].length();
2201
            for(int x = 0; x < i_len; ++x) {
2202
                if(*(i_data+x) == '\\' && x < i_len-1) {
2203
                    if(*(i_data+x+1) == '\\') {
2204
                        ++x;
2205
                    } else {
2206
                        struct {
2207
                            char in, out;
2208
                        } mapped_quotes[] = {
2209
                            { 'n', '\n' },
2210
                            { 't', '\t' },
2211
                            { 'r', '\r' },
2212
                            { 0, 0 }
2213
                        };
2214
                        for(int i = 0; mapped_quotes[i].in; ++i) {
2215
                            if(*(i_data+x+1) == mapped_quotes[i].in) {
2216
                                *(i_data+x) = mapped_quotes[i].out;
2217
                                if(x < i_len-2)
2218
                                    memmove(i_data+x+1, i_data+x+2, (i_len-x-2)*sizeof(QChar));
2219
                                --i_len;
2220
                                break;
2221
                            }
2222
                        }
2223
                    }
2224
                }
2225
            }
2226
            ret.append(QString(i_data, i_len));
2227
        }
2228
        break; }
2229
    case E_RE_ESCAPE: {
2230
        for(int i = 0; i < args.size(); ++i)
2231
            ret += QRegExp::escape(args[i]);
2232
        break; }
2233
    case E_UPPER:
2234
    case E_LOWER: {
2235
        for(int i = 0; i < args.size(); ++i) {
2236
            if(func_t == E_UPPER)
2237
                ret += args[i].toUpper();
2238
            else
2239
                ret += args[i].toLower();
2240
        }
2241
        break; }
2242
    case E_FILES: {
2243
        if(args.count() != 1 && args.count() != 2) {
2244
            fprintf(stderr, "%s:%d files(pattern) requires one argument.\n",
2245
                    parser.file.toLatin1().constData(), parser.line_no);
2246
        } else {
2247
            bool recursive = false;
2248
            if(args.count() == 2)
2249
                recursive = (args[1].toLower() == "true" || args[1].toInt());
2250
            QStringList dirs;
2251
            QString r = Option::fixPathToLocalOS(args[0]);
2252
            int slash = r.lastIndexOf(QDir::separator());
2253
            if(slash != -1) {
2254
                dirs.append(r.left(slash));
2255
                r = r.mid(slash+1);
2256
            } else {
2257
                dirs.append("");
2258
            }
2259
2260
            const QRegExp regex(r, Qt::CaseSensitive, QRegExp::Wildcard);
2261
            for(int d = 0; d < dirs.count(); d++) {
2262
                QString dir = dirs[d];
2263
                if(!dir.isEmpty() && !dir.endsWith(Option::dir_sep))
2264
                    dir += "/";
2265
2266
                QDir qdir(dir);
2267
                for(int i = 0; i < (int)qdir.count(); ++i) {
2268
                    if(qdir[i] == "." || qdir[i] == "..")
2269
                        continue;
2270
                    QString fname = dir + qdir[i];
2271
                    if(QFileInfo(fname).isDir()) {
2272
                        if(recursive)
2273
                            dirs.append(fname);
2274
                    }
2275
                    if(regex.exactMatch(qdir[i]))
2276
                        ret += fname;
2277
                }
2278
            }
2279
        }
2280
        break; }
2281
    case E_PROMPT: {
2282
        if(args.count() != 1) {
2283
            fprintf(stderr, "%s:%d prompt(question) requires one argument.\n",
2284
                    parser.file.toLatin1().constData(), parser.line_no);
2285
        } else if(projectFile() == "-") {
2286
            fprintf(stderr, "%s:%d prompt(question) cannot be used when '-o -' is used.\n",
2287
                    parser.file.toLatin1().constData(), parser.line_no);
2288
        } else {
2289
            QString msg = fixEnvVariables(args.first());
2290
            if(!msg.endsWith("?"))
2291
                msg += "?";
2292
            fprintf(stderr, "Project %s: %s ", func.toUpper().toLatin1().constData(),
2293
                    msg.toLatin1().constData());
2294
2295
            QFile qfile;
2296
            if(qfile.open(stdin, QIODevice::ReadOnly)) {
2297
                QTextStream t(&qfile);
2298
                ret = split_value_list(t.readLine());
2299
            }
2300
        }
2301
        break; }
2302
    case E_REPLACE: {
2303
        if(args.count() != 3 ) {
2304
            fprintf(stderr, "%s:%d replace(var, before, after) requires three arguments\n",
2305
                    parser.file.toLatin1().constData(), parser.line_no);
2306
        } else {
2307
            const QRegExp before( args[1] );
2308
            const QString after( args[2] );
2309
            QStringList var = values(args.first(), place);
2310
            for(QStringList::Iterator it = var.begin(); it != var.end(); ++it)
2311
                ret += it->replace(before, after);
2312
        }
2313
        break; }
2314
    default: {
2315
#ifdef QTSCRIPT_SUPPORT
2316
        {
2317
            QScriptValue jsFunc = eng.globalObject().property(func);
2318
            if(jsFunc.isFunction()) {
2319
                QScriptValueList jsArgs;
2320
                for(int i = 0; i < args.size(); ++i)
2321
                    jsArgs += QScriptValue(&eng, args.at(i));
2322
                QScriptValue jsRet = jsFunc.call(eng.globalObject(), jsArgs);
2323
                ret = qscriptvalue_cast<QStringList>(jsRet);
2324
                break;
2325
            }
2326
        }
2327
#endif
2328
        fprintf(stderr, "%s:%d: Unknown replace function: %s\n",
2329
                parser.file.toLatin1().constData(), parser.line_no,
2330
                func.toLatin1().constData());
2331
        break; }
2332
    }
2333
    return ret;
2334
}
2335
2336
bool
2337
QMakeProject::doProjectTest(QString func, QStringList args, QMap<QString, QStringList> &place)
2338
{
2339
    QList<QStringList> args_list;
2340
    for(int i = 0; i < args.size(); ++i) {
2341
        QStringList arg = split_value_list(args[i]), tmp;
2342
        for(int i = 0; i < arg.size(); ++i)
2343
            tmp += doVariableReplaceExpand(arg[i], place);
2344
        args_list += tmp;
2345
    }
2346
    return doProjectTest(func, args_list, place);
2347
}
2348
2349
bool
2350
QMakeProject::doProjectTest(QString func, QList<QStringList> args_list, QMap<QString, QStringList> &place)
2351
{
2352
    func = func.trimmed();
2353
2354
    if(testFunctions.contains(func)) {
2355
        FunctionBlock *defined = testFunctions[func];
2356
        QStringList ret;
2357
        function_blocks.push(defined);
2358
        defined->exec(args_list, this, place, ret);
2359
        Q_ASSERT(function_blocks.pop() == defined);
2360
2361
        if(ret.isEmpty()) {
2362
            return true;
2363
        } else {
2364
            if(ret.first() == "true") {
2365
                return true;
2366
            } else if(ret.first() == "false") {
2367
                return false;
2368
            } else {
2369
                bool ok;
2370
                int val = ret.first().toInt(&ok);
2371
                if(ok)
2372
                    return val;
2373
                fprintf(stderr, "%s:%d Unexpected return value from test %s [%s].\n",
2374
                        parser.file.toLatin1().constData(),
2375
                        parser.line_no, func.toLatin1().constData(),
2376
                        ret.join("::").toLatin1().constData());
2377
            }
2378
            return false;
2379
        }
2380
        return false;
2381
    }
2382
2383
    QStringList args; //why don't the builtin functions just use args_list? --Sam
2384
    for(int i = 0; i < args_list.size(); ++i)
2385
        args += args_list[i].join(QString(Option::field_sep));
2386
2387
    TestFunc func_t = qmake_testFunctions().value(func);
2388
    debug_msg(1, "Running project test: %s(%s) [%d]",
2389
              func.toLatin1().constData(), args.join("::").toLatin1().constData(), func_t);
2390
2391
    switch(func_t) {
2392
    case T_REQUIRES:
2393
        return doProjectCheckReqs(args, place);
2394
    case T_LESSTHAN:
2395
    case T_GREATERTHAN: {
2396
        if(args.count() != 2) {
2397
            fprintf(stderr, "%s:%d: %s(variable, value) requires two arguments.\n", parser.file.toLatin1().constData(),
2398
                    parser.line_no, func.toLatin1().constData());
2399
            return false;
2400
        }
2401
        QString rhs(args[1]), lhs(values(args[0], place).join(QString(Option::field_sep)));
2402
        bool ok;
2403
        int rhs_int = rhs.toInt(&ok);
2404
        if(ok) { // do integer compare
2405
            int lhs_int = lhs.toInt(&ok);
2406
            if(ok) {
2407
                if(func_t == T_GREATERTHAN)
2408
                    return lhs_int > rhs_int;
2409
                return lhs_int < rhs_int;
2410
            }
2411
        }
2412
        if(func_t == T_GREATERTHAN)
2413
            return lhs > rhs;
2414
        return lhs < rhs; }
2415
    case T_IF: {
2416
        if(args.count() != 1) {
2417
            fprintf(stderr, "%s:%d: if(condition) requires one argument.\n", parser.file.toLatin1().constData(),
2418
                    parser.line_no);
2419
            return false;
2420
        }
2421
        const QString cond = args.first();
2422
        const QChar *d = cond.unicode();
2423
        QChar quote = 0;
2424
        bool ret = true, or_op = false;
2425
        QString test;
2426
        for(int d_off = 0, parens = 0, d_len = cond.size(); d_off < d_len; ++d_off) {
2427
            if(!quote.isNull()) {
2428
                if(*(d+d_off) == quote)
2429
                    quote = QChar();
2430
            } else if(*(d+d_off) == '(') {
2431
                ++parens;
2432
            } else if(*(d+d_off) == ')') {
2433
                --parens;
2434
            } else if(*(d+d_off) == '"' /*|| *(d+d_off) == '\''*/) {
2435
                quote = *(d+d_off);
2436
            }
2437
            if(!parens && quote.isNull() && (*(d+d_off) == QLatin1Char(':') || *(d+d_off) == QLatin1Char('|') || d_off == d_len-1)) {
2438
                if(d_off == d_len-1)
2439
                    test += *(d+d_off);
2440
                if(!test.isEmpty()) {
2441
                    const bool success = doProjectTest(test, place);
2442
                    test = "";
2443
                    if(or_op)
2444
                        ret = ret || success;
2445
                    else
2446
                        ret = ret && success;
2447
                }
2448
                if(*(d+d_off) == QLatin1Char(':')) {
2449
                    or_op = false;
2450
                } else if(*(d+d_off) == QLatin1Char('|')) {
2451
                    or_op = true;
2452
                }
2453
            } else {
2454
                test += *(d+d_off);
2455
            }
2456
        }
2457
        return ret; }
2458
    case T_EQUALS:
2459
        if(args.count() != 2) {
2460
            fprintf(stderr, "%s:%d: %s(variable, value) requires two arguments.\n", parser.file.toLatin1().constData(),
2461
                    parser.line_no, func.toLatin1().constData());
2462
            return false;
2463
        }
2464
        return values(args[0], place).join(QString(Option::field_sep)) == args[1];
2465
    case T_EXISTS: {
2466
        if(args.count() != 1) {
2467
            fprintf(stderr, "%s:%d: exists(file) requires one argument.\n", parser.file.toLatin1().constData(),
2468
                    parser.line_no);
2469
            return false;
2470
        }
2471
        QString file = args.first();
2472
        file = Option::fixPathToLocalOS(file);
2473
2474
        if(QFile::exists(file))
2475
            return true;
2476
        //regular expression I guess
2477
        QString dirstr = qmake_getpwd();
2478
        int slsh = file.lastIndexOf(Option::dir_sep);
2479
        if(slsh != -1) {
2480
            dirstr = file.left(slsh+1);
2481
            file = file.right(file.length() - slsh - 1);
2482
        }
2483
        return QDir(dirstr).entryList(QStringList(file)).count(); }
2484
    case T_EXPORT:
2485
        if(args.count() != 1) {
2486
            fprintf(stderr, "%s:%d: export(variable) requires one argument.\n", parser.file.toLatin1().constData(),
2487
                    parser.line_no);
2488
            return false;
2489
        }
2490
        for(int i = 0; i < function_blocks.size(); ++i) {
2491
            FunctionBlock *f = function_blocks.at(i);
2492
            f->vars[args[0]] = values(args[0], place);
2493
            if(!i && f->calling_place)
2494
                (*f->calling_place)[args[0]] = values(args[0], place);
2495
        }
2496
        return true;
2497
    case T_CLEAR:
2498
        if(args.count() != 1) {
2499
            fprintf(stderr, "%s:%d: clear(variable) requires one argument.\n", parser.file.toLatin1().constData(),
2500
                    parser.line_no);
2501
            return false;
2502
        }
2503
        if(!place.contains(args[0]))
2504
            return false;
2505
        place[args[0]].clear();
2506
        return true;
2507
    case T_UNSET:
2508
        if(args.count() != 1) {
2509
            fprintf(stderr, "%s:%d: unset(variable) requires one argument.\n", parser.file.toLatin1().constData(),
2510
                    parser.line_no);
2511
            return false;
2512
        }
2513
        if(!place.contains(args[0]))
2514
            return false;
2515
        place.remove(args[0]);
2516
        return true;
2517
    case T_EVAL: {
2518
        if(args.count() < 1 && 0) {
2519
            fprintf(stderr, "%s:%d: eval(project) requires one argument.\n", parser.file.toLatin1().constData(),
2520
                    parser.line_no);
2521
            return false;
2522
        }
2523
        QString project = args.join(" ");
2524
        parser_info pi = parser;
2525
        parser.from_file = false;
2526
        parser.file = "(eval)";
2527
        parser.line_no = 0;
2528
        QTextStream t(&project, QIODevice::ReadOnly);
2529
        bool ret = read(t, place);
2530
        parser = pi;
2531
        return ret; }
2532
    case T_CONFIG: {
2533
        if(args.count() < 1 || args.count() > 2) {
2534
            fprintf(stderr, "%s:%d: CONFIG(config) requires one argument.\n", parser.file.toLatin1().constData(),
2535
                    parser.line_no);
2536
            return false;
2537
        }
2538
        if(args.count() == 1)
2539
            return isActiveConfig(args[0]);
2540
        const QStringList mutuals = args[1].split('|');
2541
        const QStringList &configs = values("CONFIG", place);
2542
        for(int i = configs.size()-1; i >= 0; i--) {
2543
            for(int mut = 0; mut < mutuals.count(); mut++) {
2544
                if(configs[i] == mutuals[mut].trimmed())
2545
                    return (configs[i] == args[0]);
2546
            }
2547
        }
2548
        return false; }
2549
    case T_SYSTEM: {
2550
        bool setup_env = true;
2551
        if(args.count() < 1 || args.count() > 2) {
2552
            fprintf(stderr, "%s:%d: system(exec) requires one argument.\n", parser.file.toLatin1().constData(),
2553
                    parser.line_no);
2554
            return false;
2555
        }
2556
        if(args.count() == 2) {
2557
            const QString sarg = args[1];
2558
            setup_env = (sarg.toLower() == "true" || sarg.toInt());
2559
        }
2560
        QMakeProjectEnv env;
2561
        if(setup_env)
2562
            env.execute(place);
2563
        bool ret = system(args[0].toLatin1().constData()) == 0;
2564
        return ret; }
2565
    case T_RETURN:
2566
        if(function_blocks.isEmpty()) {
2567
            fprintf(stderr, "%s:%d unexpected return()\n",
2568
                    parser.file.toLatin1().constData(), parser.line_no);
2569
        } else {
2570
            FunctionBlock *f = function_blocks.top();
2571
            f->cause_return = true;
2572
            if(args_list.count() >= 1)
2573
                f->return_value += args_list[0];
2574
        }
2575
        return true;
2576
    case T_BREAK:
2577
        if(iterator)
2578
            iterator->cause_break = true;
2579
        else if(!scope_blocks.isEmpty())
2580
            scope_blocks.top().ignore = true;
2581
        else
2582
            fprintf(stderr, "%s:%d unexpected break()\n",
2583
                    parser.file.toLatin1().constData(), parser.line_no);
2584
        return true;
2585
    case T_NEXT:
2586
        if(iterator)
2587
            iterator->cause_next = true;
2588
        else
2589
            fprintf(stderr, "%s:%d unexpected next()\n",
2590
                    parser.file.toLatin1().constData(), parser.line_no);
2591
        return true;
2592
    case T_DEFINED:
2593
        if(args.count() < 1 || args.count() > 2) {
2594
            fprintf(stderr, "%s:%d: defined(function) requires one argument.\n",
2595
                    parser.file.toLatin1().constData(), parser.line_no);
2596
        } else {
2597
           if(args.count() > 1) {
2598
               if(args[1] == "test")
2599
                   return testFunctions.contains(args[0]);
2600
               else if(args[1] == "replace")
2601
                   return replaceFunctions.contains(args[0]);
2602
               fprintf(stderr, "%s:%d: defined(function, type): unexpected type [%s].\n",
2603
                       parser.file.toLatin1().constData(), parser.line_no,
2604
                       args[1].toLatin1().constData());
2605
            } else {
2606
                if(replaceFunctions.contains(args[0]) || testFunctions.contains(args[0]))
2607
                    return true;
2608
            }
2609
        }
2610
        return false;
2611
    case T_CONTAINS: {
2612
        if(args.count() < 2 || args.count() > 3) {
2613
            fprintf(stderr, "%s:%d: contains(var, val) requires at lesat 2 arguments.\n",
2614
                    parser.file.toLatin1().constData(), parser.line_no);
2615
            return false;
2616
        }
2617
        QRegExp regx(args[1]);
2618
        const QStringList &l = values(args[0], place);
2619
        if(args.count() == 2) {
2620
            for(int i = 0; i < l.size(); ++i) {
2621
                const QString val = l[i];
2622
                if(regx.exactMatch(val) || val == args[1])
2623
                    return true;
2624
            }
2625
        } else {
2626
            const QStringList mutuals = args[2].split('|');
2627
            for(int i = l.size()-1; i >= 0; i--) {
2628
                const QString val = l[i];
2629
                for(int mut = 0; mut < mutuals.count(); mut++) {
2630
                    if(val == mutuals[mut].trimmed())
2631
                        return (regx.exactMatch(val) || val == args[1]);
2632
                }
2633
            }
2634
        }
2635
        return false; }
2636
    case T_INFILE: {
2637
        if(args.count() < 2 || args.count() > 3) {
2638
            fprintf(stderr, "%s:%d: infile(file, var, val) requires at least 2 arguments.\n",
2639
                    parser.file.toLatin1().constData(), parser.line_no);
2640
            return false;
2641
        }
2642
2643
        bool ret = false;
2644
        QMap<QString, QStringList> tmp;
2645
        if(doProjectInclude(Option::fixPathToLocalOS(args[0]), IncludeFlagNewParser, tmp) == IncludeSuccess) {
2646
            if(tmp.contains("QMAKE_INTERNAL_INCLUDED_FILES")) {
2647
                QStringList &out = place["QMAKE_INTERNAL_INCLUDED_FILES"];
2648
                const QStringList &in = tmp["QMAKE_INTERNAL_INCLUDED_FILES"];
2649
                for(int i = 0; i < in.size(); ++i) {
2650
                    if(out.indexOf(in[i]) == -1)
2651
                        out += in[i];
2652
                }
2653
            }
2654
            if(args.count() == 2) {
2655
                ret = tmp.contains(args[1]);
2656
            } else {
2657
                QRegExp regx(args[2]);
2658
                const QStringList &l = tmp[args[1]];
2659
                for(QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
2660
                    if(regx.exactMatch((*it)) || (*it) == args[2]) {
2661
                        ret = true;
2662
                        break;
2663
                    }
2664
                }
2665
            }
2666
        }
2667
        return ret; }
2668
    case T_COUNT:
2669
        if(args.count() != 2 && args.count() != 3) {
2670
            fprintf(stderr, "%s:%d: count(var, count) requires two arguments.\n", parser.file.toLatin1().constData(),
2671
                    parser.line_no);
2672
            return false;
2673
        }
2674
        if(args.count() == 3) {
2675
            QString comp = args[2];
2676
            if(comp == ">" || comp == "greaterThan")
2677
                return values(args[0], place).count() > args[1].toInt();
2678
            if(comp == ">=")
2679
                return values(args[0], place).count() >= args[1].toInt();
2680
            if(comp == "<" || comp == "lessThan")
2681
                return values(args[0], place).count() < args[1].toInt();
2682
            if(comp == "<=")
2683
                return values(args[0], place).count() <= args[1].toInt();
2684
            if(comp == "equals" || comp == "isEqual" || comp == "=" || comp == "==")
2685
                return values(args[0], place).count() == args[1].toInt();
2686
            fprintf(stderr, "%s:%d: unexpected modifier to count(%s)\n", parser.file.toLatin1().constData(),
2687
                    parser.line_no, comp.toLatin1().constData());
2688
            return false;
2689
        }
2690
        return values(args[0], place).count() == args[1].toInt();
2691
    case T_ISEMPTY:
2692
        if(args.count() != 1) {
2693
            fprintf(stderr, "%s:%d: isEmpty(var) requires one argument.\n", parser.file.toLatin1().constData(),
2694
                    parser.line_no);
2695
            return false;
2696
        }
2697
        return values(args[0], place).isEmpty();
2698
    case T_INCLUDE:
2699
    case T_LOAD: {
2700
        QString parseInto;
2701
        const bool include_statement = (func_t == T_INCLUDE);
2702
        bool ignore_error = include_statement;
2703
        if(args.count() == 2) {
2704
            if(func_t == T_INCLUDE) {
2705
                parseInto = args[1];
2706
            } else {
2707
                QString sarg = args[1];
2708
                ignore_error = (sarg.toLower() == "true" || sarg.toInt());
2709
            }
2710
        } else if(args.count() != 1) {
2711
            QString func_desc = "load(feature)";
2712
            if(include_statement)
2713
                func_desc = "include(file)";
2714
            fprintf(stderr, "%s:%d: %s requires one argument.\n", parser.file.toLatin1().constData(),
2715
                    parser.line_no, func_desc.toLatin1().constData());
2716
            return false;
2717
        }
2718
        QString file = args.first();
2719
        file = Option::fixPathToLocalOS(file);
2720
        uchar flags = IncludeFlagNone;
2721
        if(!include_statement)
2722
            flags |= IncludeFlagFeature;
2723
        IncludeStatus stat = IncludeFailure;
2724
        if(!parseInto.isEmpty()) {
2725
            QMap<QString, QStringList> symbols;
2726
            stat = doProjectInclude(file, flags|IncludeFlagNewProject, symbols);
2727
            if(stat == IncludeSuccess) {
2728
                QMap<QString, QStringList> out_place;
2729
                for(QMap<QString, QStringList>::ConstIterator it = place.begin(); it != place.end(); ++it) {
2730
                    const QString var = it.key();
2731
                    if(var != parseInto && !var.startsWith(parseInto + "."))
2732
                        out_place.insert(var, it.value());
2733
                }
2734
                for(QMap<QString, QStringList>::ConstIterator it = symbols.begin(); it != symbols.end(); ++it) {
2735
                    const QString var = it.key();
2736
                    if(!var.startsWith("."))
2737
                        out_place.insert(parseInto + "." + it.key(), it.value());
2738
                }
2739
                place = out_place;
2740
            }
2741
        } else {
2742
            stat = doProjectInclude(file, flags, place);
2743
        }
2744
        if(stat == IncludeFeatureAlreadyLoaded) {
2745
            warn_msg(WarnParser, "%s:%d: Duplicate of loaded feature %s",
2746
                     parser.file.toLatin1().constData(), parser.line_no, file.toLatin1().constData());
2747
        } else if(stat == IncludeNoExist && include_statement) {
2748
            warn_msg(WarnParser, "%s:%d: Unable to find file for inclusion %s",
2749
                     parser.file.toLatin1().constData(), parser.line_no, file.toLatin1().constData());
2750
            return false;
2751
        } else if(stat >= IncludeFailure) {
2752
            if(!ignore_error) {
2753
                printf("Project LOAD(): Feature %s cannot be found.\n", file.toLatin1().constData());
2754
                if (!ignore_error)
2755
#if defined(QT_BUILD_QMAKE_LIBRARY)
2756
                    return false;
2757
#else
2758
                    exit(3);
2759
#endif
2760
            }
2761
            return false;
2762
        }
2763
        return true; }
2764
    case T_DEBUG: {
2765
        if(args.count() != 2) {
2766
            fprintf(stderr, "%s:%d: debug(level, message) requires one argument.\n", parser.file.toLatin1().constData(),
2767
                    parser.line_no);
2768
            return false;
2769
        }
2770
        QString msg = fixEnvVariables(args[1]);
2771
        debug_msg(args[0].toInt(), "Project DEBUG: %s", msg.toLatin1().constData());
2772
        return true; }
2773
    case T_ERROR:
2774
    case T_MESSAGE:
2775
    case T_WARNING: {
2776
        if(args.count() != 1) {
2777
            fprintf(stderr, "%s:%d: %s(message) requires one argument.\n", parser.file.toLatin1().constData(),
2778
                    parser.line_no, func.toLatin1().constData());
2779
            return false;
2780
        }
2781
        QString msg = fixEnvVariables(args.first());
2782
        fprintf(stderr, "Project %s: %s\n", func.toUpper().toLatin1().constData(), msg.toLatin1().constData());
2783
        if(func == "error")
2784
#if defined(QT_BUILD_QMAKE_LIBRARY)
2785
            return false;
2786
#else
2787
            exit(2);
2788
#endif
2789
        return true; }
2790
    default:
2791
#ifdef QTSCRIPT_SUPPORT
2792
        {
2793
            QScriptValue jsFunc = eng.globalObject().property(func);
2794
            if(jsFunc.isFunction()) {
2795
                QScriptValueList jsArgs;
2796
                for(int i = 0; i < args.size(); ++i)
2797
                    jsArgs += QScriptValue(&eng, args.at(i));
2798
                QScriptValue jsRet = jsFunc.call(eng.globalObject(), jsArgs);
2799
                if(eng.hasUncaughtException())
2800
                    return false;
2801
                return qscriptvalue_cast<bool>(jsRet);
2802
            }
2803
        }
2804
#endif
2805
        fprintf(stderr, "%s:%d: Unknown test function: %s\n", parser.file.toLatin1().constData(), parser.line_no,
2806
                func.toLatin1().constData());
2807
    }
2808
    return false;
2809
}
2810
2811
bool
2812
QMakeProject::doProjectCheckReqs(const QStringList &deps, QMap<QString, QStringList> &place)
2813
{
2814
    bool ret = false;
2815
    for(QStringList::ConstIterator it = deps.begin(); it != deps.end(); ++it) {
2816
        bool test = doProjectTest((*it), place);
2817
        if(!test) {
2818
            debug_msg(1, "Project Parser: %s:%d Failed test: REQUIRES = %s",
2819
                      parser.file.toLatin1().constData(), parser.line_no,
2820
                      (*it).toLatin1().constData());
2821
            place["QMAKE_FAILED_REQUIREMENTS"].append((*it));
2822
            ret = false;
2823
        }
2824
    }
2825
    return ret;
2826
}
2827
2828
bool
2829
QMakeProject::test(const QString &v)
2830
{
2831
    QMap<QString, QStringList> tmp = vars;
2832
    return doProjectTest(v, tmp);
2833
}
2834
2835
bool
2836
QMakeProject::test(const QString &func, const QList<QStringList> &args)
2837
{
2838
    QMap<QString, QStringList> tmp = vars;
2839
    return doProjectTest(func, args, tmp);
2840
}
2841
2842
QStringList
2843
QMakeProject::expand(const QString &str)
2844
{
2845
    bool ok;
2846
    QMap<QString, QStringList> tmp = vars;
2847
    const QStringList ret = doVariableReplaceExpand(str, tmp, &ok);
2848
    if(ok)
2849
        return ret;
2850
    return QStringList();
2851
}
2852
2853
QStringList
2854
QMakeProject::expand(const QString &func, const QList<QStringList> &args)
2855
{
2856
    QMap<QString, QStringList> tmp = vars;
2857
    return doProjectExpand(func, args, tmp);
2858
}
2859
2860
bool
2861
QMakeProject::doVariableReplace(QString &str, QMap<QString, QStringList> &place)
2862
{
2863
    bool ret;
2864
    str = doVariableReplaceExpand(str, place, &ret).join(QString(Option::field_sep));
2865
    return ret;
2866
}
2867
2868
QStringList
2869
QMakeProject::doVariableReplaceExpand(const QString &str, QMap<QString, QStringList> &place, bool *ok)
2870
{
2871
    QStringList ret;
2872
    if(ok)
2873
        *ok = true;
2874
    if(str.isEmpty())
2875
        return ret;
2876
2877
    const ushort LSQUARE = '[';
2878
    const ushort RSQUARE = ']';
2879
    const ushort LCURLY = '{';
2880
    const ushort RCURLY = '}';
2881
    const ushort LPAREN = '(';
2882
    const ushort RPAREN = ')';
2883
    const ushort DOLLAR = '$';
2884
    const ushort SLASH = '\\';
2885
    const ushort UNDERSCORE = '_';
2886
    const ushort DOT = '.';
2887
    const ushort SPACE = ' ';
2888
    const ushort TAB = '\t';
2889
    const ushort SINGLEQUOTE = '\'';
2890
    const ushort DOUBLEQUOTE = '"';
2891
2892
    ushort unicode, quote = 0;
2893
    const QChar *str_data = str.data();
2894
    const int str_len = str.length();
2895
2896
    ushort term;
2897
    QString var, args;
2898
2899
    int replaced = 0;
2900
    QString current;
2901
    for(int i = 0; i < str_len; ++i) {
2902
        unicode = str_data[i].unicode();
2903
        const int start_var = i;
2904
        if(unicode == DOLLAR && str_len > i+2) {
2905
            unicode = str_data[++i].unicode();
2906
            if(unicode == DOLLAR) {
2907
                term = 0;
2908
                var.clear();
2909
                args.clear();
2910
                enum { VAR, ENVIRON, FUNCTION, PROPERTY } var_type = VAR;
2911
                unicode = str_data[++i].unicode();
2912
                if(unicode == LSQUARE) {
2913
                    unicode = str_data[++i].unicode();
2914
                    term = RSQUARE;
2915
                    var_type = PROPERTY;
2916
                } else if(unicode == LCURLY) {
2917
                    unicode = str_data[++i].unicode();
2918
                    var_type = VAR;
2919
                    term = RCURLY;
2920
                } else if(unicode == LPAREN) {
2921
                    unicode = str_data[++i].unicode();
2922
                    var_type = ENVIRON;
2923
                    term = RPAREN;
2924
                }
2925
                while(1) {
2926
                    if(!(unicode & (0xFF<<8)) &&
2927
                       unicode != DOT && unicode != UNDERSCORE &&
2928
                       //unicode != SINGLEQUOTE && unicode != DOUBLEQUOTE &&
2929
                       (unicode < 'a' || unicode > 'z') && (unicode < 'A' || unicode > 'Z') &&
2930
                       (unicode < '0' || unicode > '9'))
2931
                        break;
2932
                    var.append(QChar(unicode));
2933
                    if(++i == str_len)
2934
                        break;
2935
                    unicode = str_data[i].unicode();
2936
                    // at this point, i points to either the 'term' or 'next' character (which is in unicode)
2937
                }
2938
                if(var_type == VAR && unicode == LPAREN) {
2939
                    var_type = FUNCTION;
2940
                    int depth = 0;
2941
                    while(1) {
2942
                        if(++i == str_len)
2943
                            break;
2944
                        unicode = str_data[i].unicode();
2945
                        if(unicode == LPAREN) {
2946
                            depth++;
2947
                        } else if(unicode == RPAREN) {
2948
                            if(!depth)
2949
                                break;
2950
                            --depth;
2951
                        }
2952
                        args.append(QChar(unicode));
2953
                    }
2954
                    if(++i < str_len)
2955
                        unicode = str_data[i].unicode();
2956
                    else
2957
                        unicode = 0;
2958
                    // at this point i is pointing to the 'next' character (which is in unicode)
2959
                    // this might actually be a term character since you can do $${func()}
2960
                }
2961
                if(term) {
2962
                    if(unicode != term) {
2963
                        qmake_error_msg("Missing " + QString(term) + " terminator [found " + (unicode?QString(unicode):QString("end-of-line")) + "]");
2964
                        if(ok)
2965
                            *ok = false;
2966
                        return QStringList();
2967
                    }
2968
                } else {
2969
                    // move the 'cursor' back to the last char of the thing we were looking at
2970
                    --i;
2971
                }
2972
                // since i never points to the 'next' character, there is no reason for this to be set
2973
                unicode = 0;
2974
2975
                QStringList replacement;
2976
                if(var_type == ENVIRON) {
2977
                    replacement = split_value_list(QString::fromLocal8Bit(qgetenv(var.toLatin1().constData())));
2978
                } else if(var_type == PROPERTY) {
2979
                    if(prop)
2980
                        replacement = split_value_list(prop->value(var));
2981
                } else if(var_type == FUNCTION) {
2982
                    replacement = doProjectExpand(var, args, place);
2983
                } else if(var_type == VAR) {
2984
                    replacement = values(var, place);
2985
                }
2986
                if(!(replaced++) && start_var)
2987
                    current = str.left(start_var);
2988
                if(!replacement.isEmpty()) {
2989
                    if(quote) {
2990
                        current += replacement.join(QString(Option::field_sep));
2991
                    } else {
2992
                        current += replacement.takeFirst();
2993
                        if(!replacement.isEmpty()) {
2994
                            if(!current.isEmpty())
2995
                                ret.append(current);
2996
                            current = replacement.takeLast();
2997
                            if(!replacement.isEmpty())
2998
                                ret += replacement;
2999
                        }
3000
                    }
3001
                }
3002
                debug_msg(2, "Project Parser [var replace]: %s -> %s",
3003
                          str.toLatin1().constData(), var.toLatin1().constData(),
3004
                          replacement.join("::").toLatin1().constData());
3005
            } else {
3006
                if(replaced)
3007
                    current.append("$");
3008
            }
3009
        }
3010
        if(quote && unicode == quote) {
3011
            unicode = 0;
3012
            quote = 0;
3013
        } else if(unicode == SLASH) {
3014
            bool escape = false;
3015
            const char *symbols = "[]{}()$\\'\"";
3016
            for(const char *s = symbols; *s; ++s) {
3017
                if(str_data[i+1].unicode() == (ushort)*s) {
3018
                    i++;
3019
                    escape = true;
3020
                    if(!(replaced++))
3021
                        current = str.left(start_var);
3022
                    current.append(str.at(i));
3023
                    break;
3024
                }
3025
            }
3026
            if(escape || !replaced)
3027
                unicode =0;
3028
        } else if(!quote && (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE)) {
3029
            quote = unicode;
3030
            unicode = 0;
3031
            if(!(replaced++) && i)
3032
                current = str.left(i);
3033
        } else if(!quote && (unicode == SPACE || unicode == TAB)) {
3034
            unicode = 0;
3035
            if(!current.isEmpty()) {
3036
                ret.append(current);
3037
                current.clear();
3038
            }
3039
        }
3040
        if(replaced && unicode)
3041
            current.append(QChar(unicode));
3042
    }
3043
    if(!replaced)
3044
        ret = QStringList(str);
3045
    else if(!current.isEmpty())
3046
        ret.append(current);
3047
    //qDebug() << "REPLACE" << str << ret;
3048
    return ret;
3049
}
3050
3051
QStringList &QMakeProject::values(const QString &_var, QMap<QString, QStringList> &place)
3052
{
3053
    QString var = varMap(_var);
3054
    if(var == QLatin1String("LITERAL_WHITESPACE")) { //a real space in a token)
3055
        var = ".BUILTIN." + var;
3056
        place[var] = QStringList(QLatin1String("\t"));
3057
    } else if(var == QLatin1String("LITERAL_DOLLAR")) { //a real $
3058
        var = ".BUILTIN." + var;
3059
        place[var] = QStringList(QLatin1String("$"));
3060
    } else if(var == QLatin1String("LITERAL_HASH")) { //a real #
3061
        var = ".BUILTIN." + var;
3062
        place[var] = QStringList("#");
3063
    } else if(var == QLatin1String("OUT_PWD")) { //the out going dir
3064
        var = ".BUILTIN." + var;
3065
        place[var] =  QStringList(Option::output_dir);
3066
    } else if(var == QLatin1String("PWD") ||  //current working dir (of _FILE_)
3067
              var == QLatin1String("IN_PWD")) {
3068
        var = ".BUILTIN." + var;
3069
        place[var] = QStringList(qmake_getpwd());
3070
    } else if(var == QLatin1String("DIR_SEPARATOR")) {
3071
        var = ".BUILTIN." + var;
3072
        place[var] =  QStringList(Option::dir_sep);
3073
    } else if(var == QLatin1String("DIRLIST_SEPARATOR")) {
3074
        var = ".BUILTIN." + var;
3075
        place[var] = QStringList(Option::dirlist_sep);
3076
    } else if(var == QLatin1String("_LINE_")) { //parser line number
3077
        var = ".BUILTIN." + var;
3078
        place[var] = QStringList(QString::number(parser.line_no));
3079
    } else if(var == QLatin1String("_FILE_")) { //parser file
3080
        var = ".BUILTIN." + var;
3081
        place[var] = QStringList(parser.file);
3082
    } else if(var == QLatin1String("_DATE_")) { //current date/time
3083
        var = ".BUILTIN." + var;
3084
        place[var] = QStringList(QDateTime::currentDateTime().toString());
3085
    } else if(var == QLatin1String("_PRO_FILE_")) {
3086
        var = ".BUILTIN." + var;
3087
        place[var] = QStringList(pfile);
3088
    } else if(var == QLatin1String("_PRO_FILE_PWD_")) {
3089
        var = ".BUILTIN." + var;
3090
        place[var] =  QStringList(QFileInfo(pfile).absolutePath());
3091
    } else if(var == QLatin1String("_QMAKE_CACHE_")) {
3092
        var = ".BUILTIN." + var;
3093
        if(Option::mkfile::do_cache)
3094
            place[var] = QStringList(Option::mkfile::cachefile);
3095
    } else if(var == QLatin1String("TEMPLATE")) {
3096
        if(!Option::user_template.isEmpty()) {
3097
            var = ".BUILTIN.USER." + var;
3098
            place[var] =  QStringList(Option::user_template);
3099
        } else if(!place[var].isEmpty()) {
3100
            QString orig_template = place["TEMPLATE"].first(), real_template;
3101
            if(!Option::user_template_prefix.isEmpty() && !orig_template.startsWith(Option::user_template_prefix))
3102
                real_template = Option::user_template_prefix + orig_template;
3103
            if(real_template.endsWith(".t"))
3104
                real_template = real_template.left(real_template.length()-2);
3105
            if(!real_template.isEmpty()) {
3106
                var = ".BUILTIN." + var;
3107
                place[var] = QStringList(real_template);
3108
            }
3109
        } else {
3110
            var = ".BUILTIN." + var;
3111
            place[var] =  QStringList("app");
3112
        }
3113
    } else if(var.startsWith(QLatin1String("QMAKE_HOST."))) {
3114
        QString ret, type = var.mid(11);
3115
#if defined(Q_OS_WIN32)
3116
        if(type == "os") {
3117
            ret = "Windows";
3118
        } else if(type == "name") {
3119
            DWORD name_length = 1024;
3120
            TCHAR name[1024];
3121
            if(GetComputerName(name, &name_length))
3122
                ret = QString::fromUtf16((ushort*)name, name_length);
3123
        } else if(type == "version" || type == "version_string") {
3124
            QSysInfo::WinVersion ver = QSysInfo::WindowsVersion;
3125
            if(type == "version")
3126
                ret = QString::number(ver);
3127
            else if(ver == QSysInfo::WV_Me)
3128
                ret = "WinMe";
3129
            else if(ver == QSysInfo::WV_95)
3130
                ret = "Win95";
3131
            else if(ver == QSysInfo::WV_98)
3132
                ret = "Win98";
3133
            else if(ver == QSysInfo::WV_NT)
3134
                ret = "WinNT";
3135
            else if(ver == QSysInfo::WV_2000)
3136
                ret = "Win2000";
3137
            else if(ver == QSysInfo::WV_2000)
3138
                ret = "Win2003";
3139
            else if(ver == QSysInfo::WV_XP)
3140
                ret = "WinXP";
3141
            else if(ver == QSysInfo::WV_VISTA)
3142
                ret = "WinVista";
3143
            else
3144
                ret = "Unknown";
3145
        } else if(type == "arch") {
3146
            SYSTEM_INFO info;
3147
            GetSystemInfo(&info);
3148
            switch(info.wProcessorArchitecture) {
3149
#ifdef PROCESSOR_ARCHITECTURE_AMD64
3150
            case PROCESSOR_ARCHITECTURE_AMD64:
3151
                ret = "x86_64";
3152
                break;
3153
#endif
3154
            case PROCESSOR_ARCHITECTURE_INTEL:
3155
                ret = "x86";
3156
                break;
3157
            case PROCESSOR_ARCHITECTURE_IA64:
3158
#ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64
3159
            case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
3160
#endif
3161
                ret = "IA64";
3162
                break;
3163
            default:
3164
                ret = "Unknown";
3165
                break;
3166
            }
3167
        }
3168
#elif defined(Q_OS_UNIX)
3169
        struct utsname name;
3170
        if(!uname(&name)) {
3171
            if(type == "os")
3172
                ret = name.sysname;
3173
            else if(type == "name")
3174
                ret = name.nodename;
3175
            else if(type == "version")
3176
                ret = name.release;
3177
            else if(type == "version_string")
3178
                ret = name.version;
3179
            else if(type == "arch")
3180
                ret = name.machine;
3181
        }
3182
#endif
3183
        var = ".BUILTIN.HOST." + type;
3184
        place[var] = QStringList(ret);
3185
    } else if (var == QLatin1String("QMAKE_DIR_SEP")) {
3186
        if (place[var].isEmpty())
3187
            return values("DIR_SEPARATOR", place);
3188
    }
3189
    //qDebug("REPLACE [%s]->[%s]", qPrintable(var), qPrintable(place[var].join("::")));
3190
    return place[var];
3191
}
3192
3193
QT_END_NAMESPACE