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