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