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