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