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