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