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