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