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