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