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