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