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