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