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