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