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