Merge remote-tracking branch 'origin/api_changes'
[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         bool correct = function_blocks.pop() == defined;
1725         Q_ASSERT(correct); Q_UNUSED(correct);
1726         return ret;
1727     }
1728
1729     QStringList args; //why don't the builtin functions just use args_list? --Sam
1730     for(int i = 0; i < args_list.size(); ++i)
1731         args += args_list[i].join(QString(Option::field_sep));
1732
1733     ExpandFunc func_t = qmake_expandFunctions().value(func);
1734     if (!func_t && (func_t = qmake_expandFunctions().value(func.toLower())))
1735         warn_msg(WarnDeprecated, "%s:%d: Using uppercased builtin functions is deprecated.",
1736                  parser.file.toLatin1().constData(), parser.line_no);
1737     debug_msg(1, "Running project expand: %s(%s) [%d]",
1738               func.toLatin1().constData(), args.join("::").toLatin1().constData(), func_t);
1739
1740     QStringList ret;
1741     switch(func_t) {
1742     case E_MEMBER: {
1743         if(args.count() < 1 || args.count() > 3) {
1744             fprintf(stderr, "%s:%d: member(var, start, end) requires three arguments.\n",
1745                     parser.file.toLatin1().constData(), parser.line_no);
1746         } else {
1747             bool ok = true;
1748             const QStringList &var = values(args.first(), place);
1749             int start = 0, end = 0;
1750             if(args.count() >= 2) {
1751                 QString start_str = args[1];
1752                 start = start_str.toInt(&ok);
1753                 if(!ok) {
1754                     if(args.count() == 2) {
1755                         int dotdot = start_str.indexOf("..");
1756                         if(dotdot != -1) {
1757                             start = start_str.left(dotdot).toInt(&ok);
1758                             if(ok)
1759                                 end = start_str.mid(dotdot+2).toInt(&ok);
1760                         }
1761                     }
1762                     if(!ok)
1763                         fprintf(stderr, "%s:%d: member() argument 2 (start) '%s' invalid.\n",
1764                                 parser.file.toLatin1().constData(), parser.line_no,
1765                                 start_str.toLatin1().constData());
1766                 } else {
1767                     end = start;
1768                     if(args.count() == 3)
1769                         end = args[2].toInt(&ok);
1770                     if(!ok)
1771                         fprintf(stderr, "%s:%d: member() argument 3 (end) '%s' invalid.\n",
1772                                 parser.file.toLatin1().constData(), parser.line_no,
1773                                 args[2].toLatin1().constData());
1774                 }
1775             }
1776             if(ok) {
1777                 if(start < 0)
1778                     start += var.count();
1779                 if(end < 0)
1780                     end += var.count();
1781                 if(start < 0 || start >= var.count() || end < 0 || end >= var.count()) {
1782                     //nothing
1783                 } else if(start < end) {
1784                     for(int i = start; i <= end && (int)var.count() >= i; i++)
1785                         ret += var[i];
1786                 } else {
1787                     for(int i = start; i >= end && (int)var.count() >= i && i >= 0; i--)
1788                         ret += var[i];
1789                 }
1790             }
1791         }
1792         break; }
1793     case E_FIRST:
1794     case E_LAST: {
1795         if(args.count() != 1) {
1796             fprintf(stderr, "%s:%d: %s(var) requires one argument.\n",
1797                     parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
1798         } else {
1799             const QStringList &var = values(args.first(), place);
1800             if(!var.isEmpty()) {
1801                 if(func_t == E_FIRST)
1802                     ret = QStringList(var[0]);
1803                 else
1804                     ret = QStringList(var[var.size()-1]);
1805             }
1806         }
1807         break; }
1808     case E_CAT: {
1809         if(args.count() < 1 || args.count() > 2) {
1810             fprintf(stderr, "%s:%d: cat(file) requires one argument.\n",
1811                     parser.file.toLatin1().constData(), parser.line_no);
1812         } else {
1813             QString file = Option::normalizePath(args[0]);
1814
1815             bool singleLine = true;
1816             if(args.count() > 1)
1817                 singleLine = (args[1].toLower() == "true");
1818
1819             QFile qfile(file);
1820             if(qfile.open(QIODevice::ReadOnly)) {
1821                 QTextStream stream(&qfile);
1822                 while(!stream.atEnd()) {
1823                     ret += split_value_list(stream.readLine().trimmed());
1824                     if(!singleLine)
1825                         ret += "\n";
1826                 }
1827                 qfile.close();
1828             }
1829         }
1830         break; }
1831     case E_FROMFILE: {
1832         if(args.count() != 2) {
1833             fprintf(stderr, "%s:%d: fromfile(file, variable) requires two arguments.\n",
1834                     parser.file.toLatin1().constData(), parser.line_no);
1835         } else {
1836             QString seek_var = args[1], file = Option::normalizePath(args[0]);
1837
1838             QHash<QString, QStringList> tmp;
1839             if(doProjectInclude(file, IncludeFlagNewParser, tmp) == IncludeSuccess) {
1840                 if(tmp.contains("QMAKE_INTERNAL_INCLUDED_FILES")) {
1841                     QStringList &out = place["QMAKE_INTERNAL_INCLUDED_FILES"];
1842                     const QStringList &in = tmp["QMAKE_INTERNAL_INCLUDED_FILES"];
1843                     for(int i = 0; i < in.size(); ++i) {
1844                         if(out.indexOf(in[i]) == -1)
1845                             out += in[i];
1846                     }
1847                 }
1848                 ret = tmp[seek_var];
1849             }
1850         }
1851         break; }
1852     case E_EVAL: {
1853         if(args.count() < 1 || args.count() > 2) {
1854             fprintf(stderr, "%s:%d: eval(variable) requires one argument.\n",
1855                     parser.file.toLatin1().constData(), parser.line_no);
1856
1857         } else {
1858             const QHash<QString, QStringList> *source = &place;
1859             if(args.count() == 2) {
1860                 if(args.at(1) == "Global") {
1861                     source = &vars;
1862                 } else if(args.at(1) == "Local") {
1863                     source = &place;
1864                 } else {
1865                     fprintf(stderr, "%s:%d: unexpected source to eval.\n", parser.file.toLatin1().constData(),
1866                             parser.line_no);
1867                 }
1868             }
1869             ret += source->value(args.at(0));
1870         }
1871         break; }
1872     case E_LIST: {
1873         static int x = 0;
1874         QString tmp;
1875         tmp.sprintf(".QMAKE_INTERNAL_TMP_VAR_%d", x++);
1876         ret = QStringList(tmp);
1877         QStringList &lst = (*((QHash<QString, QStringList>*)&place))[tmp];
1878         lst.clear();
1879         for(QStringList::ConstIterator arg_it = args.begin();
1880             arg_it != args.end(); ++arg_it)
1881             lst += split_value_list((*arg_it));
1882         break; }
1883     case E_SPRINTF: {
1884         if(args.count() < 1) {
1885             fprintf(stderr, "%s:%d: sprintf(format, ...) requires one argument.\n",
1886                     parser.file.toLatin1().constData(), parser.line_no);
1887         } else {
1888             QString tmp = args.at(0);
1889             for(int i = 1; i < args.count(); ++i)
1890                 tmp = tmp.arg(args.at(i));
1891             ret = split_value_list(tmp);
1892         }
1893         break; }
1894     case E_JOIN: {
1895         if(args.count() < 1 || args.count() > 4) {
1896             fprintf(stderr, "%s:%d: join(var, glue, before, after) requires four"
1897                     "arguments.\n", parser.file.toLatin1().constData(), parser.line_no);
1898         } else {
1899             QString glue, before, after;
1900             if(args.count() >= 2)
1901                 glue = args[1];
1902             if(args.count() >= 3)
1903                 before = args[2];
1904             if(args.count() == 4)
1905                 after = args[3];
1906             const QStringList &var = values(args.first(), place);
1907             if(!var.isEmpty())
1908                 ret = split_value_list(before + var.join(glue) + after);
1909         }
1910         break; }
1911     case E_SPLIT: {
1912         if(args.count() < 1 || args.count() > 2) {
1913             fprintf(stderr, "%s:%d split(var, sep) requires one or two arguments\n",
1914                     parser.file.toLatin1().constData(), parser.line_no);
1915         } else {
1916             QString sep = QString(Option::field_sep);
1917             if(args.count() >= 2)
1918                 sep = args[1];
1919             QStringList var = values(args.first(), place);
1920             for(QStringList::ConstIterator vit = var.begin(); vit != var.end(); ++vit) {
1921                 QStringList lst = (*vit).split(sep);
1922                 for(QStringList::ConstIterator spltit = lst.begin(); spltit != lst.end(); ++spltit)
1923                     ret += (*spltit);
1924             }
1925         }
1926         break; }
1927     case E_BASENAME:
1928     case E_DIRNAME:
1929     case E_SECTION: {
1930         bool regexp = false;
1931         QString sep, var;
1932         int beg=0, end=-1;
1933         if(func_t == E_SECTION) {
1934             if(args.count() != 3 && args.count() != 4) {
1935                 fprintf(stderr, "%s:%d section(var, sep, begin, end) requires three argument\n",
1936                         parser.file.toLatin1().constData(), parser.line_no);
1937             } else {
1938                 var = args[0];
1939                 sep = args[1];
1940                 beg = args[2].toInt();
1941                 if(args.count() == 4)
1942                     end = args[3].toInt();
1943             }
1944         } else {
1945             if(args.count() != 1) {
1946                 fprintf(stderr, "%s:%d %s(var) requires one argument.\n",
1947                         parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
1948             } else {
1949                 var = args[0];
1950                 regexp = true;
1951                 sep = "[" + QRegExp::escape(Option::dir_sep) + "/]";
1952                 if(func_t == E_DIRNAME)
1953                     end = -2;
1954                 else
1955                     beg = -1;
1956             }
1957         }
1958         if(!var.isNull()) {
1959             const QStringList &l = values(var, place);
1960             for(QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
1961                 QString separator = sep;
1962                 if(regexp)
1963                     ret += (*it).section(QRegExp(separator), beg, end);
1964                 else
1965                     ret += (*it).section(separator, beg, end);
1966             }
1967         }
1968         break; }
1969     case E_FIND: {
1970         if(args.count() != 2) {
1971             fprintf(stderr, "%s:%d find(var, str) requires two arguments\n",
1972                     parser.file.toLatin1().constData(), parser.line_no);
1973         } else {
1974             QRegExp regx(args[1]);
1975             const QStringList &var = values(args.first(), place);
1976             for(QStringList::ConstIterator vit = var.begin();
1977                 vit != var.end(); ++vit) {
1978                 if(regx.indexIn(*vit) != -1)
1979                     ret += (*vit);
1980             }
1981         }
1982         break;  }
1983     case E_SYSTEM: {
1984         if(args.count() < 1 || args.count() > 2) {
1985             fprintf(stderr, "%s:%d system(execut) requires one argument.\n",
1986                     parser.file.toLatin1().constData(), parser.line_no);
1987         } else {
1988             char buff[256];
1989             bool singleLine = true;
1990             if(args.count() > 1)
1991                 singleLine = (args[1].toLower() == "true");
1992             QString output;
1993             FILE *proc = QT_POPEN(args[0].toLatin1().constData(), "r");
1994             while(proc && !feof(proc)) {
1995                 int read_in = int(fread(buff, 1, 255, proc));
1996                 if(!read_in)
1997                     break;
1998                 for(int i = 0; i < read_in; i++) {
1999                     if((singleLine && buff[i] == '\n') || buff[i] == '\t')
2000                         buff[i] = ' ';
2001                 }
2002                 buff[read_in] = '\0';
2003                 output += buff;
2004             }
2005             ret += split_value_list(output);
2006             if(proc)
2007                 QT_PCLOSE(proc);
2008         }
2009         break; }
2010     case E_UNIQUE: {
2011         if(args.count() != 1) {
2012             fprintf(stderr, "%s:%d unique(var) requires one argument.\n",
2013                     parser.file.toLatin1().constData(), parser.line_no);
2014         } else {
2015             const QStringList &var = values(args.first(), place);
2016             for(int i = 0; i < var.count(); i++) {
2017                 if(!ret.contains(var[i]))
2018                     ret.append(var[i]);
2019             }
2020         }
2021         break; }
2022     case E_QUOTE:
2023         ret = args;
2024         break;
2025     case E_ESCAPE_EXPAND: {
2026         for(int i = 0; i < args.size(); ++i) {
2027             QChar *i_data = args[i].data();
2028             int i_len = args[i].length();
2029             for(int x = 0; x < i_len; ++x) {
2030                 if(*(i_data+x) == '\\' && x < i_len-1) {
2031                     if(*(i_data+x+1) == '\\') {
2032                         ++x;
2033                     } else {
2034                         struct {
2035                             char in, out;
2036                         } mapped_quotes[] = {
2037                             { 'n', '\n' },
2038                             { 't', '\t' },
2039                             { 'r', '\r' },
2040                             { 0, 0 }
2041                         };
2042                         for(int i = 0; mapped_quotes[i].in; ++i) {
2043                             if(*(i_data+x+1) == mapped_quotes[i].in) {
2044                                 *(i_data+x) = mapped_quotes[i].out;
2045                                 if(x < i_len-2)
2046                                     memmove(i_data+x+1, i_data+x+2, (i_len-x-2)*sizeof(QChar));
2047                                 --i_len;
2048                                 break;
2049                             }
2050                         }
2051                     }
2052                 }
2053             }
2054             ret.append(QString(i_data, i_len));
2055         }
2056         break; }
2057     case E_RE_ESCAPE: {
2058         for(int i = 0; i < args.size(); ++i)
2059             ret += QRegExp::escape(args[i]);
2060         break; }
2061     case E_UPPER:
2062     case E_LOWER: {
2063         for(int i = 0; i < args.size(); ++i) {
2064             if(func_t == E_UPPER)
2065                 ret += args[i].toUpper();
2066             else
2067                 ret += args[i].toLower();
2068         }
2069         break; }
2070     case E_FILES: {
2071         if(args.count() != 1 && args.count() != 2) {
2072             fprintf(stderr, "%s:%d files(pattern) requires one argument.\n",
2073                     parser.file.toLatin1().constData(), parser.line_no);
2074         } else {
2075             bool recursive = false;
2076             if(args.count() == 2)
2077                 recursive = (args[1].toLower() == "true" || args[1].toInt());
2078             QStringList dirs;
2079             QString r = Option::normalizePath(args[0]);
2080             int slash = r.lastIndexOf(QLatin1Char('/'));
2081             if(slash != -1) {
2082                 dirs.append(r.left(slash));
2083                 r = r.mid(slash+1);
2084             } else {
2085                 dirs.append("");
2086             }
2087
2088             QRegExp regex(r, Qt::CaseSensitive, QRegExp::Wildcard);
2089             for(int d = 0; d < dirs.count(); d++) {
2090                 QString dir = dirs[d];
2091                 if (!dir.isEmpty() && !dir.endsWith(QLatin1Char('/')))
2092                     dir += "/";
2093
2094                 QDir qdir(dir);
2095                 for(int i = 0; i < (int)qdir.count(); ++i) {
2096                     if(qdir[i] == "." || qdir[i] == "..")
2097                         continue;
2098                     QString fname = dir + qdir[i];
2099                     if(QFileInfo(fname).isDir()) {
2100                         if(recursive)
2101                             dirs.append(fname);
2102                     }
2103                     if(regex.exactMatch(qdir[i]))
2104                         ret += fname;
2105                 }
2106             }
2107         }
2108         break; }
2109     case E_PROMPT: {
2110         if(args.count() != 1) {
2111             fprintf(stderr, "%s:%d prompt(question) requires one argument.\n",
2112                     parser.file.toLatin1().constData(), parser.line_no);
2113         } else if(pfile == "-") {
2114             fprintf(stderr, "%s:%d prompt(question) cannot be used when '-o -' is used.\n",
2115                     parser.file.toLatin1().constData(), parser.line_no);
2116         } else {
2117             QString msg = fixEnvVariables(args.first());
2118             if(!msg.endsWith("?"))
2119                 msg += "?";
2120             fprintf(stderr, "Project %s: %s ", func.toUpper().toLatin1().constData(),
2121                     msg.toLatin1().constData());
2122
2123             QFile qfile;
2124             if(qfile.open(stdin, QIODevice::ReadOnly)) {
2125                 QTextStream t(&qfile);
2126                 ret = split_value_list(t.readLine());
2127             }
2128         }
2129         break; }
2130     case E_REPLACE: {
2131         if(args.count() != 3 ) {
2132             fprintf(stderr, "%s:%d replace(var, before, after) requires three arguments\n",
2133                     parser.file.toLatin1().constData(), parser.line_no);
2134         } else {
2135             const QRegExp before( args[1] );
2136             const QString after( args[2] );
2137             QStringList var = values(args.first(), place);
2138             for(QStringList::Iterator it = var.begin(); it != var.end(); ++it)
2139                 ret += it->replace(before, after);
2140         }
2141         break; }
2142     case E_SIZE: {
2143         if(args.count() != 1) {
2144             fprintf(stderr, "%s:%d: size(var) requires one argument.\n",
2145                     parser.file.toLatin1().constData(), parser.line_no);
2146         } else {
2147             int size = values(args[0], place).size();
2148             ret += QString::number(size);
2149         }
2150         break; }
2151     case E_SORT_DEPENDS:
2152     case E_RESOLVE_DEPENDS: {
2153         if(args.count() < 1 || args.count() > 2) {
2154             fprintf(stderr, "%s:%d: %s(var, prefix) requires one or two arguments.\n",
2155                     parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
2156         } else {
2157             QHash<QString, QSet<QString> > dependencies;
2158             QHash<QString, QStringList> dependees;
2159             QStringList rootSet;
2160
2161             QStringList orgList = values(args[0], place);
2162             populateDeps(orgList, (args.count() != 2 ? QString() : args[1]),
2163                          dependencies, dependees, rootSet, place);
2164
2165             for (int i = 0; i < rootSet.size(); ++i) {
2166                 const QString &item = rootSet.at(i);
2167                 if ((func_t == E_RESOLVE_DEPENDS) || orgList.contains(item))
2168                     ret.prepend(item);
2169                 foreach (const QString &dep, dependees[item]) {
2170                     QSet<QString> &dset = dependencies[dep];
2171                     dset.remove(rootSet.at(i)); // *Don't* use 'item' - rootSet may have changed!
2172                     if (dset.isEmpty())
2173                         rootSet << dep;
2174                 }
2175             }
2176         }
2177         break; }
2178     default: {
2179         fprintf(stderr, "%s:%d: Unknown replace function: %s\n",
2180                 parser.file.toLatin1().constData(), parser.line_no,
2181                 func.toLatin1().constData());
2182         break; }
2183     }
2184     return ret;
2185 }
2186
2187 bool
2188 QMakeProject::doProjectTest(QString func, QStringList args, QHash<QString, QStringList> &place)
2189 {
2190     QList<QStringList> args_list;
2191     for(int i = 0; i < args.size(); ++i) {
2192         QStringList arg = split_value_list(args[i]), tmp;
2193         for(int i = 0; i < arg.size(); ++i)
2194             tmp += doVariableReplaceExpand(arg[i], place);
2195         args_list += tmp;
2196     }
2197     return doProjectTest(func, args_list, place);
2198 }
2199
2200 bool
2201 QMakeProject::doProjectTest(QString func, QList<QStringList> args_list, QHash<QString, QStringList> &place)
2202 {
2203     func = func.trimmed();
2204
2205     if(testFunctions.contains(func)) {
2206         FunctionBlock *defined = testFunctions[func];
2207         QStringList ret;
2208         function_blocks.push(defined);
2209         defined->exec(args_list, this, place, ret);
2210         bool correct = function_blocks.pop() == defined;
2211         Q_ASSERT(correct); Q_UNUSED(correct);
2212
2213         if(ret.isEmpty()) {
2214             return true;
2215         } else {
2216             if(ret.first() == "true") {
2217                 return true;
2218             } else if(ret.first() == "false") {
2219                 return false;
2220             } else {
2221                 bool ok;
2222                 int val = ret.first().toInt(&ok);
2223                 if(ok)
2224                     return val;
2225                 fprintf(stderr, "%s:%d Unexpected return value from test %s [%s].\n",
2226                         parser.file.toLatin1().constData(),
2227                         parser.line_no, func.toLatin1().constData(),
2228                         ret.join("::").toLatin1().constData());
2229             }
2230             return false;
2231         }
2232         return false;
2233     }
2234
2235     QStringList args; //why don't the builtin functions just use args_list? --Sam
2236     for(int i = 0; i < args_list.size(); ++i)
2237         args += args_list[i].join(QString(Option::field_sep));
2238
2239     TestFunc func_t = qmake_testFunctions().value(func);
2240     debug_msg(1, "Running project test: %s(%s) [%d]",
2241               func.toLatin1().constData(), args.join("::").toLatin1().constData(), func_t);
2242
2243     switch(func_t) {
2244     case T_REQUIRES:
2245         return doProjectCheckReqs(args, place);
2246     case T_LESSTHAN:
2247     case T_GREATERTHAN: {
2248         if(args.count() != 2) {
2249             fprintf(stderr, "%s:%d: %s(variable, value) requires two arguments.\n", parser.file.toLatin1().constData(),
2250                     parser.line_no, func.toLatin1().constData());
2251             return false;
2252         }
2253         QString rhs(args[1]), lhs(values(args[0], place).join(QString(Option::field_sep)));
2254         bool ok;
2255         int rhs_int = rhs.toInt(&ok);
2256         if(ok) { // do integer compare
2257             int lhs_int = lhs.toInt(&ok);
2258             if(ok) {
2259                 if(func_t == T_GREATERTHAN)
2260                     return lhs_int > rhs_int;
2261                 return lhs_int < rhs_int;
2262             }
2263         }
2264         if(func_t == T_GREATERTHAN)
2265             return lhs > rhs;
2266         return lhs < rhs; }
2267     case T_IF: {
2268         if(args.count() != 1) {
2269             fprintf(stderr, "%s:%d: if(condition) requires one argument.\n", parser.file.toLatin1().constData(),
2270                     parser.line_no);
2271             return false;
2272         }
2273         const QString cond = args.first();
2274         const QChar *d = cond.unicode();
2275         QChar quote = 0;
2276         bool ret = true, or_op = false;
2277         QString test;
2278         for(int d_off = 0, parens = 0, d_len = cond.size(); d_off < d_len; ++d_off) {
2279             if(!quote.isNull()) {
2280                 if(*(d+d_off) == quote)
2281                     quote = QChar();
2282             } else if(*(d+d_off) == '(') {
2283                 ++parens;
2284             } else if(*(d+d_off) == ')') {
2285                 --parens;
2286             } else if(*(d+d_off) == '"' /*|| *(d+d_off) == '\''*/) {
2287                 quote = *(d+d_off);
2288             }
2289             if(!parens && quote.isNull() && (*(d+d_off) == QLatin1Char(':') || *(d+d_off) == QLatin1Char('|') || d_off == d_len-1)) {
2290                 if(d_off == d_len-1)
2291                     test += *(d+d_off);
2292                 if(!test.isEmpty()) {
2293                     if (or_op != ret)
2294                         ret = doProjectTest(test, place);
2295                     test.clear();
2296                 }
2297                 if(*(d+d_off) == QLatin1Char(':')) {
2298                     or_op = false;
2299                 } else if(*(d+d_off) == QLatin1Char('|')) {
2300                     or_op = true;
2301                 }
2302             } else {
2303                 test += *(d+d_off);
2304             }
2305         }
2306         return ret; }
2307     case T_EQUALS:
2308         if(args.count() != 2) {
2309             fprintf(stderr, "%s:%d: %s(variable, value) requires two arguments.\n", parser.file.toLatin1().constData(),
2310                     parser.line_no, func.toLatin1().constData());
2311             return false;
2312         }
2313         return values(args[0], place).join(QString(Option::field_sep)) == args[1];
2314     case T_EXISTS: {
2315         if(args.count() != 1) {
2316             fprintf(stderr, "%s:%d: exists(file) requires one argument.\n", parser.file.toLatin1().constData(),
2317                     parser.line_no);
2318             return false;
2319         }
2320         QString file = Option::normalizePath(args.first());
2321
2322         if(QFile::exists(file))
2323             return true;
2324         //regular expression I guess
2325         QString dirstr = qmake_getpwd();
2326         int slsh = file.lastIndexOf(QLatin1Char('/'));
2327         if(slsh != -1) {
2328             dirstr = file.left(slsh+1);
2329             file = file.right(file.length() - slsh - 1);
2330         }
2331         return QDir(dirstr).entryList(QStringList(file)).count(); }
2332     case T_EXPORT:
2333         if(args.count() != 1) {
2334             fprintf(stderr, "%s:%d: export(variable) requires one argument.\n", parser.file.toLatin1().constData(),
2335                     parser.line_no);
2336             return false;
2337         }
2338         for(int i = 0; i < function_blocks.size(); ++i) {
2339             FunctionBlock *f = function_blocks.at(i);
2340             f->vars[args[0]] = values(args[0], place);
2341             if(!i && f->calling_place)
2342                 (*f->calling_place)[args[0]] = values(args[0], place);
2343         }
2344         return true;
2345     case T_CLEAR:
2346         if(args.count() != 1) {
2347             fprintf(stderr, "%s:%d: clear(variable) requires one argument.\n", parser.file.toLatin1().constData(),
2348                     parser.line_no);
2349             return false;
2350         }
2351         if(!place.contains(args[0]))
2352             return false;
2353         place[args[0]].clear();
2354         return true;
2355     case T_UNSET:
2356         if(args.count() != 1) {
2357             fprintf(stderr, "%s:%d: unset(variable) requires one argument.\n", parser.file.toLatin1().constData(),
2358                     parser.line_no);
2359             return false;
2360         }
2361         if(!place.contains(args[0]))
2362             return false;
2363         place.remove(args[0]);
2364         return true;
2365     case T_EVAL: {
2366         if(args.count() < 1 && 0) {
2367             fprintf(stderr, "%s:%d: eval(project) requires one argument.\n", parser.file.toLatin1().constData(),
2368                     parser.line_no);
2369             return false;
2370         }
2371         QString project = args.join(" ");
2372         parser_info pi = parser;
2373         parser.from_file = false;
2374         parser.file = "(eval)";
2375         parser.line_no = 0;
2376         QTextStream t(&project, QIODevice::ReadOnly);
2377         bool ret = read(t, place);
2378         parser = pi;
2379         return ret; }
2380     case T_CONFIG: {
2381         if(args.count() < 1 || args.count() > 2) {
2382             fprintf(stderr, "%s:%d: CONFIG(config) requires one argument.\n", parser.file.toLatin1().constData(),
2383                     parser.line_no);
2384             return false;
2385         }
2386         if(args.count() == 1)
2387             return isActiveConfig(args[0]);
2388         const QStringList mutuals = args[1].split('|');
2389         const QStringList &configs = values("CONFIG", place);
2390         for(int i = configs.size()-1; i >= 0; i--) {
2391             for(int mut = 0; mut < mutuals.count(); mut++) {
2392                 if(configs[i] == mutuals[mut].trimmed())
2393                     return (configs[i] == args[0]);
2394             }
2395         }
2396         return false; }
2397     case T_SYSTEM:
2398         if(args.count() < 1 || args.count() > 2) {
2399             fprintf(stderr, "%s:%d: system(exec) requires one argument.\n", parser.file.toLatin1().constData(),
2400                     parser.line_no);
2401             return false;
2402         }
2403         if(args.count() == 2) {
2404             const QString sarg = args[1];
2405             if (sarg.toLower() == "true" || sarg.toInt())
2406                 warn_msg(WarnParser, "%s:%d: system()'s second argument is now hard-wired to false.\n",
2407                          parser.file.toLatin1().constData(), parser.line_no);
2408         }
2409         return system(args[0].toLatin1().constData()) == 0;
2410     case T_RETURN:
2411         if(function_blocks.isEmpty()) {
2412             fprintf(stderr, "%s:%d unexpected return()\n",
2413                     parser.file.toLatin1().constData(), parser.line_no);
2414         } else {
2415             FunctionBlock *f = function_blocks.top();
2416             f->cause_return = true;
2417             if(args_list.count() >= 1)
2418                 f->return_value += args_list[0];
2419         }
2420         return true;
2421     case T_BREAK:
2422         if(iterator)
2423             iterator->cause_break = true;
2424         else
2425             fprintf(stderr, "%s:%d unexpected break()\n",
2426                     parser.file.toLatin1().constData(), parser.line_no);
2427         return true;
2428     case T_NEXT:
2429         if(iterator)
2430             iterator->cause_next = true;
2431         else
2432             fprintf(stderr, "%s:%d unexpected next()\n",
2433                     parser.file.toLatin1().constData(), parser.line_no);
2434         return true;
2435     case T_DEFINED:
2436         if(args.count() < 1 || args.count() > 2) {
2437             fprintf(stderr, "%s:%d: defined(function) requires one argument.\n",
2438                     parser.file.toLatin1().constData(), parser.line_no);
2439         } else {
2440            if(args.count() > 1) {
2441                if(args[1] == "test")
2442                    return testFunctions.contains(args[0]);
2443                else if(args[1] == "replace")
2444                    return replaceFunctions.contains(args[0]);
2445                fprintf(stderr, "%s:%d: defined(function, type): unexpected type [%s].\n",
2446                        parser.file.toLatin1().constData(), parser.line_no,
2447                        args[1].toLatin1().constData());
2448             } else {
2449                 if(replaceFunctions.contains(args[0]) || testFunctions.contains(args[0]))
2450                     return true;
2451             }
2452         }
2453         return false;
2454     case T_CONTAINS: {
2455         if(args.count() < 2 || args.count() > 3) {
2456             fprintf(stderr, "%s:%d: contains(var, val) requires at lesat 2 arguments.\n",
2457                     parser.file.toLatin1().constData(), parser.line_no);
2458             return false;
2459         }
2460         QRegExp regx(args[1]);
2461         const QStringList &l = values(args[0], place);
2462         if(args.count() == 2) {
2463             for(int i = 0; i < l.size(); ++i) {
2464                 const QString val = l[i];
2465                 if(regx.exactMatch(val) || val == args[1])
2466                     return true;
2467             }
2468         } else {
2469             const QStringList mutuals = args[2].split('|');
2470             for(int i = l.size()-1; i >= 0; i--) {
2471                 const QString val = l[i];
2472                 for(int mut = 0; mut < mutuals.count(); mut++) {
2473                     if(val == mutuals[mut].trimmed())
2474                         return (regx.exactMatch(val) || val == args[1]);
2475                 }
2476             }
2477         }
2478         return false; }
2479     case T_INFILE: {
2480         if(args.count() < 2 || args.count() > 3) {
2481             fprintf(stderr, "%s:%d: infile(file, var, val) requires at least 2 arguments.\n",
2482                     parser.file.toLatin1().constData(), parser.line_no);
2483             return false;
2484         }
2485
2486         bool ret = false;
2487         QHash<QString, QStringList> tmp;
2488         if(doProjectInclude(Option::normalizePath(args[0]), IncludeFlagNewParser, tmp) == IncludeSuccess) {
2489             if(tmp.contains("QMAKE_INTERNAL_INCLUDED_FILES")) {
2490                 QStringList &out = place["QMAKE_INTERNAL_INCLUDED_FILES"];
2491                 const QStringList &in = tmp["QMAKE_INTERNAL_INCLUDED_FILES"];
2492                 for(int i = 0; i < in.size(); ++i) {
2493                     if(out.indexOf(in[i]) == -1)
2494                         out += in[i];
2495                 }
2496             }
2497             if(args.count() == 2) {
2498                 ret = tmp.contains(args[1]);
2499             } else {
2500                 QRegExp regx(args[2]);
2501                 const QStringList &l = tmp[args[1]];
2502                 for(QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
2503                     if(regx.exactMatch((*it)) || (*it) == args[2]) {
2504                         ret = true;
2505                         break;
2506                     }
2507                 }
2508             }
2509         }
2510         return ret; }
2511     case T_COUNT:
2512         if(args.count() != 2 && args.count() != 3) {
2513             fprintf(stderr, "%s:%d: count(var, count) requires two arguments.\n", parser.file.toLatin1().constData(),
2514                     parser.line_no);
2515             return false;
2516         }
2517         if(args.count() == 3) {
2518             QString comp = args[2];
2519             if(comp == ">" || comp == "greaterThan")
2520                 return values(args[0], place).count() > args[1].toInt();
2521             if(comp == ">=")
2522                 return values(args[0], place).count() >= args[1].toInt();
2523             if(comp == "<" || comp == "lessThan")
2524                 return values(args[0], place).count() < args[1].toInt();
2525             if(comp == "<=")
2526                 return values(args[0], place).count() <= args[1].toInt();
2527             if(comp == "equals" || comp == "isEqual" || comp == "=" || comp == "==")
2528                 return values(args[0], place).count() == args[1].toInt();
2529             fprintf(stderr, "%s:%d: unexpected modifier to count(%s)\n", parser.file.toLatin1().constData(),
2530                     parser.line_no, comp.toLatin1().constData());
2531             return false;
2532         }
2533         return values(args[0], place).count() == args[1].toInt();
2534     case T_ISEMPTY:
2535         if(args.count() != 1) {
2536             fprintf(stderr, "%s:%d: isEmpty(var) requires one argument.\n", parser.file.toLatin1().constData(),
2537                     parser.line_no);
2538             return false;
2539         }
2540         return values(args[0], place).isEmpty();
2541     case T_INCLUDE:
2542     case T_LOAD: {
2543         QString parseInto;
2544         const bool include_statement = (func_t == T_INCLUDE);
2545         bool ignore_error = false;
2546         if(args.count() >= 2) {
2547             if(func_t == T_INCLUDE) {
2548                 parseInto = args[1];
2549                 if (args.count() == 3){
2550                     QString sarg = args[2];
2551                     if (sarg.toLower() == "true" || sarg.toInt())
2552                         ignore_error = true;
2553                 }
2554             } else {
2555                 QString sarg = args[1];
2556                 ignore_error = (sarg.toLower() == "true" || sarg.toInt());
2557             }
2558         } else if(args.count() != 1) {
2559             QString func_desc = "load(feature)";
2560             if(include_statement)
2561                 func_desc = "include(file)";
2562             fprintf(stderr, "%s:%d: %s requires one argument.\n", parser.file.toLatin1().constData(),
2563                     parser.line_no, func_desc.toLatin1().constData());
2564             return false;
2565         }
2566         QString file = Option::normalizePath(args.first());
2567         uchar flags = IncludeFlagNone;
2568         if(!include_statement)
2569             flags |= IncludeFlagFeature;
2570         IncludeStatus stat = IncludeFailure;
2571         if(!parseInto.isEmpty()) {
2572             QHash<QString, QStringList> symbols;
2573             stat = doProjectInclude(file, flags|IncludeFlagNewProject, symbols);
2574             if(stat == IncludeSuccess) {
2575                 QHash<QString, QStringList> out_place;
2576                 for(QHash<QString, QStringList>::ConstIterator it = place.begin(); it != place.end(); ++it) {
2577                     const QString var = it.key();
2578                     if(var != parseInto && !var.startsWith(parseInto + "."))
2579                         out_place.insert(var, it.value());
2580                 }
2581                 for(QHash<QString, QStringList>::ConstIterator it = symbols.begin(); it != symbols.end(); ++it) {
2582                     const QString var = it.key();
2583                     if(!var.startsWith("."))
2584                         out_place.insert(parseInto + "." + it.key(), it.value());
2585                 }
2586                 place = out_place;
2587             }
2588         } else {
2589             stat = doProjectInclude(file, flags, place);
2590         }
2591         if(stat == IncludeFeatureAlreadyLoaded) {
2592             warn_msg(WarnParser, "%s:%d: Duplicate of loaded feature %s",
2593                      parser.file.toLatin1().constData(), parser.line_no, file.toLatin1().constData());
2594         } else if(stat == IncludeNoExist && !ignore_error) {
2595             warn_msg(WarnAll, "%s:%d: Unable to find file for inclusion %s",
2596                      parser.file.toLatin1().constData(), parser.line_no, file.toLatin1().constData());
2597             return false;
2598         } else if(stat >= IncludeFailure) {
2599             if(!ignore_error) {
2600                 printf("Project LOAD(): Feature %s cannot be found.\n", file.toLatin1().constData());
2601                 if (!ignore_error)
2602 #if defined(QT_BUILD_QMAKE_LIBRARY)
2603                     return false;
2604 #else
2605                     exit(3);
2606 #endif
2607             }
2608             return false;
2609         }
2610         return true; }
2611     case T_DEBUG: {
2612         if(args.count() != 2) {
2613             fprintf(stderr, "%s:%d: debug(level, message) requires one argument.\n", parser.file.toLatin1().constData(),
2614                     parser.line_no);
2615             return false;
2616         }
2617         QString msg = fixEnvVariables(args[1]);
2618         debug_msg(args[0].toInt(), "Project DEBUG: %s", msg.toLatin1().constData());
2619         return true; }
2620     case T_ERROR:
2621     case T_MESSAGE:
2622     case T_WARNING: {
2623         if(args.count() != 1) {
2624             fprintf(stderr, "%s:%d: %s(message) requires one argument.\n", parser.file.toLatin1().constData(),
2625                     parser.line_no, func.toLatin1().constData());
2626             return false;
2627         }
2628         QString msg = fixEnvVariables(args.first());
2629         fprintf(stderr, "Project %s: %s\n", func.toUpper().toLatin1().constData(), msg.toLatin1().constData());
2630         if(func == "error")
2631 #if defined(QT_BUILD_QMAKE_LIBRARY)
2632             return false;
2633 #else
2634             exit(2);
2635 #endif
2636         return true; }
2637     case T_OPTION:
2638         if (args.count() != 1) {
2639             fprintf(stderr, "%s:%d: option() requires one argument.\n",
2640                     parser.file.toLatin1().constData(), parser.line_no);
2641             return false;
2642         }
2643         if (args.first() == "recursive") {
2644             recursive = true;
2645         } else {
2646             fprintf(stderr, "%s:%d: unrecognized option() argument '%s'.\n",
2647                     parser.file.toLatin1().constData(), parser.line_no,
2648                     args.first().toLatin1().constData());
2649             return false;
2650         }
2651         return true;
2652     default:
2653         fprintf(stderr, "%s:%d: Unknown test function: %s\n", parser.file.toLatin1().constData(), parser.line_no,
2654                 func.toLatin1().constData());
2655     }
2656     return false;
2657 }
2658
2659 bool
2660 QMakeProject::doProjectCheckReqs(const QStringList &deps, QHash<QString, QStringList> &place)
2661 {
2662     bool ret = false;
2663     for(QStringList::ConstIterator it = deps.begin(); it != deps.end(); ++it) {
2664         bool test = doProjectTest((*it), place);
2665         if(!test) {
2666             debug_msg(1, "Project Parser: %s:%d Failed test: REQUIRES = %s",
2667                       parser.file.toLatin1().constData(), parser.line_no,
2668                       (*it).toLatin1().constData());
2669             place["QMAKE_FAILED_REQUIREMENTS"].append((*it));
2670             ret = false;
2671         }
2672     }
2673     return ret;
2674 }
2675
2676 bool
2677 QMakeProject::test(const QString &v)
2678 {
2679     QHash<QString, QStringList> tmp = vars;
2680     return doProjectTest(v, tmp);
2681 }
2682
2683 bool
2684 QMakeProject::test(const QString &func, const QList<QStringList> &args)
2685 {
2686     QHash<QString, QStringList> tmp = vars;
2687     return doProjectTest(func, args, tmp);
2688 }
2689
2690 QStringList
2691 QMakeProject::expand(const QString &str)
2692 {
2693     bool ok;
2694     QHash<QString, QStringList> tmp = vars;
2695     const QStringList ret = doVariableReplaceExpand(str, tmp, &ok);
2696     if(ok)
2697         return ret;
2698     return QStringList();
2699 }
2700
2701 QString
2702 QMakeProject::expand(const QString &str, const QString &file, int line)
2703 {
2704     bool ok;
2705     parser_info pi = parser;
2706     parser.file = file;
2707     parser.line_no = line;
2708     parser.from_file = false;
2709     QHash<QString, QStringList> tmp = vars;
2710     const QStringList ret = doVariableReplaceExpand(str, tmp, &ok);
2711     parser = pi;
2712     return ok ? ret.join(QString(Option::field_sep)) : QString();
2713 }
2714
2715 QStringList
2716 QMakeProject::expand(const QString &func, const QList<QStringList> &args)
2717 {
2718     QHash<QString, QStringList> tmp = vars;
2719     return doProjectExpand(func, args, tmp);
2720 }
2721
2722 bool
2723 QMakeProject::doVariableReplace(QString &str, QHash<QString, QStringList> &place)
2724 {
2725     bool ret;
2726     str = doVariableReplaceExpand(str, place, &ret).join(QString(Option::field_sep));
2727     return ret;
2728 }
2729
2730 QStringList
2731 QMakeProject::doVariableReplaceExpand(const QString &str, QHash<QString, QStringList> &place, bool *ok)
2732 {
2733     QStringList ret;
2734     if(ok)
2735         *ok = true;
2736     if(str.isEmpty())
2737         return ret;
2738
2739     const ushort LSQUARE = '[';
2740     const ushort RSQUARE = ']';
2741     const ushort LCURLY = '{';
2742     const ushort RCURLY = '}';
2743     const ushort LPAREN = '(';
2744     const ushort RPAREN = ')';
2745     const ushort DOLLAR = '$';
2746     const ushort SLASH = '\\';
2747     const ushort UNDERSCORE = '_';
2748     const ushort DOT = '.';
2749     const ushort SPACE = ' ';
2750     const ushort TAB = '\t';
2751     const ushort SINGLEQUOTE = '\'';
2752     const ushort DOUBLEQUOTE = '"';
2753
2754     ushort unicode, quote = 0;
2755     const QChar *str_data = str.data();
2756     const int str_len = str.length();
2757
2758     ushort term;
2759     QString var, args;
2760
2761     int replaced = 0;
2762     QString current;
2763     for(int i = 0; i < str_len; ++i) {
2764         unicode = str_data[i].unicode();
2765         const int start_var = i;
2766         if(unicode == DOLLAR && str_len > i+2) {
2767             unicode = str_data[++i].unicode();
2768             if(unicode == DOLLAR) {
2769                 term = 0;
2770                 var.clear();
2771                 args.clear();
2772                 enum { VAR, ENVIRON, FUNCTION, PROPERTY } var_type = VAR;
2773                 unicode = str_data[++i].unicode();
2774                 if(unicode == LSQUARE) {
2775                     unicode = str_data[++i].unicode();
2776                     term = RSQUARE;
2777                     var_type = PROPERTY;
2778                 } else if(unicode == LCURLY) {
2779                     unicode = str_data[++i].unicode();
2780                     var_type = VAR;
2781                     term = RCURLY;
2782                 } else if(unicode == LPAREN) {
2783                     unicode = str_data[++i].unicode();
2784                     var_type = ENVIRON;
2785                     term = RPAREN;
2786                 }
2787                 while(1) {
2788                     if(!(unicode & (0xFF<<8)) &&
2789                        unicode != DOT && unicode != UNDERSCORE &&
2790                        //unicode != SINGLEQUOTE && unicode != DOUBLEQUOTE &&
2791                        (unicode < 'a' || unicode > 'z') && (unicode < 'A' || unicode > 'Z') &&
2792                        (unicode < '0' || unicode > '9') && (!term || unicode != '/'))
2793                         break;
2794                     var.append(QChar(unicode));
2795                     if(++i == str_len)
2796                         break;
2797                     unicode = str_data[i].unicode();
2798                     // at this point, i points to either the 'term' or 'next' character (which is in unicode)
2799                 }
2800                 if(var_type == VAR && unicode == LPAREN) {
2801                     var_type = FUNCTION;
2802                     int depth = 0;
2803                     while(1) {
2804                         if(++i == str_len)
2805                             break;
2806                         unicode = str_data[i].unicode();
2807                         if(unicode == LPAREN) {
2808                             depth++;
2809                         } else if(unicode == RPAREN) {
2810                             if(!depth)
2811                                 break;
2812                             --depth;
2813                         }
2814                         args.append(QChar(unicode));
2815                     }
2816                     if(++i < str_len)
2817                         unicode = str_data[i].unicode();
2818                     else
2819                         unicode = 0;
2820                     // at this point i is pointing to the 'next' character (which is in unicode)
2821                     // this might actually be a term character since you can do $${func()}
2822                 }
2823                 if(term) {
2824                     if(unicode != term) {
2825                         qmake_error_msg("Missing " + QString(term) + " terminator [found " + (unicode?QString(unicode):QString("end-of-line")) + "]");
2826                         if(ok)
2827                             *ok = false;
2828                         return QStringList();
2829                     }
2830                 } else {
2831                     // move the 'cursor' back to the last char of the thing we were looking at
2832                     --i;
2833                 }
2834                 // since i never points to the 'next' character, there is no reason for this to be set
2835                 unicode = 0;
2836
2837                 QStringList replacement;
2838                 if(var_type == ENVIRON) {
2839                     replacement = split_value_list(QString::fromLocal8Bit(qgetenv(var.toLatin1().constData())));
2840                 } else if(var_type == PROPERTY) {
2841                     if(prop)
2842                         replacement = split_value_list(prop->value(var));
2843                 } else if(var_type == FUNCTION) {
2844                     replacement = doProjectExpand(var, args, place);
2845                 } else if(var_type == VAR) {
2846                     replacement = values(var, place);
2847                 }
2848                 if(!(replaced++) && start_var)
2849                     current = str.left(start_var);
2850                 if(!replacement.isEmpty()) {
2851                     if(quote) {
2852                         current += replacement.join(QString(Option::field_sep));
2853                     } else {
2854                         current += replacement.takeFirst();
2855                         if(!replacement.isEmpty()) {
2856                             if(!current.isEmpty())
2857                                 ret.append(current);
2858                             current = replacement.takeLast();
2859                             if(!replacement.isEmpty())
2860                                 ret += replacement;
2861                         }
2862                     }
2863                 }
2864                 debug_msg(2, "Project Parser [var replace]: %s -> %s",
2865                           str.toLatin1().constData(), var.toLatin1().constData(),
2866                           replacement.join("::").toLatin1().constData());
2867             } else {
2868                 if(replaced)
2869                     current.append("$");
2870             }
2871         }
2872         if(quote && unicode == quote) {
2873             unicode = 0;
2874             quote = 0;
2875         } else if(unicode == SLASH) {
2876             bool escape = false;
2877             const char *symbols = "[]{}()$\\'\"";
2878             for(const char *s = symbols; *s; ++s) {
2879                 if(str_data[i+1].unicode() == (ushort)*s) {
2880                     i++;
2881                     escape = true;
2882                     if(!(replaced++))
2883                         current = str.left(start_var);
2884                     current.append(str.at(i));
2885                     break;
2886                 }
2887             }
2888             if(!escape && !backslashWarned) {
2889                 backslashWarned = true;
2890                 warn_msg(WarnDeprecated, "%s:%d: Unescaped backslashes are deprecated.",
2891                          parser.file.toLatin1().constData(), parser.line_no);
2892             }
2893             if(escape || !replaced)
2894                 unicode =0;
2895         } else if(!quote && (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE)) {
2896             quote = unicode;
2897             unicode = 0;
2898             if(!(replaced++) && i)
2899                 current = str.left(i);
2900         } else if(!quote && (unicode == SPACE || unicode == TAB)) {
2901             unicode = 0;
2902             if(!current.isEmpty()) {
2903                 ret.append(current);
2904                 current.clear();
2905             }
2906         }
2907         if(replaced && unicode)
2908             current.append(QChar(unicode));
2909     }
2910     if(!replaced)
2911         ret = QStringList(str);
2912     else if(!current.isEmpty())
2913         ret.append(current);
2914     //qDebug() << "REPLACE" << str << ret;
2915     if (quote)
2916         warn_msg(WarnDeprecated, "%s:%d: Unmatched quotes are deprecated.",
2917                  parser.file.toLatin1().constData(), parser.line_no);
2918     return ret;
2919 }
2920
2921 QStringList &QMakeProject::values(const QString &_var, QHash<QString, QStringList> &place)
2922 {
2923     QString var = varMap(_var);
2924     if(var == QLatin1String("LITERAL_WHITESPACE")) { //a real space in a token)
2925         var = ".BUILTIN." + var;
2926         place[var] = QStringList(QLatin1String("\t"));
2927     } else if(var == QLatin1String("LITERAL_DOLLAR")) { //a real $
2928         var = ".BUILTIN." + var;
2929         place[var] = QStringList(QLatin1String("$"));
2930     } else if(var == QLatin1String("LITERAL_HASH")) { //a real #
2931         var = ".BUILTIN." + var;
2932         place[var] = QStringList("#");
2933     } else if(var == QLatin1String("OUT_PWD")) { //the out going dir
2934         var = ".BUILTIN." + var;
2935         place[var] =  QStringList(Option::output_dir);
2936     } else if(var == QLatin1String("PWD") ||  //current working dir (of _FILE_)
2937               var == QLatin1String("IN_PWD")) {
2938         var = ".BUILTIN." + var;
2939         place[var] = QStringList(qmake_getpwd());
2940     } else if(var == QLatin1String("DIR_SEPARATOR")) {
2941         validateModes();
2942         var = ".BUILTIN." + var;
2943         place[var] =  QStringList(Option::dir_sep);
2944     } else if(var == QLatin1String("DIRLIST_SEPARATOR")) {
2945         var = ".BUILTIN." + var;
2946         place[var] = QStringList(Option::dirlist_sep);
2947     } else if(var == QLatin1String("_LINE_")) { //parser line number
2948         var = ".BUILTIN." + var;
2949         place[var] = QStringList(QString::number(parser.line_no));
2950     } else if(var == QLatin1String("_FILE_")) { //parser file
2951         var = ".BUILTIN." + var;
2952         place[var] = QStringList(parser.file);
2953     } else if(var == QLatin1String("_DATE_")) { //current date/time
2954         var = ".BUILTIN." + var;
2955         place[var] = QStringList(QDateTime::currentDateTime().toString());
2956     } else if(var == QLatin1String("_PRO_FILE_")) {
2957         var = ".BUILTIN." + var;
2958         place[var] = QStringList(pfile);
2959     } else if(var == QLatin1String("_PRO_FILE_PWD_")) {
2960         var = ".BUILTIN." + var;
2961         place[var] = QStringList(pfile.isEmpty() ? qmake_getpwd() : QFileInfo(pfile).absolutePath());
2962     } else if(var == QLatin1String("_QMAKE_CACHE_")) {
2963         var = ".BUILTIN." + var;
2964         if(Option::mkfile::do_cache)
2965             place[var] = QStringList(Option::mkfile::cachefile);
2966     } else if(var == QLatin1String("TEMPLATE")) {
2967         if(!Option::user_template.isEmpty()) {
2968             var = ".BUILTIN.USER." + var;
2969             place[var] =  QStringList(Option::user_template);
2970         } else {
2971             QString orig_template, real_template;
2972             if(!place[var].isEmpty())
2973                 orig_template = place[var].first();
2974             real_template = orig_template.isEmpty() ? "app" : orig_template;
2975             if(!Option::user_template_prefix.isEmpty() && !orig_template.startsWith(Option::user_template_prefix))
2976                 real_template.prepend(Option::user_template_prefix);
2977             if(real_template != orig_template) {
2978                 var = ".BUILTIN." + var;
2979                 place[var] = QStringList(real_template);
2980             }
2981         }
2982     } else if(var.startsWith(QLatin1String("QMAKE_HOST."))) {
2983         QString ret, type = var.mid(11);
2984 #if defined(Q_OS_WIN32)
2985         if(type == "os") {
2986             ret = "Windows";
2987         } else if(type == "name") {
2988             DWORD name_length = 1024;
2989             wchar_t name[1024];
2990             if (GetComputerName(name, &name_length))
2991                 ret = QString::fromWCharArray(name);
2992         } else if(type == "version" || type == "version_string") {
2993             QSysInfo::WinVersion ver = QSysInfo::WindowsVersion;
2994             if(type == "version")
2995                 ret = QString::number(ver);
2996             else if(ver == QSysInfo::WV_Me)
2997                 ret = "WinMe";
2998             else if(ver == QSysInfo::WV_95)
2999                 ret = "Win95";
3000             else if(ver == QSysInfo::WV_98)
3001                 ret = "Win98";
3002             else if(ver == QSysInfo::WV_NT)
3003                 ret = "WinNT";
3004             else if(ver == QSysInfo::WV_2000)
3005                 ret = "Win2000";
3006             else if(ver == QSysInfo::WV_2000)
3007                 ret = "Win2003";
3008             else if(ver == QSysInfo::WV_XP)
3009                 ret = "WinXP";
3010             else if(ver == QSysInfo::WV_VISTA)
3011                 ret = "WinVista";
3012             else
3013                 ret = "Unknown";
3014         } else if(type == "arch") {
3015             SYSTEM_INFO info;
3016             GetSystemInfo(&info);
3017             switch(info.wProcessorArchitecture) {
3018 #ifdef PROCESSOR_ARCHITECTURE_AMD64
3019             case PROCESSOR_ARCHITECTURE_AMD64:
3020                 ret = "x86_64";
3021                 break;
3022 #endif
3023             case PROCESSOR_ARCHITECTURE_INTEL:
3024                 ret = "x86";
3025                 break;
3026             case PROCESSOR_ARCHITECTURE_IA64:
3027 #ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64
3028             case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
3029 #endif
3030                 ret = "IA64";
3031                 break;
3032             default:
3033                 ret = "Unknown";
3034                 break;
3035             }
3036         }
3037 #elif defined(Q_OS_UNIX)
3038         struct utsname name;
3039         if(!uname(&name)) {
3040             if(type == "os")
3041                 ret = name.sysname;
3042             else if(type == "name")
3043                 ret = name.nodename;
3044             else if(type == "version")
3045                 ret = name.release;
3046             else if(type == "version_string")
3047                 ret = name.version;
3048             else if(type == "arch")
3049                 ret = name.machine;
3050         }
3051 #endif
3052         var = ".BUILTIN.HOST." + type;
3053         place[var] = QStringList(ret);
3054     } else if (var == QLatin1String("QMAKE_DIR_SEP")) {
3055         if (place[var].isEmpty())
3056             return values("DIR_SEPARATOR", place);
3057     } else if (var == QLatin1String("QMAKE_EXT_OBJ")) {
3058         if (place[var].isEmpty()) {
3059             var = ".BUILTIN." + var;
3060             place[var] = QStringList(Option::obj_ext);
3061         }
3062     } else if (var == QLatin1String("QMAKE_QMAKE")) {
3063         if (place[var].isEmpty())
3064             place[var] = QStringList(Option::fixPathToTargetOS(
3065                 !Option::qmake_abslocation.isEmpty()
3066                     ? Option::qmake_abslocation
3067                     : QLibraryInfo::location(QLibraryInfo::HostBinariesPath) + "/qmake",
3068                 false));
3069     }
3070 #if defined(Q_OS_WIN32) && defined(Q_CC_MSVC)
3071       else if(var.startsWith(QLatin1String("QMAKE_TARGET."))) {
3072             QString ret, type = var.mid(13);
3073             if(type == "arch") {
3074                 QString paths = QString::fromLocal8Bit(qgetenv("PATH"));
3075                 QString vcBin64 = QString::fromLocal8Bit(qgetenv("VCINSTALLDIR"));
3076                 if (!vcBin64.endsWith('\\'))
3077                     vcBin64.append('\\');
3078                 vcBin64.append("bin\\amd64");
3079                 QString vcBinX86_64 = QString::fromLocal8Bit(qgetenv("VCINSTALLDIR"));
3080                 if (!vcBinX86_64.endsWith('\\'))
3081                     vcBinX86_64.append('\\');
3082                 vcBinX86_64.append("bin\\x86_amd64");
3083                 if(paths.contains(vcBin64,Qt::CaseInsensitive) || paths.contains(vcBinX86_64,Qt::CaseInsensitive))
3084                     ret = "x86_64";
3085                 else
3086                     ret = "x86";
3087             }
3088             place[var] = QStringList(ret);
3089     }
3090 #endif
3091     //qDebug("REPLACE [%s]->[%s]", qPrintable(var), qPrintable(place[var].join("::")));
3092     return place[var];
3093 }
3094
3095 bool QMakeProject::isEmpty(const QString &v)
3096 {
3097     QHash<QString, QStringList>::ConstIterator it = vars.constFind(varMap(v));
3098     return it == vars.constEnd() || it->isEmpty();
3099 }
3100
3101 QT_END_NAMESPACE