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