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