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