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