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