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