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