make QMakeMetaInfo a little less inefficient with libtool .la files
[profile/ivi/qtbase.git] / qmake / project.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the qmake application of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "project.h"
43 #include "property.h"
44 #include "option.h"
45 #include "cachekeys.h"
46 #include "generators/metamakefile.h"
47
48 #include <qdatetime.h>
49 #include <qfile.h>
50 #include <qfileinfo.h>
51 #include <qdir.h>
52 #include <qregexp.h>
53 #include <qtextstream.h>
54 #include <qstack.h>
55 #include <qdebug.h>
56 #ifdef Q_OS_UNIX
57 #include <time.h>
58 #include <utime.h>
59 #include <errno.h>
60 #include <unistd.h>
61 #include <sys/stat.h>
62 #include <sys/utsname.h>
63 #elif defined(Q_OS_WIN32)
64 #include <windows.h>
65 #endif
66 #include <stdio.h>
67 #include <stdlib.h>
68
69 #ifdef Q_OS_WIN32
70 #define QT_POPEN _popen
71 #define QT_PCLOSE _pclose
72 #else
73 #define QT_POPEN popen
74 #define QT_PCLOSE pclose
75 #endif
76
77 QT_BEGIN_NAMESPACE
78
79 //expand functions
80 enum ExpandFunc { E_MEMBER=1, E_FIRST, E_LAST, E_CAT, E_FROMFILE, E_EVAL, E_LIST,
81                   E_SPRINTF, E_FORMAT_NUMBER, E_JOIN, E_SPLIT, E_BASENAME, E_DIRNAME, E_SECTION,
82                   E_FIND, E_SYSTEM, E_UNIQUE, E_REVERSE, E_QUOTE, E_ESCAPE_EXPAND,
83                   E_UPPER, E_LOWER, E_FILES, E_PROMPT, E_RE_ESCAPE, E_VAL_ESCAPE, E_REPLACE,
84                   E_SIZE, E_SORT_DEPENDS, E_RESOLVE_DEPENDS, E_ENUMERATE_VARS,
85                   E_SHADOWED, E_ABSOLUTE_PATH, E_RELATIVE_PATH, E_CLEAN_PATH,
86                   E_SYSTEM_PATH, E_SHELL_PATH, E_SYSTEM_QUOTE, E_SHELL_QUOTE };
87 QHash<QString, ExpandFunc> qmake_expandFunctions()
88 {
89     static QHash<QString, ExpandFunc> *qmake_expand_functions = 0;
90     if(!qmake_expand_functions) {
91         qmake_expand_functions = new QHash<QString, ExpandFunc>;
92         qmakeAddCacheClear(qmakeDeleteCacheClear<QHash<QString, ExpandFunc> >, (void**)&qmake_expand_functions);
93         qmake_expand_functions->insert("member", E_MEMBER);
94         qmake_expand_functions->insert("first", E_FIRST);
95         qmake_expand_functions->insert("last", E_LAST);
96         qmake_expand_functions->insert("cat", E_CAT);
97         qmake_expand_functions->insert("fromfile", E_FROMFILE);
98         qmake_expand_functions->insert("eval", E_EVAL);
99         qmake_expand_functions->insert("list", E_LIST);
100         qmake_expand_functions->insert("sprintf", E_SPRINTF);
101         qmake_expand_functions->insert("format_number", E_FORMAT_NUMBER);
102         qmake_expand_functions->insert("join", E_JOIN);
103         qmake_expand_functions->insert("split", E_SPLIT);
104         qmake_expand_functions->insert("basename", E_BASENAME);
105         qmake_expand_functions->insert("dirname", E_DIRNAME);
106         qmake_expand_functions->insert("section", E_SECTION);
107         qmake_expand_functions->insert("find", E_FIND);
108         qmake_expand_functions->insert("system", E_SYSTEM);
109         qmake_expand_functions->insert("unique", E_UNIQUE);
110         qmake_expand_functions->insert("reverse", E_REVERSE);
111         qmake_expand_functions->insert("quote", E_QUOTE);
112         qmake_expand_functions->insert("escape_expand", E_ESCAPE_EXPAND);
113         qmake_expand_functions->insert("upper", E_UPPER);
114         qmake_expand_functions->insert("lower", E_LOWER);
115         qmake_expand_functions->insert("re_escape", E_RE_ESCAPE);
116         qmake_expand_functions->insert("val_escape", E_VAL_ESCAPE);
117         qmake_expand_functions->insert("files", E_FILES);
118         qmake_expand_functions->insert("prompt", E_PROMPT);
119         qmake_expand_functions->insert("replace", E_REPLACE);
120         qmake_expand_functions->insert("size", E_SIZE);
121         qmake_expand_functions->insert("sort_depends", E_SORT_DEPENDS);
122         qmake_expand_functions->insert("resolve_depends", E_RESOLVE_DEPENDS);
123         qmake_expand_functions->insert("enumerate_vars", E_ENUMERATE_VARS);
124         qmake_expand_functions->insert("shadowed", E_SHADOWED);
125         qmake_expand_functions->insert("absolute_path", E_ABSOLUTE_PATH);
126         qmake_expand_functions->insert("relative_path", E_RELATIVE_PATH);
127         qmake_expand_functions->insert("clean_path", E_CLEAN_PATH);
128         qmake_expand_functions->insert("system_path", E_SYSTEM_PATH);
129         qmake_expand_functions->insert("shell_path", E_SHELL_PATH);
130         qmake_expand_functions->insert("system_quote", E_SYSTEM_QUOTE);
131         qmake_expand_functions->insert("shell_quote", E_SHELL_QUOTE);
132     }
133     return *qmake_expand_functions;
134 }
135 //replace functions
136 enum TestFunc { T_REQUIRES=1, T_GREATERTHAN, T_LESSTHAN, T_EQUALS,
137                 T_EXISTS, T_EXPORT, T_CLEAR, T_UNSET, T_EVAL, T_CONFIG, T_SYSTEM,
138                 T_RETURN, T_BREAK, T_NEXT, T_DEFINED, T_CONTAINS, T_INFILE,
139                 T_COUNT, T_ISEMPTY, T_INCLUDE, T_LOAD,
140                 T_DEBUG, T_ERROR, T_MESSAGE, T_WARNING, T_LOG,
141                 T_IF, T_OPTION, T_CACHE, T_MKPATH, T_WRITE_FILE, T_TOUCH };
142 QHash<QString, TestFunc> qmake_testFunctions()
143 {
144     static QHash<QString, TestFunc> *qmake_test_functions = 0;
145     if(!qmake_test_functions) {
146         qmake_test_functions = new QHash<QString, TestFunc>;
147         qmake_test_functions->insert("requires", T_REQUIRES);
148         qmake_test_functions->insert("greaterThan", T_GREATERTHAN);
149         qmake_test_functions->insert("lessThan", T_LESSTHAN);
150         qmake_test_functions->insert("equals", T_EQUALS);
151         qmake_test_functions->insert("isEqual", T_EQUALS);
152         qmake_test_functions->insert("exists", T_EXISTS);
153         qmake_test_functions->insert("export", T_EXPORT);
154         qmake_test_functions->insert("clear", T_CLEAR);
155         qmake_test_functions->insert("unset", T_UNSET);
156         qmake_test_functions->insert("eval", T_EVAL);
157         qmake_test_functions->insert("CONFIG", T_CONFIG);
158         qmake_test_functions->insert("if", T_IF);
159         qmake_test_functions->insert("isActiveConfig", T_CONFIG);
160         qmake_test_functions->insert("system", T_SYSTEM);
161         qmake_test_functions->insert("return", T_RETURN);
162         qmake_test_functions->insert("break", T_BREAK);
163         qmake_test_functions->insert("next", T_NEXT);
164         qmake_test_functions->insert("defined", T_DEFINED);
165         qmake_test_functions->insert("contains", T_CONTAINS);
166         qmake_test_functions->insert("infile", T_INFILE);
167         qmake_test_functions->insert("count", T_COUNT);
168         qmake_test_functions->insert("isEmpty", T_ISEMPTY);
169         qmake_test_functions->insert("include", T_INCLUDE);
170         qmake_test_functions->insert("load", T_LOAD);
171         qmake_test_functions->insert("debug", T_DEBUG);
172         qmake_test_functions->insert("error", T_ERROR);
173         qmake_test_functions->insert("message", T_MESSAGE);
174         qmake_test_functions->insert("warning", T_WARNING);
175         qmake_test_functions->insert("log", T_LOG);
176         qmake_test_functions->insert("option", T_OPTION);
177         qmake_test_functions->insert("cache", T_CACHE);
178         qmake_test_functions->insert("mkpath", T_MKPATH);
179         qmake_test_functions->insert("write_file", T_WRITE_FILE);
180         qmake_test_functions->insert("touch", T_TOUCH);
181     }
182     return *qmake_test_functions;
183 }
184
185 struct parser_info {
186     QString file;
187     int line_no;
188     bool from_file;
189 } parser;
190
191 static QString cached_source_root;
192 static QString cached_build_root;
193 static QStringList cached_qmakepath;
194 static QStringList cached_qmakefeatures;
195
196 static QStringList *all_feature_roots[2] = { 0, 0 };
197
198 static void
199 invalidateFeatureRoots()
200 {
201     for (int i = 0; i < 2; i++)
202         if (all_feature_roots[i])
203             all_feature_roots[i]->clear();
204 }
205
206 static QString remove_quotes(const QString &arg)
207 {
208     const ushort SINGLEQUOTE = '\'';
209     const ushort DOUBLEQUOTE = '"';
210
211     const QChar *arg_data = arg.data();
212     const ushort first = arg_data->unicode();
213     const int arg_len = arg.length();
214     if(first == SINGLEQUOTE || first == DOUBLEQUOTE) {
215         const ushort last = (arg_data+arg_len-1)->unicode();
216         if(last == first)
217             return arg.mid(1, arg_len-2);
218     }
219     return arg;
220 }
221
222 static QString varMap(const QString &x)
223 {
224     QString ret(x);
225     if(ret == "INTERFACES")
226         ret = "FORMS";
227     else if(ret == "QMAKE_POST_BUILD")
228         ret = "QMAKE_POST_LINK";
229     else if(ret == "TARGETDEPS")
230         ret = "POST_TARGETDEPS";
231     else if(ret == "LIBPATH")
232         ret = "QMAKE_LIBDIR";
233     else if(ret == "QMAKE_EXT_MOC")
234         ret = "QMAKE_EXT_CPP_MOC";
235     else if(ret == "QMAKE_MOD_MOC")
236         ret = "QMAKE_H_MOD_MOC";
237     else if(ret == "QMAKE_LFLAGS_SHAPP")
238         ret = "QMAKE_LFLAGS_APP";
239     else if(ret == "PRECOMPH")
240         ret = "PRECOMPILED_HEADER";
241     else if(ret == "PRECOMPCPP")
242         ret = "PRECOMPILED_SOURCE";
243     else if(ret == "INCPATH")
244         ret = "INCLUDEPATH";
245     else if(ret == "QMAKE_EXTRA_WIN_COMPILERS" || ret == "QMAKE_EXTRA_UNIX_COMPILERS")
246         ret = "QMAKE_EXTRA_COMPILERS";
247     else if(ret == "QMAKE_EXTRA_WIN_TARGETS" || ret == "QMAKE_EXTRA_UNIX_TARGETS")
248         ret = "QMAKE_EXTRA_TARGETS";
249     else if(ret == "QMAKE_EXTRA_UNIX_INCLUDES")
250         ret = "QMAKE_EXTRA_INCLUDES";
251     else if(ret == "QMAKE_EXTRA_UNIX_VARIABLES")
252         ret = "QMAKE_EXTRA_VARIABLES";
253     else if(ret == "QMAKE_RPATH")
254         ret = "QMAKE_LFLAGS_RPATH";
255     else if(ret == "QMAKE_FRAMEWORKDIR")
256         ret = "QMAKE_FRAMEWORKPATH";
257     else if(ret == "QMAKE_FRAMEWORKDIR_FLAGS")
258         ret = "QMAKE_FRAMEWORKPATH_FLAGS";
259     else if(ret == "IN_PWD")
260         ret = "PWD";
261     else
262         return ret;
263     warn_msg(WarnDeprecated, "%s:%d: Variable %s is deprecated; use %s instead.",
264              parser.file.toLatin1().constData(), parser.line_no,
265              x.toLatin1().constData(), ret.toLatin1().constData());
266     return ret;
267 }
268
269 static QStringList split_arg_list(const QString &params)
270 {
271     int quote = 0;
272     QStringList args;
273
274     const ushort LPAREN = '(';
275     const ushort RPAREN = ')';
276     const ushort SINGLEQUOTE = '\'';
277     const ushort DOUBLEQUOTE = '"';
278     const ushort BACKSLASH = '\\';
279     const ushort COMMA = ',';
280     const ushort SPACE = ' ';
281     //const ushort TAB = '\t';
282
283     const QChar *params_data = params.data();
284     const int params_len = params.length();
285     for(int last = 0; ;) {
286         while(last < params_len && (params_data[last].unicode() == SPACE
287                                     /*|| params_data[last].unicode() == TAB*/))
288             ++last;
289         for(int x = last, parens = 0; ; x++) {
290             if(x == params_len) {
291                 while(x > last && params_data[x-1].unicode() == SPACE)
292                     --x;
293                 args << params.mid(last, x - last);
294                 // Could do a check for unmatched parens here, but split_value_list()
295                 // is called on all our output, so mistakes will be caught anyway.
296                 return args;
297             }
298             ushort unicode = params_data[x].unicode();
299             if(x != (int)params_len-1 && unicode == BACKSLASH &&
300                 (params_data[x+1].unicode() == SINGLEQUOTE || params_data[x+1].unicode() == DOUBLEQUOTE)) {
301                 x++; //get that 'escape'
302             } else if(quote && unicode == quote) {
303                 quote = 0;
304             } else if(!quote && (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE)) {
305                 quote = unicode;
306             } else if(unicode == RPAREN) {
307                 --parens;
308             } else if(unicode == LPAREN) {
309                 ++parens;
310             }
311             if(!parens && !quote && unicode == COMMA) {
312                 int prev = last;
313                 last = x+1;
314                 while(x > prev && params_data[x-1].unicode() == SPACE)
315                     --x;
316                 args << params.mid(prev, x - prev);
317                 break;
318             }
319         }
320     }
321 }
322
323 static QStringList split_value_list(const QString &vals)
324 {
325     QString build;
326     QStringList ret;
327     ushort quote = 0;
328     int parens = 0;
329
330     const ushort LPAREN = '(';
331     const ushort RPAREN = ')';
332     const ushort SINGLEQUOTE = '\'';
333     const ushort DOUBLEQUOTE = '"';
334     const ushort BACKSLASH = '\\';
335
336     ushort unicode;
337     const QChar *vals_data = vals.data();
338     const int vals_len = vals.length();
339     for(int x = 0; x < vals_len; x++) {
340         unicode = vals_data[x].unicode();
341         if(x != (int)vals_len-1 && unicode == BACKSLASH &&
342             (vals_data[x+1].unicode() == SINGLEQUOTE || vals_data[x+1].unicode() == DOUBLEQUOTE)) {
343             build += vals_data[x++]; //get that 'escape'
344         } else if(quote && unicode == quote) {
345             quote = 0;
346         } else if(!quote && (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE)) {
347             quote = unicode;
348         } else if(unicode == RPAREN) {
349             --parens;
350         } else if(unicode == LPAREN) {
351             ++parens;
352         }
353
354         if(!parens && !quote && (vals_data[x] == Option::field_sep)) {
355             ret << build;
356             build.clear();
357         } else {
358             build += vals_data[x];
359         }
360     }
361     if(!build.isEmpty())
362         ret << build;
363     if (parens)
364         warn_msg(WarnDeprecated, "%s:%d: Unmatched parentheses are deprecated.",
365                  parser.file.toLatin1().constData(), parser.line_no);
366     // Could do a check for unmatched quotes here, but doVariableReplaceExpand()
367     // is called on all our output, so mistakes will be caught anyway.
368     return ret;
369 }
370
371 //just a parsable entity
372 struct ParsableBlock
373 {
374     ParsableBlock() : ref_cnt(1) { }
375     virtual ~ParsableBlock() { }
376
377     struct Parse {
378         QString text;
379         parser_info pi;
380         Parse(const QString &t) : text(t){ pi = parser; }
381     };
382     QList<Parse> parselist;
383
384     inline int ref() { return ++ref_cnt; }
385     inline int deref() { return --ref_cnt; }
386
387 protected:
388     int ref_cnt;
389     virtual bool continueBlock() = 0;
390     bool eval(QMakeProject *p, QHash<QString, QStringList> &place);
391 };
392
393 bool ParsableBlock::eval(QMakeProject *p, QHash<QString, QStringList> &place)
394 {
395     //save state
396     parser_info pi = parser;
397     const int block_count = p->scope_blocks.count();
398
399     //execute
400     bool ret = true;
401     for(int i = 0; i < parselist.count(); i++) {
402         parser = parselist.at(i).pi;
403         if(!(ret = p->parse(parselist.at(i).text, place)) || !continueBlock())
404             break;
405     }
406
407     //restore state
408     parser = pi;
409     while(p->scope_blocks.count() > block_count)
410         p->scope_blocks.pop();
411     return ret;
412 }
413
414 //defined functions
415 struct FunctionBlock : public ParsableBlock
416 {
417     FunctionBlock() : calling_place(0), scope_level(1), cause_return(false) { }
418
419     QHash<QString, QStringList> vars;
420     QHash<QString, QStringList> *calling_place;
421     QStringList return_value;
422     int scope_level;
423     bool cause_return;
424
425     bool exec(const QList<QStringList> &args,
426               QMakeProject *p, QHash<QString, QStringList> &place, QStringList &functionReturn);
427     virtual bool continueBlock() { return !cause_return; }
428 };
429
430 bool FunctionBlock::exec(const QList<QStringList> &args,
431                          QMakeProject *proj, QHash<QString, QStringList> &place,
432                          QStringList &functionReturn)
433 {
434     //save state
435 #if 1
436     calling_place = &place;
437 #else
438     calling_place = &proj->variables();
439 #endif
440     return_value.clear();
441     cause_return = false;
442
443     //execute
444 #if 0
445     vars = proj->variables(); // should be place so that local variables can be inherited
446 #else
447     vars = place;
448 #endif
449     vars["ARGS"].clear();
450     for(int i = 0; i < args.count(); i++) {
451         vars["ARGS"] += args[i];
452         vars[QString::number(i+1)] = args[i];
453     }
454     bool ret = ParsableBlock::eval(proj, vars);
455     functionReturn = return_value;
456
457     //restore state
458     calling_place = 0;
459     return_value.clear();
460     vars.clear();
461     return ret;
462 }
463
464 //loops
465 struct IteratorBlock : public ParsableBlock
466 {
467     IteratorBlock() : scope_level(1), loop_forever(false), cause_break(false), cause_next(false) { }
468
469     int scope_level;
470
471     struct Test {
472         QString func;
473         QStringList args;
474         bool invert;
475         parser_info pi;
476         Test(const QString &f, QStringList &a, bool i) : func(f), args(a), invert(i) { pi = parser; }
477     };
478     QList<Test> test;
479
480     QString variable;
481
482     bool loop_forever, cause_break, cause_next;
483     QStringList list;
484
485     bool exec(QMakeProject *p, QHash<QString, QStringList> &place);
486     virtual bool continueBlock() { return !cause_next && !cause_break; }
487 };
488 bool IteratorBlock::exec(QMakeProject *p, QHash<QString, QStringList> &place)
489 {
490     bool ret = true;
491     QStringList::Iterator it;
492     if(!loop_forever)
493         it = list.begin();
494     int iterate_count = 0;
495     //save state
496     IteratorBlock *saved_iterator = p->iterator;
497     p->iterator = this;
498
499     //do the loop
500     while(loop_forever || it != list.end()) {
501         cause_next = cause_break = false;
502         if(!loop_forever && (*it).isEmpty()) { //ignore empty items
503             ++it;
504             continue;
505         }
506
507         //set up the loop variable
508         QStringList va;
509         if(!variable.isEmpty()) {
510             va = place[variable];
511             if(loop_forever)
512                 place[variable] = QStringList(QString::number(iterate_count));
513             else
514                 place[variable] = QStringList(*it);
515         }
516         //do the iterations
517         bool succeed = true;
518         for(QList<Test>::Iterator test_it = test.begin(); test_it != test.end(); ++test_it) {
519             parser = (*test_it).pi;
520             succeed = p->doProjectTest((*test_it).func, (*test_it).args, place);
521             if((*test_it).invert)
522                 succeed = !succeed;
523             if(!succeed)
524                 break;
525         }
526         if(succeed)
527             ret = ParsableBlock::eval(p, place);
528         //restore the variable in the map
529         if(!variable.isEmpty())
530             place[variable] = va;
531         //loop counters
532         if(!loop_forever)
533             ++it;
534         iterate_count++;
535         if(!ret || cause_break)
536             break;
537     }
538
539     //restore state
540     p->iterator = saved_iterator;
541     return ret;
542 }
543
544 QMakeProject::ScopeBlock::~ScopeBlock()
545 {
546 #if 0
547     if(iterate)
548         delete iterate;
549 #endif
550 }
551
552 static void qmake_error_msg(const QString &msg)
553 {
554     fprintf(stderr, "%s:%d: %s\n", parser.file.toLatin1().constData(), parser.line_no,
555             msg.toLatin1().constData());
556 }
557
558 /*
559    1) environment variable QMAKEFEATURES (as separated by colons)
560    2) property variable QMAKEFEATURES (as separated by colons)
561    3) <project_root> (where .qmake.cache lives) + FEATURES_DIR
562    4) environment variable QMAKEPATH (as separated by colons) + /mkspecs/FEATURES_DIR
563    5) your QMAKESPEC/features dir
564    6) your data_install/mkspecs/FEATURES_DIR
565    7) your QMAKESPEC/../FEATURES_DIR dir
566
567    FEATURES_DIR is defined as:
568
569    1) features/(unix|win32|macx)/
570    2) features/
571 */
572 QStringList QMakeProject::qmakeFeaturePaths()
573 {
574     const QString mkspecs_concat = QLatin1String("/mkspecs");
575     const QString base_concat = QLatin1String("/features");
576     QStringList concat;
577     foreach (const QString &sfx, values("QMAKE_PLATFORM"))
578         concat << base_concat + QLatin1Char('/') + sfx;
579     concat << base_concat;
580
581     QStringList feature_roots = splitPathList(QString::fromLocal8Bit(qgetenv("QMAKEFEATURES")));
582     feature_roots += cached_qmakefeatures;
583     if(prop)
584         feature_roots += splitPathList(prop->value("QMAKEFEATURES"));
585     QStringList feature_bases;
586     if (!cached_build_root.isEmpty())
587         feature_bases << cached_build_root;
588     if (!cached_source_root.isEmpty())
589         feature_bases << cached_source_root;
590     QStringList qmakepath = splitPathList(QString::fromLocal8Bit(qgetenv("QMAKEPATH")));
591     qmakepath += cached_qmakepath;
592     foreach (const QString &path, qmakepath)
593         feature_bases << (path + mkspecs_concat);
594     if (!real_spec.isEmpty()) {
595         // The spec is already platform-dependent, so no subdirs here.
596         feature_roots << real_spec + base_concat;
597
598         // Also check directly under the root directory of the mkspecs collection
599         QFileInfo specfi(real_spec);
600         QDir specrootdir(specfi.absolutePath());
601         while (!specrootdir.isRoot()) {
602             const QString specrootpath = specrootdir.path();
603             if (specrootpath.endsWith(mkspecs_concat)) {
604                 if (QFile::exists(specrootpath + base_concat))
605                     feature_bases << specrootpath;
606                 break;
607             }
608             specrootdir.cdUp();
609         }
610     }
611     feature_bases << (QLibraryInfo::rawLocation(QLibraryInfo::HostDataPath,
612                                                 QLibraryInfo::EffectivePaths) + mkspecs_concat);
613     foreach (const QString &fb, feature_bases)
614         foreach (const QString &cc, concat)
615             feature_roots << (fb + cc);
616     feature_roots.removeDuplicates();
617
618     QStringList ret;
619     foreach (const QString &root, feature_roots)
620         if (QFileInfo(root).exists())
621             ret << root;
622     return ret;
623 }
624
625 QStringList qmake_mkspec_paths()
626 {
627     QStringList ret;
628     const QString concat = QLatin1String("/mkspecs");
629
630     QStringList qmakepath = splitPathList(QString::fromLocal8Bit(qgetenv("QMAKEPATH")));
631     qmakepath += cached_qmakepath;
632     foreach (const QString &path, qmakepath)
633         ret << (path + concat);
634     if (!cached_build_root.isEmpty())
635         ret << cached_build_root + concat;
636     if (!cached_source_root.isEmpty())
637         ret << cached_source_root + concat;
638     ret << QLibraryInfo::rawLocation(QLibraryInfo::HostDataPath, QLibraryInfo::EffectivePaths) + concat;
639     ret.removeDuplicates();
640
641     return ret;
642 }
643
644 static void
645 setTemplate(QStringList &varlist)
646 {
647     if (!Option::user_template.isEmpty()) { // Don't permit override
648         varlist = QStringList(Option::user_template);
649     } else {
650         if (varlist.isEmpty())
651             varlist << "app";
652         else
653             varlist.erase(varlist.begin() + 1, varlist.end());
654     }
655     if (!Option::user_template_prefix.isEmpty()
656         && !varlist.first().startsWith(Option::user_template_prefix)) {
657         varlist.first().prepend(Option::user_template_prefix);
658     }
659 }
660
661 QMakeProject::~QMakeProject()
662 {
663     if(own_prop)
664         delete prop;
665     cleanup();
666 }
667
668
669 void
670 QMakeProject::init(QMakeProperty *p)
671 {
672     if(!p) {
673         prop = new QMakeProperty;
674         own_prop = true;
675     } else {
676         prop = p;
677         own_prop = false;
678     }
679     host_build = false;
680     reset();
681 }
682
683 void
684 QMakeProject::cleanup()
685 {
686     for (QHash<QString, FunctionBlock*>::iterator it = replaceFunctions.begin(); it != replaceFunctions.end(); ++it)
687         if (!it.value()->deref())
688             delete it.value();
689     replaceFunctions.clear();
690     for (QHash<QString, FunctionBlock*>::iterator it = testFunctions.begin(); it != testFunctions.end(); ++it)
691         if (!it.value()->deref())
692             delete it.value();
693     testFunctions.clear();
694 }
695
696 // Duplicate project. It is *not* allowed to call the complex read() functions on the copy.
697 QMakeProject::QMakeProject(QMakeProject *p, const QHash<QString, QStringList> *_vars)
698 {
699     init(p->properties());
700     vars = _vars ? *_vars : p->variables();
701     host_build = p->host_build;
702     for(QHash<QString, FunctionBlock*>::iterator it = p->replaceFunctions.begin(); it != p->replaceFunctions.end(); ++it) {
703         it.value()->ref();
704         replaceFunctions.insert(it.key(), it.value());
705     }
706     for(QHash<QString, FunctionBlock*>::iterator it = p->testFunctions.begin(); it != p->testFunctions.end(); ++it) {
707         it.value()->ref();
708         testFunctions.insert(it.key(), it.value());
709     }
710 }
711
712 void
713 QMakeProject::reset()
714 {
715     // scope_blocks starts with one non-ignoring entity
716     scope_blocks.clear();
717     scope_blocks.push(ScopeBlock());
718     iterator = 0;
719     function = 0;
720     backslashWarned = false;
721     need_restart = false;
722 }
723
724 bool
725 QMakeProject::parse(const QString &t, QHash<QString, QStringList> &place, int numLines)
726 {
727     // To preserve the integrity of any UTF-8 characters in .pro file, temporarily replace the
728     // non-breaking space (0xA0) characters with another non-space character, so that
729     // QString::simplified() call will not replace it with space.
730     // Note: There won't be any two byte characters in .pro files, so 0x10A0 should be a safe
731     // replacement character.
732     static QChar nbsp(0xA0);
733     static QChar nbspFix(0x01A0);
734     QString s;
735     if (t.indexOf(nbsp) != -1) {
736         s = t;
737         s.replace(nbsp, nbspFix);
738         s = s.simplified();
739         s.replace(nbspFix, nbsp);
740     } else {
741         s = t.simplified();
742     }
743
744     int hash_mark = s.indexOf("#");
745     if(hash_mark != -1) //good bye comments
746         s = s.left(hash_mark);
747     if(s.isEmpty()) // blank_line
748         return true;
749
750     if(scope_blocks.top().ignore) {
751         bool continue_parsing = false;
752         // adjust scope for each block which appears on a single line
753         for(int i = 0; i < s.length(); i++) {
754             if(s[i] == '{') {
755                 scope_blocks.push(ScopeBlock(true));
756             } else if(s[i] == '}') {
757                 if(scope_blocks.count() == 1) {
758                     fprintf(stderr, "Braces mismatch %s:%d\n", parser.file.toLatin1().constData(), parser.line_no);
759                     return false;
760                 }
761                 ScopeBlock sb = scope_blocks.pop();
762                 if(sb.iterate) {
763                     sb.iterate->exec(this, place);
764                     delete sb.iterate;
765                     sb.iterate = 0;
766                 }
767                 if(!scope_blocks.top().ignore) {
768                     debug_msg(1, "Project Parser: %s:%d : Leaving block %d", parser.file.toLatin1().constData(),
769                               parser.line_no, scope_blocks.count()+1);
770                     s = s.mid(i+1).trimmed();
771                     continue_parsing = !s.isEmpty();
772                     break;
773                 }
774             }
775         }
776         if(!continue_parsing) {
777             debug_msg(1, "Project Parser: %s:%d : Ignored due to block being false.",
778                       parser.file.toLatin1().constData(), parser.line_no);
779             return true;
780         }
781     }
782
783     if(function) {
784         QString append;
785         int d_off = 0;
786         const QChar *d = s.unicode();
787         bool function_finished = false;
788         while(d_off < s.length()) {
789             if(*(d+d_off) == QLatin1Char('}')) {
790                 function->scope_level--;
791                 if(!function->scope_level) {
792                     function_finished = true;
793                     break;
794                 }
795             } else if(*(d+d_off) == QLatin1Char('{')) {
796                 function->scope_level++;
797             }
798             append += *(d+d_off);
799             ++d_off;
800         }
801         if(!append.isEmpty())
802             function->parselist.append(IteratorBlock::Parse(append));
803         if(function_finished) {
804             function = 0;
805             s = QString(d+d_off, s.length()-d_off);
806         } else {
807             return true;
808         }
809     } else if(IteratorBlock *it = scope_blocks.top().iterate) {
810         QString append;
811         int d_off = 0;
812         const QChar *d = s.unicode();
813         bool iterate_finished = false;
814         while(d_off < s.length()) {
815             if(*(d+d_off) == QLatin1Char('}')) {
816                 it->scope_level--;
817                 if(!it->scope_level) {
818                     iterate_finished = true;
819                     break;
820                 }
821             } else if(*(d+d_off) == QLatin1Char('{')) {
822                 it->scope_level++;
823             }
824             append += *(d+d_off);
825             ++d_off;
826         }
827         if(!append.isEmpty())
828             scope_blocks.top().iterate->parselist.append(IteratorBlock::Parse(append));
829         if(iterate_finished) {
830             scope_blocks.top().iterate = 0;
831             bool ret = it->exec(this, place);
832             delete it;
833             if(!ret)
834                 return false;
835             s = s.mid(d_off);
836         } else {
837             return true;
838         }
839     }
840
841     QString scope, var, op;
842     QStringList val;
843 #define SKIP_WS(d, o, l) while(o < l && (*(d+o) == QLatin1Char(' ') || *(d+o) == QLatin1Char('\t'))) ++o
844     const QChar *d = s.unicode();
845     int d_off = 0;
846     SKIP_WS(d, d_off, s.length());
847     IteratorBlock *iterator = 0;
848     bool scope_failed = false, else_line = false, or_op=false;
849     QChar quote = 0;
850     int parens = 0, scope_count=0, start_block = 0;
851     while(d_off < s.length()) {
852         if(!parens) {
853             if(*(d+d_off) == QLatin1Char('='))
854                 break;
855             if(*(d+d_off) == QLatin1Char('+') || *(d+d_off) == QLatin1Char('-') ||
856                *(d+d_off) == QLatin1Char('*') || *(d+d_off) == QLatin1Char('~')) {
857                 if(*(d+d_off+1) == QLatin1Char('=')) {
858                     break;
859                 } else if(*(d+d_off+1) == QLatin1Char(' ')) {
860                     const QChar *k = d+d_off+1;
861                     int k_off = 0;
862                     SKIP_WS(k, k_off, s.length()-d_off);
863                     if(*(k+k_off) == QLatin1Char('=')) {
864                         QString msg;
865                         qmake_error_msg(QString(d+d_off, 1) + "must be followed immediately by =");
866                         return false;
867                     }
868                 }
869             }
870         }
871
872         if(!quote.isNull()) {
873             if(*(d+d_off) == quote)
874                 quote = QChar();
875         } else if(*(d+d_off) == '(') {
876             ++parens;
877         } else if(*(d+d_off) == ')') {
878             --parens;
879         } else if(*(d+d_off) == '"' /*|| *(d+d_off) == '\''*/) {
880             quote = *(d+d_off);
881         }
882
883         if(!parens && quote.isNull() &&
884            (*(d+d_off) == QLatin1Char(':') || *(d+d_off) == QLatin1Char('{') ||
885             *(d+d_off) == QLatin1Char(')') || *(d+d_off) == QLatin1Char('|'))) {
886             scope_count++;
887             scope = var.trimmed();
888             if(*(d+d_off) == QLatin1Char(')'))
889                 scope += *(d+d_off); // need this
890             var = "";
891
892             bool test = scope_failed;
893             if(scope.isEmpty()) {
894                 test = true;
895             } else if(scope.toLower() == "else") { //else is a builtin scope here as it modifies state
896                 if(scope_count != 1 || scope_blocks.top().else_status == ScopeBlock::TestNone) {
897                     qmake_error_msg(("Unexpected " + scope + " ('" + s + "')").toLatin1());
898                     return false;
899                 }
900                 else_line = true;
901                 test = (scope_blocks.top().else_status == ScopeBlock::TestSeek);
902                 debug_msg(1, "Project Parser: %s:%d : Else%s %s.", parser.file.toLatin1().constData(), parser.line_no,
903                           scope == "else" ? "" : QString(" (" + scope + ")").toLatin1().constData(),
904                           test ? "considered" : "excluded");
905             } else {
906                 QString comp_scope = scope;
907                 bool invert_test = (comp_scope.at(0) == QLatin1Char('!'));
908                 if(invert_test)
909                     comp_scope = comp_scope.mid(1);
910                 int lparen = comp_scope.indexOf('(');
911                 if(or_op == scope_failed) {
912                     if(lparen != -1) { // if there is an lparen in the scope, it IS a function
913                         int rparen = comp_scope.lastIndexOf(')');
914                         if(rparen == -1) {
915                             qmake_error_msg("Function missing right paren: " + comp_scope);
916                             return false;
917                         }
918                         QString func = comp_scope.left(lparen);
919                         QStringList args = split_arg_list(comp_scope.mid(lparen+1, rparen - lparen - 1));
920                         if(function) {
921                             fprintf(stderr, "%s:%d: No tests can come after a function definition!\n",
922                                     parser.file.toLatin1().constData(), parser.line_no);
923                             return false;
924                         } else if(func == "for") { //for is a builtin function here, as it modifies state
925                             if(args.count() > 2 || args.count() < 1) {
926                                 fprintf(stderr, "%s:%d: for(iterate, list) requires two arguments.\n",
927                                         parser.file.toLatin1().constData(), parser.line_no);
928                                 return false;
929                             } else if(iterator) {
930                                 fprintf(stderr, "%s:%d unexpected nested for()\n",
931                                         parser.file.toLatin1().constData(), parser.line_no);
932                                 return false;
933                             }
934
935                             iterator = new IteratorBlock;
936                             QString it_list;
937                             if(args.count() == 1) {
938                                 doVariableReplace(args[0], place);
939                                 it_list = args[0];
940                                 if(args[0] != "ever") {
941                                     delete iterator;
942                                     iterator = 0;
943                                     fprintf(stderr, "%s:%d: for(iterate, list) requires two arguments.\n",
944                                             parser.file.toLatin1().constData(), parser.line_no);
945                                     return false;
946                                 }
947                                 it_list = "forever";
948                             } else if(args.count() == 2) {
949                                 iterator->variable = args[0];
950                                 doVariableReplace(args[1], place);
951                                 it_list = args[1];
952                             }
953                             QStringList list = place[it_list];
954                             if(list.isEmpty()) {
955                                 if(it_list == "forever") {
956                                     iterator->loop_forever = true;
957                                 } else {
958                                     int dotdot = it_list.indexOf("..");
959                                     if(dotdot != -1) {
960                                         bool ok;
961                                         int start = it_list.left(dotdot).toInt(&ok);
962                                         if(ok) {
963                                             int end = it_list.mid(dotdot+2).toInt(&ok);
964                                             if(ok) {
965                                                 if(start < end) {
966                                                     for(int i = start; i <= end; i++)
967                                                         list << QString::number(i);
968                                                 } else {
969                                                     for(int i = start; i >= end; i--)
970                                                         list << QString::number(i);
971                                                 }
972                                             }
973                                         }
974                                     }
975                                 }
976                             }
977                             iterator->list = list;
978                             test = !invert_test;
979                         } else if(iterator) {
980                             iterator->test.append(IteratorBlock::Test(func, args, invert_test));
981                             test = !invert_test;
982                         } else if(func == "defineTest" || func == "defineReplace") {
983                             if(!function_blocks.isEmpty()) {
984                                 fprintf(stderr,
985                                         "%s:%d: cannot define a function within another definition.\n",
986                                         parser.file.toLatin1().constData(), parser.line_no);
987                                 return false;
988                             }
989                             if(args.count() != 1) {
990                                 fprintf(stderr, "%s:%d: %s(function_name) requires one argument.\n",
991                                         parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
992                                 return false;
993                             }
994                             QHash<QString, FunctionBlock*> *map = 0;
995                             if(func == "defineTest")
996                                 map = &testFunctions;
997                             else
998                                 map = &replaceFunctions;
999 #if 0
1000                             if(!map || map->contains(args[0])) {
1001                                 fprintf(stderr, "%s:%d: Function[%s] multiply defined.\n",
1002                                         parser.file.toLatin1().constData(), parser.line_no, args[0].toLatin1().constData());
1003                                 return false;
1004                             }
1005 #endif
1006                             function = new FunctionBlock;
1007                             map->insert(args[0], function);
1008                             test = true;
1009                         } else {
1010                             test = doProjectTest(func, args, place);
1011                             if(*(d+d_off) == QLatin1Char(')') && d_off == s.length()-1) {
1012                                 if(invert_test)
1013                                     test = !test;
1014                                 scope_blocks.top().else_status =
1015                                     (test ? ScopeBlock::TestFound : ScopeBlock::TestSeek);
1016                                 return true;  // assume we are done
1017                             }
1018                         }
1019                     } else {
1020                         QString cscope = comp_scope.trimmed();
1021                         doVariableReplace(cscope, place);
1022                         test = isActiveConfig(cscope.trimmed(), true, &place);
1023                     }
1024                     if(invert_test)
1025                         test = !test;
1026                 }
1027             }
1028             if(!test && !scope_failed)
1029                 debug_msg(1, "Project Parser: %s:%d : Test (%s) failed.", parser.file.toLatin1().constData(),
1030                           parser.line_no, scope.toLatin1().constData());
1031             if(test == or_op)
1032                 scope_failed = !test;
1033             or_op = (*(d+d_off) == QLatin1Char('|'));
1034
1035             if(*(d+d_off) == QLatin1Char('{')) { // scoping block
1036                 start_block++;
1037                 if(iterator) {
1038                     for(int off = 0, braces = 0; true; ++off) {
1039                         if(*(d+d_off+off) == QLatin1Char('{'))
1040                             ++braces;
1041                         else if(*(d+d_off+off) == QLatin1Char('}') && braces)
1042                             --braces;
1043                         if(!braces || d_off+off == s.length()) {
1044                             iterator->parselist.append(s.mid(d_off, off-1));
1045                             if(braces > 1)
1046                                 iterator->scope_level += braces-1;
1047                             d_off += off-1;
1048                             break;
1049                         }
1050                     }
1051                 }
1052             }
1053         } else if(!parens && *(d+d_off) == QLatin1Char('}')) {
1054             if(start_block) {
1055                 --start_block;
1056             } else if(!scope_blocks.count()) {
1057                 warn_msg(WarnParser, "Possible braces mismatch %s:%d", parser.file.toLatin1().constData(), parser.line_no);
1058             } else {
1059                 if(scope_blocks.count() == 1) {
1060                     fprintf(stderr, "Braces mismatch %s:%d\n", parser.file.toLatin1().constData(), parser.line_no);
1061                     return false;
1062                 }
1063                 debug_msg(1, "Project Parser: %s:%d : Leaving block %d", parser.file.toLatin1().constData(),
1064                           parser.line_no, scope_blocks.count());
1065                 ScopeBlock sb = scope_blocks.pop();
1066                 if(sb.iterate)
1067                     sb.iterate->exec(this, place);
1068             }
1069         } else {
1070             var += *(d+d_off);
1071         }
1072         ++d_off;
1073     }
1074     var = var.trimmed();
1075
1076     if(!else_line || (else_line && !scope_failed))
1077         scope_blocks.top().else_status = (!scope_failed ? ScopeBlock::TestFound : ScopeBlock::TestSeek);
1078     if(start_block) {
1079         ScopeBlock next_block(scope_failed);
1080         next_block.iterate = iterator;
1081         if(iterator)
1082             next_block.else_status = ScopeBlock::TestNone;
1083         else if(scope_failed)
1084             next_block.else_status = ScopeBlock::TestSeek;
1085         else
1086             next_block.else_status = ScopeBlock::TestFound;
1087         scope_blocks.push(next_block);
1088         debug_msg(1, "Project Parser: %s:%d : Entering block %d (%d). [%s]", parser.file.toLatin1().constData(),
1089                   parser.line_no, scope_blocks.count(), scope_failed, s.toLatin1().constData());
1090     } else if(iterator) {
1091         iterator->parselist.append(QString(var+s.mid(d_off)));
1092         bool ret = iterator->exec(this, place);
1093         delete iterator;
1094         return ret;
1095     }
1096
1097     if((!scope_count && !var.isEmpty()) || (scope_count == 1 && else_line))
1098         scope_blocks.top().else_status = ScopeBlock::TestNone;
1099     if(d_off == s.length()) {
1100         if(!var.trimmed().isEmpty())
1101             qmake_error_msg(("Parse Error ('" + s + "')").toLatin1());
1102         return var.isEmpty(); // allow just a scope
1103     }
1104
1105     SKIP_WS(d, d_off, s.length());
1106     for(; d_off < s.length() && op.indexOf('=') == -1; op += *(d+(d_off++)))
1107         ;
1108     op.replace(QRegExp("\\s"), "");
1109
1110     SKIP_WS(d, d_off, s.length());
1111     QString vals = s.mid(d_off); // vals now contains the space separated list of values
1112     int rbraces = vals.count('}'), lbraces = vals.count('{');
1113     if(scope_blocks.count() > 1 && rbraces - lbraces == 1 && vals.endsWith('}')) {
1114         debug_msg(1, "Project Parser: %s:%d : Leaving block %d", parser.file.toLatin1().constData(),
1115                   parser.line_no, scope_blocks.count());
1116         ScopeBlock sb = scope_blocks.pop();
1117         if(sb.iterate)
1118             sb.iterate->exec(this, place);
1119         vals.truncate(vals.length()-1);
1120     } else if(rbraces != lbraces) {
1121         warn_msg(WarnParser, "Possible braces mismatch {%s} %s:%d",
1122                  vals.toLatin1().constData(), parser.file.toLatin1().constData(), parser.line_no);
1123     }
1124     if(scope_failed)
1125         return true; // oh well
1126 #undef SKIP_WS
1127
1128     doVariableReplace(var, place);
1129     var = varMap(var); //backwards compatibility
1130
1131     if(vals.contains('=') && numLines > 1)
1132         warn_msg(WarnParser, "Possible accidental line continuation: {%s} at %s:%d",
1133                  var.toLatin1().constData(), parser.file.toLatin1().constData(), parser.line_no);
1134
1135     QStringList &varlist = place[var]; // varlist is the list in the symbol table
1136
1137     if(Option::debug_level >= 1) {
1138         QString tmp_vals = vals;
1139         doVariableReplace(tmp_vals, place);
1140         debug_msg(1, "Project Parser: %s:%d :%s: :%s: (%s)", parser.file.toLatin1().constData(), parser.line_no,
1141                   var.toLatin1().constData(), op.toLatin1().constData(), tmp_vals.toLatin1().constData());
1142     }
1143
1144     // now do the operation
1145     if(op == "~=") {
1146         doVariableReplace(vals, place);
1147         if(vals.length() < 4 || vals.at(0) != 's') {
1148             qmake_error_msg(("~= operator only can handle s/// function ('" +
1149                             s + "')").toLatin1());
1150             return false;
1151         }
1152         QChar sep = vals.at(1);
1153         QStringList func = vals.split(sep);
1154         if(func.count() < 3 || func.count() > 4) {
1155             qmake_error_msg(("~= operator only can handle s/// function ('" +
1156                 s + "')").toLatin1());
1157             return false;
1158         }
1159         bool global = false, case_sense = true, quote = false;
1160         if(func.count() == 4) {
1161             global = func[3].indexOf('g') != -1;
1162             case_sense = func[3].indexOf('i') == -1;
1163             quote = func[3].indexOf('q') != -1;
1164         }
1165         QString from = func[1], to = func[2];
1166         if(quote)
1167             from = QRegExp::escape(from);
1168         QRegExp regexp(from, case_sense ? Qt::CaseSensitive : Qt::CaseInsensitive);
1169         for(QStringList::Iterator varit = varlist.begin(); varit != varlist.end();) {
1170             if((*varit).contains(regexp)) {
1171                 (*varit) = (*varit).replace(regexp, to);
1172                 if ((*varit).isEmpty())
1173                     varit = varlist.erase(varit);
1174                 else
1175                     ++varit;
1176                 if(!global)
1177                     break;
1178             } else
1179                 ++varit;
1180         }
1181     } else {
1182         QStringList vallist;
1183         {
1184             //doVariableReplace(vals, place);
1185             QStringList tmp = split_value_list(vals);
1186             for(int i = 0; i < tmp.size(); ++i)
1187                 vallist += doVariableReplaceExpand(tmp[i], place);
1188         }
1189
1190         if(op == "=") {
1191 #if 0 // This is way too noisy
1192             if(!varlist.isEmpty()) {
1193                 bool send_warning = false;
1194                 if(var != "TEMPLATE" && var != "TARGET") {
1195                     QSet<QString> incoming_vals = vallist.toSet();
1196                     for(int i = 0; i < varlist.size(); ++i) {
1197                         const QString var = varlist.at(i).trimmed();
1198                         if(!var.isEmpty() && !incoming_vals.contains(var)) {
1199                             send_warning = true;
1200                             break;
1201                         }
1202                     }
1203                 }
1204                 if(send_warning)
1205                     warn_msg(WarnParser, "Operator=(%s) clears variables previously set: %s:%d",
1206                              var.toLatin1().constData(), parser.file.toLatin1().constData(), parser.line_no);
1207             }
1208 #endif
1209             varlist.clear();
1210         }
1211         for(QStringList::ConstIterator valit = vallist.begin();
1212             valit != vallist.end(); ++valit) {
1213             if((*valit).isEmpty())
1214                 continue;
1215             if((op == "*=" && !varlist.contains((*valit))) ||
1216                op == "=" || op == "+=")
1217                 varlist.append((*valit));
1218             else if(op == "-=")
1219                 varlist.removeAll((*valit));
1220         }
1221         if(var == "REQUIRES") // special case to get communicated to backends!
1222             doProjectCheckReqs(vallist, place);
1223         else if (var == QLatin1String("TEMPLATE"))
1224             setTemplate(varlist);
1225     }
1226     return true;
1227 }
1228
1229 bool
1230 QMakeProject::read(QTextStream &file, QHash<QString, QStringList> &place)
1231 {
1232     int numLines = 0;
1233     bool ret = true;
1234     QString s;
1235     while(!file.atEnd()) {
1236         parser.line_no++;
1237         QString line = file.readLine().trimmed();
1238         int prelen = line.length();
1239
1240         int hash_mark = line.indexOf("#");
1241         if(hash_mark != -1) //good bye comments
1242             line = line.left(hash_mark).trimmed();
1243         if(!line.isEmpty() && line.right(1) == "\\") {
1244             if(!line.startsWith("#")) {
1245                 line.truncate(line.length() - 1);
1246                 s += line + Option::field_sep;
1247                 ++numLines;
1248             }
1249         } else if(!line.isEmpty() || (line.isEmpty() && !prelen)) {
1250             if(s.isEmpty() && line.isEmpty())
1251                 continue;
1252             if(!line.isEmpty()) {
1253                 s += line;
1254                 ++numLines;
1255             }
1256             if(!s.isEmpty()) {
1257                 if(!(ret = parse(s, place, numLines))) {
1258                     s = "";
1259                     numLines = 0;
1260                     break;
1261                 }
1262                 s = "";
1263                 numLines = 0;
1264                 if (need_restart)
1265                     break;
1266             }
1267         }
1268     }
1269     if (!s.isEmpty())
1270         ret = parse(s, place, numLines);
1271     return ret;
1272 }
1273
1274 bool
1275 QMakeProject::read(const QString &file, QHash<QString, QStringList> &place)
1276 {
1277     parser_info pi = parser;
1278     reset();
1279
1280     const QString oldpwd = qmake_getpwd();
1281     QString filename = Option::normalizePath(file, false);
1282     bool ret = false, using_stdin = false;
1283     QFile qfile;
1284     if(filename == QLatin1String("-")) {
1285         qfile.setFileName("");
1286         ret = qfile.open(stdin, QIODevice::ReadOnly);
1287         using_stdin = true;
1288     } else if(QFileInfo(file).isDir()) {
1289         return false;
1290     } else {
1291         qfile.setFileName(filename);
1292         ret = qfile.open(QIODevice::ReadOnly);
1293         qmake_setpwd(QFileInfo(filename).absolutePath());
1294     }
1295     if(ret) {
1296         place["PWD"] = QStringList(qmake_getpwd());
1297         parser_info pi = parser;
1298         parser.from_file = true;
1299         parser.file = filename;
1300         parser.line_no = 0;
1301         if (qfile.peek(3) == QByteArray("\xef\xbb\xbf")) {
1302             //UTF-8 BOM will cause subtle errors
1303             qmake_error_msg("Unexpected UTF-8 BOM found");
1304             ret = false;
1305         } else {
1306             QTextStream t(&qfile);
1307             ret = read(t, place);
1308         }
1309         if(!using_stdin)
1310             qfile.close();
1311     }
1312     if (!need_restart && scope_blocks.count() != 1) {
1313         qmake_error_msg("Unterminated conditional block at end of file");
1314         ret = false;
1315     }
1316     parser = pi;
1317     qmake_setpwd(oldpwd);
1318     return ret;
1319 }
1320
1321 bool
1322 QMakeProject::read(const QString &project, uchar cmd)
1323 {
1324     pfile = QFileInfo(project).absoluteFilePath();
1325     return read(cmd);
1326 }
1327
1328 bool
1329 QMakeProject::read(uchar cmd)
1330 {
1331   again:
1332     if (init_vars.isEmpty()) {
1333         loadDefaults();
1334         init_vars = vars;
1335     } else {
1336         vars = init_vars;
1337     }
1338     if (cmd & ReadSetup) {
1339       if (base_vars.isEmpty()) {
1340         QString superdir;
1341         QString project_root;
1342         QStringList qmakepath;
1343         QStringList qmakefeatures;
1344         project_build_root.clear();
1345         if (Option::mkfile::do_cache) {        // parse the cache
1346             QHash<QString, QStringList> cache;
1347             QString rdir = Option::output_dir;
1348             forever {
1349                 QFileInfo qfi(rdir, QLatin1String(".qmake.super"));
1350                 if (qfi.exists()) {
1351                     superfile = qfi.filePath();
1352                     if (!read(superfile, cache))
1353                         return false;
1354                     superdir = rdir;
1355                     break;
1356                 }
1357                 QFileInfo qdfi(rdir);
1358                 if (qdfi.isRoot())
1359                     break;
1360                 rdir = qdfi.path();
1361             }
1362             if (Option::mkfile::cachefile.isEmpty())  { //find it as it has not been specified
1363                 QString sdir = qmake_getpwd();
1364                 QString dir = Option::output_dir;
1365                 forever {
1366                     QFileInfo qsfi(sdir, QLatin1String(".qmake.conf"));
1367                     if (qsfi.exists()) {
1368                         conffile = qsfi.filePath();
1369                         if (!read(conffile, cache))
1370                             return false;
1371                     }
1372                     QFileInfo qfi(dir, QLatin1String(".qmake.cache"));
1373                     if (qfi.exists()) {
1374                         cachefile = qfi.filePath();
1375                         if (!read(cachefile, cache))
1376                             return false;
1377                     }
1378                     if (!conffile.isEmpty() || !cachefile.isEmpty()) {
1379                         project_root = sdir;
1380                         project_build_root = dir;
1381                         break;
1382                     }
1383                     if (dir == superdir)
1384                         break;
1385                     QFileInfo qsdfi(sdir);
1386                     QFileInfo qdfi(dir);
1387                     if (qsdfi.isRoot() || qdfi.isRoot())
1388                         break;
1389                     sdir = qsdfi.path();
1390                     dir = qdfi.path();
1391                 }
1392             } else {
1393                 QFileInfo fi(Option::mkfile::cachefile);
1394                 cachefile = QDir::cleanPath(fi.absoluteFilePath());
1395                 if (!read(cachefile, cache))
1396                     return false;
1397                 project_build_root = QDir::cleanPath(fi.absolutePath());
1398                 // This intentionally bypasses finding a source root,
1399                 // as the result would be more or less arbitrary.
1400             }
1401
1402             if (Option::mkfile::xqmakespec.isEmpty() && !cache["XQMAKESPEC"].isEmpty())
1403                 Option::mkfile::xqmakespec = cache["XQMAKESPEC"].first();
1404             if (Option::mkfile::qmakespec.isEmpty() && !cache["QMAKESPEC"].isEmpty()) {
1405                 Option::mkfile::qmakespec = cache["QMAKESPEC"].first();
1406                 if (Option::mkfile::xqmakespec.isEmpty())
1407                     Option::mkfile::xqmakespec = Option::mkfile::qmakespec;
1408             }
1409             qmakepath = cache.value(QLatin1String("QMAKEPATH"));
1410             qmakefeatures = cache.value(QLatin1String("QMAKEFEATURES"));
1411
1412             if (!superfile.isEmpty())
1413                 vars["_QMAKE_SUPER_CACHE_"] << superfile;
1414             if (!cachefile.isEmpty())
1415                 vars["_QMAKE_CACHE_"] << cachefile;
1416         }
1417
1418         // Look for mkspecs/ in source and build. First to win determines the root.
1419         QString sdir = qmake_getpwd();
1420         QString dir = Option::output_dir;
1421         while (dir != project_build_root) {
1422             if ((dir != sdir && QFileInfo(sdir, QLatin1String("mkspecs")).isDir())
1423                     || QFileInfo(dir, QLatin1String("mkspecs")).isDir()) {
1424                 if (dir != sdir)
1425                     project_root = sdir;
1426                 project_build_root = dir;
1427                 break;
1428             }
1429             if (dir == superdir)
1430                 break;
1431             QFileInfo qsdfi(sdir);
1432             QFileInfo qdfi(dir);
1433             if (qsdfi.isRoot() || qdfi.isRoot())
1434                 break;
1435             sdir = qsdfi.path();
1436             dir = qdfi.path();
1437         }
1438
1439         if (qmakepath != cached_qmakepath || qmakefeatures != cached_qmakefeatures
1440             || project_build_root != cached_build_root) { // No need to check source dir, as it goes in sync
1441             cached_source_root = project_root;
1442             cached_build_root = project_build_root;
1443             cached_qmakepath = qmakepath;
1444             cached_qmakefeatures = qmakefeatures;
1445             invalidateFeatureRoots();
1446         }
1447
1448         {             // parse mkspec
1449             QString *specp = host_build ? &Option::mkfile::qmakespec : &Option::mkfile::xqmakespec;
1450             QString qmakespec = *specp;
1451             if (qmakespec.isEmpty())
1452                 qmakespec = host_build ? "default-host" : "default";
1453             if (QDir::isRelativePath(qmakespec)) {
1454                     QStringList mkspec_roots = qmake_mkspec_paths();
1455                     debug_msg(2, "Looking for mkspec %s in (%s)", qmakespec.toLatin1().constData(),
1456                               mkspec_roots.join("::").toLatin1().constData());
1457                     bool found_mkspec = false;
1458                     for (QStringList::ConstIterator it = mkspec_roots.begin(); it != mkspec_roots.end(); ++it) {
1459                         QString mkspec = (*it) + QLatin1Char('/') + qmakespec;
1460                         if (QFile::exists(mkspec)) {
1461                             found_mkspec = true;
1462                             *specp = qmakespec = mkspec;
1463                             break;
1464                         }
1465                     }
1466                     if (!found_mkspec) {
1467                         fprintf(stderr, "Could not find mkspecs for your QMAKESPEC(%s) after trying:\n\t%s\n",
1468                                 qmakespec.toLatin1().constData(), mkspec_roots.join("\n\t").toLatin1().constData());
1469                         return false;
1470                     }
1471             }
1472
1473             // We do this before reading the spec, so it can use module and feature paths from
1474             // here without resorting to tricks. This is the only planned use case anyway.
1475             if (!superfile.isEmpty()) {
1476                 debug_msg(1, "Project super cache file: reading %s", superfile.toLatin1().constData());
1477                 read(superfile, vars);
1478             }
1479
1480             // parse qmake configuration
1481             doProjectInclude("spec_pre", IncludeFlagFeature, vars);
1482             while(qmakespec.endsWith(QLatin1Char('/')))
1483                 qmakespec.truncate(qmakespec.length()-1);
1484             QString spec = qmakespec + QLatin1String("/qmake.conf");
1485             debug_msg(1, "QMAKESPEC conf: reading %s", spec.toLatin1().constData());
1486             if (!read(spec, vars)) {
1487                 fprintf(stderr, "Failure to read QMAKESPEC conf file %s.\n", spec.toLatin1().constData());
1488                 return false;
1489             }
1490 #ifdef Q_OS_UNIX
1491             real_spec = QFileInfo(qmakespec).canonicalFilePath();
1492 #else
1493             // We can't resolve symlinks as they do on Unix, so configure.exe puts the source of the
1494             // qmake.conf at the end of the default/qmake.conf in the QMAKESPEC_ORG variable.
1495             QString orig_spec = first(QLatin1String("QMAKESPEC_ORIGINAL"));
1496             real_spec = orig_spec.isEmpty() ? qmakespec : orig_spec;
1497 #endif
1498             vars["QMAKESPEC"] << real_spec;
1499             short_spec = QFileInfo(real_spec).fileName();
1500             doProjectInclude("spec_post", IncludeFlagFeature, vars);
1501             // The spec extends the feature search path, so invalidate the cache.
1502             invalidateFeatureRoots();
1503             // The MinGW and x-build specs may change the separator; $$shell_{path,quote}() need it
1504             Option::dir_sep = first(QLatin1String("QMAKE_DIR_SEP"));
1505
1506             if (!conffile.isEmpty()) {
1507                 debug_msg(1, "Project config file: reading %s", conffile.toLatin1().constData());
1508                 read(conffile, vars);
1509             }
1510             if (!cachefile.isEmpty()) {
1511                 debug_msg(1, "QMAKECACHE file: reading %s", cachefile.toLatin1().constData());
1512                 read(cachefile, vars);
1513             }
1514         }
1515
1516         base_vars = vars;
1517       } else {
1518         vars = base_vars; // start with the base
1519       }
1520         setupProject();
1521     } else if (cmd & ReadFeatures) {
1522         // Even when ReadSetup is not set, but ReadFeatures is,
1523         // we still need to process spec_pre.prf to load some
1524         // default values and other settings.
1525         debug_msg(1, "Processing spec_pre (but skipping actual spec): %s", vars["CONFIG"].join("::").toLatin1().constData());
1526         doProjectInclude("spec_pre", IncludeFlagFeature, vars);
1527     }
1528
1529     for (QHash<QString, QStringList>::ConstIterator it = extra_vars.constBegin();
1530          it != extra_vars.constEnd(); ++it)
1531         vars.insert(it.key(), it.value());
1532
1533     if(cmd & ReadFeatures) {
1534         debug_msg(1, "Processing default_pre: %s", vars["CONFIG"].join("::").toLatin1().constData());
1535         doProjectInclude("default_pre", IncludeFlagFeature, vars);
1536     }
1537
1538     //before commandline
1539     if (cmd & ReadSetup) {
1540         parser.file = "(internal)";
1541         parser.from_file = false;
1542         parser.line_no = 1; //really arg count now.. duh
1543         reset();
1544         for(QStringList::ConstIterator it = Option::before_user_vars.begin();
1545             it != Option::before_user_vars.end(); ++it) {
1546             if(!parse((*it), vars)) {
1547                 fprintf(stderr, "Argument failed to parse: %s\n", (*it).toLatin1().constData());
1548                 return false;
1549             }
1550             parser.line_no++;
1551         }
1552     }
1553
1554     // After user configs, to override them
1555     if (!extra_configs.isEmpty()) {
1556         parser.file = "(extra configs)";
1557         parser.from_file = false;
1558         parser.line_no = 1; //really arg count now.. duh
1559         parse("CONFIG += " + extra_configs.join(" "), vars);
1560     }
1561
1562     if(cmd & ReadProFile) { // parse project file
1563         debug_msg(1, "Project file: reading %s", pfile.toLatin1().constData());
1564         if(pfile != "-" && !QFile::exists(pfile) && !pfile.endsWith(Option::pro_ext))
1565             pfile += Option::pro_ext;
1566         if(!read(pfile, vars))
1567             return false;
1568         if (need_restart) {
1569             base_vars.clear();
1570             cleanup();
1571             goto again;
1572         }
1573     }
1574
1575     if (cmd & ReadSetup) {
1576         parser.file = "(internal)";
1577         parser.from_file = false;
1578         parser.line_no = 1; //really arg count now.. duh
1579         reset();
1580         for(QStringList::ConstIterator it = Option::after_user_vars.begin();
1581             it != Option::after_user_vars.end(); ++it) {
1582             if(!parse((*it), vars)) {
1583                 fprintf(stderr, "Argument failed to parse: %s\n", (*it).toLatin1().constData());
1584                 return false;
1585             }
1586             parser.line_no++;
1587         }
1588     }
1589
1590     // Again, to ensure the project does not mess with us.
1591     // Specifically, do not allow a project to override debug/release within a
1592     // debug_and_release build pass - it's too late for that at this point anyway.
1593     if (!extra_configs.isEmpty()) {
1594         parser.file = "(extra configs)";
1595         parser.from_file = false;
1596         parser.line_no = 1; //really arg count now.. duh
1597         parse("CONFIG += " + extra_configs.join(" "), vars);
1598     }
1599
1600     if(cmd & ReadFeatures) {
1601         debug_msg(1, "Processing default_post: %s", vars["CONFIG"].join("::").toLatin1().constData());
1602         doProjectInclude("default_post", IncludeFlagFeature, vars);
1603
1604         QHash<QString, bool> processed;
1605         const QStringList &configs = vars["CONFIG"];
1606         debug_msg(1, "Processing CONFIG features: %s", configs.join("::").toLatin1().constData());
1607         while(1) {
1608             bool finished = true;
1609             for(int i = configs.size()-1; i >= 0; --i) {
1610                 const QString config = configs[i].toLower();
1611                 if(!processed.contains(config)) {
1612                     processed.insert(config, true);
1613                     if(doProjectInclude(config, IncludeFlagFeature, vars) == IncludeSuccess) {
1614                         finished = false;
1615                         break;
1616                     }
1617                 }
1618             }
1619             if(finished)
1620                 break;
1621         }
1622     }
1623     return true;
1624 }
1625
1626 void
1627 QMakeProject::setupProject()
1628 {
1629     setTemplate(vars["TEMPLATE"]);
1630     if (pfile != "-")
1631         vars["TARGET"] << QFileInfo(pfile).baseName();
1632     vars["_PRO_FILE_"] << pfile;
1633     vars["_PRO_FILE_PWD_"] << (pfile.isEmpty() ? qmake_getpwd() : QFileInfo(pfile).absolutePath());
1634     vars["OUT_PWD"] << Option::output_dir;
1635 }
1636
1637 void
1638 QMakeProject::loadDefaults()
1639 {
1640     vars["LITERAL_WHITESPACE"] << QLatin1String("\t");
1641     vars["LITERAL_DOLLAR"] << QLatin1String("$");
1642     vars["LITERAL_HASH"] << QLatin1String("#");
1643     vars["DIR_SEPARATOR"] << Option::dir_sep;
1644     vars["DIRLIST_SEPARATOR"] << Option::dirlist_sep;
1645     vars["QMAKE_QMAKE"] << Option::qmake_abslocation;
1646     vars["_DATE_"] << QDateTime::currentDateTime().toString();
1647 #if defined(Q_OS_WIN32)
1648     vars["QMAKE_HOST.os"] << QString::fromLatin1("Windows");
1649
1650     DWORD name_length = 1024;
1651     wchar_t name[1024];
1652     if (GetComputerName(name, &name_length))
1653         vars["QMAKE_HOST.name"] << QString::fromWCharArray(name);
1654
1655     QSysInfo::WinVersion ver = QSysInfo::WindowsVersion;
1656     vars["QMAKE_HOST.version"] << QString::number(ver);
1657     QString verStr;
1658     switch (ver) {
1659     case QSysInfo::WV_Me: verStr = QLatin1String("WinMe"); break;
1660     case QSysInfo::WV_95: verStr = QLatin1String("Win95"); break;
1661     case QSysInfo::WV_98: verStr = QLatin1String("Win98"); break;
1662     case QSysInfo::WV_NT: verStr = QLatin1String("WinNT"); break;
1663     case QSysInfo::WV_2000: verStr = QLatin1String("Win2000"); break;
1664     case QSysInfo::WV_2003: verStr = QLatin1String("Win2003"); break;
1665     case QSysInfo::WV_XP: verStr = QLatin1String("WinXP"); break;
1666     case QSysInfo::WV_VISTA: verStr = QLatin1String("WinVista"); break;
1667     default: verStr = QLatin1String("Unknown"); break;
1668     }
1669     vars["QMAKE_HOST.version_string"] << verStr;
1670
1671     SYSTEM_INFO info;
1672     GetSystemInfo(&info);
1673     QString archStr;
1674     switch (info.wProcessorArchitecture) {
1675 # ifdef PROCESSOR_ARCHITECTURE_AMD64
1676     case PROCESSOR_ARCHITECTURE_AMD64:
1677         archStr = QLatin1String("x86_64");
1678         break;
1679 # endif
1680     case PROCESSOR_ARCHITECTURE_INTEL:
1681         archStr = QLatin1String("x86");
1682         break;
1683     case PROCESSOR_ARCHITECTURE_IA64:
1684 # ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64
1685     case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
1686 # endif
1687         archStr = QLatin1String("IA64");
1688         break;
1689     default:
1690         archStr = QLatin1String("Unknown");
1691         break;
1692     }
1693     vars["QMAKE_HOST.arch"] << archStr;
1694
1695 # if defined(Q_CC_MSVC)
1696     QString paths = QString::fromLocal8Bit(qgetenv("PATH"));
1697     QString vcBin64 = QString::fromLocal8Bit(qgetenv("VCINSTALLDIR"));
1698     if (!vcBin64.endsWith('\\'))
1699         vcBin64.append('\\');
1700     vcBin64.append("bin\\amd64");
1701     QString vcBinX86_64 = QString::fromLocal8Bit(qgetenv("VCINSTALLDIR"));
1702     if (!vcBinX86_64.endsWith('\\'))
1703         vcBinX86_64.append('\\');
1704     vcBinX86_64.append("bin\\x86_amd64");
1705     if (paths.contains(vcBin64,Qt::CaseInsensitive) || paths.contains(vcBinX86_64,Qt::CaseInsensitive))
1706         vars["QMAKE_TARGET.arch"] << QString::fromLatin1("x86_64");
1707     else
1708         vars["QMAKE_TARGET.arch"] << QString::fromLatin1("x86");
1709 # endif
1710 #elif defined(Q_OS_UNIX)
1711     struct utsname name;
1712     if (!uname(&name)) {
1713         vars["QMAKE_HOST.os"] << QString::fromLocal8Bit(name.sysname);
1714         vars["QMAKE_HOST.name"] << QString::fromLocal8Bit(name.nodename);
1715         vars["QMAKE_HOST.version"] << QString::fromLocal8Bit(name.release);
1716         vars["QMAKE_HOST.version_string"] << QString::fromLocal8Bit(name.version);
1717         vars["QMAKE_HOST.arch"] << QString::fromLocal8Bit(name.machine);
1718     }
1719 #endif
1720 }
1721
1722 bool
1723 QMakeProject::isActiveConfig(const QString &x, bool regex, QHash<QString, QStringList> *place)
1724 {
1725     if(x.isEmpty())
1726         return true;
1727
1728     //magic types for easy flipping
1729     if(x == "true")
1730         return true;
1731     else if(x == "false")
1732         return false;
1733
1734     if (x == "host_build")
1735         return host_build;
1736
1737     //mkspecs
1738     QRegExp re(x, Qt::CaseSensitive, QRegExp::Wildcard);
1739     if ((regex && re.exactMatch(short_spec)) || (!regex && short_spec == x))
1740         return true;
1741
1742     //simple matching
1743     const QStringList &configs = (place ? (*place)["CONFIG"] : vars["CONFIG"]);
1744     for(QStringList::ConstIterator it = configs.begin(); it != configs.end(); ++it) {
1745         if(((regex && re.exactMatch((*it))) || (!regex && (*it) == x)) && re.exactMatch((*it)))
1746             return true;
1747     }
1748     return false;
1749 }
1750
1751 bool
1752 QMakeProject::doProjectTest(QString str, QHash<QString, QStringList> &place)
1753 {
1754     QString chk = remove_quotes(str);
1755     if(chk.isEmpty())
1756         return true;
1757     bool invert_test = (chk.left(1) == "!");
1758     if(invert_test)
1759         chk = chk.mid(1);
1760
1761     bool test=false;
1762     int lparen = chk.indexOf('(');
1763     if(lparen != -1) { // if there is an lparen in the chk, it IS a function
1764         int rparen = chk.indexOf(')', lparen);
1765         if(rparen == -1) {
1766             qmake_error_msg("Function missing right paren: " + chk);
1767         } else {
1768             QString func = chk.left(lparen);
1769             test = doProjectTest(func, chk.mid(lparen+1, rparen - lparen - 1), place);
1770         }
1771     } else {
1772         test = isActiveConfig(chk, true, &place);
1773     }
1774     if(invert_test)
1775         return !test;
1776     return test;
1777 }
1778
1779 bool
1780 QMakeProject::doProjectTest(QString func, const QString &params,
1781                             QHash<QString, QStringList> &place)
1782 {
1783     return doProjectTest(func, split_arg_list(params), place);
1784 }
1785
1786 QMakeProject::IncludeStatus
1787 QMakeProject::doProjectInclude(QString file, uchar flags, QHash<QString, QStringList> &place)
1788 {
1789     if(flags & IncludeFlagFeature) {
1790         if(!file.endsWith(Option::prf_ext))
1791             file += Option::prf_ext;
1792         {
1793             QStringList *&feature_roots = all_feature_roots[host_build];
1794             if(!feature_roots) {
1795                 feature_roots = new QStringList;
1796                 qmakeAddCacheClear(qmakeDeleteCacheClear<QStringList>, (void**)&feature_roots);
1797             }
1798             if (feature_roots->isEmpty())
1799                 *feature_roots = qmakeFeaturePaths();
1800             debug_msg(2, "Looking for feature '%s' in (%s)", file.toLatin1().constData(),
1801                         feature_roots->join("::").toLatin1().constData());
1802             int start_root = 0;
1803             if(parser.from_file) {
1804                 QFileInfo currFile(parser.file), prfFile(file);
1805                 if(currFile.fileName() == prfFile.fileName()) {
1806                     currFile = QFileInfo(currFile.canonicalFilePath());
1807                     for(int root = 0; root < feature_roots->size(); ++root) {
1808                         prfFile = QFileInfo(feature_roots->at(root) +
1809                                             QLatin1Char('/') + file).canonicalFilePath();
1810                         if(prfFile == currFile) {
1811                             start_root = root+1;
1812                             break;
1813                         }
1814                     }
1815                 }
1816             }
1817             for(int root = start_root; root < feature_roots->size(); ++root) {
1818                 QString prf(feature_roots->at(root) + QLatin1Char('/') + file);
1819                 if (QFile::exists(prf)) {
1820                     file = prf;
1821                     goto foundf;
1822                 }
1823             }
1824             return IncludeNoExist;
1825           foundf: ;
1826         }
1827         if(place["QMAKE_INTERNAL_INCLUDED_FEATURES"].indexOf(file) != -1)
1828             return IncludeFeatureAlreadyLoaded;
1829         place["QMAKE_INTERNAL_INCLUDED_FEATURES"].append(file);
1830     } else if (QDir::isRelativePath(file)) {
1831         QStringList include_roots;
1832         if(Option::output_dir != qmake_getpwd())
1833             include_roots << qmake_getpwd();
1834         include_roots << Option::output_dir;
1835         for(int root = 0; root < include_roots.size(); ++root) {
1836             QString testName = QDir::fromNativeSeparators(include_roots[root]);
1837             if (!testName.endsWith(QLatin1Char('/')))
1838                 testName += QLatin1Char('/');
1839             testName += file;
1840             if(QFile::exists(testName)) {
1841                 file = testName;
1842                 goto foundi;
1843             }
1844         }
1845         return IncludeNoExist;
1846       foundi: ;
1847     } else if (!QFile::exists(file)) {
1848         return IncludeNoExist;
1849     }
1850     debug_msg(1, "Project Parser: %s'ing file %s.", (flags & IncludeFlagFeature) ? "load" : "include",
1851               file.toLatin1().constData());
1852
1853     QString orig_file = file;
1854     int di = file.lastIndexOf(QLatin1Char('/'));
1855     QString oldpwd = qmake_getpwd();
1856     if(di != -1) {
1857         if(!qmake_setpwd(file.left(file.lastIndexOf(QLatin1Char('/'))))) {
1858             fprintf(stderr, "Cannot find directory: %s\n", file.left(di).toLatin1().constData());
1859             return IncludeFailure;
1860         }
1861     }
1862     bool parsed = false;
1863     parser_info pi = parser;
1864     {
1865         if(flags & (IncludeFlagNewProject|IncludeFlagNewParser)) {
1866             // The "project's variables" are used in other places (eg. export()) so it's not
1867             // possible to use "place" everywhere. Instead just set variables and grab them later
1868             QMakeProject proj(prop);
1869             if(flags & IncludeFlagNewParser) {
1870                 parsed = proj.read(file, proj.variables()); // parse just that file (fromfile, infile)
1871             } else {
1872                 parsed = proj.read(file); // parse all aux files (load/include into)
1873             }
1874             place = proj.variables();
1875         } else {
1876             QStack<ScopeBlock> sc = scope_blocks;
1877             IteratorBlock *it = iterator;
1878             FunctionBlock *fu = function;
1879             parsed = read(file, place);
1880             iterator = it;
1881             function = fu;
1882             scope_blocks = sc;
1883         }
1884     }
1885     if(parsed) {
1886         if(place["QMAKE_INTERNAL_INCLUDED_FILES"].indexOf(orig_file) == -1)
1887             place["QMAKE_INTERNAL_INCLUDED_FILES"].append(orig_file);
1888     } else {
1889         warn_msg(WarnParser, "%s:%d: Failure to include file %s.",
1890                  pi.file.toLatin1().constData(), pi.line_no, orig_file.toLatin1().constData());
1891     }
1892     parser = pi;
1893     qmake_setpwd(oldpwd);
1894     place["PWD"] = QStringList(qmake_getpwd());
1895     if(!parsed)
1896         return IncludeParseFailure;
1897     return IncludeSuccess;
1898 }
1899
1900 static void
1901 subAll(QStringList *val, const QStringList &diffval)
1902 {
1903     foreach (const QString &dv, diffval)
1904         val->removeAll(dv);
1905 }
1906
1907 inline static
1908 bool hasSpecialChars(const QString &arg, const uchar (&iqm)[16])
1909 {
1910     for (int x = arg.length() - 1; x >= 0; --x) {
1911         ushort c = arg.unicode()[x].unicode();
1912         if ((c < sizeof(iqm) * 8) && (iqm[c / 8] & (1 << (c & 7))))
1913             return true;
1914     }
1915     return false;
1916 }
1917
1918 static QString
1919 shellQuoteUnix(const QString &arg)
1920 {
1921     // Chars that should be quoted (TM). This includes:
1922     static const uchar iqm[] = {
1923         0xff, 0xff, 0xff, 0xff, 0xdf, 0x07, 0x00, 0xd8,
1924         0x00, 0x00, 0x00, 0x38, 0x01, 0x00, 0x00, 0x78
1925     }; // 0-32 \'"$`<>|;&(){}*?#!~[]
1926
1927     if (!arg.length())
1928         return QString::fromLatin1("\"\"");
1929
1930     QString ret(arg);
1931     if (hasSpecialChars(ret, iqm)) {
1932         ret.replace(QLatin1Char('\''), QLatin1String("'\\''"));
1933         ret.prepend(QLatin1Char('\''));
1934         ret.append(QLatin1Char('\''));
1935     }
1936     return ret;
1937 }
1938
1939 static QString
1940 shellQuoteWin(const QString &arg)
1941 {
1942     // Chars that should be quoted (TM). This includes:
1943     // - control chars & space
1944     // - the shell meta chars "&()<>^|
1945     // - the potential separators ,;=
1946     static const uchar iqm[] = {
1947         0xff, 0xff, 0xff, 0xff, 0x45, 0x13, 0x00, 0x78,
1948         0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x10
1949     };
1950
1951     if (!arg.length())
1952         return QString::fromLatin1("\"\"");
1953
1954     QString ret(arg);
1955     if (hasSpecialChars(ret, iqm)) {
1956         // Quotes are escaped and their preceding backslashes are doubled.
1957         // It's impossible to escape anything inside a quoted string on cmd
1958         // level, so the outer quoting must be "suspended".
1959         ret.replace(QRegExp(QLatin1String("(\\\\*)\"")), QLatin1String("\"\\1\\1\\^\"\""));
1960         // The argument must not end with a \ since this would be interpreted
1961         // as escaping the quote -- rather put the \ behind the quote: e.g.
1962         // rather use "foo"\ than "foo\"
1963         int i = ret.length();
1964         while (i > 0 && ret.at(i - 1) == QLatin1Char('\\'))
1965             --i;
1966         ret.insert(i, QLatin1Char('"'));
1967         ret.prepend(QLatin1Char('"'));
1968     }
1969     return ret;
1970 }
1971
1972 static QString
1973 quoteValue(const QString &val)
1974 {
1975     QString ret;
1976     ret.reserve(val.length());
1977     bool quote = val.isEmpty();
1978     bool escaping = false;
1979     for (int i = 0, l = val.length(); i < l; i++) {
1980         QChar c = val.unicode()[i];
1981         ushort uc = c.unicode();
1982         if (uc < 32) {
1983             if (!escaping) {
1984                 escaping = true;
1985                 ret += QLatin1String("$$escape_expand(");
1986             }
1987             switch (uc) {
1988             case '\r':
1989                 ret += QLatin1String("\\\\r");
1990                 break;
1991             case '\n':
1992                 ret += QLatin1String("\\\\n");
1993                 break;
1994             case '\t':
1995                 ret += QLatin1String("\\\\t");
1996                 break;
1997             default:
1998                 ret += QString::fromLatin1("\\\\x%1").arg(uc, 2, 16, QLatin1Char('0'));
1999                 break;
2000             }
2001         } else {
2002             if (escaping) {
2003                 escaping = false;
2004                 ret += QLatin1Char(')');
2005             }
2006             switch (uc) {
2007             case '\\':
2008                 ret += QLatin1String("\\\\");
2009                 break;
2010             case '"':
2011                 ret += QLatin1String("\\\"");
2012                 break;
2013             case '\'':
2014                 ret += QLatin1String("\\'");
2015                 break;
2016             case '$':
2017                 ret += QLatin1String("\\$");
2018                 break;
2019             case '#':
2020                 ret += QLatin1String("$${LITERAL_HASH}");
2021                 break;
2022             case 32:
2023                 quote = true;
2024                 // fallthrough
2025             default:
2026                 ret += c;
2027                 break;
2028             }
2029         }
2030     }
2031     if (escaping)
2032         ret += QLatin1Char(')');
2033     if (quote) {
2034         ret.prepend(QLatin1Char('"'));
2035         ret.append(QLatin1Char('"'));
2036     }
2037     return ret;
2038 }
2039
2040 static bool
2041 writeFile(const QString &name, QIODevice::OpenMode mode, const QString &contents, QString *errStr)
2042 {
2043     QByteArray bytes = contents.toLocal8Bit();
2044     QFile cfile(name);
2045     if (!(mode & QIODevice::Append) && cfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
2046         if (cfile.readAll() == bytes)
2047             return true;
2048         cfile.close();
2049     }
2050     if (!cfile.open(mode | QIODevice::WriteOnly | QIODevice::Text)) {
2051         *errStr = cfile.errorString();
2052         return false;
2053     }
2054     cfile.write(bytes);
2055     cfile.close();
2056     if (cfile.error() != QFile::NoError) {
2057         *errStr = cfile.errorString();
2058         return false;
2059     }
2060     return true;
2061 }
2062
2063 static QByteArray
2064 getCommandOutput(const QString &args)
2065 {
2066     QByteArray out;
2067     if (FILE *proc = QT_POPEN(args.toLatin1().constData(), "r")) {
2068         while (!feof(proc)) {
2069             char buff[10 * 1024];
2070             int read_in = int(fread(buff, 1, sizeof(buff), proc));
2071             if (!read_in)
2072                 break;
2073             out += QByteArray(buff, read_in);
2074         }
2075         QT_PCLOSE(proc);
2076     }
2077     return out;
2078 }
2079
2080 #ifdef Q_OS_WIN
2081 static QString windowsErrorCode()
2082 {
2083     wchar_t *string = 0;
2084     FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
2085                   NULL,
2086                   GetLastError(),
2087                   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2088                   (LPWSTR)&string,
2089                   0,
2090                   NULL);
2091     QString ret = QString::fromWCharArray(string);
2092     LocalFree((HLOCAL)string);
2093     return ret;
2094 }
2095 #endif
2096
2097 QStringList
2098 QMakeProject::doProjectExpand(QString func, const QString &params,
2099                               QHash<QString, QStringList> &place)
2100 {
2101     return doProjectExpand(func, split_arg_list(params), place);
2102 }
2103
2104 QStringList
2105 QMakeProject::doProjectExpand(QString func, QStringList args,
2106                               QHash<QString, QStringList> &place)
2107 {
2108     QList<QStringList> args_list;
2109     for(int i = 0; i < args.size(); ++i) {
2110         QStringList arg = split_value_list(args[i]), tmp;
2111         for(int i = 0; i < arg.size(); ++i)
2112             tmp += doVariableReplaceExpand(arg[i], place);;
2113         args_list += tmp;
2114     }
2115     return doProjectExpand(func, args_list, place);
2116 }
2117
2118 static void
2119 populateDeps(const QStringList &deps, const QString &prefix,
2120              QHash<QString, QSet<QString> > &dependencies, QHash<QString, QStringList> &dependees,
2121              QStringList &rootSet, QHash<QString, QStringList> &place)
2122 {
2123     foreach (const QString &item, deps)
2124         if (!dependencies.contains(item)) {
2125             QSet<QString> &dset = dependencies[item]; // Always create entry
2126             QStringList depends = place.value(prefix + item + ".depends");
2127             if (depends.isEmpty()) {
2128                 rootSet << item;
2129             } else {
2130                 foreach (const QString &dep, depends) {
2131                     dset.insert(dep);
2132                     dependees[dep] << item;
2133                 }
2134                 populateDeps(depends, prefix, dependencies, dependees, rootSet, place);
2135             }
2136         }
2137 }
2138
2139 QStringList
2140 QMakeProject::doProjectExpand(QString func, QList<QStringList> args_list,
2141                               QHash<QString, QStringList> &place)
2142 {
2143     func = func.trimmed();
2144     if(replaceFunctions.contains(func)) {
2145         FunctionBlock *defined = replaceFunctions[func];
2146         function_blocks.push(defined);
2147         QStringList ret;
2148         defined->exec(args_list, this, place, ret);
2149         bool correct = function_blocks.pop() == defined;
2150         Q_ASSERT(correct); Q_UNUSED(correct);
2151         return ret;
2152     }
2153
2154     QStringList args; //why don't the builtin functions just use args_list? --Sam
2155     for(int i = 0; i < args_list.size(); ++i)
2156         args += args_list[i].join(QString(Option::field_sep));
2157
2158     ExpandFunc func_t = qmake_expandFunctions().value(func);
2159     if (!func_t && (func_t = qmake_expandFunctions().value(func.toLower())))
2160         warn_msg(WarnDeprecated, "%s:%d: Using uppercased builtin functions is deprecated.",
2161                  parser.file.toLatin1().constData(), parser.line_no);
2162     debug_msg(1, "Running project expand: %s(%s) [%d]",
2163               func.toLatin1().constData(), args.join("::").toLatin1().constData(), func_t);
2164
2165     QStringList ret;
2166     switch(func_t) {
2167     case E_MEMBER: {
2168         if(args.count() < 1 || args.count() > 3) {
2169             fprintf(stderr, "%s:%d: member(var, start, end) requires three arguments.\n",
2170                     parser.file.toLatin1().constData(), parser.line_no);
2171         } else {
2172             bool ok = true;
2173             const QStringList &var = values(args.first(), place);
2174             int start = 0, end = 0;
2175             if(args.count() >= 2) {
2176                 QString start_str = args[1];
2177                 start = start_str.toInt(&ok);
2178                 if(!ok) {
2179                     if(args.count() == 2) {
2180                         int dotdot = start_str.indexOf("..");
2181                         if(dotdot != -1) {
2182                             start = start_str.left(dotdot).toInt(&ok);
2183                             if(ok)
2184                                 end = start_str.mid(dotdot+2).toInt(&ok);
2185                         }
2186                     }
2187                     if(!ok)
2188                         fprintf(stderr, "%s:%d: member() argument 2 (start) '%s' invalid.\n",
2189                                 parser.file.toLatin1().constData(), parser.line_no,
2190                                 start_str.toLatin1().constData());
2191                 } else {
2192                     end = start;
2193                     if(args.count() == 3)
2194                         end = args[2].toInt(&ok);
2195                     if(!ok)
2196                         fprintf(stderr, "%s:%d: member() argument 3 (end) '%s' invalid.\n",
2197                                 parser.file.toLatin1().constData(), parser.line_no,
2198                                 args[2].toLatin1().constData());
2199                 }
2200             }
2201             if(ok) {
2202                 if(start < 0)
2203                     start += var.count();
2204                 if(end < 0)
2205                     end += var.count();
2206                 if(start < 0 || start >= var.count() || end < 0 || end >= var.count()) {
2207                     //nothing
2208                 } else if(start < end) {
2209                     for(int i = start; i <= end && (int)var.count() >= i; i++)
2210                         ret += var[i];
2211                 } else {
2212                     for(int i = start; i >= end && (int)var.count() >= i && i >= 0; i--)
2213                         ret += var[i];
2214                 }
2215             }
2216         }
2217         break; }
2218     case E_FIRST:
2219     case E_LAST: {
2220         if(args.count() != 1) {
2221             fprintf(stderr, "%s:%d: %s(var) requires one argument.\n",
2222                     parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
2223         } else {
2224             const QStringList &var = values(args.first(), place);
2225             if(!var.isEmpty()) {
2226                 if(func_t == E_FIRST)
2227                     ret = QStringList(var[0]);
2228                 else
2229                     ret = QStringList(var[var.size()-1]);
2230             }
2231         }
2232         break; }
2233     case E_CAT: {
2234         if(args.count() < 1 || args.count() > 2) {
2235             fprintf(stderr, "%s:%d: cat(file) requires one argument.\n",
2236                     parser.file.toLatin1().constData(), parser.line_no);
2237         } else {
2238             QString file = Option::normalizePath(args[0]);
2239
2240             bool blob = false;
2241             bool lines = false;
2242             bool singleLine = true;
2243             if (args.count() > 1) {
2244                 if (!args.at(1).compare(QLatin1String("false"), Qt::CaseInsensitive))
2245                     singleLine = false;
2246                 else if (!args.at(1).compare(QLatin1String("blob"), Qt::CaseInsensitive))
2247                     blob = true;
2248                 else if (!args.at(1).compare(QLatin1String("lines"), Qt::CaseInsensitive))
2249                     lines = true;
2250             }
2251             QFile qfile(file);
2252             if(qfile.open(QIODevice::ReadOnly)) {
2253                 QTextStream stream(&qfile);
2254                 if (blob) {
2255                     ret += stream.readAll();
2256                 } else {
2257                     while (!stream.atEnd()) {
2258                         if (lines) {
2259                             ret += stream.readLine();
2260                         } else {
2261                             ret += split_value_list(stream.readLine().trimmed());
2262                             if (!singleLine)
2263                                 ret += "\n";
2264                         }
2265                     }
2266                 }
2267             }
2268         }
2269         break; }
2270     case E_FROMFILE: {
2271         if(args.count() != 2) {
2272             fprintf(stderr, "%s:%d: fromfile(file, variable) requires two arguments.\n",
2273                     parser.file.toLatin1().constData(), parser.line_no);
2274         } else {
2275             QString seek_var = args[1], file = Option::normalizePath(args[0]);
2276
2277             QHash<QString, QStringList> tmp;
2278             if(doProjectInclude(file, IncludeFlagNewParser, tmp) == IncludeSuccess) {
2279                 if(tmp.contains("QMAKE_INTERNAL_INCLUDED_FILES")) {
2280                     QStringList &out = place["QMAKE_INTERNAL_INCLUDED_FILES"];
2281                     const QStringList &in = tmp["QMAKE_INTERNAL_INCLUDED_FILES"];
2282                     for(int i = 0; i < in.size(); ++i) {
2283                         if(out.indexOf(in[i]) == -1)
2284                             out += in[i];
2285                     }
2286                 }
2287                 ret = tmp[seek_var];
2288             }
2289         }
2290         break; }
2291     case E_EVAL: {
2292         if (args.count() != 1) {
2293             fprintf(stderr, "%s:%d: eval(variable) requires one argument.\n",
2294                     parser.file.toLatin1().constData(), parser.line_no);
2295
2296         } else {
2297             ret += place.value(args.at(0));
2298         }
2299         break; }
2300     case E_LIST: {
2301         static int x = 0;
2302         QString tmp;
2303         tmp.sprintf(".QMAKE_INTERNAL_TMP_VAR_%d", x++);
2304         ret = QStringList(tmp);
2305         QStringList &lst = (*((QHash<QString, QStringList>*)&place))[tmp];
2306         lst.clear();
2307         for(QStringList::ConstIterator arg_it = args.begin();
2308             arg_it != args.end(); ++arg_it)
2309             lst += split_value_list((*arg_it));
2310         break; }
2311     case E_SPRINTF: {
2312         if(args.count() < 1) {
2313             fprintf(stderr, "%s:%d: sprintf(format, ...) requires one argument.\n",
2314                     parser.file.toLatin1().constData(), parser.line_no);
2315         } else {
2316             QString tmp = args.at(0);
2317             for(int i = 1; i < args.count(); ++i)
2318                 tmp = tmp.arg(args.at(i));
2319             ret = split_value_list(tmp);
2320         }
2321         break; }
2322     case E_FORMAT_NUMBER:
2323         if (args.count() > 2) {
2324             fprintf(stderr, "%s:%d: format_number(number[, options...]) requires one or two arguments.\n",
2325                     parser.file.toLatin1().constData(), parser.line_no);
2326         } else {
2327             int ibase = 10;
2328             int obase = 10;
2329             int width = 0;
2330             bool zeropad = false;
2331             bool leftalign = false;
2332             enum { DefaultSign, PadSign, AlwaysSign } sign = DefaultSign;
2333             if (args.count() >= 2) {
2334                 foreach (const QString &opt, split_value_list(args.at(1))) {
2335                     if (opt.startsWith(QLatin1String("ibase="))) {
2336                         ibase = opt.mid(6).toInt();
2337                     } else if (opt.startsWith(QLatin1String("obase="))) {
2338                         obase = opt.mid(6).toInt();
2339                     } else if (opt.startsWith(QLatin1String("width="))) {
2340                         width = opt.mid(6).toInt();
2341                     } else if (opt == QLatin1String("zeropad")) {
2342                         zeropad = true;
2343                     } else if (opt == QLatin1String("padsign")) {
2344                         sign = PadSign;
2345                     } else if (opt == QLatin1String("alwayssign")) {
2346                         sign = AlwaysSign;
2347                     } else if (opt == QLatin1String("leftalign")) {
2348                         leftalign = true;
2349                     } else {
2350                         fprintf(stderr, "%s:%d: format_number(): invalid format option %s.\n",
2351                                 parser.file.toLatin1().constData(), parser.line_no,
2352                                 opt.toLatin1().constData());
2353                         goto formfail;
2354                     }
2355                 }
2356             }
2357             if (args.at(0).contains(QLatin1Char('.'))) {
2358                 fprintf(stderr, "%s:%d: format_number(): floats are currently not supported.\n",
2359                         parser.file.toLatin1().constData(), parser.line_no);
2360                 break;
2361             }
2362             bool ok;
2363             qlonglong num = args.at(0).toLongLong(&ok, ibase);
2364             if (!ok) {
2365                 fprintf(stderr, "%s:%d: format_number(): malformed number %s for base %d.\n",
2366                         parser.file.toLatin1().constData(), parser.line_no,
2367                         args.at(0).toLatin1().constData(), ibase);
2368                 break;
2369             }
2370             QString outstr;
2371             if (num < 0) {
2372                 num = -num;
2373                 outstr = QLatin1Char('-');
2374             } else if (sign == AlwaysSign) {
2375                 outstr = QLatin1Char('+');
2376             } else if (sign == PadSign) {
2377                 outstr = QLatin1Char(' ');
2378             }
2379             QString numstr = QString::number(num, obase);
2380             int space = width - outstr.length() - numstr.length();
2381             if (space <= 0) {
2382                 outstr += numstr;
2383             } else if (leftalign) {
2384                 outstr += numstr + QString(space, QLatin1Char(' '));
2385             } else if (zeropad) {
2386                 outstr += QString(space, QLatin1Char('0')) + numstr;
2387             } else {
2388                 outstr.prepend(QString(space, QLatin1Char(' ')));
2389                 outstr += numstr;
2390             }
2391             ret += outstr;
2392         }
2393       formfail:
2394         break;
2395     case E_JOIN: {
2396         if(args.count() < 1 || args.count() > 4) {
2397             fprintf(stderr, "%s:%d: join(var, glue, before, after) requires four"
2398                     "arguments.\n", parser.file.toLatin1().constData(), parser.line_no);
2399         } else {
2400             QString glue, before, after;
2401             if(args.count() >= 2)
2402                 glue = args[1];
2403             if(args.count() >= 3)
2404                 before = args[2];
2405             if(args.count() == 4)
2406                 after = args[3];
2407             const QStringList &var = values(args.first(), place);
2408             if(!var.isEmpty())
2409                 ret = split_value_list(before + var.join(glue) + after);
2410         }
2411         break; }
2412     case E_SPLIT: {
2413         if(args.count() < 1 || args.count() > 2) {
2414             fprintf(stderr, "%s:%d split(var, sep) requires one or two arguments\n",
2415                     parser.file.toLatin1().constData(), parser.line_no);
2416         } else {
2417             QString sep = QString(Option::field_sep);
2418             if(args.count() >= 2)
2419                 sep = args[1];
2420             QStringList var = values(args.first(), place);
2421             for(QStringList::ConstIterator vit = var.begin(); vit != var.end(); ++vit) {
2422                 QStringList lst = (*vit).split(sep);
2423                 for(QStringList::ConstIterator spltit = lst.begin(); spltit != lst.end(); ++spltit)
2424                     ret += (*spltit);
2425             }
2426         }
2427         break; }
2428     case E_BASENAME:
2429     case E_DIRNAME:
2430     case E_SECTION: {
2431         bool regexp = false;
2432         QString sep, var;
2433         int beg=0, end=-1;
2434         if(func_t == E_SECTION) {
2435             if(args.count() != 3 && args.count() != 4) {
2436                 fprintf(stderr, "%s:%d section(var, sep, begin, end) requires three argument\n",
2437                         parser.file.toLatin1().constData(), parser.line_no);
2438             } else {
2439                 var = args[0];
2440                 sep = args[1];
2441                 beg = args[2].toInt();
2442                 if(args.count() == 4)
2443                     end = args[3].toInt();
2444             }
2445         } else {
2446             if(args.count() != 1) {
2447                 fprintf(stderr, "%s:%d %s(var) requires one argument.\n",
2448                         parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
2449             } else {
2450                 var = args[0];
2451                 regexp = true;
2452                 sep = "[" + QRegExp::escape(Option::dir_sep) + "/]";
2453                 if(func_t == E_DIRNAME)
2454                     end = -2;
2455                 else
2456                     beg = -1;
2457             }
2458         }
2459         if(!var.isNull()) {
2460             const QStringList &l = values(var, place);
2461             for(QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
2462                 QString separator = sep;
2463                 if(regexp)
2464                     ret += (*it).section(QRegExp(separator), beg, end);
2465                 else
2466                     ret += (*it).section(separator, beg, end);
2467             }
2468         }
2469         break; }
2470     case E_FIND: {
2471         if(args.count() != 2) {
2472             fprintf(stderr, "%s:%d find(var, str) requires two arguments\n",
2473                     parser.file.toLatin1().constData(), parser.line_no);
2474         } else {
2475             QRegExp regx(args[1]);
2476             const QStringList &var = values(args.first(), place);
2477             for(QStringList::ConstIterator vit = var.begin();
2478                 vit != var.end(); ++vit) {
2479                 if(regx.indexIn(*vit) != -1)
2480                     ret += (*vit);
2481             }
2482         }
2483         break;  }
2484     case E_SYSTEM: {
2485         if(args.count() < 1 || args.count() > 2) {
2486             fprintf(stderr, "%s:%d system(execut) requires one argument.\n",
2487                     parser.file.toLatin1().constData(), parser.line_no);
2488         } else {
2489             bool blob = false;
2490             bool lines = false;
2491             bool singleLine = true;
2492             if (args.count() > 1) {
2493                 if (!args.at(1).compare(QLatin1String("false"), Qt::CaseInsensitive))
2494                     singleLine = false;
2495                 else if (!args.at(1).compare(QLatin1String("blob"), Qt::CaseInsensitive))
2496                     blob = true;
2497                 else if (!args.at(1).compare(QLatin1String("lines"), Qt::CaseInsensitive))
2498                     lines = true;
2499             }
2500             QByteArray bytes = getCommandOutput(args.at(0));
2501             if (lines) {
2502                 QTextStream stream(bytes);
2503                 while (!stream.atEnd())
2504                     ret += stream.readLine();
2505             } else {
2506                 QString output = QString::fromLocal8Bit(bytes);
2507                 if (blob) {
2508                     ret += output;
2509                 } else {
2510                     output.replace(QLatin1Char('\t'), QLatin1Char(' '));
2511                     if (singleLine)
2512                         output.replace(QLatin1Char('\n'), QLatin1Char(' '));
2513                     ret += split_value_list(output);
2514                 }
2515             }
2516         }
2517         break; }
2518     case E_UNIQUE: {
2519         if(args.count() != 1) {
2520             fprintf(stderr, "%s:%d unique(var) requires one argument.\n",
2521                     parser.file.toLatin1().constData(), parser.line_no);
2522         } else {
2523             const QStringList &var = values(args.first(), place);
2524             for(int i = 0; i < var.count(); i++) {
2525                 if(!ret.contains(var[i]))
2526                     ret.append(var[i]);
2527             }
2528         }
2529         break; }
2530     case E_REVERSE:
2531         if (args.count() != 1) {
2532             fprintf(stderr, "%s:%d reverse(var) requires one argument.\n",
2533                     parser.file.toLatin1().constData(), parser.line_no);
2534         } else {
2535             QStringList var = values(args.first(), place);
2536             for (int i = 0; i < var.size() / 2; i++)
2537                 var.swap(i, var.size() - i - 1);
2538             ret += var;
2539         }
2540         break;
2541     case E_QUOTE:
2542         ret = args;
2543         break;
2544     case E_ESCAPE_EXPAND: {
2545         for(int i = 0; i < args.size(); ++i) {
2546             QChar *i_data = args[i].data();
2547             int i_len = args[i].length();
2548             for(int x = 0; x < i_len; ++x) {
2549                 if(*(i_data+x) == '\\' && x < i_len-1) {
2550                     if(*(i_data+x+1) == '\\') {
2551                         ++x;
2552                     } else {
2553                         struct {
2554                             char in, out;
2555                         } mapped_quotes[] = {
2556                             { 'n', '\n' },
2557                             { 't', '\t' },
2558                             { 'r', '\r' },
2559                             { 0, 0 }
2560                         };
2561                         for(int i = 0; mapped_quotes[i].in; ++i) {
2562                             if(*(i_data+x+1) == mapped_quotes[i].in) {
2563                                 *(i_data+x) = mapped_quotes[i].out;
2564                                 if(x < i_len-2)
2565                                     memmove(i_data+x+1, i_data+x+2, (i_len-x-2)*sizeof(QChar));
2566                                 --i_len;
2567                                 break;
2568                             }
2569                         }
2570                     }
2571                 }
2572             }
2573             ret.append(QString(i_data, i_len));
2574         }
2575         break; }
2576     case E_RE_ESCAPE: {
2577         for(int i = 0; i < args.size(); ++i)
2578             ret += QRegExp::escape(args[i]);
2579         break; }
2580     case E_VAL_ESCAPE:
2581         if (args.count() != 1) {
2582             fprintf(stderr, "%s:%d val_escape(var) requires one argument.\n",
2583                     parser.file.toLatin1().constData(), parser.line_no);
2584         } else {
2585             QStringList vals = values(args.at(0), place);
2586             ret.reserve(vals.length());
2587             foreach (const QString &str, vals)
2588                 ret += quoteValue(str);
2589         }
2590         break;
2591     case E_UPPER:
2592     case E_LOWER: {
2593         for(int i = 0; i < args.size(); ++i) {
2594             if(func_t == E_UPPER)
2595                 ret += args[i].toUpper();
2596             else
2597                 ret += args[i].toLower();
2598         }
2599         break; }
2600     case E_FILES: {
2601         if(args.count() != 1 && args.count() != 2) {
2602             fprintf(stderr, "%s:%d files(pattern) requires one argument.\n",
2603                     parser.file.toLatin1().constData(), parser.line_no);
2604         } else {
2605             bool recursive = false;
2606             if(args.count() == 2)
2607                 recursive = (args[1].toLower() == "true" || args[1].toInt());
2608             QStringList dirs;
2609             QString r = Option::normalizePath(args[0]);
2610             int slash = r.lastIndexOf(QLatin1Char('/'));
2611             if(slash != -1) {
2612                 dirs.append(r.left(slash));
2613                 r = r.mid(slash+1);
2614             } else {
2615                 dirs.append("");
2616             }
2617
2618             QRegExp regex(r, Qt::CaseSensitive, QRegExp::Wildcard);
2619             for(int d = 0; d < dirs.count(); d++) {
2620                 QString dir = dirs[d];
2621                 if (!dir.isEmpty() && !dir.endsWith(QLatin1Char('/')))
2622                     dir += "/";
2623
2624                 QDir qdir(dir);
2625                 for(int i = 0; i < (int)qdir.count(); ++i) {
2626                     if(qdir[i] == "." || qdir[i] == "..")
2627                         continue;
2628                     QString fname = dir + qdir[i];
2629                     if(QFileInfo(fname).isDir()) {
2630                         if(recursive)
2631                             dirs.append(fname);
2632                     }
2633                     if(regex.exactMatch(qdir[i]))
2634                         ret += fname;
2635                 }
2636             }
2637         }
2638         break; }
2639     case E_PROMPT: {
2640         if(args.count() != 1) {
2641             fprintf(stderr, "%s:%d prompt(question) requires one argument.\n",
2642                     parser.file.toLatin1().constData(), parser.line_no);
2643         } else if(pfile == "-") {
2644             fprintf(stderr, "%s:%d prompt(question) cannot be used when '-o -' is used.\n",
2645                     parser.file.toLatin1().constData(), parser.line_no);
2646         } else {
2647             QString msg = fixEnvVariables(args.first());
2648             if(!msg.endsWith("?"))
2649                 msg += "?";
2650             fprintf(stderr, "Project %s: %s ", func.toUpper().toLatin1().constData(),
2651                     msg.toLatin1().constData());
2652
2653             QFile qfile;
2654             if(qfile.open(stdin, QIODevice::ReadOnly)) {
2655                 QTextStream t(&qfile);
2656                 ret = split_value_list(t.readLine());
2657             }
2658         }
2659         break; }
2660     case E_REPLACE: {
2661         if(args.count() != 3 ) {
2662             fprintf(stderr, "%s:%d replace(var, before, after) requires three arguments\n",
2663                     parser.file.toLatin1().constData(), parser.line_no);
2664         } else {
2665             const QRegExp before( args[1] );
2666             const QString after( args[2] );
2667             QStringList var = values(args.first(), place);
2668             for(QStringList::Iterator it = var.begin(); it != var.end(); ++it)
2669                 ret += it->replace(before, after);
2670         }
2671         break; }
2672     case E_SIZE: {
2673         if(args.count() != 1) {
2674             fprintf(stderr, "%s:%d: size(var) requires one argument.\n",
2675                     parser.file.toLatin1().constData(), parser.line_no);
2676         } else {
2677             int size = values(args[0], place).size();
2678             ret += QString::number(size);
2679         }
2680         break; }
2681     case E_SORT_DEPENDS:
2682     case E_RESOLVE_DEPENDS: {
2683         if(args.count() < 1 || args.count() > 2) {
2684             fprintf(stderr, "%s:%d: %s(var, prefix) requires one or two arguments.\n",
2685                     parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
2686         } else {
2687             QHash<QString, QSet<QString> > dependencies;
2688             QHash<QString, QStringList> dependees;
2689             QStringList rootSet;
2690
2691             QStringList orgList = values(args[0], place);
2692             populateDeps(orgList, (args.count() != 2 ? QString() : args[1]),
2693                          dependencies, dependees, rootSet, place);
2694
2695             for (int i = 0; i < rootSet.size(); ++i) {
2696                 const QString &item = rootSet.at(i);
2697                 if ((func_t == E_RESOLVE_DEPENDS) || orgList.contains(item))
2698                     ret.prepend(item);
2699                 foreach (const QString &dep, dependees[item]) {
2700                     QSet<QString> &dset = dependencies[dep];
2701                     dset.remove(rootSet.at(i)); // *Don't* use 'item' - rootSet may have changed!
2702                     if (dset.isEmpty())
2703                         rootSet << dep;
2704                 }
2705             }
2706         }
2707         break; }
2708     case E_ENUMERATE_VARS:
2709         ret += place.keys();
2710         break;
2711     case E_SHADOWED: {
2712         QString val = QDir::cleanPath(QFileInfo(args.at(0)).absoluteFilePath());
2713         if (Option::mkfile::source_root.isEmpty()) {
2714             ret += val;
2715         } else if (val.startsWith(Option::mkfile::source_root)
2716                    && (val.length() == Option::mkfile::source_root.length()
2717                        || val.at(Option::mkfile::source_root.length()) == QLatin1Char('/'))) {
2718             ret += Option::mkfile::build_root + val.mid(Option::mkfile::source_root.length());
2719         }
2720         break; }
2721     case E_ABSOLUTE_PATH:
2722         if (args.count() > 2)
2723             fprintf(stderr, "%s:%d absolute_path(path[, base]) requires one or two arguments.\n",
2724                     parser.file.toLatin1().constData(), parser.line_no);
2725         else
2726             ret += QDir::cleanPath(QDir(args.count() > 1 ? args.at(1) : QString())
2727                                    .absoluteFilePath(args.at(0)));
2728         break;
2729     case E_RELATIVE_PATH:
2730         if (args.count() > 2) {
2731             fprintf(stderr, "%s:%d relative_path(path[, base]) requires one or two arguments.\n",
2732                     parser.file.toLatin1().constData(), parser.line_no);
2733         } else {
2734             QDir baseDir(args.count() > 1 ? args.at(1) : QString());
2735             ret += baseDir.relativeFilePath(baseDir.absoluteFilePath(args.at(0)));
2736         }
2737         break;
2738     case E_CLEAN_PATH:
2739         if (args.count() != 1)
2740             fprintf(stderr, "%s:%d clean_path(path) requires one argument.\n",
2741                     parser.file.toLatin1().constData(), parser.line_no);
2742         else
2743             ret += QDir::cleanPath(args.at(0));
2744         break;
2745     case E_SYSTEM_PATH:
2746         if (args.count() != 1)
2747             fprintf(stderr, "%s:%d system_path(path) requires one argument.\n",
2748                     parser.file.toLatin1().constData(), parser.line_no);
2749         else
2750             ret += Option::fixPathToLocalOS(args.at(0), false);
2751         break;
2752     case E_SHELL_PATH:
2753         if (args.count() != 1)
2754             fprintf(stderr, "%s:%d shell_path(path) requires one argument.\n",
2755                     parser.file.toLatin1().constData(), parser.line_no);
2756         else
2757             ret += Option::fixPathToTargetOS(args.at(0), false);
2758         break;
2759     case E_SYSTEM_QUOTE:
2760         if (args.count() != 1)
2761             fprintf(stderr, "%s:%d system_quote(args) requires one argument.\n",
2762                     parser.file.toLatin1().constData(), parser.line_no);
2763         else
2764 #ifdef Q_OS_WIN
2765             ret += shellQuoteWin(args.at(0));
2766 #else
2767             ret += shellQuoteUnix(args.at(0));
2768 #endif
2769         break;
2770     case E_SHELL_QUOTE:
2771         if (args.count() != 1)
2772             fprintf(stderr, "%s:%d shell_quote(args) requires one argument.\n",
2773                     parser.file.toLatin1().constData(), parser.line_no);
2774         else if (Option::dir_sep.at(0) != QLatin1Char('/'))
2775             ret += shellQuoteWin(args.at(0));
2776         else
2777             ret += shellQuoteUnix(args.at(0));
2778         break;
2779     default: {
2780         fprintf(stderr, "%s:%d: Unknown replace function: %s\n",
2781                 parser.file.toLatin1().constData(), parser.line_no,
2782                 func.toLatin1().constData());
2783         break; }
2784     }
2785     return ret;
2786 }
2787
2788 bool
2789 QMakeProject::doProjectTest(QString func, QStringList args, QHash<QString, QStringList> &place)
2790 {
2791     QList<QStringList> args_list;
2792     for(int i = 0; i < args.size(); ++i) {
2793         QStringList arg = split_value_list(args[i]), tmp;
2794         for(int i = 0; i < arg.size(); ++i)
2795             tmp += doVariableReplaceExpand(arg[i], place);
2796         args_list += tmp;
2797     }
2798     return doProjectTest(func, args_list, place);
2799 }
2800
2801 bool
2802 QMakeProject::doProjectTest(QString func, QList<QStringList> args_list, QHash<QString, QStringList> &place)
2803 {
2804     func = func.trimmed();
2805
2806     if(testFunctions.contains(func)) {
2807         FunctionBlock *defined = testFunctions[func];
2808         QStringList ret;
2809         function_blocks.push(defined);
2810         defined->exec(args_list, this, place, ret);
2811         bool correct = function_blocks.pop() == defined;
2812         Q_ASSERT(correct); Q_UNUSED(correct);
2813
2814         if(ret.isEmpty()) {
2815             return true;
2816         } else {
2817             if(ret.first() == "true") {
2818                 return true;
2819             } else if(ret.first() == "false") {
2820                 return false;
2821             } else {
2822                 bool ok;
2823                 int val = ret.first().toInt(&ok);
2824                 if(ok)
2825                     return val;
2826                 fprintf(stderr, "%s:%d Unexpected return value from test %s [%s].\n",
2827                         parser.file.toLatin1().constData(),
2828                         parser.line_no, func.toLatin1().constData(),
2829                         ret.join("::").toLatin1().constData());
2830             }
2831             return false;
2832         }
2833         return false;
2834     }
2835
2836     QStringList args; //why don't the builtin functions just use args_list? --Sam
2837     for(int i = 0; i < args_list.size(); ++i)
2838         args += args_list[i].join(QString(Option::field_sep));
2839
2840     TestFunc func_t = qmake_testFunctions().value(func);
2841     debug_msg(1, "Running project test: %s(%s) [%d]",
2842               func.toLatin1().constData(), args.join("::").toLatin1().constData(), func_t);
2843
2844     switch(func_t) {
2845     case T_REQUIRES:
2846         return doProjectCheckReqs(args, place);
2847     case T_LESSTHAN:
2848     case T_GREATERTHAN: {
2849         if(args.count() != 2) {
2850             fprintf(stderr, "%s:%d: %s(variable, value) requires two arguments.\n", parser.file.toLatin1().constData(),
2851                     parser.line_no, func.toLatin1().constData());
2852             return false;
2853         }
2854         QString rhs(args[1]), lhs(values(args[0], place).join(QString(Option::field_sep)));
2855         bool ok;
2856         int rhs_int = rhs.toInt(&ok);
2857         if(ok) { // do integer compare
2858             int lhs_int = lhs.toInt(&ok);
2859             if(ok) {
2860                 if(func_t == T_GREATERTHAN)
2861                     return lhs_int > rhs_int;
2862                 return lhs_int < rhs_int;
2863             }
2864         }
2865         if(func_t == T_GREATERTHAN)
2866             return lhs > rhs;
2867         return lhs < rhs; }
2868     case T_IF: {
2869         if(args.count() != 1) {
2870             fprintf(stderr, "%s:%d: if(condition) requires one argument.\n", parser.file.toLatin1().constData(),
2871                     parser.line_no);
2872             return false;
2873         }
2874         const QString cond = args.first();
2875         const QChar *d = cond.unicode();
2876         QChar quote = 0;
2877         bool ret = true, or_op = false;
2878         QString test;
2879         for(int d_off = 0, parens = 0, d_len = cond.size(); d_off < d_len; ++d_off) {
2880             if(!quote.isNull()) {
2881                 if(*(d+d_off) == quote)
2882                     quote = QChar();
2883             } else if(*(d+d_off) == '(') {
2884                 ++parens;
2885             } else if(*(d+d_off) == ')') {
2886                 --parens;
2887             } else if(*(d+d_off) == '"' /*|| *(d+d_off) == '\''*/) {
2888                 quote = *(d+d_off);
2889             }
2890             if(!parens && quote.isNull() && (*(d+d_off) == QLatin1Char(':') || *(d+d_off) == QLatin1Char('|') || d_off == d_len-1)) {
2891                 if(d_off == d_len-1)
2892                     test += *(d+d_off);
2893                 if(!test.isEmpty()) {
2894                     if (or_op != ret)
2895                         ret = doProjectTest(test, place);
2896                     test.clear();
2897                 }
2898                 if(*(d+d_off) == QLatin1Char(':')) {
2899                     or_op = false;
2900                 } else if(*(d+d_off) == QLatin1Char('|')) {
2901                     or_op = true;
2902                 }
2903             } else {
2904                 test += *(d+d_off);
2905             }
2906         }
2907         return ret; }
2908     case T_EQUALS:
2909         if(args.count() != 2) {
2910             fprintf(stderr, "%s:%d: %s(variable, value) requires two arguments.\n", parser.file.toLatin1().constData(),
2911                     parser.line_no, func.toLatin1().constData());
2912             return false;
2913         }
2914         return values(args[0], place).join(QString(Option::field_sep)) == args[1];
2915     case T_EXISTS: {
2916         if(args.count() != 1) {
2917             fprintf(stderr, "%s:%d: exists(file) requires one argument.\n", parser.file.toLatin1().constData(),
2918                     parser.line_no);
2919             return false;
2920         }
2921         QString file = Option::normalizePath(args.first());
2922
2923         if(QFile::exists(file))
2924             return true;
2925         //regular expression I guess
2926         QString dirstr = qmake_getpwd();
2927         int slsh = file.lastIndexOf(QLatin1Char('/'));
2928         if(slsh != -1) {
2929             dirstr = file.left(slsh+1);
2930             file = file.right(file.length() - slsh - 1);
2931         }
2932         return QDir(dirstr).entryList(QStringList(file)).count(); }
2933     case T_EXPORT:
2934         if(args.count() != 1) {
2935             fprintf(stderr, "%s:%d: export(variable) requires one argument.\n", parser.file.toLatin1().constData(),
2936                     parser.line_no);
2937             return false;
2938         }
2939         for(int i = 0; i < function_blocks.size(); ++i) {
2940             FunctionBlock *f = function_blocks.at(i);
2941             f->vars[args[0]] = values(args[0], place);
2942             if(!i && f->calling_place)
2943                 (*f->calling_place)[args[0]] = values(args[0], place);
2944         }
2945         return true;
2946     case T_CLEAR:
2947         if(args.count() != 1) {
2948             fprintf(stderr, "%s:%d: clear(variable) requires one argument.\n", parser.file.toLatin1().constData(),
2949                     parser.line_no);
2950             return false;
2951         }
2952         if(!place.contains(args[0]))
2953             return false;
2954         place[args[0]].clear();
2955         return true;
2956     case T_UNSET:
2957         if(args.count() != 1) {
2958             fprintf(stderr, "%s:%d: unset(variable) requires one argument.\n", parser.file.toLatin1().constData(),
2959                     parser.line_no);
2960             return false;
2961         }
2962         if(!place.contains(args[0]))
2963             return false;
2964         place.remove(args[0]);
2965         return true;
2966     case T_EVAL: {
2967         if(args.count() < 1 && 0) {
2968             fprintf(stderr, "%s:%d: eval(project) requires one argument.\n", parser.file.toLatin1().constData(),
2969                     parser.line_no);
2970             return false;
2971         }
2972         QString project = args.join(" ");
2973         parser_info pi = parser;
2974         parser.from_file = false;
2975         parser.file = "(eval)";
2976         parser.line_no = 0;
2977         QTextStream t(&project, QIODevice::ReadOnly);
2978         bool ret = read(t, place);
2979         parser = pi;
2980         return ret; }
2981     case T_CONFIG: {
2982         if(args.count() < 1 || args.count() > 2) {
2983             fprintf(stderr, "%s:%d: CONFIG(config) requires one argument.\n", parser.file.toLatin1().constData(),
2984                     parser.line_no);
2985             return false;
2986         }
2987         if(args.count() == 1)
2988             return isActiveConfig(args[0]);
2989         const QStringList mutuals = args[1].split('|');
2990         const QStringList &configs = values("CONFIG", place);
2991         for(int i = configs.size()-1; i >= 0; i--) {
2992             for(int mut = 0; mut < mutuals.count(); mut++) {
2993                 if(configs[i] == mutuals[mut].trimmed())
2994                     return (configs[i] == args[0]);
2995             }
2996         }
2997         return false; }
2998     case T_SYSTEM:
2999         if(args.count() < 1 || args.count() > 2) {
3000             fprintf(stderr, "%s:%d: system(exec) requires one argument.\n", parser.file.toLatin1().constData(),
3001                     parser.line_no);
3002             return false;
3003         }
3004         if(args.count() == 2) {
3005             const QString sarg = args[1];
3006             if (sarg.toLower() == "true" || sarg.toInt())
3007                 warn_msg(WarnParser, "%s:%d: system()'s second argument is now hard-wired to false.\n",
3008                          parser.file.toLatin1().constData(), parser.line_no);
3009         }
3010         return system(args[0].toLatin1().constData()) == 0;
3011     case T_RETURN:
3012         if(function_blocks.isEmpty()) {
3013             fprintf(stderr, "%s:%d unexpected return()\n",
3014                     parser.file.toLatin1().constData(), parser.line_no);
3015         } else {
3016             FunctionBlock *f = function_blocks.top();
3017             f->cause_return = true;
3018             if(args_list.count() >= 1)
3019                 f->return_value += args_list[0];
3020         }
3021         return true;
3022     case T_BREAK:
3023         if(iterator)
3024             iterator->cause_break = true;
3025         else
3026             fprintf(stderr, "%s:%d unexpected break()\n",
3027                     parser.file.toLatin1().constData(), parser.line_no);
3028         return true;
3029     case T_NEXT:
3030         if(iterator)
3031             iterator->cause_next = true;
3032         else
3033             fprintf(stderr, "%s:%d unexpected next()\n",
3034                     parser.file.toLatin1().constData(), parser.line_no);
3035         return true;
3036     case T_DEFINED:
3037         if(args.count() < 1 || args.count() > 2) {
3038             fprintf(stderr, "%s:%d: defined(function) requires one argument.\n",
3039                     parser.file.toLatin1().constData(), parser.line_no);
3040         } else {
3041            if(args.count() > 1) {
3042                if(args[1] == "test")
3043                    return testFunctions.contains(args[0]);
3044                else if(args[1] == "replace")
3045                    return replaceFunctions.contains(args[0]);
3046                else if(args[1] == "var")
3047                    return place.contains(args[0]);
3048                fprintf(stderr, "%s:%d: defined(function, type): unexpected type [%s].\n",
3049                        parser.file.toLatin1().constData(), parser.line_no,
3050                        args[1].toLatin1().constData());
3051             } else {
3052                 if(replaceFunctions.contains(args[0]) || testFunctions.contains(args[0]))
3053                     return true;
3054             }
3055         }
3056         return false;
3057     case T_CONTAINS: {
3058         if(args.count() < 2 || args.count() > 3) {
3059             fprintf(stderr, "%s:%d: contains(var, val) requires at lesat 2 arguments.\n",
3060                     parser.file.toLatin1().constData(), parser.line_no);
3061             return false;
3062         }
3063         QRegExp regx(args[1]);
3064         const QStringList &l = values(args[0], place);
3065         if(args.count() == 2) {
3066             for(int i = 0; i < l.size(); ++i) {
3067                 const QString val = l[i];
3068                 if(regx.exactMatch(val) || val == args[1])
3069                     return true;
3070             }
3071         } else {
3072             const QStringList mutuals = args[2].split('|');
3073             for(int i = l.size()-1; i >= 0; i--) {
3074                 const QString val = l[i];
3075                 for(int mut = 0; mut < mutuals.count(); mut++) {
3076                     if(val == mutuals[mut].trimmed())
3077                         return (regx.exactMatch(val) || val == args[1]);
3078                 }
3079             }
3080         }
3081         return false; }
3082     case T_INFILE: {
3083         if(args.count() < 2 || args.count() > 3) {
3084             fprintf(stderr, "%s:%d: infile(file, var, val) requires at least 2 arguments.\n",
3085                     parser.file.toLatin1().constData(), parser.line_no);
3086             return false;
3087         }
3088
3089         bool ret = false;
3090         QHash<QString, QStringList> tmp;
3091         if(doProjectInclude(Option::normalizePath(args[0]), IncludeFlagNewParser, tmp) == IncludeSuccess) {
3092             if(tmp.contains("QMAKE_INTERNAL_INCLUDED_FILES")) {
3093                 QStringList &out = place["QMAKE_INTERNAL_INCLUDED_FILES"];
3094                 const QStringList &in = tmp["QMAKE_INTERNAL_INCLUDED_FILES"];
3095                 for(int i = 0; i < in.size(); ++i) {
3096                     if(out.indexOf(in[i]) == -1)
3097                         out += in[i];
3098                 }
3099             }
3100             if(args.count() == 2) {
3101                 ret = tmp.contains(args[1]);
3102             } else {
3103                 QRegExp regx(args[2]);
3104                 const QStringList &l = tmp[args[1]];
3105                 for(QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
3106                     if(regx.exactMatch((*it)) || (*it) == args[2]) {
3107                         ret = true;
3108                         break;
3109                     }
3110                 }
3111             }
3112         }
3113         return ret; }
3114     case T_COUNT:
3115         if(args.count() != 2 && args.count() != 3) {
3116             fprintf(stderr, "%s:%d: count(var, count) requires two arguments.\n", parser.file.toLatin1().constData(),
3117                     parser.line_no);
3118             return false;
3119         }
3120         if(args.count() == 3) {
3121             QString comp = args[2];
3122             if(comp == ">" || comp == "greaterThan")
3123                 return values(args[0], place).count() > args[1].toInt();
3124             if(comp == ">=")
3125                 return values(args[0], place).count() >= args[1].toInt();
3126             if(comp == "<" || comp == "lessThan")
3127                 return values(args[0], place).count() < args[1].toInt();
3128             if(comp == "<=")
3129                 return values(args[0], place).count() <= args[1].toInt();
3130             if(comp == "equals" || comp == "isEqual" || comp == "=" || comp == "==")
3131                 return values(args[0], place).count() == args[1].toInt();
3132             fprintf(stderr, "%s:%d: unexpected modifier to count(%s)\n", parser.file.toLatin1().constData(),
3133                     parser.line_no, comp.toLatin1().constData());
3134             return false;
3135         }
3136         return values(args[0], place).count() == args[1].toInt();
3137     case T_ISEMPTY:
3138         if(args.count() != 1) {
3139             fprintf(stderr, "%s:%d: isEmpty(var) requires one argument.\n", parser.file.toLatin1().constData(),
3140                     parser.line_no);
3141             return false;
3142         }
3143         return values(args[0], place).isEmpty();
3144     case T_INCLUDE:
3145     case T_LOAD: {
3146         QString parseInto;
3147         const bool include_statement = (func_t == T_INCLUDE);
3148         bool ignore_error = false;
3149         if(args.count() >= 2) {
3150             if(func_t == T_INCLUDE) {
3151                 parseInto = args[1];
3152                 if (args.count() == 3){
3153                     QString sarg = args[2];
3154                     if (sarg.toLower() == "true" || sarg.toInt())
3155                         ignore_error = true;
3156                 }
3157             } else {
3158                 QString sarg = args[1];
3159                 ignore_error = (sarg.toLower() == "true" || sarg.toInt());
3160             }
3161         } else if(args.count() != 1) {
3162             QString func_desc = "load(feature)";
3163             if(include_statement)
3164                 func_desc = "include(file)";
3165             fprintf(stderr, "%s:%d: %s requires one argument.\n", parser.file.toLatin1().constData(),
3166                     parser.line_no, func_desc.toLatin1().constData());
3167             return false;
3168         }
3169         QString file = Option::normalizePath(args.first());
3170         uchar flags = IncludeFlagNone;
3171         if(!include_statement)
3172             flags |= IncludeFlagFeature;
3173         IncludeStatus stat = IncludeFailure;
3174         if(!parseInto.isEmpty()) {
3175             QHash<QString, QStringList> symbols;
3176             stat = doProjectInclude(file, flags|IncludeFlagNewProject, symbols);
3177             if(stat == IncludeSuccess) {
3178                 QHash<QString, QStringList> out_place;
3179                 for(QHash<QString, QStringList>::ConstIterator it = place.begin(); it != place.end(); ++it) {
3180                     const QString var = it.key();
3181                     if(var != parseInto && !var.startsWith(parseInto + "."))
3182                         out_place.insert(var, it.value());
3183                 }
3184                 for(QHash<QString, QStringList>::ConstIterator it = symbols.begin(); it != symbols.end(); ++it) {
3185                     const QString var = it.key();
3186                     if(!var.startsWith("."))
3187                         out_place.insert(parseInto + "." + it.key(), it.value());
3188                 }
3189                 place = out_place;
3190             }
3191         } else {
3192             stat = doProjectInclude(file, flags, place);
3193         }
3194         if(stat == IncludeFeatureAlreadyLoaded) {
3195             warn_msg(WarnParser, "%s:%d: Duplicate of loaded feature %s",
3196                      parser.file.toLatin1().constData(), parser.line_no, file.toLatin1().constData());
3197         } else if(stat == IncludeNoExist && !ignore_error) {
3198             warn_msg(WarnAll, "%s:%d: Unable to find file for inclusion %s",
3199                      parser.file.toLatin1().constData(), parser.line_no, file.toLatin1().constData());
3200             return false;
3201         } else if(stat >= IncludeFailure) {
3202             if(!ignore_error) {
3203                 printf("Project LOAD(): Feature %s cannot be found.\n", file.toLatin1().constData());
3204                 if (!ignore_error)
3205 #if defined(QT_BUILD_QMAKE_LIBRARY)
3206                     return false;
3207 #else
3208                     exit(3);
3209 #endif
3210             }
3211             return false;
3212         }
3213         return true; }
3214     case T_DEBUG: {
3215         if(args.count() != 2) {
3216             fprintf(stderr, "%s:%d: debug(level, message) requires one argument.\n", parser.file.toLatin1().constData(),
3217                     parser.line_no);
3218             return false;
3219         }
3220         QString msg = fixEnvVariables(args[1]);
3221         debug_msg(args[0].toInt(), "Project DEBUG: %s", msg.toLatin1().constData());
3222         return true; }
3223     case T_LOG:
3224     case T_ERROR:
3225     case T_MESSAGE:
3226     case T_WARNING: {
3227         if(args.count() != 1) {
3228             fprintf(stderr, "%s:%d: %s(message) requires one argument.\n", parser.file.toLatin1().constData(),
3229                     parser.line_no, func.toLatin1().constData());
3230             return false;
3231         }
3232         QString msg = fixEnvVariables(args.first());
3233         if (func_t == T_LOG) {
3234             fputs(msg.toLatin1().constData(), stderr);
3235         } else {
3236             fprintf(stderr, "Project %s: %s\n", func.toUpper().toLatin1().constData(), msg.toLatin1().constData());
3237             if (func == "error")
3238 #if defined(QT_BUILD_QMAKE_LIBRARY)
3239                 return false;
3240 #else
3241                 exit(2);
3242 #endif
3243         }
3244         return true; }
3245     case T_OPTION:
3246         if (args.count() != 1) {
3247             fprintf(stderr, "%s:%d: option() requires one argument.\n",
3248                     parser.file.toLatin1().constData(), parser.line_no);
3249             return false;
3250         }
3251         if (args.first() == "host_build") {
3252             if (!host_build && isActiveConfig("cross_compile")) {
3253                 host_build = true;
3254                 need_restart = true;
3255             }
3256         } else {
3257             fprintf(stderr, "%s:%d: unrecognized option() argument '%s'.\n",
3258                     parser.file.toLatin1().constData(), parser.line_no,
3259                     args.first().toLatin1().constData());
3260             return false;
3261         }
3262         return true;
3263     case T_CACHE: {
3264         if (args.count() > 3) {
3265             fprintf(stderr, "%s:%d: cache(var, [set|add|sub] [transient] [super], [srcvar]) requires one to three arguments.\n",
3266                     parser.file.toLatin1().constData(), parser.line_no);
3267             return false;
3268         }
3269         bool persist = true;
3270         bool super = false;
3271         enum { CacheSet, CacheAdd, CacheSub } mode = CacheSet;
3272         QString srcvar;
3273         if (args.count() >= 2) {
3274             foreach (const QString &opt, split_value_list(args.at(1))) {
3275                 if (opt == QLatin1String("transient")) {
3276                     persist = false;
3277                 } else if (opt == QLatin1String("super")) {
3278                     super = true;
3279                 } else if (opt == QLatin1String("set")) {
3280                     mode = CacheSet;
3281                 } else if (opt == QLatin1String("add")) {
3282                     mode = CacheAdd;
3283                 } else if (opt == QLatin1String("sub")) {
3284                     mode = CacheSub;
3285                 } else {
3286                     fprintf(stderr, "%s:%d: cache(): invalid flag %s.\n",
3287                             parser.file.toLatin1().constData(), parser.line_no,
3288                             opt.toLatin1().constData());
3289                     return false;
3290                 }
3291             }
3292             if (args.count() >= 3) {
3293                 srcvar = args.at(2);
3294             } else if (mode != CacheSet) {
3295                 fprintf(stderr, "%s:%d: cache(): modes other than 'set' require a source variable.\n",
3296                         parser.file.toLatin1().constData(), parser.line_no);
3297                 return false;
3298             }
3299         }
3300         QString varstr;
3301         QString dstvar = args.at(0);
3302         if (!dstvar.isEmpty()) {
3303             if (srcvar.isEmpty())
3304                 srcvar = dstvar;
3305             if (!place.contains(srcvar)) {
3306                 fprintf(stderr, "%s:%d: variable %s is not defined.\n",
3307                         parser.file.toLatin1().constData(), parser.line_no,
3308                         srcvar.toLatin1().constData());
3309                 return false;
3310             }
3311             // The current ("native") value can differ from the cached value, e.g., the current
3312             // CONFIG will typically have more values than the cached one. Therefore we deal with
3313             // them separately.
3314             const QStringList diffval = values(srcvar, place);
3315             const QStringList oldval = base_vars.value(dstvar);
3316             QStringList newval;
3317             if (mode == CacheSet) {
3318                 newval = diffval;
3319             } else {
3320                 newval = oldval;
3321                 if (mode == CacheAdd)
3322                     newval += diffval;
3323                 else
3324                     subAll(&newval, diffval);
3325             }
3326             // We assume that whatever got the cached value to be what it is now will do so
3327             // the next time as well, so it is OK that the early exit here will skip the
3328             // persisting as well.
3329             if (oldval == newval)
3330                 return true;
3331             base_vars[dstvar] = newval;
3332             do {
3333                 if (dstvar == "QMAKEPATH")
3334                     cached_qmakepath = newval;
3335                 else if (dstvar == "QMAKEFEATURES")
3336                     cached_qmakefeatures = newval;
3337                 else
3338                     break;
3339                 invalidateFeatureRoots();
3340             } while (false);
3341             if (!persist)
3342                 return true;
3343             varstr = dstvar;
3344             if (mode == CacheAdd)
3345                 varstr += QLatin1String(" +=");
3346             else if (mode == CacheSub)
3347                 varstr += QLatin1String(" -=");
3348             else
3349                 varstr += QLatin1String(" =");
3350             if (diffval.count() == 1) {
3351                 varstr += QLatin1Char(' ');
3352                 varstr += quoteValue(diffval.at(0));
3353             } else if (!diffval.isEmpty()) {
3354                 foreach (const QString &vval, diffval) {
3355                     varstr += QLatin1String(" \\\n    ");
3356                     varstr += quoteValue(vval);
3357                 }
3358             }
3359             varstr += QLatin1Char('\n');
3360         }
3361         QString fn;
3362         if (super) {
3363             if (superfile.isEmpty()) {
3364                 superfile = Option::output_dir + QLatin1String("/.qmake.super");
3365                 printf("Info: creating super cache file %s\n", superfile.toLatin1().constData());
3366                 vars["_QMAKE_SUPER_CACHE_"] << superfile;
3367             }
3368             fn = superfile;
3369         } else {
3370             if (cachefile.isEmpty()) {
3371                 cachefile = Option::output_dir + QLatin1String("/.qmake.cache");
3372                 printf("Info: creating cache file %s\n", cachefile.toLatin1().constData());
3373                 vars["_QMAKE_CACHE_"] << cachefile;
3374                 if (cached_build_root.isEmpty()) {
3375                     cached_build_root = Option::output_dir;
3376                     cached_source_root = values("_PRO_FILE_PWD_", place).first();
3377                     if (cached_source_root == cached_build_root)
3378                         cached_source_root.clear();
3379                     invalidateFeatureRoots();
3380                 }
3381             }
3382             fn = cachefile;
3383         }
3384         QFileInfo qfi(fn);
3385         if (!QDir::current().mkpath(qfi.path())) {
3386             fprintf(stderr, "%s:%d: ERROR creating cache directory %s\n",
3387                     parser.file.toLatin1().constData(), parser.line_no,
3388                     qfi.path().toLatin1().constData());
3389             return false;
3390         }
3391         QString errStr;
3392         if (!writeFile(fn, QIODevice::Append, varstr, &errStr)) {
3393             fprintf(stderr, "ERROR writing cache file %s: %s\n",
3394                     fn.toLatin1().constData(), errStr.toLatin1().constData());
3395 #if defined(QT_BUILD_QMAKE_LIBRARY)
3396             return false;
3397 #else
3398             exit(2);
3399 #endif
3400         }
3401         return true; }
3402     case T_MKPATH:
3403         if (args.count() != 1) {
3404             fprintf(stderr, "%s:%d: mkpath(name) requires one argument.\n",
3405                     parser.file.toLatin1().constData(), parser.line_no);
3406             return false;
3407         }
3408         if (!QDir::current().mkpath(args.at(0))) {
3409             fprintf(stderr, "%s:%d: ERROR creating directory %s\n",
3410                     parser.file.toLatin1().constData(), parser.line_no,
3411                     QDir::toNativeSeparators(args.at(0)).toLatin1().constData());
3412             return false;
3413         }
3414         return true;
3415     case T_WRITE_FILE: {
3416         if (args.count() > 3) {
3417             fprintf(stderr, "%s:%d: write_file(name, [content var, [append]]) requires one to three arguments.\n",
3418                     parser.file.toLatin1().constData(), parser.line_no);
3419             return false;
3420         }
3421         QIODevice::OpenMode mode = QIODevice::Truncate;
3422         QString contents;
3423         if (args.count() >= 2) {
3424             QStringList vals = values(args.at(1), place);
3425             if (!vals.isEmpty())
3426                 contents = vals.join(QLatin1String("\n")) + QLatin1Char('\n');
3427             if (args.count() >= 3)
3428                 if (!args.at(2).compare(QLatin1String("append"), Qt::CaseInsensitive))
3429                     mode = QIODevice::Append;
3430         }
3431         QFileInfo qfi(args.at(0));
3432         if (!QDir::current().mkpath(qfi.path())) {
3433             fprintf(stderr, "%s:%d: ERROR creating directory %s\n",
3434                     parser.file.toLatin1().constData(), parser.line_no,
3435                     qfi.path().toLatin1().constData());
3436             return false;
3437         }
3438         QString errStr;
3439         if (!writeFile(args.at(0), mode, contents, &errStr)) {
3440             fprintf(stderr, "%s:%d ERROR writing %s: %s\n",
3441                     parser.file.toLatin1().constData(), parser.line_no,
3442                     args.at(0).toLatin1().constData(), errStr.toLatin1().constData());
3443             return false;
3444         }
3445         return true; }
3446     case T_TOUCH: {
3447         if (args.count() != 2) {
3448             fprintf(stderr, "%s:%d: touch(file, reffile) requires two arguments.\n",
3449                     parser.file.toLatin1().constData(), parser.line_no);
3450             return false;
3451         }
3452 #ifdef Q_OS_UNIX
3453         struct stat st;
3454         if (stat(args.at(1).toLocal8Bit().constData(), &st)) {
3455             fprintf(stderr, "%s:%d: ERROR: cannot stat() reference file %s: %s.\n",
3456                     parser.file.toLatin1().constData(), parser.line_no,
3457                     args.at(1).toLatin1().constData(), strerror(errno));
3458             return false;
3459         }
3460         struct utimbuf utb;
3461         utb.actime = time(0);
3462         utb.modtime = st.st_mtime;
3463         if (utime(args.at(0).toLocal8Bit().constData(), &utb)) {
3464             fprintf(stderr, "%s:%d: ERROR: cannot touch %s: %s.\n",
3465                     parser.file.toLatin1().constData(), parser.line_no,
3466                     args.at(0).toLatin1().constData(), strerror(errno));
3467             return false;
3468         }
3469 #else
3470         HANDLE rHand = CreateFile((wchar_t*)args.at(1).utf16(),
3471                                   GENERIC_READ, FILE_SHARE_READ,
3472                                   NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
3473         if (rHand == INVALID_HANDLE_VALUE) {
3474             fprintf(stderr, "%s:%d: ERROR: cannot open() reference file %s: %s.\n",
3475                     parser.file.toLatin1().constData(), parser.line_no,
3476                     args.at(1).toLatin1().constData(),
3477                     windowsErrorCode().toLatin1().constData());
3478             return false;
3479         }
3480         FILETIME ft;
3481         GetFileTime(rHand, 0, 0, &ft);
3482         CloseHandle(rHand);
3483         HANDLE wHand = CreateFile((wchar_t*)args.at(0).utf16(),
3484                                   GENERIC_WRITE, FILE_SHARE_READ,
3485                                   NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
3486         if (wHand == INVALID_HANDLE_VALUE) {
3487             fprintf(stderr, "%s:%d: ERROR: cannot open %s: %s.\n",
3488                     parser.file.toLatin1().constData(), parser.line_no,
3489                     args.at(0).toLatin1().constData(),
3490                     windowsErrorCode().toLatin1().constData());
3491             return false;
3492         }
3493         SetFileTime(wHand, 0, 0, &ft);
3494         CloseHandle(wHand);
3495 #endif
3496         break; }
3497     default:
3498         fprintf(stderr, "%s:%d: Unknown test function: %s\n", parser.file.toLatin1().constData(), parser.line_no,
3499                 func.toLatin1().constData());
3500     }
3501     return false;
3502 }
3503
3504 bool
3505 QMakeProject::doProjectCheckReqs(const QStringList &deps, QHash<QString, QStringList> &place)
3506 {
3507     bool ret = false;
3508     for(QStringList::ConstIterator it = deps.begin(); it != deps.end(); ++it) {
3509         bool test = doProjectTest((*it), place);
3510         if(!test) {
3511             debug_msg(1, "Project Parser: %s:%d Failed test: REQUIRES = %s",
3512                       parser.file.toLatin1().constData(), parser.line_no,
3513                       (*it).toLatin1().constData());
3514             place["QMAKE_FAILED_REQUIREMENTS"].append((*it));
3515             ret = false;
3516         }
3517     }
3518     return ret;
3519 }
3520
3521 bool
3522 QMakeProject::test(const QString &v)
3523 {
3524     QHash<QString, QStringList> tmp = vars;
3525     return doProjectTest(v, tmp);
3526 }
3527
3528 bool
3529 QMakeProject::test(const QString &func, const QList<QStringList> &args)
3530 {
3531     QHash<QString, QStringList> tmp = vars;
3532     return doProjectTest(func, args, tmp);
3533 }
3534
3535 QStringList
3536 QMakeProject::expand(const QString &str)
3537 {
3538     bool ok;
3539     QHash<QString, QStringList> tmp = vars;
3540     const QStringList ret = doVariableReplaceExpand(str, tmp, &ok);
3541     if(ok)
3542         return ret;
3543     return QStringList();
3544 }
3545
3546 QString
3547 QMakeProject::expand(const QString &str, const QString &file, int line)
3548 {
3549     bool ok;
3550     parser_info pi = parser;
3551     parser.file = file;
3552     parser.line_no = line;
3553     parser.from_file = false;
3554     QHash<QString, QStringList> tmp = vars;
3555     const QStringList ret = doVariableReplaceExpand(str, tmp, &ok);
3556     parser = pi;
3557     return ok ? ret.join(QString(Option::field_sep)) : QString();
3558 }
3559
3560 QStringList
3561 QMakeProject::expand(const QString &func, const QList<QStringList> &args)
3562 {
3563     QHash<QString, QStringList> tmp = vars;
3564     return doProjectExpand(func, args, tmp);
3565 }
3566
3567 bool
3568 QMakeProject::doVariableReplace(QString &str, QHash<QString, QStringList> &place)
3569 {
3570     bool ret;
3571     str = doVariableReplaceExpand(str, place, &ret).join(QString(Option::field_sep));
3572     return ret;
3573 }
3574
3575 QStringList
3576 QMakeProject::doVariableReplaceExpand(const QString &str, QHash<QString, QStringList> &place, bool *ok)
3577 {
3578     QStringList ret;
3579     if(ok)
3580         *ok = true;
3581     if(str.isEmpty())
3582         return ret;
3583
3584     const ushort LSQUARE = '[';
3585     const ushort RSQUARE = ']';
3586     const ushort LCURLY = '{';
3587     const ushort RCURLY = '}';
3588     const ushort LPAREN = '(';
3589     const ushort RPAREN = ')';
3590     const ushort DOLLAR = '$';
3591     const ushort SLASH = '\\';
3592     const ushort UNDERSCORE = '_';
3593     const ushort DOT = '.';
3594     const ushort SPACE = ' ';
3595     const ushort TAB = '\t';
3596     const ushort SINGLEQUOTE = '\'';
3597     const ushort DOUBLEQUOTE = '"';
3598
3599     ushort unicode, quote = 0;
3600     const QChar *str_data = str.data();
3601     const int str_len = str.length();
3602
3603     ushort term;
3604     QString var, args;
3605
3606     int replaced = 0;
3607     QString current;
3608     for(int i = 0; i < str_len; ++i) {
3609         unicode = str_data[i].unicode();
3610         const int start_var = i;
3611         if(unicode == DOLLAR && str_len > i+2) {
3612             unicode = str_data[++i].unicode();
3613             if(unicode == DOLLAR) {
3614                 term = 0;
3615                 var.clear();
3616                 args.clear();
3617                 enum { VAR, ENVIRON, FUNCTION, PROPERTY } var_type = VAR;
3618                 unicode = str_data[++i].unicode();
3619                 if(unicode == LSQUARE) {
3620                     unicode = str_data[++i].unicode();
3621                     term = RSQUARE;
3622                     var_type = PROPERTY;
3623                 } else if(unicode == LCURLY) {
3624                     unicode = str_data[++i].unicode();
3625                     var_type = VAR;
3626                     term = RCURLY;
3627                 } else if(unicode == LPAREN) {
3628                     unicode = str_data[++i].unicode();
3629                     var_type = ENVIRON;
3630                     term = RPAREN;
3631                 }
3632                 while(1) {
3633                     if(!(unicode & (0xFF<<8)) &&
3634                        unicode != DOT && unicode != UNDERSCORE &&
3635                        //unicode != SINGLEQUOTE && unicode != DOUBLEQUOTE &&
3636                        (unicode < 'a' || unicode > 'z') && (unicode < 'A' || unicode > 'Z') &&
3637                        (unicode < '0' || unicode > '9') && (!term || unicode != '/'))
3638                         break;
3639                     var.append(QChar(unicode));
3640                     if(++i == str_len)
3641                         break;
3642                     unicode = str_data[i].unicode();
3643                     // at this point, i points to either the 'term' or 'next' character (which is in unicode)
3644                 }
3645                 if(var_type == VAR && unicode == LPAREN) {
3646                     var_type = FUNCTION;
3647                     int depth = 0;
3648                     while(1) {
3649                         if(++i == str_len)
3650                             break;
3651                         unicode = str_data[i].unicode();
3652                         if(unicode == LPAREN) {
3653                             depth++;
3654                         } else if(unicode == RPAREN) {
3655                             if(!depth)
3656                                 break;
3657                             --depth;
3658                         }
3659                         args.append(QChar(unicode));
3660                     }
3661                     if(++i < str_len)
3662                         unicode = str_data[i].unicode();
3663                     else
3664                         unicode = 0;
3665                     // at this point i is pointing to the 'next' character (which is in unicode)
3666                     // this might actually be a term character since you can do $${func()}
3667                 }
3668                 if(term) {
3669                     if(unicode != term) {
3670                         qmake_error_msg("Missing " + QString(term) + " terminator [found " + (unicode?QString(unicode):QString("end-of-line")) + "]");
3671                         if(ok)
3672                             *ok = false;
3673                         return QStringList();
3674                     }
3675                 } else {
3676                     // move the 'cursor' back to the last char of the thing we were looking at
3677                     --i;
3678                 }
3679                 // since i never points to the 'next' character, there is no reason for this to be set
3680                 unicode = 0;
3681
3682                 QStringList replacement;
3683                 if(var_type == ENVIRON) {
3684                     replacement = split_value_list(QString::fromLocal8Bit(qgetenv(var.toLatin1().constData())));
3685                 } else if(var_type == PROPERTY) {
3686                     if (var == "QMAKE_MKSPECS")
3687                         replacement = split_value_list(qmake_mkspec_paths().join(Option::dirlist_sep));
3688                     else if (prop)
3689                         replacement = split_value_list(prop->value(var));
3690                 } else if(var_type == FUNCTION) {
3691                     replacement = doProjectExpand(var, args, place);
3692                 } else if(var_type == VAR) {
3693                     replacement = magicValues(var, place);
3694                 }
3695                 if(!(replaced++) && start_var)
3696                     current = str.left(start_var);
3697                 if(!replacement.isEmpty()) {
3698                     if(quote) {
3699                         current += replacement.join(QString(Option::field_sep));
3700                     } else {
3701                         current += replacement.takeFirst();
3702                         if(!replacement.isEmpty()) {
3703                             if(!current.isEmpty())
3704                                 ret.append(current);
3705                             current = replacement.takeLast();
3706                             if(!replacement.isEmpty())
3707                                 ret += replacement;
3708                         }
3709                     }
3710                 }
3711                 debug_msg(2, "Project Parser [var replace]: %s -> %s",
3712                           str.toLatin1().constData(), var.toLatin1().constData(),
3713                           replacement.join("::").toLatin1().constData());
3714             } else {
3715                 if(replaced)
3716                     current.append("$");
3717             }
3718         }
3719         if(quote && unicode == quote) {
3720             unicode = 0;
3721             quote = 0;
3722         } else if(unicode == SLASH) {
3723             bool escape = false;
3724             const char *symbols = "[]{}()$\\'\"";
3725             for(const char *s = symbols; *s; ++s) {
3726                 if(str_data[i+1].unicode() == (ushort)*s) {
3727                     i++;
3728                     escape = true;
3729                     if(!(replaced++))
3730                         current = str.left(start_var);
3731                     current.append(str.at(i));
3732                     break;
3733                 }
3734             }
3735             if(!escape && !backslashWarned) {
3736                 backslashWarned = true;
3737                 warn_msg(WarnDeprecated, "%s:%d: Unescaped backslashes are deprecated.",
3738                          parser.file.toLatin1().constData(), parser.line_no);
3739             }
3740             if(escape || !replaced)
3741                 unicode =0;
3742         } else if(!quote && (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE)) {
3743             quote = unicode;
3744             unicode = 0;
3745             if(!(replaced++) && i)
3746                 current = str.left(i);
3747         } else if(!quote && (unicode == SPACE || unicode == TAB)) {
3748             unicode = 0;
3749             if(!current.isEmpty()) {
3750                 ret.append(current);
3751                 current.clear();
3752             }
3753         }
3754         if(replaced && unicode)
3755             current.append(QChar(unicode));
3756     }
3757     if(!replaced)
3758         ret = QStringList(str);
3759     else if(!current.isEmpty())
3760         ret.append(current);
3761     //qDebug() << "REPLACE" << str << ret;
3762     if (quote)
3763         warn_msg(WarnDeprecated, "%s:%d: Unmatched quotes are deprecated.",
3764                  parser.file.toLatin1().constData(), parser.line_no);
3765     return ret;
3766 }
3767
3768 QStringList QMakeProject::magicValues(const QString &_var, const QHash<QString, QStringList> &place) const
3769 {
3770     QString var = varMap(_var);
3771     if (var == QLatin1String("_LINE_")) { //parser line number
3772         return QStringList(QString::number(parser.line_no));
3773     } else if(var == QLatin1String("_FILE_")) { //parser file
3774         return QStringList(parser.file);
3775     }
3776     return place[var];
3777 }
3778
3779 QStringList &QMakeProject::values(const QString &_var, QHash<QString, QStringList> &place)
3780 {
3781     QString var = varMap(_var);
3782     return place[var];
3783 }
3784
3785 bool QMakeProject::isEmpty(const QString &v) const
3786 {
3787     QHash<QString, QStringList>::ConstIterator it = vars.constFind(v);
3788     return it == vars.constEnd() || it->isEmpty();
3789 }
3790
3791 void
3792 QMakeProject::dump() const
3793 {
3794     QStringList out;
3795     for (QHash<QString, QStringList>::ConstIterator it = vars.begin(); it != vars.end(); ++it) {
3796         if (!it.key().startsWith('.')) {
3797             QString str = it.key() + " =";
3798             foreach (const QString &v, it.value())
3799                 str += ' ' + quoteValue(v);
3800             out << str;
3801         }
3802     }
3803     out.sort();
3804     foreach (const QString &v, out)
3805         puts(qPrintable(v));
3806 }
3807
3808 QT_END_NAMESPACE