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