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