1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the qmake application of the Qt Toolkit.
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.
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.
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.
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.
40 ****************************************************************************/
45 #include "cachekeys.h"
46 #include "generators/metamakefile.h"
48 #include <qdatetime.h>
50 #include <qfileinfo.h>
53 #include <qtextstream.h>
62 #include <sys/utsname.h>
63 #elif defined(Q_OS_WIN32)
70 #define QT_POPEN _popen
71 #define QT_PCLOSE _pclose
73 #define QT_POPEN popen
74 #define QT_PCLOSE pclose
80 enum ExpandFunc { E_MEMBER=1, E_FIRST, E_LAST, E_CAT, E_FROMFILE, E_EVAL, E_LIST,
81 E_SPRINTF, E_FORMAT_NUMBER, E_JOIN, E_SPLIT, E_BASENAME, E_DIRNAME, E_SECTION,
82 E_FIND, E_SYSTEM, E_UNIQUE, E_REVERSE, E_QUOTE, E_ESCAPE_EXPAND,
83 E_UPPER, E_LOWER, E_FILES, E_PROMPT, E_RE_ESCAPE, E_VAL_ESCAPE, E_REPLACE,
84 E_SIZE, E_SORT_DEPENDS, E_RESOLVE_DEPENDS, E_ENUMERATE_VARS,
85 E_SHADOWED, E_ABSOLUTE_PATH, E_RELATIVE_PATH, E_CLEAN_PATH,
86 E_SYSTEM_PATH, E_SHELL_PATH, E_SYSTEM_QUOTE, E_SHELL_QUOTE };
87 QHash<QString, ExpandFunc> qmake_expandFunctions()
89 static QHash<QString, ExpandFunc> *qmake_expand_functions = 0;
90 if(!qmake_expand_functions) {
91 qmake_expand_functions = new QHash<QString, ExpandFunc>;
92 qmakeAddCacheClear(qmakeDeleteCacheClear<QHash<QString, ExpandFunc> >, (void**)&qmake_expand_functions);
93 qmake_expand_functions->insert("member", E_MEMBER);
94 qmake_expand_functions->insert("first", E_FIRST);
95 qmake_expand_functions->insert("last", E_LAST);
96 qmake_expand_functions->insert("cat", E_CAT);
97 qmake_expand_functions->insert("fromfile", E_FROMFILE);
98 qmake_expand_functions->insert("eval", E_EVAL);
99 qmake_expand_functions->insert("list", E_LIST);
100 qmake_expand_functions->insert("sprintf", E_SPRINTF);
101 qmake_expand_functions->insert("format_number", E_FORMAT_NUMBER);
102 qmake_expand_functions->insert("join", E_JOIN);
103 qmake_expand_functions->insert("split", E_SPLIT);
104 qmake_expand_functions->insert("basename", E_BASENAME);
105 qmake_expand_functions->insert("dirname", E_DIRNAME);
106 qmake_expand_functions->insert("section", E_SECTION);
107 qmake_expand_functions->insert("find", E_FIND);
108 qmake_expand_functions->insert("system", E_SYSTEM);
109 qmake_expand_functions->insert("unique", E_UNIQUE);
110 qmake_expand_functions->insert("reverse", E_REVERSE);
111 qmake_expand_functions->insert("quote", E_QUOTE);
112 qmake_expand_functions->insert("escape_expand", E_ESCAPE_EXPAND);
113 qmake_expand_functions->insert("upper", E_UPPER);
114 qmake_expand_functions->insert("lower", E_LOWER);
115 qmake_expand_functions->insert("re_escape", E_RE_ESCAPE);
116 qmake_expand_functions->insert("val_escape", E_VAL_ESCAPE);
117 qmake_expand_functions->insert("files", E_FILES);
118 qmake_expand_functions->insert("prompt", E_PROMPT);
119 qmake_expand_functions->insert("replace", E_REPLACE);
120 qmake_expand_functions->insert("size", E_SIZE);
121 qmake_expand_functions->insert("sort_depends", E_SORT_DEPENDS);
122 qmake_expand_functions->insert("resolve_depends", E_RESOLVE_DEPENDS);
123 qmake_expand_functions->insert("enumerate_vars", E_ENUMERATE_VARS);
124 qmake_expand_functions->insert("shadowed", E_SHADOWED);
125 qmake_expand_functions->insert("absolute_path", E_ABSOLUTE_PATH);
126 qmake_expand_functions->insert("relative_path", E_RELATIVE_PATH);
127 qmake_expand_functions->insert("clean_path", E_CLEAN_PATH);
128 qmake_expand_functions->insert("system_path", E_SYSTEM_PATH);
129 qmake_expand_functions->insert("shell_path", E_SHELL_PATH);
130 qmake_expand_functions->insert("system_quote", E_SYSTEM_QUOTE);
131 qmake_expand_functions->insert("shell_quote", E_SHELL_QUOTE);
133 return *qmake_expand_functions;
136 enum TestFunc { T_REQUIRES=1, T_GREATERTHAN, T_LESSTHAN, T_EQUALS,
137 T_EXISTS, T_EXPORT, T_CLEAR, T_UNSET, T_EVAL, T_CONFIG, T_SYSTEM,
138 T_RETURN, T_BREAK, T_NEXT, T_DEFINED, T_CONTAINS, T_INFILE,
139 T_COUNT, T_ISEMPTY, T_INCLUDE, T_LOAD,
140 T_DEBUG, T_ERROR, T_MESSAGE, T_WARNING, T_LOG,
141 T_IF, T_OPTION, T_CACHE, T_MKPATH, T_WRITE_FILE, T_TOUCH };
142 QHash<QString, TestFunc> qmake_testFunctions()
144 static QHash<QString, TestFunc> *qmake_test_functions = 0;
145 if(!qmake_test_functions) {
146 qmake_test_functions = new QHash<QString, TestFunc>;
147 qmake_test_functions->insert("requires", T_REQUIRES);
148 qmake_test_functions->insert("greaterThan", T_GREATERTHAN);
149 qmake_test_functions->insert("lessThan", T_LESSTHAN);
150 qmake_test_functions->insert("equals", T_EQUALS);
151 qmake_test_functions->insert("isEqual", T_EQUALS);
152 qmake_test_functions->insert("exists", T_EXISTS);
153 qmake_test_functions->insert("export", T_EXPORT);
154 qmake_test_functions->insert("clear", T_CLEAR);
155 qmake_test_functions->insert("unset", T_UNSET);
156 qmake_test_functions->insert("eval", T_EVAL);
157 qmake_test_functions->insert("CONFIG", T_CONFIG);
158 qmake_test_functions->insert("if", T_IF);
159 qmake_test_functions->insert("isActiveConfig", T_CONFIG);
160 qmake_test_functions->insert("system", T_SYSTEM);
161 qmake_test_functions->insert("return", T_RETURN);
162 qmake_test_functions->insert("break", T_BREAK);
163 qmake_test_functions->insert("next", T_NEXT);
164 qmake_test_functions->insert("defined", T_DEFINED);
165 qmake_test_functions->insert("contains", T_CONTAINS);
166 qmake_test_functions->insert("infile", T_INFILE);
167 qmake_test_functions->insert("count", T_COUNT);
168 qmake_test_functions->insert("isEmpty", T_ISEMPTY);
169 qmake_test_functions->insert("include", T_INCLUDE);
170 qmake_test_functions->insert("load", T_LOAD);
171 qmake_test_functions->insert("debug", T_DEBUG);
172 qmake_test_functions->insert("error", T_ERROR);
173 qmake_test_functions->insert("message", T_MESSAGE);
174 qmake_test_functions->insert("warning", T_WARNING);
175 qmake_test_functions->insert("log", T_LOG);
176 qmake_test_functions->insert("option", T_OPTION);
177 qmake_test_functions->insert("cache", T_CACHE);
178 qmake_test_functions->insert("mkpath", T_MKPATH);
179 qmake_test_functions->insert("write_file", T_WRITE_FILE);
180 qmake_test_functions->insert("touch", T_TOUCH);
182 return *qmake_test_functions;
191 static QString cached_source_root;
192 static QString cached_build_root;
193 static QStringList cached_qmakepath;
194 static QStringList cached_qmakefeatures;
196 static QStringList *all_feature_roots[2] = { 0, 0 };
199 invalidateFeatureRoots()
201 for (int i = 0; i < 2; i++)
202 if (all_feature_roots[i])
203 all_feature_roots[i]->clear();
206 static QString remove_quotes(const QString &arg)
208 const ushort SINGLEQUOTE = '\'';
209 const ushort DOUBLEQUOTE = '"';
211 const QChar *arg_data = arg.data();
212 const ushort first = arg_data->unicode();
213 const int arg_len = arg.length();
214 if(first == SINGLEQUOTE || first == DOUBLEQUOTE) {
215 const ushort last = (arg_data+arg_len-1)->unicode();
217 return arg.mid(1, arg_len-2);
222 static QString varMap(const QString &x)
225 if(ret == "INTERFACES")
227 else if(ret == "QMAKE_POST_BUILD")
228 ret = "QMAKE_POST_LINK";
229 else if(ret == "TARGETDEPS")
230 ret = "POST_TARGETDEPS";
231 else if(ret == "LIBPATH")
232 ret = "QMAKE_LIBDIR";
233 else if(ret == "QMAKE_EXT_MOC")
234 ret = "QMAKE_EXT_CPP_MOC";
235 else if(ret == "QMAKE_MOD_MOC")
236 ret = "QMAKE_H_MOD_MOC";
237 else if(ret == "QMAKE_LFLAGS_SHAPP")
238 ret = "QMAKE_LFLAGS_APP";
239 else if(ret == "PRECOMPH")
240 ret = "PRECOMPILED_HEADER";
241 else if(ret == "PRECOMPCPP")
242 ret = "PRECOMPILED_SOURCE";
243 else if(ret == "INCPATH")
245 else if(ret == "QMAKE_EXTRA_WIN_COMPILERS" || ret == "QMAKE_EXTRA_UNIX_COMPILERS")
246 ret = "QMAKE_EXTRA_COMPILERS";
247 else if(ret == "QMAKE_EXTRA_WIN_TARGETS" || ret == "QMAKE_EXTRA_UNIX_TARGETS")
248 ret = "QMAKE_EXTRA_TARGETS";
249 else if(ret == "QMAKE_EXTRA_UNIX_INCLUDES")
250 ret = "QMAKE_EXTRA_INCLUDES";
251 else if(ret == "QMAKE_EXTRA_UNIX_VARIABLES")
252 ret = "QMAKE_EXTRA_VARIABLES";
253 else if(ret == "QMAKE_RPATH")
254 ret = "QMAKE_LFLAGS_RPATH";
255 else if(ret == "QMAKE_FRAMEWORKDIR")
256 ret = "QMAKE_FRAMEWORKPATH";
257 else if(ret == "QMAKE_FRAMEWORKDIR_FLAGS")
258 ret = "QMAKE_FRAMEWORKPATH_FLAGS";
259 else if(ret == "IN_PWD")
263 warn_msg(WarnDeprecated, "%s:%d: Variable %s is deprecated; use %s instead.",
264 parser.file.toLatin1().constData(), parser.line_no,
265 x.toLatin1().constData(), ret.toLatin1().constData());
269 static QStringList split_arg_list(const QString ¶ms)
274 const ushort LPAREN = '(';
275 const ushort RPAREN = ')';
276 const ushort SINGLEQUOTE = '\'';
277 const ushort DOUBLEQUOTE = '"';
278 const ushort BACKSLASH = '\\';
279 const ushort COMMA = ',';
280 const ushort SPACE = ' ';
281 //const ushort TAB = '\t';
283 const QChar *params_data = params.data();
284 const int params_len = params.length();
285 for(int last = 0; ;) {
286 while(last < params_len && (params_data[last].unicode() == SPACE
287 /*|| params_data[last].unicode() == TAB*/))
289 for(int x = last, parens = 0; ; x++) {
290 if(x == params_len) {
291 while(x > last && params_data[x-1].unicode() == SPACE)
293 args << params.mid(last, x - last);
294 // Could do a check for unmatched parens here, but split_value_list()
295 // is called on all our output, so mistakes will be caught anyway.
298 ushort unicode = params_data[x].unicode();
299 if(x != (int)params_len-1 && unicode == BACKSLASH &&
300 (params_data[x+1].unicode() == SINGLEQUOTE || params_data[x+1].unicode() == DOUBLEQUOTE)) {
301 x++; //get that 'escape'
302 } else if(quote && unicode == quote) {
304 } else if(!quote && (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE)) {
306 } else if(unicode == RPAREN) {
308 } else if(unicode == LPAREN) {
311 if(!parens && !quote && unicode == COMMA) {
314 while(x > prev && params_data[x-1].unicode() == SPACE)
316 args << params.mid(prev, x - prev);
323 static QStringList split_value_list(const QString &vals)
330 const ushort LPAREN = '(';
331 const ushort RPAREN = ')';
332 const ushort SINGLEQUOTE = '\'';
333 const ushort DOUBLEQUOTE = '"';
334 const ushort BACKSLASH = '\\';
337 const QChar *vals_data = vals.data();
338 const int vals_len = vals.length();
339 for(int x = 0; x < vals_len; x++) {
340 unicode = vals_data[x].unicode();
341 if(x != (int)vals_len-1 && unicode == BACKSLASH &&
342 (vals_data[x+1].unicode() == SINGLEQUOTE || vals_data[x+1].unicode() == DOUBLEQUOTE)) {
343 build += vals_data[x++]; //get that 'escape'
344 } else if(quote && unicode == quote) {
346 } else if(!quote && (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE)) {
348 } else if(unicode == RPAREN) {
350 } else if(unicode == LPAREN) {
354 if(!parens && !quote && (vals_data[x] == Option::field_sep)) {
358 build += vals_data[x];
364 warn_msg(WarnDeprecated, "%s:%d: Unmatched parentheses are deprecated.",
365 parser.file.toLatin1().constData(), parser.line_no);
366 // Could do a check for unmatched quotes here, but doVariableReplaceExpand()
367 // is called on all our output, so mistakes will be caught anyway.
371 //just a parsable entity
374 ParsableBlock() : ref_cnt(1) { }
375 virtual ~ParsableBlock() { }
380 Parse(const QString &t) : text(t){ pi = parser; }
382 QList<Parse> parselist;
384 inline int ref() { return ++ref_cnt; }
385 inline int deref() { return --ref_cnt; }
389 virtual bool continueBlock() = 0;
390 bool eval(QMakeProject *p, QHash<QString, QStringList> &place);
393 bool ParsableBlock::eval(QMakeProject *p, QHash<QString, QStringList> &place)
396 parser_info pi = parser;
397 const int block_count = p->scope_blocks.count();
401 for(int i = 0; i < parselist.count(); i++) {
402 parser = parselist.at(i).pi;
403 if(!(ret = p->parse(parselist.at(i).text, place)) || !continueBlock())
409 while(p->scope_blocks.count() > block_count)
410 p->scope_blocks.pop();
415 struct FunctionBlock : public ParsableBlock
417 FunctionBlock() : calling_place(0), scope_level(1), cause_return(false) { }
419 QHash<QString, QStringList> vars;
420 QHash<QString, QStringList> *calling_place;
421 QStringList return_value;
425 bool exec(const QList<QStringList> &args,
426 QMakeProject *p, QHash<QString, QStringList> &place, QStringList &functionReturn);
427 virtual bool continueBlock() { return !cause_return; }
430 bool FunctionBlock::exec(const QList<QStringList> &args,
431 QMakeProject *proj, QHash<QString, QStringList> &place,
432 QStringList &functionReturn)
436 calling_place = &place;
438 calling_place = &proj->variables();
440 return_value.clear();
441 cause_return = false;
445 vars = proj->variables(); // should be place so that local variables can be inherited
449 vars["ARGS"].clear();
450 for(int i = 0; i < args.count(); i++) {
451 vars["ARGS"] += args[i];
452 vars[QString::number(i+1)] = args[i];
454 bool ret = ParsableBlock::eval(proj, vars);
455 functionReturn = return_value;
459 return_value.clear();
465 struct IteratorBlock : public ParsableBlock
467 IteratorBlock() : scope_level(1), loop_forever(false), cause_break(false), cause_next(false) { }
476 Test(const QString &f, QStringList &a, bool i) : func(f), args(a), invert(i) { pi = parser; }
482 bool loop_forever, cause_break, cause_next;
485 bool exec(QMakeProject *p, QHash<QString, QStringList> &place);
486 virtual bool continueBlock() { return !cause_next && !cause_break; }
488 bool IteratorBlock::exec(QMakeProject *p, QHash<QString, QStringList> &place)
491 QStringList::Iterator it;
494 int iterate_count = 0;
496 IteratorBlock *saved_iterator = p->iterator;
500 while(loop_forever || it != list.end()) {
501 cause_next = cause_break = false;
502 if(!loop_forever && (*it).isEmpty()) { //ignore empty items
507 //set up the loop variable
509 if(!variable.isEmpty()) {
510 va = place[variable];
512 place[variable] = QStringList(QString::number(iterate_count));
514 place[variable] = QStringList(*it);
518 for(QList<Test>::Iterator test_it = test.begin(); test_it != test.end(); ++test_it) {
519 parser = (*test_it).pi;
520 succeed = p->doProjectTest((*test_it).func, (*test_it).args, place);
521 if((*test_it).invert)
527 ret = ParsableBlock::eval(p, place);
528 //restore the variable in the map
529 if(!variable.isEmpty())
530 place[variable] = va;
535 if(!ret || cause_break)
540 p->iterator = saved_iterator;
544 QMakeProject::ScopeBlock::~ScopeBlock()
552 static void qmake_error_msg(const QString &msg)
554 fprintf(stderr, "%s:%d: %s\n", parser.file.toLatin1().constData(), parser.line_no,
555 msg.toLatin1().constData());
559 1) environment variable QMAKEFEATURES (as separated by colons)
560 2) property variable QMAKEFEATURES (as separated by colons)
561 3) <project_root> (where .qmake.cache lives) + FEATURES_DIR
562 4) environment variable QMAKEPATH (as separated by colons) + /mkspecs/FEATURES_DIR
563 5) your QMAKESPEC/features dir
564 6) your data_install/mkspecs/FEATURES_DIR
565 7) your QMAKESPEC/../FEATURES_DIR dir
567 FEATURES_DIR is defined as:
569 1) features/(unix|win32|macx)/
572 QStringList QMakeProject::qmakeFeaturePaths()
574 const QString mkspecs_concat = QLatin1String("/mkspecs");
575 const QString base_concat = QLatin1String("/features");
577 foreach (const QString &sfx, values("QMAKE_PLATFORM"))
578 concat << base_concat + QLatin1Char('/') + sfx;
579 concat << base_concat;
581 QStringList feature_roots = splitPathList(QString::fromLocal8Bit(qgetenv("QMAKEFEATURES")));
582 feature_roots += cached_qmakefeatures;
584 feature_roots += splitPathList(prop->value("QMAKEFEATURES"));
585 QStringList feature_bases;
586 if (!cached_build_root.isEmpty())
587 feature_bases << cached_build_root;
588 if (!cached_source_root.isEmpty())
589 feature_bases << cached_source_root;
590 QStringList qmakepath = splitPathList(QString::fromLocal8Bit(qgetenv("QMAKEPATH")));
591 qmakepath += cached_qmakepath;
592 foreach (const QString &path, qmakepath)
593 feature_bases << (path + mkspecs_concat);
594 if (!real_spec.isEmpty()) {
595 // The spec is already platform-dependent, so no subdirs here.
596 feature_roots << real_spec + base_concat;
598 // Also check directly under the root directory of the mkspecs collection
599 QFileInfo specfi(real_spec);
600 QDir specrootdir(specfi.absolutePath());
601 while (!specrootdir.isRoot()) {
602 const QString specrootpath = specrootdir.path();
603 if (specrootpath.endsWith(mkspecs_concat)) {
604 if (QFile::exists(specrootpath + base_concat))
605 feature_bases << specrootpath;
611 feature_bases << (QLibraryInfo::rawLocation(QLibraryInfo::HostDataPath,
612 QLibraryInfo::EffectivePaths) + mkspecs_concat);
613 foreach (const QString &fb, feature_bases)
614 foreach (const QString &cc, concat)
615 feature_roots << (fb + cc);
616 feature_roots.removeDuplicates();
619 foreach (const QString &root, feature_roots)
620 if (QFileInfo(root).exists())
625 QStringList qmake_mkspec_paths()
628 const QString concat = QLatin1String("/mkspecs");
630 QStringList qmakepath = splitPathList(QString::fromLocal8Bit(qgetenv("QMAKEPATH")));
631 qmakepath += cached_qmakepath;
632 foreach (const QString &path, qmakepath)
633 ret << (path + concat);
634 if (!cached_build_root.isEmpty())
635 ret << cached_build_root + concat;
636 if (!cached_source_root.isEmpty())
637 ret << cached_source_root + concat;
638 ret << QLibraryInfo::rawLocation(QLibraryInfo::HostDataPath, QLibraryInfo::EffectivePaths) + concat;
639 ret.removeDuplicates();
645 setTemplate(QStringList &varlist)
647 if (!Option::user_template.isEmpty()) { // Don't permit override
648 varlist = QStringList(Option::user_template);
650 if (varlist.isEmpty())
653 varlist.erase(varlist.begin() + 1, varlist.end());
655 if (!Option::user_template_prefix.isEmpty()
656 && !varlist.first().startsWith(Option::user_template_prefix)) {
657 varlist.first().prepend(Option::user_template_prefix);
661 QMakeProject::~QMakeProject()
670 QMakeProject::init(QMakeProperty *p)
673 prop = new QMakeProperty;
684 QMakeProject::cleanup()
686 for (QHash<QString, FunctionBlock*>::iterator it = replaceFunctions.begin(); it != replaceFunctions.end(); ++it)
687 if (!it.value()->deref())
689 replaceFunctions.clear();
690 for (QHash<QString, FunctionBlock*>::iterator it = testFunctions.begin(); it != testFunctions.end(); ++it)
691 if (!it.value()->deref())
693 testFunctions.clear();
696 // Duplicate project. It is *not* allowed to call the complex read() functions on the copy.
697 QMakeProject::QMakeProject(QMakeProject *p, const QHash<QString, QStringList> *_vars)
699 init(p->properties());
700 vars = _vars ? *_vars : p->variables();
701 host_build = p->host_build;
702 for(QHash<QString, FunctionBlock*>::iterator it = p->replaceFunctions.begin(); it != p->replaceFunctions.end(); ++it) {
704 replaceFunctions.insert(it.key(), it.value());
706 for(QHash<QString, FunctionBlock*>::iterator it = p->testFunctions.begin(); it != p->testFunctions.end(); ++it) {
708 testFunctions.insert(it.key(), it.value());
713 QMakeProject::reset()
715 // scope_blocks starts with one non-ignoring entity
716 scope_blocks.clear();
717 scope_blocks.push(ScopeBlock());
720 backslashWarned = false;
721 need_restart = false;
725 QMakeProject::parse(const QString &t, QHash<QString, QStringList> &place, int numLines)
727 // To preserve the integrity of any UTF-8 characters in .pro file, temporarily replace the
728 // non-breaking space (0xA0) characters with another non-space character, so that
729 // QString::simplified() call will not replace it with space.
730 // Note: There won't be any two byte characters in .pro files, so 0x10A0 should be a safe
731 // replacement character.
732 static QChar nbsp(0xA0);
733 static QChar nbspFix(0x01A0);
735 if (t.indexOf(nbsp) != -1) {
737 s.replace(nbsp, nbspFix);
739 s.replace(nbspFix, nbsp);
744 int hash_mark = s.indexOf("#");
745 if(hash_mark != -1) //good bye comments
746 s = s.left(hash_mark);
747 if(s.isEmpty()) // blank_line
750 if(scope_blocks.top().ignore) {
751 bool continue_parsing = false;
752 // adjust scope for each block which appears on a single line
753 for(int i = 0; i < s.length(); i++) {
755 scope_blocks.push(ScopeBlock(true));
756 } else if(s[i] == '}') {
757 if(scope_blocks.count() == 1) {
758 fprintf(stderr, "Braces mismatch %s:%d\n", parser.file.toLatin1().constData(), parser.line_no);
761 ScopeBlock sb = scope_blocks.pop();
763 sb.iterate->exec(this, place);
767 if(!scope_blocks.top().ignore) {
768 debug_msg(1, "Project Parser: %s:%d : Leaving block %d", parser.file.toLatin1().constData(),
769 parser.line_no, scope_blocks.count()+1);
770 s = s.mid(i+1).trimmed();
771 continue_parsing = !s.isEmpty();
776 if(!continue_parsing) {
777 debug_msg(1, "Project Parser: %s:%d : Ignored due to block being false.",
778 parser.file.toLatin1().constData(), parser.line_no);
786 const QChar *d = s.unicode();
787 bool function_finished = false;
788 while(d_off < s.length()) {
789 if(*(d+d_off) == QLatin1Char('}')) {
790 function->scope_level--;
791 if(!function->scope_level) {
792 function_finished = true;
795 } else if(*(d+d_off) == QLatin1Char('{')) {
796 function->scope_level++;
798 append += *(d+d_off);
801 if(!append.isEmpty())
802 function->parselist.append(IteratorBlock::Parse(append));
803 if(function_finished) {
805 s = QString(d+d_off, s.length()-d_off);
809 } else if(IteratorBlock *it = scope_blocks.top().iterate) {
812 const QChar *d = s.unicode();
813 bool iterate_finished = false;
814 while(d_off < s.length()) {
815 if(*(d+d_off) == QLatin1Char('}')) {
817 if(!it->scope_level) {
818 iterate_finished = true;
821 } else if(*(d+d_off) == QLatin1Char('{')) {
824 append += *(d+d_off);
827 if(!append.isEmpty())
828 scope_blocks.top().iterate->parselist.append(IteratorBlock::Parse(append));
829 if(iterate_finished) {
830 scope_blocks.top().iterate = 0;
831 bool ret = it->exec(this, place);
841 QString scope, var, op;
843 #define SKIP_WS(d, o, l) while(o < l && (*(d+o) == QLatin1Char(' ') || *(d+o) == QLatin1Char('\t'))) ++o
844 const QChar *d = s.unicode();
846 SKIP_WS(d, d_off, s.length());
847 IteratorBlock *iterator = 0;
848 bool scope_failed = false, else_line = false, or_op=false;
850 int parens = 0, scope_count=0, start_block = 0;
851 while(d_off < s.length()) {
853 if(*(d+d_off) == QLatin1Char('='))
855 if(*(d+d_off) == QLatin1Char('+') || *(d+d_off) == QLatin1Char('-') ||
856 *(d+d_off) == QLatin1Char('*') || *(d+d_off) == QLatin1Char('~')) {
857 if(*(d+d_off+1) == QLatin1Char('=')) {
859 } else if(*(d+d_off+1) == QLatin1Char(' ')) {
860 const QChar *k = d+d_off+1;
862 SKIP_WS(k, k_off, s.length()-d_off);
863 if(*(k+k_off) == QLatin1Char('=')) {
865 qmake_error_msg(QString(d+d_off, 1) + "must be followed immediately by =");
872 if(!quote.isNull()) {
873 if(*(d+d_off) == quote)
875 } else if(*(d+d_off) == '(') {
877 } else if(*(d+d_off) == ')') {
879 } else if(*(d+d_off) == '"' /*|| *(d+d_off) == '\''*/) {
883 if(!parens && quote.isNull() &&
884 (*(d+d_off) == QLatin1Char(':') || *(d+d_off) == QLatin1Char('{') ||
885 *(d+d_off) == QLatin1Char(')') || *(d+d_off) == QLatin1Char('|'))) {
887 scope = var.trimmed();
888 if(*(d+d_off) == QLatin1Char(')'))
889 scope += *(d+d_off); // need this
892 bool test = scope_failed;
893 if(scope.isEmpty()) {
895 } else if(scope.toLower() == "else") { //else is a builtin scope here as it modifies state
896 if(scope_count != 1 || scope_blocks.top().else_status == ScopeBlock::TestNone) {
897 qmake_error_msg(("Unexpected " + scope + " ('" + s + "')").toLatin1());
901 test = (scope_blocks.top().else_status == ScopeBlock::TestSeek);
902 debug_msg(1, "Project Parser: %s:%d : Else%s %s.", parser.file.toLatin1().constData(), parser.line_no,
903 scope == "else" ? "" : QString(" (" + scope + ")").toLatin1().constData(),
904 test ? "considered" : "excluded");
906 QString comp_scope = scope;
907 bool invert_test = (comp_scope.at(0) == QLatin1Char('!'));
909 comp_scope = comp_scope.mid(1);
910 int lparen = comp_scope.indexOf('(');
911 if(or_op == scope_failed) {
912 if(lparen != -1) { // if there is an lparen in the scope, it IS a function
913 int rparen = comp_scope.lastIndexOf(')');
915 qmake_error_msg("Function missing right paren: " + comp_scope);
918 QString func = comp_scope.left(lparen);
919 QStringList args = split_arg_list(comp_scope.mid(lparen+1, rparen - lparen - 1));
921 fprintf(stderr, "%s:%d: No tests can come after a function definition!\n",
922 parser.file.toLatin1().constData(), parser.line_no);
924 } else if(func == "for") { //for is a builtin function here, as it modifies state
925 if(args.count() > 2 || args.count() < 1) {
926 fprintf(stderr, "%s:%d: for(iterate, list) requires two arguments.\n",
927 parser.file.toLatin1().constData(), parser.line_no);
929 } else if(iterator) {
930 fprintf(stderr, "%s:%d unexpected nested for()\n",
931 parser.file.toLatin1().constData(), parser.line_no);
935 iterator = new IteratorBlock;
937 if(args.count() == 1) {
938 doVariableReplace(args[0], place);
940 if(args[0] != "ever") {
943 fprintf(stderr, "%s:%d: for(iterate, list) requires two arguments.\n",
944 parser.file.toLatin1().constData(), parser.line_no);
948 } else if(args.count() == 2) {
949 iterator->variable = args[0];
950 doVariableReplace(args[1], place);
953 QStringList list = place[it_list];
955 if(it_list == "forever") {
956 iterator->loop_forever = true;
958 int dotdot = it_list.indexOf("..");
961 int start = it_list.left(dotdot).toInt(&ok);
963 int end = it_list.mid(dotdot+2).toInt(&ok);
966 for(int i = start; i <= end; i++)
967 list << QString::number(i);
969 for(int i = start; i >= end; i--)
970 list << QString::number(i);
977 iterator->list = list;
979 } else if(iterator) {
980 iterator->test.append(IteratorBlock::Test(func, args, invert_test));
982 } else if(func == "defineTest" || func == "defineReplace") {
983 if(!function_blocks.isEmpty()) {
985 "%s:%d: cannot define a function within another definition.\n",
986 parser.file.toLatin1().constData(), parser.line_no);
989 if(args.count() != 1) {
990 fprintf(stderr, "%s:%d: %s(function_name) requires one argument.\n",
991 parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
994 QHash<QString, FunctionBlock*> *map = 0;
995 if(func == "defineTest")
996 map = &testFunctions;
998 map = &replaceFunctions;
1000 if(!map || map->contains(args[0])) {
1001 fprintf(stderr, "%s:%d: Function[%s] multiply defined.\n",
1002 parser.file.toLatin1().constData(), parser.line_no, args[0].toLatin1().constData());
1006 function = new FunctionBlock;
1007 map->insert(args[0], function);
1010 test = doProjectTest(func, args, place);
1011 if(*(d+d_off) == QLatin1Char(')') && d_off == s.length()-1) {
1014 scope_blocks.top().else_status =
1015 (test ? ScopeBlock::TestFound : ScopeBlock::TestSeek);
1016 return true; // assume we are done
1020 QString cscope = comp_scope.trimmed();
1021 doVariableReplace(cscope, place);
1022 test = isActiveConfig(cscope.trimmed(), true, &place);
1028 if(!test && !scope_failed)
1029 debug_msg(1, "Project Parser: %s:%d : Test (%s) failed.", parser.file.toLatin1().constData(),
1030 parser.line_no, scope.toLatin1().constData());
1032 scope_failed = !test;
1033 or_op = (*(d+d_off) == QLatin1Char('|'));
1035 if(*(d+d_off) == QLatin1Char('{')) { // scoping block
1038 for(int off = 0, braces = 0; true; ++off) {
1039 if(*(d+d_off+off) == QLatin1Char('{'))
1041 else if(*(d+d_off+off) == QLatin1Char('}') && braces)
1043 if(!braces || d_off+off == s.length()) {
1044 iterator->parselist.append(s.mid(d_off, off-1));
1046 iterator->scope_level += braces-1;
1053 } else if(!parens && *(d+d_off) == QLatin1Char('}')) {
1056 } else if(!scope_blocks.count()) {
1057 warn_msg(WarnParser, "Possible braces mismatch %s:%d", parser.file.toLatin1().constData(), parser.line_no);
1059 if(scope_blocks.count() == 1) {
1060 fprintf(stderr, "Braces mismatch %s:%d\n", parser.file.toLatin1().constData(), parser.line_no);
1063 debug_msg(1, "Project Parser: %s:%d : Leaving block %d", parser.file.toLatin1().constData(),
1064 parser.line_no, scope_blocks.count());
1065 ScopeBlock sb = scope_blocks.pop();
1067 sb.iterate->exec(this, place);
1074 var = var.trimmed();
1076 if(!else_line || (else_line && !scope_failed))
1077 scope_blocks.top().else_status = (!scope_failed ? ScopeBlock::TestFound : ScopeBlock::TestSeek);
1079 ScopeBlock next_block(scope_failed);
1080 next_block.iterate = iterator;
1082 next_block.else_status = ScopeBlock::TestNone;
1083 else if(scope_failed)
1084 next_block.else_status = ScopeBlock::TestSeek;
1086 next_block.else_status = ScopeBlock::TestFound;
1087 scope_blocks.push(next_block);
1088 debug_msg(1, "Project Parser: %s:%d : Entering block %d (%d). [%s]", parser.file.toLatin1().constData(),
1089 parser.line_no, scope_blocks.count(), scope_failed, s.toLatin1().constData());
1090 } else if(iterator) {
1091 iterator->parselist.append(QString(var+s.mid(d_off)));
1092 bool ret = iterator->exec(this, place);
1097 if((!scope_count && !var.isEmpty()) || (scope_count == 1 && else_line))
1098 scope_blocks.top().else_status = ScopeBlock::TestNone;
1099 if(d_off == s.length()) {
1100 if(!var.trimmed().isEmpty())
1101 qmake_error_msg(("Parse Error ('" + s + "')").toLatin1());
1102 return var.isEmpty(); // allow just a scope
1105 SKIP_WS(d, d_off, s.length());
1106 for(; d_off < s.length() && op.indexOf('=') == -1; op += *(d+(d_off++)))
1108 op.replace(QRegExp("\\s"), "");
1110 SKIP_WS(d, d_off, s.length());
1111 QString vals = s.mid(d_off); // vals now contains the space separated list of values
1112 int rbraces = vals.count('}'), lbraces = vals.count('{');
1113 if(scope_blocks.count() > 1 && rbraces - lbraces == 1 && vals.endsWith('}')) {
1114 debug_msg(1, "Project Parser: %s:%d : Leaving block %d", parser.file.toLatin1().constData(),
1115 parser.line_no, scope_blocks.count());
1116 ScopeBlock sb = scope_blocks.pop();
1118 sb.iterate->exec(this, place);
1119 vals.truncate(vals.length()-1);
1120 } else if(rbraces != lbraces) {
1121 warn_msg(WarnParser, "Possible braces mismatch {%s} %s:%d",
1122 vals.toLatin1().constData(), parser.file.toLatin1().constData(), parser.line_no);
1125 return true; // oh well
1128 doVariableReplace(var, place);
1129 var = varMap(var); //backwards compatibility
1131 if(vals.contains('=') && numLines > 1)
1132 warn_msg(WarnParser, "Possible accidental line continuation: {%s} at %s:%d",
1133 var.toLatin1().constData(), parser.file.toLatin1().constData(), parser.line_no);
1135 QStringList &varlist = place[var]; // varlist is the list in the symbol table
1137 if(Option::debug_level >= 1) {
1138 QString tmp_vals = vals;
1139 doVariableReplace(tmp_vals, place);
1140 debug_msg(1, "Project Parser: %s:%d :%s: :%s: (%s)", parser.file.toLatin1().constData(), parser.line_no,
1141 var.toLatin1().constData(), op.toLatin1().constData(), tmp_vals.toLatin1().constData());
1144 // now do the operation
1146 doVariableReplace(vals, place);
1147 if(vals.length() < 4 || vals.at(0) != 's') {
1148 qmake_error_msg(("~= operator only can handle s/// function ('" +
1149 s + "')").toLatin1());
1152 QChar sep = vals.at(1);
1153 QStringList func = vals.split(sep);
1154 if(func.count() < 3 || func.count() > 4) {
1155 qmake_error_msg(("~= operator only can handle s/// function ('" +
1156 s + "')").toLatin1());
1159 bool global = false, case_sense = true, quote = false;
1160 if(func.count() == 4) {
1161 global = func[3].indexOf('g') != -1;
1162 case_sense = func[3].indexOf('i') == -1;
1163 quote = func[3].indexOf('q') != -1;
1165 QString from = func[1], to = func[2];
1167 from = QRegExp::escape(from);
1168 QRegExp regexp(from, case_sense ? Qt::CaseSensitive : Qt::CaseInsensitive);
1169 for(QStringList::Iterator varit = varlist.begin(); varit != varlist.end();) {
1170 if((*varit).contains(regexp)) {
1171 (*varit) = (*varit).replace(regexp, to);
1172 if ((*varit).isEmpty())
1173 varit = varlist.erase(varit);
1182 QStringList vallist;
1184 //doVariableReplace(vals, place);
1185 QStringList tmp = split_value_list(vals);
1186 for(int i = 0; i < tmp.size(); ++i)
1187 vallist += doVariableReplaceExpand(tmp[i], place);
1191 #if 0 // This is way too noisy
1192 if(!varlist.isEmpty()) {
1193 bool send_warning = false;
1194 if(var != "TEMPLATE" && var != "TARGET") {
1195 QSet<QString> incoming_vals = vallist.toSet();
1196 for(int i = 0; i < varlist.size(); ++i) {
1197 const QString var = varlist.at(i).trimmed();
1198 if(!var.isEmpty() && !incoming_vals.contains(var)) {
1199 send_warning = true;
1205 warn_msg(WarnParser, "Operator=(%s) clears variables previously set: %s:%d",
1206 var.toLatin1().constData(), parser.file.toLatin1().constData(), parser.line_no);
1211 for(QStringList::ConstIterator valit = vallist.begin();
1212 valit != vallist.end(); ++valit) {
1213 if((*valit).isEmpty())
1215 if((op == "*=" && !varlist.contains((*valit))) ||
1216 op == "=" || op == "+=")
1217 varlist.append((*valit));
1219 varlist.removeAll((*valit));
1221 if(var == "REQUIRES") // special case to get communicated to backends!
1222 doProjectCheckReqs(vallist, place);
1223 else if (var == QLatin1String("TEMPLATE"))
1224 setTemplate(varlist);
1230 QMakeProject::read(QTextStream &file, QHash<QString, QStringList> &place)
1235 while(!file.atEnd()) {
1237 QString line = file.readLine().trimmed();
1238 int prelen = line.length();
1240 int hash_mark = line.indexOf("#");
1241 if(hash_mark != -1) //good bye comments
1242 line = line.left(hash_mark).trimmed();
1243 if(!line.isEmpty() && line.right(1) == "\\") {
1244 if(!line.startsWith("#")) {
1245 line.truncate(line.length() - 1);
1246 s += line + Option::field_sep;
1249 } else if(!line.isEmpty() || (line.isEmpty() && !prelen)) {
1250 if(s.isEmpty() && line.isEmpty())
1252 if(!line.isEmpty()) {
1257 if(!(ret = parse(s, place, numLines))) {
1270 ret = parse(s, place, numLines);
1275 QMakeProject::read(const QString &file, QHash<QString, QStringList> &place)
1277 parser_info pi = parser;
1280 const QString oldpwd = qmake_getpwd();
1281 QString filename = Option::normalizePath(file, false);
1282 bool ret = false, using_stdin = false;
1284 if(filename == QLatin1String("-")) {
1285 qfile.setFileName("");
1286 ret = qfile.open(stdin, QIODevice::ReadOnly);
1288 } else if(QFileInfo(file).isDir()) {
1291 qfile.setFileName(filename);
1292 ret = qfile.open(QIODevice::ReadOnly);
1293 qmake_setpwd(QFileInfo(filename).absolutePath());
1296 place["PWD"] = QStringList(qmake_getpwd());
1297 parser_info pi = parser;
1298 parser.from_file = true;
1299 parser.file = filename;
1301 if (qfile.peek(3) == QByteArray("\xef\xbb\xbf")) {
1302 //UTF-8 BOM will cause subtle errors
1303 qmake_error_msg("Unexpected UTF-8 BOM found");
1306 QTextStream t(&qfile);
1307 ret = read(t, place);
1312 if (!need_restart && scope_blocks.count() != 1) {
1313 qmake_error_msg("Unterminated conditional block at end of file");
1317 qmake_setpwd(oldpwd);
1322 QMakeProject::read(const QString &project, uchar cmd)
1324 pfile = QFileInfo(project).absoluteFilePath();
1329 QMakeProject::read(uchar cmd)
1332 if (init_vars.isEmpty()) {
1338 if (cmd & ReadSetup) {
1339 if (base_vars.isEmpty()) {
1341 QString project_root;
1342 QStringList qmakepath;
1343 QStringList qmakefeatures;
1344 project_build_root.clear();
1345 if (Option::mkfile::do_cache) { // parse the cache
1346 QHash<QString, QStringList> cache;
1347 QString rdir = Option::output_dir;
1349 QFileInfo qfi(rdir, QLatin1String(".qmake.super"));
1351 superfile = qfi.filePath();
1352 if (!read(superfile, cache))
1357 QFileInfo qdfi(rdir);
1362 if (Option::mkfile::cachefile.isEmpty()) { //find it as it has not been specified
1363 QString sdir = qmake_getpwd();
1364 QString dir = Option::output_dir;
1366 QFileInfo qsfi(sdir, QLatin1String(".qmake.conf"));
1367 if (qsfi.exists()) {
1368 conffile = qsfi.filePath();
1369 if (!read(conffile, cache))
1372 QFileInfo qfi(dir, QLatin1String(".qmake.cache"));
1374 cachefile = qfi.filePath();
1375 if (!read(cachefile, cache))
1378 if (!conffile.isEmpty() || !cachefile.isEmpty()) {
1379 project_root = sdir;
1380 project_build_root = dir;
1383 if (dir == superdir)
1385 QFileInfo qsdfi(sdir);
1386 QFileInfo qdfi(dir);
1387 if (qsdfi.isRoot() || qdfi.isRoot())
1389 sdir = qsdfi.path();
1393 QFileInfo fi(Option::mkfile::cachefile);
1394 cachefile = QDir::cleanPath(fi.absoluteFilePath());
1395 if (!read(cachefile, cache))
1397 project_build_root = QDir::cleanPath(fi.absolutePath());
1398 // This intentionally bypasses finding a source root,
1399 // as the result would be more or less arbitrary.
1402 if (Option::mkfile::xqmakespec.isEmpty() && !cache["XQMAKESPEC"].isEmpty())
1403 Option::mkfile::xqmakespec = cache["XQMAKESPEC"].first();
1404 if (Option::mkfile::qmakespec.isEmpty() && !cache["QMAKESPEC"].isEmpty()) {
1405 Option::mkfile::qmakespec = cache["QMAKESPEC"].first();
1406 if (Option::mkfile::xqmakespec.isEmpty())
1407 Option::mkfile::xqmakespec = Option::mkfile::qmakespec;
1409 qmakepath = cache.value(QLatin1String("QMAKEPATH"));
1410 qmakefeatures = cache.value(QLatin1String("QMAKEFEATURES"));
1412 if (!superfile.isEmpty())
1413 vars["_QMAKE_SUPER_CACHE_"] << superfile;
1414 if (!cachefile.isEmpty())
1415 vars["_QMAKE_CACHE_"] << cachefile;
1418 // Look for mkspecs/ in source and build. First to win determines the root.
1419 QString sdir = qmake_getpwd();
1420 QString dir = Option::output_dir;
1421 while (dir != project_build_root) {
1422 if ((dir != sdir && QFileInfo(sdir, QLatin1String("mkspecs")).isDir())
1423 || QFileInfo(dir, QLatin1String("mkspecs")).isDir()) {
1425 project_root = sdir;
1426 project_build_root = dir;
1429 if (dir == superdir)
1431 QFileInfo qsdfi(sdir);
1432 QFileInfo qdfi(dir);
1433 if (qsdfi.isRoot() || qdfi.isRoot())
1435 sdir = qsdfi.path();
1439 if (qmakepath != cached_qmakepath || qmakefeatures != cached_qmakefeatures
1440 || project_build_root != cached_build_root) { // No need to check source dir, as it goes in sync
1441 cached_source_root = project_root;
1442 cached_build_root = project_build_root;
1443 cached_qmakepath = qmakepath;
1444 cached_qmakefeatures = qmakefeatures;
1445 invalidateFeatureRoots();
1449 QString *specp = host_build ? &Option::mkfile::qmakespec : &Option::mkfile::xqmakespec;
1450 QString qmakespec = *specp;
1451 if (qmakespec.isEmpty())
1452 qmakespec = host_build ? "default-host" : "default";
1453 if (QDir::isRelativePath(qmakespec)) {
1454 QStringList mkspec_roots = qmake_mkspec_paths();
1455 debug_msg(2, "Looking for mkspec %s in (%s)", qmakespec.toLatin1().constData(),
1456 mkspec_roots.join("::").toLatin1().constData());
1457 bool found_mkspec = false;
1458 for (QStringList::ConstIterator it = mkspec_roots.begin(); it != mkspec_roots.end(); ++it) {
1459 QString mkspec = (*it) + QLatin1Char('/') + qmakespec;
1460 if (QFile::exists(mkspec)) {
1461 found_mkspec = true;
1462 *specp = qmakespec = mkspec;
1466 if (!found_mkspec) {
1467 fprintf(stderr, "Could not find mkspecs for your QMAKESPEC(%s) after trying:\n\t%s\n",
1468 qmakespec.toLatin1().constData(), mkspec_roots.join("\n\t").toLatin1().constData());
1473 // We do this before reading the spec, so it can use module and feature paths from
1474 // here without resorting to tricks. This is the only planned use case anyway.
1475 if (!superfile.isEmpty()) {
1476 debug_msg(1, "Project super cache file: reading %s", superfile.toLatin1().constData());
1477 read(superfile, vars);
1480 // parse qmake configuration
1481 doProjectInclude("spec_pre", IncludeFlagFeature, vars);
1482 while(qmakespec.endsWith(QLatin1Char('/')))
1483 qmakespec.truncate(qmakespec.length()-1);
1484 QString spec = qmakespec + QLatin1String("/qmake.conf");
1485 debug_msg(1, "QMAKESPEC conf: reading %s", spec.toLatin1().constData());
1486 if (!read(spec, vars)) {
1487 fprintf(stderr, "Failure to read QMAKESPEC conf file %s.\n", spec.toLatin1().constData());
1491 real_spec = QFileInfo(qmakespec).canonicalFilePath();
1493 // We can't resolve symlinks as they do on Unix, so configure.exe puts the source of the
1494 // qmake.conf at the end of the default/qmake.conf in the QMAKESPEC_ORG variable.
1495 QString orig_spec = first(QLatin1String("QMAKESPEC_ORIGINAL"));
1496 real_spec = orig_spec.isEmpty() ? qmakespec : orig_spec;
1498 vars["QMAKESPEC"] << real_spec;
1499 short_spec = QFileInfo(real_spec).fileName();
1500 doProjectInclude("spec_post", IncludeFlagFeature, vars);
1501 // The spec extends the feature search path, so invalidate the cache.
1502 invalidateFeatureRoots();
1503 // The MinGW and x-build specs may change the separator; $$shell_{path,quote}() need it
1504 Option::dir_sep = first(QLatin1String("QMAKE_DIR_SEP"));
1506 if (!conffile.isEmpty()) {
1507 debug_msg(1, "Project config file: reading %s", conffile.toLatin1().constData());
1508 read(conffile, vars);
1510 if (!cachefile.isEmpty()) {
1511 debug_msg(1, "QMAKECACHE file: reading %s", cachefile.toLatin1().constData());
1512 read(cachefile, vars);
1518 vars = base_vars; // start with the base
1521 } else if (cmd & ReadFeatures) {
1522 // Even when ReadSetup is not set, but ReadFeatures is,
1523 // we still need to process spec_pre.prf to load some
1524 // default values and other settings.
1525 debug_msg(1, "Processing spec_pre (but skipping actual spec): %s", vars["CONFIG"].join("::").toLatin1().constData());
1526 doProjectInclude("spec_pre", IncludeFlagFeature, vars);
1529 for (QHash<QString, QStringList>::ConstIterator it = extra_vars.constBegin();
1530 it != extra_vars.constEnd(); ++it)
1531 vars.insert(it.key(), it.value());
1533 if(cmd & ReadFeatures) {
1534 debug_msg(1, "Processing default_pre: %s", vars["CONFIG"].join("::").toLatin1().constData());
1535 doProjectInclude("default_pre", IncludeFlagFeature, vars);
1538 //before commandline
1539 if (cmd & ReadSetup) {
1540 parser.file = "(internal)";
1541 parser.from_file = false;
1542 parser.line_no = 1; //really arg count now.. duh
1544 for(QStringList::ConstIterator it = Option::before_user_vars.begin();
1545 it != Option::before_user_vars.end(); ++it) {
1546 if(!parse((*it), vars)) {
1547 fprintf(stderr, "Argument failed to parse: %s\n", (*it).toLatin1().constData());
1554 // After user configs, to override them
1555 if (!extra_configs.isEmpty()) {
1556 parser.file = "(extra configs)";
1557 parser.from_file = false;
1558 parser.line_no = 1; //really arg count now.. duh
1559 parse("CONFIG += " + extra_configs.join(" "), vars);
1562 if(cmd & ReadProFile) { // parse project file
1563 debug_msg(1, "Project file: reading %s", pfile.toLatin1().constData());
1564 if(pfile != "-" && !QFile::exists(pfile) && !pfile.endsWith(Option::pro_ext))
1565 pfile += Option::pro_ext;
1566 if(!read(pfile, vars))
1575 if (cmd & ReadSetup) {
1576 parser.file = "(internal)";
1577 parser.from_file = false;
1578 parser.line_no = 1; //really arg count now.. duh
1580 for(QStringList::ConstIterator it = Option::after_user_vars.begin();
1581 it != Option::after_user_vars.end(); ++it) {
1582 if(!parse((*it), vars)) {
1583 fprintf(stderr, "Argument failed to parse: %s\n", (*it).toLatin1().constData());
1590 // Again, to ensure the project does not mess with us.
1591 // Specifically, do not allow a project to override debug/release within a
1592 // debug_and_release build pass - it's too late for that at this point anyway.
1593 if (!extra_configs.isEmpty()) {
1594 parser.file = "(extra configs)";
1595 parser.from_file = false;
1596 parser.line_no = 1; //really arg count now.. duh
1597 parse("CONFIG += " + extra_configs.join(" "), vars);
1600 if(cmd & ReadFeatures) {
1601 debug_msg(1, "Processing default_post: %s", vars["CONFIG"].join("::").toLatin1().constData());
1602 doProjectInclude("default_post", IncludeFlagFeature, vars);
1604 QHash<QString, bool> processed;
1605 const QStringList &configs = vars["CONFIG"];
1606 debug_msg(1, "Processing CONFIG features: %s", configs.join("::").toLatin1().constData());
1608 bool finished = true;
1609 for(int i = configs.size()-1; i >= 0; --i) {
1610 const QString config = configs[i].toLower();
1611 if(!processed.contains(config)) {
1612 processed.insert(config, true);
1613 if(doProjectInclude(config, IncludeFlagFeature, vars) == IncludeSuccess) {
1627 QMakeProject::setupProject()
1629 setTemplate(vars["TEMPLATE"]);
1631 vars["TARGET"] << QFileInfo(pfile).baseName();
1632 vars["_PRO_FILE_"] << pfile;
1633 vars["_PRO_FILE_PWD_"] << (pfile.isEmpty() ? qmake_getpwd() : QFileInfo(pfile).absolutePath());
1634 vars["OUT_PWD"] << Option::output_dir;
1638 QMakeProject::loadDefaults()
1640 vars["LITERAL_WHITESPACE"] << QLatin1String("\t");
1641 vars["LITERAL_DOLLAR"] << QLatin1String("$");
1642 vars["LITERAL_HASH"] << QLatin1String("#");
1643 vars["DIR_SEPARATOR"] << Option::dir_sep;
1644 vars["DIRLIST_SEPARATOR"] << Option::dirlist_sep;
1645 vars["QMAKE_QMAKE"] << Option::qmake_abslocation;
1646 vars["_DATE_"] << QDateTime::currentDateTime().toString();
1647 #if defined(Q_OS_WIN32)
1648 vars["QMAKE_HOST.os"] << QString::fromLatin1("Windows");
1650 DWORD name_length = 1024;
1652 if (GetComputerName(name, &name_length))
1653 vars["QMAKE_HOST.name"] << QString::fromWCharArray(name);
1655 QSysInfo::WinVersion ver = QSysInfo::WindowsVersion;
1656 vars["QMAKE_HOST.version"] << QString::number(ver);
1659 case QSysInfo::WV_Me: verStr = QLatin1String("WinMe"); break;
1660 case QSysInfo::WV_95: verStr = QLatin1String("Win95"); break;
1661 case QSysInfo::WV_98: verStr = QLatin1String("Win98"); break;
1662 case QSysInfo::WV_NT: verStr = QLatin1String("WinNT"); break;
1663 case QSysInfo::WV_2000: verStr = QLatin1String("Win2000"); break;
1664 case QSysInfo::WV_2003: verStr = QLatin1String("Win2003"); break;
1665 case QSysInfo::WV_XP: verStr = QLatin1String("WinXP"); break;
1666 case QSysInfo::WV_VISTA: verStr = QLatin1String("WinVista"); break;
1667 default: verStr = QLatin1String("Unknown"); break;
1669 vars["QMAKE_HOST.version_string"] << verStr;
1672 GetSystemInfo(&info);
1674 switch (info.wProcessorArchitecture) {
1675 # ifdef PROCESSOR_ARCHITECTURE_AMD64
1676 case PROCESSOR_ARCHITECTURE_AMD64:
1677 archStr = QLatin1String("x86_64");
1680 case PROCESSOR_ARCHITECTURE_INTEL:
1681 archStr = QLatin1String("x86");
1683 case PROCESSOR_ARCHITECTURE_IA64:
1684 # ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64
1685 case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
1687 archStr = QLatin1String("IA64");
1690 archStr = QLatin1String("Unknown");
1693 vars["QMAKE_HOST.arch"] << archStr;
1695 # if defined(Q_CC_MSVC)
1696 QString paths = QString::fromLocal8Bit(qgetenv("PATH"));
1697 QString vcBin64 = QString::fromLocal8Bit(qgetenv("VCINSTALLDIR"));
1698 if (!vcBin64.endsWith('\\'))
1699 vcBin64.append('\\');
1700 vcBin64.append("bin\\amd64");
1701 QString vcBinX86_64 = QString::fromLocal8Bit(qgetenv("VCINSTALLDIR"));
1702 if (!vcBinX86_64.endsWith('\\'))
1703 vcBinX86_64.append('\\');
1704 vcBinX86_64.append("bin\\x86_amd64");
1705 if (paths.contains(vcBin64,Qt::CaseInsensitive) || paths.contains(vcBinX86_64,Qt::CaseInsensitive))
1706 vars["QMAKE_TARGET.arch"] << QString::fromLatin1("x86_64");
1708 vars["QMAKE_TARGET.arch"] << QString::fromLatin1("x86");
1710 #elif defined(Q_OS_UNIX)
1711 struct utsname name;
1712 if (!uname(&name)) {
1713 vars["QMAKE_HOST.os"] << QString::fromLocal8Bit(name.sysname);
1714 vars["QMAKE_HOST.name"] << QString::fromLocal8Bit(name.nodename);
1715 vars["QMAKE_HOST.version"] << QString::fromLocal8Bit(name.release);
1716 vars["QMAKE_HOST.version_string"] << QString::fromLocal8Bit(name.version);
1717 vars["QMAKE_HOST.arch"] << QString::fromLocal8Bit(name.machine);
1723 QMakeProject::isActiveConfig(const QString &x, bool regex, QHash<QString, QStringList> *place)
1728 //magic types for easy flipping
1731 else if(x == "false")
1734 if (x == "host_build")
1738 QRegExp re(x, Qt::CaseSensitive, QRegExp::Wildcard);
1739 if ((regex && re.exactMatch(short_spec)) || (!regex && short_spec == x))
1743 const QStringList &configs = (place ? (*place)["CONFIG"] : vars["CONFIG"]);
1744 for(QStringList::ConstIterator it = configs.begin(); it != configs.end(); ++it) {
1745 if(((regex && re.exactMatch((*it))) || (!regex && (*it) == x)) && re.exactMatch((*it)))
1752 QMakeProject::doProjectTest(QString str, QHash<QString, QStringList> &place)
1754 QString chk = remove_quotes(str);
1757 bool invert_test = (chk.left(1) == "!");
1762 int lparen = chk.indexOf('(');
1763 if(lparen != -1) { // if there is an lparen in the chk, it IS a function
1764 int rparen = chk.indexOf(')', lparen);
1766 qmake_error_msg("Function missing right paren: " + chk);
1768 QString func = chk.left(lparen);
1769 test = doProjectTest(func, chk.mid(lparen+1, rparen - lparen - 1), place);
1772 test = isActiveConfig(chk, true, &place);
1780 QMakeProject::doProjectTest(QString func, const QString ¶ms,
1781 QHash<QString, QStringList> &place)
1783 return doProjectTest(func, split_arg_list(params), place);
1786 QMakeProject::IncludeStatus
1787 QMakeProject::doProjectInclude(QString file, uchar flags, QHash<QString, QStringList> &place)
1789 if(flags & IncludeFlagFeature) {
1790 if(!file.endsWith(Option::prf_ext))
1791 file += Option::prf_ext;
1793 QStringList *&feature_roots = all_feature_roots[host_build];
1794 if(!feature_roots) {
1795 feature_roots = new QStringList;
1796 qmakeAddCacheClear(qmakeDeleteCacheClear<QStringList>, (void**)&feature_roots);
1798 if (feature_roots->isEmpty())
1799 *feature_roots = qmakeFeaturePaths();
1800 debug_msg(2, "Looking for feature '%s' in (%s)", file.toLatin1().constData(),
1801 feature_roots->join("::").toLatin1().constData());
1803 if(parser.from_file) {
1804 QFileInfo currFile(parser.file), prfFile(file);
1805 if(currFile.fileName() == prfFile.fileName()) {
1806 currFile = QFileInfo(currFile.canonicalFilePath());
1807 for(int root = 0; root < feature_roots->size(); ++root) {
1808 prfFile = QFileInfo(feature_roots->at(root) +
1809 QLatin1Char('/') + file).canonicalFilePath();
1810 if(prfFile == currFile) {
1811 start_root = root+1;
1817 for(int root = start_root; root < feature_roots->size(); ++root) {
1818 QString prf(feature_roots->at(root) + QLatin1Char('/') + file);
1819 if (QFile::exists(prf)) {
1824 return IncludeNoExist;
1827 if(place["QMAKE_INTERNAL_INCLUDED_FEATURES"].indexOf(file) != -1)
1828 return IncludeFeatureAlreadyLoaded;
1829 place["QMAKE_INTERNAL_INCLUDED_FEATURES"].append(file);
1830 } else if (QDir::isRelativePath(file)) {
1831 QStringList include_roots;
1832 if(Option::output_dir != qmake_getpwd())
1833 include_roots << qmake_getpwd();
1834 include_roots << Option::output_dir;
1835 for(int root = 0; root < include_roots.size(); ++root) {
1836 QString testName = QDir::fromNativeSeparators(include_roots[root]);
1837 if (!testName.endsWith(QLatin1Char('/')))
1838 testName += QLatin1Char('/');
1840 if(QFile::exists(testName)) {
1845 return IncludeNoExist;
1847 } else if (!QFile::exists(file)) {
1848 return IncludeNoExist;
1850 debug_msg(1, "Project Parser: %s'ing file %s.", (flags & IncludeFlagFeature) ? "load" : "include",
1851 file.toLatin1().constData());
1853 QString orig_file = file;
1854 int di = file.lastIndexOf(QLatin1Char('/'));
1855 QString oldpwd = qmake_getpwd();
1857 if(!qmake_setpwd(file.left(file.lastIndexOf(QLatin1Char('/'))))) {
1858 fprintf(stderr, "Cannot find directory: %s\n", file.left(di).toLatin1().constData());
1859 return IncludeFailure;
1862 bool parsed = false;
1863 parser_info pi = parser;
1865 if(flags & (IncludeFlagNewProject|IncludeFlagNewParser)) {
1866 // The "project's variables" are used in other places (eg. export()) so it's not
1867 // possible to use "place" everywhere. Instead just set variables and grab them later
1868 QMakeProject proj(prop);
1869 if(flags & IncludeFlagNewParser) {
1870 parsed = proj.read(file, proj.variables()); // parse just that file (fromfile, infile)
1872 parsed = proj.read(file); // parse all aux files (load/include into)
1874 place = proj.variables();
1876 QStack<ScopeBlock> sc = scope_blocks;
1877 IteratorBlock *it = iterator;
1878 FunctionBlock *fu = function;
1879 parsed = read(file, place);
1886 if(place["QMAKE_INTERNAL_INCLUDED_FILES"].indexOf(orig_file) == -1)
1887 place["QMAKE_INTERNAL_INCLUDED_FILES"].append(orig_file);
1889 warn_msg(WarnParser, "%s:%d: Failure to include file %s.",
1890 pi.file.toLatin1().constData(), pi.line_no, orig_file.toLatin1().constData());
1893 qmake_setpwd(oldpwd);
1894 place["PWD"] = QStringList(qmake_getpwd());
1896 return IncludeParseFailure;
1897 return IncludeSuccess;
1901 subAll(QStringList *val, const QStringList &diffval)
1903 foreach (const QString &dv, diffval)
1908 bool hasSpecialChars(const QString &arg, const uchar (&iqm)[16])
1910 for (int x = arg.length() - 1; x >= 0; --x) {
1911 ushort c = arg.unicode()[x].unicode();
1912 if ((c < sizeof(iqm) * 8) && (iqm[c / 8] & (1 << (c & 7))))
1919 shellQuoteUnix(const QString &arg)
1921 // Chars that should be quoted (TM). This includes:
1922 static const uchar iqm[] = {
1923 0xff, 0xff, 0xff, 0xff, 0xdf, 0x07, 0x00, 0xd8,
1924 0x00, 0x00, 0x00, 0x38, 0x01, 0x00, 0x00, 0x78
1925 }; // 0-32 \'"$`<>|;&(){}*?#!~[]
1928 return QString::fromLatin1("\"\"");
1931 if (hasSpecialChars(ret, iqm)) {
1932 ret.replace(QLatin1Char('\''), QLatin1String("'\\''"));
1933 ret.prepend(QLatin1Char('\''));
1934 ret.append(QLatin1Char('\''));
1940 shellQuoteWin(const QString &arg)
1942 // Chars that should be quoted (TM). This includes:
1943 // - control chars & space
1944 // - the shell meta chars "&()<>^|
1945 // - the potential separators ,;=
1946 static const uchar iqm[] = {
1947 0xff, 0xff, 0xff, 0xff, 0x45, 0x13, 0x00, 0x78,
1948 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x10
1952 return QString::fromLatin1("\"\"");
1955 if (hasSpecialChars(ret, iqm)) {
1956 // Quotes are escaped and their preceding backslashes are doubled.
1957 // It's impossible to escape anything inside a quoted string on cmd
1958 // level, so the outer quoting must be "suspended".
1959 ret.replace(QRegExp(QLatin1String("(\\\\*)\"")), QLatin1String("\"\\1\\1\\^\"\""));
1960 // The argument must not end with a \ since this would be interpreted
1961 // as escaping the quote -- rather put the \ behind the quote: e.g.
1962 // rather use "foo"\ than "foo\"
1963 int i = ret.length();
1964 while (i > 0 && ret.at(i - 1) == QLatin1Char('\\'))
1966 ret.insert(i, QLatin1Char('"'));
1967 ret.prepend(QLatin1Char('"'));
1973 quoteValue(const QString &val)
1976 ret.reserve(val.length());
1977 bool quote = val.isEmpty();
1978 bool escaping = false;
1979 for (int i = 0, l = val.length(); i < l; i++) {
1980 QChar c = val.unicode()[i];
1981 ushort uc = c.unicode();
1985 ret += QLatin1String("$$escape_expand(");
1989 ret += QLatin1String("\\\\r");
1992 ret += QLatin1String("\\\\n");
1995 ret += QLatin1String("\\\\t");
1998 ret += QString::fromLatin1("\\\\x%1").arg(uc, 2, 16, QLatin1Char('0'));
2004 ret += QLatin1Char(')');
2008 ret += QLatin1String("\\\\");
2011 ret += QLatin1String("\\\"");
2014 ret += QLatin1String("\\'");
2017 ret += QLatin1String("\\$");
2020 ret += QLatin1String("$${LITERAL_HASH}");
2032 ret += QLatin1Char(')');
2034 ret.prepend(QLatin1Char('"'));
2035 ret.append(QLatin1Char('"'));
2041 writeFile(const QString &name, QIODevice::OpenMode mode, const QString &contents, QString *errStr)
2043 QByteArray bytes = contents.toLocal8Bit();
2045 if (!(mode & QIODevice::Append) && cfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
2046 if (cfile.readAll() == bytes)
2050 if (!cfile.open(mode | QIODevice::WriteOnly | QIODevice::Text)) {
2051 *errStr = cfile.errorString();
2056 if (cfile.error() != QFile::NoError) {
2057 *errStr = cfile.errorString();
2064 getCommandOutput(const QString &args)
2067 if (FILE *proc = QT_POPEN(args.toLatin1().constData(), "r")) {
2068 while (!feof(proc)) {
2069 char buff[10 * 1024];
2070 int read_in = int(fread(buff, 1, sizeof(buff), proc));
2073 out += QByteArray(buff, read_in);
2081 static QString windowsErrorCode()
2083 wchar_t *string = 0;
2084 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
2087 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2091 QString ret = QString::fromWCharArray(string);
2092 LocalFree((HLOCAL)string);
2098 QMakeProject::doProjectExpand(QString func, const QString ¶ms,
2099 QHash<QString, QStringList> &place)
2101 return doProjectExpand(func, split_arg_list(params), place);
2105 QMakeProject::doProjectExpand(QString func, QStringList args,
2106 QHash<QString, QStringList> &place)
2108 QList<QStringList> args_list;
2109 for(int i = 0; i < args.size(); ++i) {
2110 QStringList arg = split_value_list(args[i]), tmp;
2111 for(int i = 0; i < arg.size(); ++i)
2112 tmp += doVariableReplaceExpand(arg[i], place);;
2115 return doProjectExpand(func, args_list, place);
2119 populateDeps(const QStringList &deps, const QString &prefix,
2120 QHash<QString, QSet<QString> > &dependencies, QHash<QString, QStringList> &dependees,
2121 QStringList &rootSet, QHash<QString, QStringList> &place)
2123 foreach (const QString &item, deps)
2124 if (!dependencies.contains(item)) {
2125 QSet<QString> &dset = dependencies[item]; // Always create entry
2126 QStringList depends = place.value(prefix + item + ".depends");
2127 if (depends.isEmpty()) {
2130 foreach (const QString &dep, depends) {
2132 dependees[dep] << item;
2134 populateDeps(depends, prefix, dependencies, dependees, rootSet, place);
2140 QMakeProject::doProjectExpand(QString func, QList<QStringList> args_list,
2141 QHash<QString, QStringList> &place)
2143 func = func.trimmed();
2144 if(replaceFunctions.contains(func)) {
2145 FunctionBlock *defined = replaceFunctions[func];
2146 function_blocks.push(defined);
2148 defined->exec(args_list, this, place, ret);
2149 bool correct = function_blocks.pop() == defined;
2150 Q_ASSERT(correct); Q_UNUSED(correct);
2154 QStringList args; //why don't the builtin functions just use args_list? --Sam
2155 for(int i = 0; i < args_list.size(); ++i)
2156 args += args_list[i].join(QString(Option::field_sep));
2158 ExpandFunc func_t = qmake_expandFunctions().value(func);
2159 if (!func_t && (func_t = qmake_expandFunctions().value(func.toLower())))
2160 warn_msg(WarnDeprecated, "%s:%d: Using uppercased builtin functions is deprecated.",
2161 parser.file.toLatin1().constData(), parser.line_no);
2162 debug_msg(1, "Running project expand: %s(%s) [%d]",
2163 func.toLatin1().constData(), args.join("::").toLatin1().constData(), func_t);
2168 if(args.count() < 1 || args.count() > 3) {
2169 fprintf(stderr, "%s:%d: member(var, start, end) requires three arguments.\n",
2170 parser.file.toLatin1().constData(), parser.line_no);
2173 const QStringList &var = values(args.first(), place);
2174 int start = 0, end = 0;
2175 if(args.count() >= 2) {
2176 QString start_str = args[1];
2177 start = start_str.toInt(&ok);
2179 if(args.count() == 2) {
2180 int dotdot = start_str.indexOf("..");
2182 start = start_str.left(dotdot).toInt(&ok);
2184 end = start_str.mid(dotdot+2).toInt(&ok);
2188 fprintf(stderr, "%s:%d: member() argument 2 (start) '%s' invalid.\n",
2189 parser.file.toLatin1().constData(), parser.line_no,
2190 start_str.toLatin1().constData());
2193 if(args.count() == 3)
2194 end = args[2].toInt(&ok);
2196 fprintf(stderr, "%s:%d: member() argument 3 (end) '%s' invalid.\n",
2197 parser.file.toLatin1().constData(), parser.line_no,
2198 args[2].toLatin1().constData());
2203 start += var.count();
2206 if(start < 0 || start >= var.count() || end < 0 || end >= var.count()) {
2208 } else if(start < end) {
2209 for(int i = start; i <= end && (int)var.count() >= i; i++)
2212 for(int i = start; i >= end && (int)var.count() >= i && i >= 0; i--)
2220 if(args.count() != 1) {
2221 fprintf(stderr, "%s:%d: %s(var) requires one argument.\n",
2222 parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
2224 const QStringList &var = values(args.first(), place);
2225 if(!var.isEmpty()) {
2226 if(func_t == E_FIRST)
2227 ret = QStringList(var[0]);
2229 ret = QStringList(var[var.size()-1]);
2234 if(args.count() < 1 || args.count() > 2) {
2235 fprintf(stderr, "%s:%d: cat(file) requires one argument.\n",
2236 parser.file.toLatin1().constData(), parser.line_no);
2238 QString file = Option::normalizePath(args[0]);
2242 bool singleLine = true;
2243 if (args.count() > 1) {
2244 if (!args.at(1).compare(QLatin1String("false"), Qt::CaseInsensitive))
2246 else if (!args.at(1).compare(QLatin1String("blob"), Qt::CaseInsensitive))
2248 else if (!args.at(1).compare(QLatin1String("lines"), Qt::CaseInsensitive))
2252 if(qfile.open(QIODevice::ReadOnly)) {
2253 QTextStream stream(&qfile);
2255 ret += stream.readAll();
2257 while (!stream.atEnd()) {
2259 ret += stream.readLine();
2261 ret += split_value_list(stream.readLine().trimmed());
2271 if(args.count() != 2) {
2272 fprintf(stderr, "%s:%d: fromfile(file, variable) requires two arguments.\n",
2273 parser.file.toLatin1().constData(), parser.line_no);
2275 QString seek_var = args[1], file = Option::normalizePath(args[0]);
2277 QHash<QString, QStringList> tmp;
2278 if(doProjectInclude(file, IncludeFlagNewParser, tmp) == IncludeSuccess) {
2279 if(tmp.contains("QMAKE_INTERNAL_INCLUDED_FILES")) {
2280 QStringList &out = place["QMAKE_INTERNAL_INCLUDED_FILES"];
2281 const QStringList &in = tmp["QMAKE_INTERNAL_INCLUDED_FILES"];
2282 for(int i = 0; i < in.size(); ++i) {
2283 if(out.indexOf(in[i]) == -1)
2287 ret = tmp[seek_var];
2292 if (args.count() != 1) {
2293 fprintf(stderr, "%s:%d: eval(variable) requires one argument.\n",
2294 parser.file.toLatin1().constData(), parser.line_no);
2297 ret += place.value(args.at(0));
2303 tmp.sprintf(".QMAKE_INTERNAL_TMP_VAR_%d", x++);
2304 ret = QStringList(tmp);
2305 QStringList &lst = (*((QHash<QString, QStringList>*)&place))[tmp];
2307 for(QStringList::ConstIterator arg_it = args.begin();
2308 arg_it != args.end(); ++arg_it)
2309 lst += split_value_list((*arg_it));
2312 if(args.count() < 1) {
2313 fprintf(stderr, "%s:%d: sprintf(format, ...) requires one argument.\n",
2314 parser.file.toLatin1().constData(), parser.line_no);
2316 QString tmp = args.at(0);
2317 for(int i = 1; i < args.count(); ++i)
2318 tmp = tmp.arg(args.at(i));
2319 ret = split_value_list(tmp);
2322 case E_FORMAT_NUMBER:
2323 if (args.count() > 2) {
2324 fprintf(stderr, "%s:%d: format_number(number[, options...]) requires one or two arguments.\n",
2325 parser.file.toLatin1().constData(), parser.line_no);
2330 bool zeropad = false;
2331 bool leftalign = false;
2332 enum { DefaultSign, PadSign, AlwaysSign } sign = DefaultSign;
2333 if (args.count() >= 2) {
2334 foreach (const QString &opt, split_value_list(args.at(1))) {
2335 if (opt.startsWith(QLatin1String("ibase="))) {
2336 ibase = opt.mid(6).toInt();
2337 } else if (opt.startsWith(QLatin1String("obase="))) {
2338 obase = opt.mid(6).toInt();
2339 } else if (opt.startsWith(QLatin1String("width="))) {
2340 width = opt.mid(6).toInt();
2341 } else if (opt == QLatin1String("zeropad")) {
2343 } else if (opt == QLatin1String("padsign")) {
2345 } else if (opt == QLatin1String("alwayssign")) {
2347 } else if (opt == QLatin1String("leftalign")) {
2350 fprintf(stderr, "%s:%d: format_number(): invalid format option %s.\n",
2351 parser.file.toLatin1().constData(), parser.line_no,
2352 opt.toLatin1().constData());
2357 if (args.at(0).contains(QLatin1Char('.'))) {
2358 fprintf(stderr, "%s:%d: format_number(): floats are currently not supported.\n",
2359 parser.file.toLatin1().constData(), parser.line_no);
2363 qlonglong num = args.at(0).toLongLong(&ok, ibase);
2365 fprintf(stderr, "%s:%d: format_number(): malformed number %s for base %d.\n",
2366 parser.file.toLatin1().constData(), parser.line_no,
2367 args.at(0).toLatin1().constData(), ibase);
2373 outstr = QLatin1Char('-');
2374 } else if (sign == AlwaysSign) {
2375 outstr = QLatin1Char('+');
2376 } else if (sign == PadSign) {
2377 outstr = QLatin1Char(' ');
2379 QString numstr = QString::number(num, obase);
2380 int space = width - outstr.length() - numstr.length();
2383 } else if (leftalign) {
2384 outstr += numstr + QString(space, QLatin1Char(' '));
2385 } else if (zeropad) {
2386 outstr += QString(space, QLatin1Char('0')) + numstr;
2388 outstr.prepend(QString(space, QLatin1Char(' ')));
2396 if(args.count() < 1 || args.count() > 4) {
2397 fprintf(stderr, "%s:%d: join(var, glue, before, after) requires four"
2398 "arguments.\n", parser.file.toLatin1().constData(), parser.line_no);
2400 QString glue, before, after;
2401 if(args.count() >= 2)
2403 if(args.count() >= 3)
2405 if(args.count() == 4)
2407 const QStringList &var = values(args.first(), place);
2409 ret = split_value_list(before + var.join(glue) + after);
2413 if(args.count() < 1 || args.count() > 2) {
2414 fprintf(stderr, "%s:%d split(var, sep) requires one or two arguments\n",
2415 parser.file.toLatin1().constData(), parser.line_no);
2417 QString sep = QString(Option::field_sep);
2418 if(args.count() >= 2)
2420 QStringList var = values(args.first(), place);
2421 for(QStringList::ConstIterator vit = var.begin(); vit != var.end(); ++vit) {
2422 QStringList lst = (*vit).split(sep);
2423 for(QStringList::ConstIterator spltit = lst.begin(); spltit != lst.end(); ++spltit)
2431 bool regexp = false;
2434 if(func_t == E_SECTION) {
2435 if(args.count() != 3 && args.count() != 4) {
2436 fprintf(stderr, "%s:%d section(var, sep, begin, end) requires three argument\n",
2437 parser.file.toLatin1().constData(), parser.line_no);
2441 beg = args[2].toInt();
2442 if(args.count() == 4)
2443 end = args[3].toInt();
2446 if(args.count() != 1) {
2447 fprintf(stderr, "%s:%d %s(var) requires one argument.\n",
2448 parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
2452 sep = "[" + QRegExp::escape(Option::dir_sep) + "/]";
2453 if(func_t == E_DIRNAME)
2460 const QStringList &l = values(var, place);
2461 for(QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
2462 QString separator = sep;
2464 ret += (*it).section(QRegExp(separator), beg, end);
2466 ret += (*it).section(separator, beg, end);
2471 if(args.count() != 2) {
2472 fprintf(stderr, "%s:%d find(var, str) requires two arguments\n",
2473 parser.file.toLatin1().constData(), parser.line_no);
2475 QRegExp regx(args[1]);
2476 const QStringList &var = values(args.first(), place);
2477 for(QStringList::ConstIterator vit = var.begin();
2478 vit != var.end(); ++vit) {
2479 if(regx.indexIn(*vit) != -1)
2485 if(args.count() < 1 || args.count() > 2) {
2486 fprintf(stderr, "%s:%d system(execut) requires one argument.\n",
2487 parser.file.toLatin1().constData(), parser.line_no);
2491 bool singleLine = true;
2492 if (args.count() > 1) {
2493 if (!args.at(1).compare(QLatin1String("false"), Qt::CaseInsensitive))
2495 else if (!args.at(1).compare(QLatin1String("blob"), Qt::CaseInsensitive))
2497 else if (!args.at(1).compare(QLatin1String("lines"), Qt::CaseInsensitive))
2500 QByteArray bytes = getCommandOutput(args.at(0));
2502 QTextStream stream(bytes);
2503 while (!stream.atEnd())
2504 ret += stream.readLine();
2506 QString output = QString::fromLocal8Bit(bytes);
2510 output.replace(QLatin1Char('\t'), QLatin1Char(' '));
2512 output.replace(QLatin1Char('\n'), QLatin1Char(' '));
2513 ret += split_value_list(output);
2519 if(args.count() != 1) {
2520 fprintf(stderr, "%s:%d unique(var) requires one argument.\n",
2521 parser.file.toLatin1().constData(), parser.line_no);
2523 const QStringList &var = values(args.first(), place);
2524 for(int i = 0; i < var.count(); i++) {
2525 if(!ret.contains(var[i]))
2531 if (args.count() != 1) {
2532 fprintf(stderr, "%s:%d reverse(var) requires one argument.\n",
2533 parser.file.toLatin1().constData(), parser.line_no);
2535 QStringList var = values(args.first(), place);
2536 for (int i = 0; i < var.size() / 2; i++)
2537 var.swap(i, var.size() - i - 1);
2544 case E_ESCAPE_EXPAND: {
2545 for(int i = 0; i < args.size(); ++i) {
2546 QChar *i_data = args[i].data();
2547 int i_len = args[i].length();
2548 for(int x = 0; x < i_len; ++x) {
2549 if(*(i_data+x) == '\\' && x < i_len-1) {
2550 if(*(i_data+x+1) == '\\') {
2555 } mapped_quotes[] = {
2561 for(int i = 0; mapped_quotes[i].in; ++i) {
2562 if(*(i_data+x+1) == mapped_quotes[i].in) {
2563 *(i_data+x) = mapped_quotes[i].out;
2565 memmove(i_data+x+1, i_data+x+2, (i_len-x-2)*sizeof(QChar));
2573 ret.append(QString(i_data, i_len));
2577 for(int i = 0; i < args.size(); ++i)
2578 ret += QRegExp::escape(args[i]);
2581 if (args.count() != 1) {
2582 fprintf(stderr, "%s:%d val_escape(var) requires one argument.\n",
2583 parser.file.toLatin1().constData(), parser.line_no);
2585 QStringList vals = values(args.at(0), place);
2586 ret.reserve(vals.length());
2587 foreach (const QString &str, vals)
2588 ret += quoteValue(str);
2593 for(int i = 0; i < args.size(); ++i) {
2594 if(func_t == E_UPPER)
2595 ret += args[i].toUpper();
2597 ret += args[i].toLower();
2601 if(args.count() != 1 && args.count() != 2) {
2602 fprintf(stderr, "%s:%d files(pattern) requires one argument.\n",
2603 parser.file.toLatin1().constData(), parser.line_no);
2605 bool recursive = false;
2606 if(args.count() == 2)
2607 recursive = (args[1].toLower() == "true" || args[1].toInt());
2609 QString r = Option::normalizePath(args[0]);
2610 int slash = r.lastIndexOf(QLatin1Char('/'));
2612 dirs.append(r.left(slash));
2618 QRegExp regex(r, Qt::CaseSensitive, QRegExp::Wildcard);
2619 for(int d = 0; d < dirs.count(); d++) {
2620 QString dir = dirs[d];
2621 if (!dir.isEmpty() && !dir.endsWith(QLatin1Char('/')))
2625 for(int i = 0; i < (int)qdir.count(); ++i) {
2626 if(qdir[i] == "." || qdir[i] == "..")
2628 QString fname = dir + qdir[i];
2629 if(QFileInfo(fname).isDir()) {
2633 if(regex.exactMatch(qdir[i]))
2640 if(args.count() != 1) {
2641 fprintf(stderr, "%s:%d prompt(question) requires one argument.\n",
2642 parser.file.toLatin1().constData(), parser.line_no);
2643 } else if(pfile == "-") {
2644 fprintf(stderr, "%s:%d prompt(question) cannot be used when '-o -' is used.\n",
2645 parser.file.toLatin1().constData(), parser.line_no);
2647 QString msg = fixEnvVariables(args.first());
2648 if(!msg.endsWith("?"))
2650 fprintf(stderr, "Project %s: %s ", func.toUpper().toLatin1().constData(),
2651 msg.toLatin1().constData());
2654 if(qfile.open(stdin, QIODevice::ReadOnly)) {
2655 QTextStream t(&qfile);
2656 ret = split_value_list(t.readLine());
2661 if(args.count() != 3 ) {
2662 fprintf(stderr, "%s:%d replace(var, before, after) requires three arguments\n",
2663 parser.file.toLatin1().constData(), parser.line_no);
2665 const QRegExp before( args[1] );
2666 const QString after( args[2] );
2667 QStringList var = values(args.first(), place);
2668 for(QStringList::Iterator it = var.begin(); it != var.end(); ++it)
2669 ret += it->replace(before, after);
2673 if(args.count() != 1) {
2674 fprintf(stderr, "%s:%d: size(var) requires one argument.\n",
2675 parser.file.toLatin1().constData(), parser.line_no);
2677 int size = values(args[0], place).size();
2678 ret += QString::number(size);
2681 case E_SORT_DEPENDS:
2682 case E_RESOLVE_DEPENDS: {
2683 if(args.count() < 1 || args.count() > 2) {
2684 fprintf(stderr, "%s:%d: %s(var, prefix) requires one or two arguments.\n",
2685 parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
2687 QHash<QString, QSet<QString> > dependencies;
2688 QHash<QString, QStringList> dependees;
2689 QStringList rootSet;
2691 QStringList orgList = values(args[0], place);
2692 populateDeps(orgList, (args.count() != 2 ? QString() : args[1]),
2693 dependencies, dependees, rootSet, place);
2695 for (int i = 0; i < rootSet.size(); ++i) {
2696 const QString &item = rootSet.at(i);
2697 if ((func_t == E_RESOLVE_DEPENDS) || orgList.contains(item))
2699 foreach (const QString &dep, dependees[item]) {
2700 QSet<QString> &dset = dependencies[dep];
2701 dset.remove(rootSet.at(i)); // *Don't* use 'item' - rootSet may have changed!
2708 case E_ENUMERATE_VARS:
2709 ret += place.keys();
2712 QString val = QDir::cleanPath(QFileInfo(args.at(0)).absoluteFilePath());
2713 if (Option::mkfile::source_root.isEmpty()) {
2715 } else if (val.startsWith(Option::mkfile::source_root)
2716 && (val.length() == Option::mkfile::source_root.length()
2717 || val.at(Option::mkfile::source_root.length()) == QLatin1Char('/'))) {
2718 ret += Option::mkfile::build_root + val.mid(Option::mkfile::source_root.length());
2721 case E_ABSOLUTE_PATH:
2722 if (args.count() > 2)
2723 fprintf(stderr, "%s:%d absolute_path(path[, base]) requires one or two arguments.\n",
2724 parser.file.toLatin1().constData(), parser.line_no);
2726 ret += QDir::cleanPath(QDir(args.count() > 1 ? args.at(1) : QString())
2727 .absoluteFilePath(args.at(0)));
2729 case E_RELATIVE_PATH:
2730 if (args.count() > 2) {
2731 fprintf(stderr, "%s:%d relative_path(path[, base]) requires one or two arguments.\n",
2732 parser.file.toLatin1().constData(), parser.line_no);
2734 QDir baseDir(args.count() > 1 ? args.at(1) : QString());
2735 ret += baseDir.relativeFilePath(baseDir.absoluteFilePath(args.at(0)));
2739 if (args.count() != 1)
2740 fprintf(stderr, "%s:%d clean_path(path) requires one argument.\n",
2741 parser.file.toLatin1().constData(), parser.line_no);
2743 ret += QDir::cleanPath(args.at(0));
2746 if (args.count() != 1)
2747 fprintf(stderr, "%s:%d system_path(path) requires one argument.\n",
2748 parser.file.toLatin1().constData(), parser.line_no);
2750 ret += Option::fixPathToLocalOS(args.at(0), false);
2753 if (args.count() != 1)
2754 fprintf(stderr, "%s:%d shell_path(path) requires one argument.\n",
2755 parser.file.toLatin1().constData(), parser.line_no);
2757 ret += Option::fixPathToTargetOS(args.at(0), false);
2759 case E_SYSTEM_QUOTE:
2760 if (args.count() != 1)
2761 fprintf(stderr, "%s:%d system_quote(args) requires one argument.\n",
2762 parser.file.toLatin1().constData(), parser.line_no);
2765 ret += shellQuoteWin(args.at(0));
2767 ret += shellQuoteUnix(args.at(0));
2771 if (args.count() != 1)
2772 fprintf(stderr, "%s:%d shell_quote(args) requires one argument.\n",
2773 parser.file.toLatin1().constData(), parser.line_no);
2774 else if (Option::dir_sep.at(0) != QLatin1Char('/'))
2775 ret += shellQuoteWin(args.at(0));
2777 ret += shellQuoteUnix(args.at(0));
2780 fprintf(stderr, "%s:%d: Unknown replace function: %s\n",
2781 parser.file.toLatin1().constData(), parser.line_no,
2782 func.toLatin1().constData());
2789 QMakeProject::doProjectTest(QString func, QStringList args, QHash<QString, QStringList> &place)
2791 QList<QStringList> args_list;
2792 for(int i = 0; i < args.size(); ++i) {
2793 QStringList arg = split_value_list(args[i]), tmp;
2794 for(int i = 0; i < arg.size(); ++i)
2795 tmp += doVariableReplaceExpand(arg[i], place);
2798 return doProjectTest(func, args_list, place);
2802 QMakeProject::doProjectTest(QString func, QList<QStringList> args_list, QHash<QString, QStringList> &place)
2804 func = func.trimmed();
2806 if(testFunctions.contains(func)) {
2807 FunctionBlock *defined = testFunctions[func];
2809 function_blocks.push(defined);
2810 defined->exec(args_list, this, place, ret);
2811 bool correct = function_blocks.pop() == defined;
2812 Q_ASSERT(correct); Q_UNUSED(correct);
2817 if(ret.first() == "true") {
2819 } else if(ret.first() == "false") {
2823 int val = ret.first().toInt(&ok);
2826 fprintf(stderr, "%s:%d Unexpected return value from test %s [%s].\n",
2827 parser.file.toLatin1().constData(),
2828 parser.line_no, func.toLatin1().constData(),
2829 ret.join("::").toLatin1().constData());
2836 QStringList args; //why don't the builtin functions just use args_list? --Sam
2837 for(int i = 0; i < args_list.size(); ++i)
2838 args += args_list[i].join(QString(Option::field_sep));
2840 TestFunc func_t = qmake_testFunctions().value(func);
2841 debug_msg(1, "Running project test: %s(%s) [%d]",
2842 func.toLatin1().constData(), args.join("::").toLatin1().constData(), func_t);
2846 return doProjectCheckReqs(args, place);
2848 case T_GREATERTHAN: {
2849 if(args.count() != 2) {
2850 fprintf(stderr, "%s:%d: %s(variable, value) requires two arguments.\n", parser.file.toLatin1().constData(),
2851 parser.line_no, func.toLatin1().constData());
2854 QString rhs(args[1]), lhs(values(args[0], place).join(QString(Option::field_sep)));
2856 int rhs_int = rhs.toInt(&ok);
2857 if(ok) { // do integer compare
2858 int lhs_int = lhs.toInt(&ok);
2860 if(func_t == T_GREATERTHAN)
2861 return lhs_int > rhs_int;
2862 return lhs_int < rhs_int;
2865 if(func_t == T_GREATERTHAN)
2869 if(args.count() != 1) {
2870 fprintf(stderr, "%s:%d: if(condition) requires one argument.\n", parser.file.toLatin1().constData(),
2874 const QString cond = args.first();
2875 const QChar *d = cond.unicode();
2877 bool ret = true, or_op = false;
2879 for(int d_off = 0, parens = 0, d_len = cond.size(); d_off < d_len; ++d_off) {
2880 if(!quote.isNull()) {
2881 if(*(d+d_off) == quote)
2883 } else if(*(d+d_off) == '(') {
2885 } else if(*(d+d_off) == ')') {
2887 } else if(*(d+d_off) == '"' /*|| *(d+d_off) == '\''*/) {
2890 if(!parens && quote.isNull() && (*(d+d_off) == QLatin1Char(':') || *(d+d_off) == QLatin1Char('|') || d_off == d_len-1)) {
2891 if(d_off == d_len-1)
2893 if(!test.isEmpty()) {
2895 ret = doProjectTest(test, place);
2898 if(*(d+d_off) == QLatin1Char(':')) {
2900 } else if(*(d+d_off) == QLatin1Char('|')) {
2909 if(args.count() != 2) {
2910 fprintf(stderr, "%s:%d: %s(variable, value) requires two arguments.\n", parser.file.toLatin1().constData(),
2911 parser.line_no, func.toLatin1().constData());
2914 return values(args[0], place).join(QString(Option::field_sep)) == args[1];
2916 if(args.count() != 1) {
2917 fprintf(stderr, "%s:%d: exists(file) requires one argument.\n", parser.file.toLatin1().constData(),
2921 QString file = Option::normalizePath(args.first());
2923 if(QFile::exists(file))
2925 //regular expression I guess
2926 QString dirstr = qmake_getpwd();
2927 int slsh = file.lastIndexOf(QLatin1Char('/'));
2929 dirstr = file.left(slsh+1);
2930 file = file.right(file.length() - slsh - 1);
2932 return QDir(dirstr).entryList(QStringList(file)).count(); }
2934 if(args.count() != 1) {
2935 fprintf(stderr, "%s:%d: export(variable) requires one argument.\n", parser.file.toLatin1().constData(),
2939 for(int i = 0; i < function_blocks.size(); ++i) {
2940 FunctionBlock *f = function_blocks.at(i);
2941 f->vars[args[0]] = values(args[0], place);
2942 if(!i && f->calling_place)
2943 (*f->calling_place)[args[0]] = values(args[0], place);
2947 if(args.count() != 1) {
2948 fprintf(stderr, "%s:%d: clear(variable) requires one argument.\n", parser.file.toLatin1().constData(),
2952 if(!place.contains(args[0]))
2954 place[args[0]].clear();
2957 if(args.count() != 1) {
2958 fprintf(stderr, "%s:%d: unset(variable) requires one argument.\n", parser.file.toLatin1().constData(),
2962 if(!place.contains(args[0]))
2964 place.remove(args[0]);
2967 if(args.count() < 1 && 0) {
2968 fprintf(stderr, "%s:%d: eval(project) requires one argument.\n", parser.file.toLatin1().constData(),
2972 QString project = args.join(" ");
2973 parser_info pi = parser;
2974 parser.from_file = false;
2975 parser.file = "(eval)";
2977 QTextStream t(&project, QIODevice::ReadOnly);
2978 bool ret = read(t, place);
2982 if(args.count() < 1 || args.count() > 2) {
2983 fprintf(stderr, "%s:%d: CONFIG(config) requires one argument.\n", parser.file.toLatin1().constData(),
2987 if(args.count() == 1)
2988 return isActiveConfig(args[0]);
2989 const QStringList mutuals = args[1].split('|');
2990 const QStringList &configs = values("CONFIG", place);
2991 for(int i = configs.size()-1; i >= 0; i--) {
2992 for(int mut = 0; mut < mutuals.count(); mut++) {
2993 if(configs[i] == mutuals[mut].trimmed())
2994 return (configs[i] == args[0]);
2999 if(args.count() < 1 || args.count() > 2) {
3000 fprintf(stderr, "%s:%d: system(exec) requires one argument.\n", parser.file.toLatin1().constData(),
3004 if(args.count() == 2) {
3005 const QString sarg = args[1];
3006 if (sarg.toLower() == "true" || sarg.toInt())
3007 warn_msg(WarnParser, "%s:%d: system()'s second argument is now hard-wired to false.\n",
3008 parser.file.toLatin1().constData(), parser.line_no);
3010 return system(args[0].toLatin1().constData()) == 0;
3012 if(function_blocks.isEmpty()) {
3013 fprintf(stderr, "%s:%d unexpected return()\n",
3014 parser.file.toLatin1().constData(), parser.line_no);
3016 FunctionBlock *f = function_blocks.top();
3017 f->cause_return = true;
3018 if(args_list.count() >= 1)
3019 f->return_value += args_list[0];
3024 iterator->cause_break = true;
3026 fprintf(stderr, "%s:%d unexpected break()\n",
3027 parser.file.toLatin1().constData(), parser.line_no);
3031 iterator->cause_next = true;
3033 fprintf(stderr, "%s:%d unexpected next()\n",
3034 parser.file.toLatin1().constData(), parser.line_no);
3037 if(args.count() < 1 || args.count() > 2) {
3038 fprintf(stderr, "%s:%d: defined(function) requires one argument.\n",
3039 parser.file.toLatin1().constData(), parser.line_no);
3041 if(args.count() > 1) {
3042 if(args[1] == "test")
3043 return testFunctions.contains(args[0]);
3044 else if(args[1] == "replace")
3045 return replaceFunctions.contains(args[0]);
3046 else if(args[1] == "var")
3047 return place.contains(args[0]);
3048 fprintf(stderr, "%s:%d: defined(function, type): unexpected type [%s].\n",
3049 parser.file.toLatin1().constData(), parser.line_no,
3050 args[1].toLatin1().constData());
3052 if(replaceFunctions.contains(args[0]) || testFunctions.contains(args[0]))
3058 if(args.count() < 2 || args.count() > 3) {
3059 fprintf(stderr, "%s:%d: contains(var, val) requires at lesat 2 arguments.\n",
3060 parser.file.toLatin1().constData(), parser.line_no);
3063 QRegExp regx(args[1]);
3064 const QStringList &l = values(args[0], place);
3065 if(args.count() == 2) {
3066 for(int i = 0; i < l.size(); ++i) {
3067 const QString val = l[i];
3068 if(regx.exactMatch(val) || val == args[1])
3072 const QStringList mutuals = args[2].split('|');
3073 for(int i = l.size()-1; i >= 0; i--) {
3074 const QString val = l[i];
3075 for(int mut = 0; mut < mutuals.count(); mut++) {
3076 if(val == mutuals[mut].trimmed())
3077 return (regx.exactMatch(val) || val == args[1]);
3083 if(args.count() < 2 || args.count() > 3) {
3084 fprintf(stderr, "%s:%d: infile(file, var, val) requires at least 2 arguments.\n",
3085 parser.file.toLatin1().constData(), parser.line_no);
3090 QHash<QString, QStringList> tmp;
3091 if(doProjectInclude(Option::normalizePath(args[0]), IncludeFlagNewParser, tmp) == IncludeSuccess) {
3092 if(tmp.contains("QMAKE_INTERNAL_INCLUDED_FILES")) {
3093 QStringList &out = place["QMAKE_INTERNAL_INCLUDED_FILES"];
3094 const QStringList &in = tmp["QMAKE_INTERNAL_INCLUDED_FILES"];
3095 for(int i = 0; i < in.size(); ++i) {
3096 if(out.indexOf(in[i]) == -1)
3100 if(args.count() == 2) {
3101 ret = tmp.contains(args[1]);
3103 QRegExp regx(args[2]);
3104 const QStringList &l = tmp[args[1]];
3105 for(QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
3106 if(regx.exactMatch((*it)) || (*it) == args[2]) {
3115 if(args.count() != 2 && args.count() != 3) {
3116 fprintf(stderr, "%s:%d: count(var, count) requires two arguments.\n", parser.file.toLatin1().constData(),
3120 if(args.count() == 3) {
3121 QString comp = args[2];
3122 if(comp == ">" || comp == "greaterThan")
3123 return values(args[0], place).count() > args[1].toInt();
3125 return values(args[0], place).count() >= args[1].toInt();
3126 if(comp == "<" || comp == "lessThan")
3127 return values(args[0], place).count() < args[1].toInt();
3129 return values(args[0], place).count() <= args[1].toInt();
3130 if(comp == "equals" || comp == "isEqual" || comp == "=" || comp == "==")
3131 return values(args[0], place).count() == args[1].toInt();
3132 fprintf(stderr, "%s:%d: unexpected modifier to count(%s)\n", parser.file.toLatin1().constData(),
3133 parser.line_no, comp.toLatin1().constData());
3136 return values(args[0], place).count() == args[1].toInt();
3138 if(args.count() != 1) {
3139 fprintf(stderr, "%s:%d: isEmpty(var) requires one argument.\n", parser.file.toLatin1().constData(),
3143 return values(args[0], place).isEmpty();
3147 const bool include_statement = (func_t == T_INCLUDE);
3148 bool ignore_error = false;
3149 if(args.count() >= 2) {
3150 if(func_t == T_INCLUDE) {
3151 parseInto = args[1];
3152 if (args.count() == 3){
3153 QString sarg = args[2];
3154 if (sarg.toLower() == "true" || sarg.toInt())
3155 ignore_error = true;
3158 QString sarg = args[1];
3159 ignore_error = (sarg.toLower() == "true" || sarg.toInt());
3161 } else if(args.count() != 1) {
3162 QString func_desc = "load(feature)";
3163 if(include_statement)
3164 func_desc = "include(file)";
3165 fprintf(stderr, "%s:%d: %s requires one argument.\n", parser.file.toLatin1().constData(),
3166 parser.line_no, func_desc.toLatin1().constData());
3169 QString file = Option::normalizePath(args.first());
3170 uchar flags = IncludeFlagNone;
3171 if(!include_statement)
3172 flags |= IncludeFlagFeature;
3173 IncludeStatus stat = IncludeFailure;
3174 if(!parseInto.isEmpty()) {
3175 QHash<QString, QStringList> symbols;
3176 stat = doProjectInclude(file, flags|IncludeFlagNewProject, symbols);
3177 if(stat == IncludeSuccess) {
3178 QHash<QString, QStringList> out_place;
3179 for(QHash<QString, QStringList>::ConstIterator it = place.begin(); it != place.end(); ++it) {
3180 const QString var = it.key();
3181 if(var != parseInto && !var.startsWith(parseInto + "."))
3182 out_place.insert(var, it.value());
3184 for(QHash<QString, QStringList>::ConstIterator it = symbols.begin(); it != symbols.end(); ++it) {
3185 const QString var = it.key();
3186 if(!var.startsWith("."))
3187 out_place.insert(parseInto + "." + it.key(), it.value());
3192 stat = doProjectInclude(file, flags, place);
3194 if(stat == IncludeFeatureAlreadyLoaded) {
3195 warn_msg(WarnParser, "%s:%d: Duplicate of loaded feature %s",
3196 parser.file.toLatin1().constData(), parser.line_no, file.toLatin1().constData());
3197 } else if(stat == IncludeNoExist && !ignore_error) {
3198 warn_msg(WarnAll, "%s:%d: Unable to find file for inclusion %s",
3199 parser.file.toLatin1().constData(), parser.line_no, file.toLatin1().constData());
3201 } else if(stat >= IncludeFailure) {
3203 printf("Project LOAD(): Feature %s cannot be found.\n", file.toLatin1().constData());
3205 #if defined(QT_BUILD_QMAKE_LIBRARY)
3215 if(args.count() != 2) {
3216 fprintf(stderr, "%s:%d: debug(level, message) requires one argument.\n", parser.file.toLatin1().constData(),
3220 QString msg = fixEnvVariables(args[1]);
3221 debug_msg(args[0].toInt(), "Project DEBUG: %s", msg.toLatin1().constData());
3227 if(args.count() != 1) {
3228 fprintf(stderr, "%s:%d: %s(message) requires one argument.\n", parser.file.toLatin1().constData(),
3229 parser.line_no, func.toLatin1().constData());
3232 QString msg = fixEnvVariables(args.first());
3233 if (func_t == T_LOG) {
3234 fputs(msg.toLatin1().constData(), stderr);
3236 fprintf(stderr, "Project %s: %s\n", func.toUpper().toLatin1().constData(), msg.toLatin1().constData());
3237 if (func == "error")
3238 #if defined(QT_BUILD_QMAKE_LIBRARY)
3246 if (args.count() != 1) {
3247 fprintf(stderr, "%s:%d: option() requires one argument.\n",
3248 parser.file.toLatin1().constData(), parser.line_no);
3251 if (args.first() == "host_build") {
3252 if (!host_build && isActiveConfig("cross_compile")) {
3254 need_restart = true;
3257 fprintf(stderr, "%s:%d: unrecognized option() argument '%s'.\n",
3258 parser.file.toLatin1().constData(), parser.line_no,
3259 args.first().toLatin1().constData());
3264 if (args.count() > 3) {
3265 fprintf(stderr, "%s:%d: cache(var, [set|add|sub] [transient] [super], [srcvar]) requires one to three arguments.\n",
3266 parser.file.toLatin1().constData(), parser.line_no);
3269 bool persist = true;
3271 enum { CacheSet, CacheAdd, CacheSub } mode = CacheSet;
3273 if (args.count() >= 2) {
3274 foreach (const QString &opt, split_value_list(args.at(1))) {
3275 if (opt == QLatin1String("transient")) {
3277 } else if (opt == QLatin1String("super")) {
3279 } else if (opt == QLatin1String("set")) {
3281 } else if (opt == QLatin1String("add")) {
3283 } else if (opt == QLatin1String("sub")) {
3286 fprintf(stderr, "%s:%d: cache(): invalid flag %s.\n",
3287 parser.file.toLatin1().constData(), parser.line_no,
3288 opt.toLatin1().constData());
3292 if (args.count() >= 3) {
3293 srcvar = args.at(2);
3294 } else if (mode != CacheSet) {
3295 fprintf(stderr, "%s:%d: cache(): modes other than 'set' require a source variable.\n",
3296 parser.file.toLatin1().constData(), parser.line_no);
3301 QString dstvar = args.at(0);
3302 if (!dstvar.isEmpty()) {
3303 if (srcvar.isEmpty())
3305 if (!place.contains(srcvar)) {
3306 fprintf(stderr, "%s:%d: variable %s is not defined.\n",
3307 parser.file.toLatin1().constData(), parser.line_no,
3308 srcvar.toLatin1().constData());
3311 // The current ("native") value can differ from the cached value, e.g., the current
3312 // CONFIG will typically have more values than the cached one. Therefore we deal with
3314 const QStringList diffval = values(srcvar, place);
3315 const QStringList oldval = base_vars.value(dstvar);
3317 if (mode == CacheSet) {
3321 if (mode == CacheAdd)
3324 subAll(&newval, diffval);
3326 // We assume that whatever got the cached value to be what it is now will do so
3327 // the next time as well, so it is OK that the early exit here will skip the
3328 // persisting as well.
3329 if (oldval == newval)
3331 base_vars[dstvar] = newval;
3333 if (dstvar == "QMAKEPATH")
3334 cached_qmakepath = newval;
3335 else if (dstvar == "QMAKEFEATURES")
3336 cached_qmakefeatures = newval;
3339 invalidateFeatureRoots();
3344 if (mode == CacheAdd)
3345 varstr += QLatin1String(" +=");
3346 else if (mode == CacheSub)
3347 varstr += QLatin1String(" -=");
3349 varstr += QLatin1String(" =");
3350 if (diffval.count() == 1) {
3351 varstr += QLatin1Char(' ');
3352 varstr += quoteValue(diffval.at(0));
3353 } else if (!diffval.isEmpty()) {
3354 foreach (const QString &vval, diffval) {
3355 varstr += QLatin1String(" \\\n ");
3356 varstr += quoteValue(vval);
3359 varstr += QLatin1Char('\n');
3363 if (superfile.isEmpty()) {
3364 superfile = Option::output_dir + QLatin1String("/.qmake.super");
3365 printf("Info: creating super cache file %s\n", superfile.toLatin1().constData());
3366 vars["_QMAKE_SUPER_CACHE_"] << superfile;
3370 if (cachefile.isEmpty()) {
3371 cachefile = Option::output_dir + QLatin1String("/.qmake.cache");
3372 printf("Info: creating cache file %s\n", cachefile.toLatin1().constData());
3373 vars["_QMAKE_CACHE_"] << cachefile;
3374 if (cached_build_root.isEmpty()) {
3375 cached_build_root = Option::output_dir;
3376 cached_source_root = values("_PRO_FILE_PWD_", place).first();
3377 if (cached_source_root == cached_build_root)
3378 cached_source_root.clear();
3379 invalidateFeatureRoots();
3385 if (!QDir::current().mkpath(qfi.path())) {
3386 fprintf(stderr, "%s:%d: ERROR creating cache directory %s\n",
3387 parser.file.toLatin1().constData(), parser.line_no,
3388 qfi.path().toLatin1().constData());
3392 if (!writeFile(fn, QIODevice::Append, varstr, &errStr)) {
3393 fprintf(stderr, "ERROR writing cache file %s: %s\n",
3394 fn.toLatin1().constData(), errStr.toLatin1().constData());
3395 #if defined(QT_BUILD_QMAKE_LIBRARY)
3403 if (args.count() != 1) {
3404 fprintf(stderr, "%s:%d: mkpath(name) requires one argument.\n",
3405 parser.file.toLatin1().constData(), parser.line_no);
3408 if (!QDir::current().mkpath(args.at(0))) {
3409 fprintf(stderr, "%s:%d: ERROR creating directory %s\n",
3410 parser.file.toLatin1().constData(), parser.line_no,
3411 QDir::toNativeSeparators(args.at(0)).toLatin1().constData());
3415 case T_WRITE_FILE: {
3416 if (args.count() > 3) {
3417 fprintf(stderr, "%s:%d: write_file(name, [content var, [append]]) requires one to three arguments.\n",
3418 parser.file.toLatin1().constData(), parser.line_no);
3421 QIODevice::OpenMode mode = QIODevice::Truncate;
3423 if (args.count() >= 2) {
3424 QStringList vals = values(args.at(1), place);
3425 if (!vals.isEmpty())
3426 contents = vals.join(QLatin1String("\n")) + QLatin1Char('\n');
3427 if (args.count() >= 3)
3428 if (!args.at(2).compare(QLatin1String("append"), Qt::CaseInsensitive))
3429 mode = QIODevice::Append;
3431 QFileInfo qfi(args.at(0));
3432 if (!QDir::current().mkpath(qfi.path())) {
3433 fprintf(stderr, "%s:%d: ERROR creating directory %s\n",
3434 parser.file.toLatin1().constData(), parser.line_no,
3435 qfi.path().toLatin1().constData());
3439 if (!writeFile(args.at(0), mode, contents, &errStr)) {
3440 fprintf(stderr, "%s:%d ERROR writing %s: %s\n",
3441 parser.file.toLatin1().constData(), parser.line_no,
3442 args.at(0).toLatin1().constData(), errStr.toLatin1().constData());
3447 if (args.count() != 2) {
3448 fprintf(stderr, "%s:%d: touch(file, reffile) requires two arguments.\n",
3449 parser.file.toLatin1().constData(), parser.line_no);
3454 if (stat(args.at(1).toLocal8Bit().constData(), &st)) {
3455 fprintf(stderr, "%s:%d: ERROR: cannot stat() reference file %s: %s.\n",
3456 parser.file.toLatin1().constData(), parser.line_no,
3457 args.at(1).toLatin1().constData(), strerror(errno));
3461 utb.actime = time(0);
3462 utb.modtime = st.st_mtime;
3463 if (utime(args.at(0).toLocal8Bit().constData(), &utb)) {
3464 fprintf(stderr, "%s:%d: ERROR: cannot touch %s: %s.\n",
3465 parser.file.toLatin1().constData(), parser.line_no,
3466 args.at(0).toLatin1().constData(), strerror(errno));
3470 HANDLE rHand = CreateFile((wchar_t*)args.at(1).utf16(),
3471 GENERIC_READ, FILE_SHARE_READ,
3472 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
3473 if (rHand == INVALID_HANDLE_VALUE) {
3474 fprintf(stderr, "%s:%d: ERROR: cannot open() reference file %s: %s.\n",
3475 parser.file.toLatin1().constData(), parser.line_no,
3476 args.at(1).toLatin1().constData(),
3477 windowsErrorCode().toLatin1().constData());
3481 GetFileTime(rHand, 0, 0, &ft);
3483 HANDLE wHand = CreateFile((wchar_t*)args.at(0).utf16(),
3484 GENERIC_WRITE, FILE_SHARE_READ,
3485 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
3486 if (wHand == INVALID_HANDLE_VALUE) {
3487 fprintf(stderr, "%s:%d: ERROR: cannot open %s: %s.\n",
3488 parser.file.toLatin1().constData(), parser.line_no,
3489 args.at(0).toLatin1().constData(),
3490 windowsErrorCode().toLatin1().constData());
3493 SetFileTime(wHand, 0, 0, &ft);
3498 fprintf(stderr, "%s:%d: Unknown test function: %s\n", parser.file.toLatin1().constData(), parser.line_no,
3499 func.toLatin1().constData());
3505 QMakeProject::doProjectCheckReqs(const QStringList &deps, QHash<QString, QStringList> &place)
3508 for(QStringList::ConstIterator it = deps.begin(); it != deps.end(); ++it) {
3509 bool test = doProjectTest((*it), place);
3511 debug_msg(1, "Project Parser: %s:%d Failed test: REQUIRES = %s",
3512 parser.file.toLatin1().constData(), parser.line_no,
3513 (*it).toLatin1().constData());
3514 place["QMAKE_FAILED_REQUIREMENTS"].append((*it));
3522 QMakeProject::test(const QString &v)
3524 QHash<QString, QStringList> tmp = vars;
3525 return doProjectTest(v, tmp);
3529 QMakeProject::test(const QString &func, const QList<QStringList> &args)
3531 QHash<QString, QStringList> tmp = vars;
3532 return doProjectTest(func, args, tmp);
3536 QMakeProject::expand(const QString &str)
3539 QHash<QString, QStringList> tmp = vars;
3540 const QStringList ret = doVariableReplaceExpand(str, tmp, &ok);
3543 return QStringList();
3547 QMakeProject::expand(const QString &str, const QString &file, int line)
3550 parser_info pi = parser;
3552 parser.line_no = line;
3553 parser.from_file = false;
3554 QHash<QString, QStringList> tmp = vars;
3555 const QStringList ret = doVariableReplaceExpand(str, tmp, &ok);
3557 return ok ? ret.join(QString(Option::field_sep)) : QString();
3561 QMakeProject::expand(const QString &func, const QList<QStringList> &args)
3563 QHash<QString, QStringList> tmp = vars;
3564 return doProjectExpand(func, args, tmp);
3568 QMakeProject::doVariableReplace(QString &str, QHash<QString, QStringList> &place)
3571 str = doVariableReplaceExpand(str, place, &ret).join(QString(Option::field_sep));
3576 QMakeProject::doVariableReplaceExpand(const QString &str, QHash<QString, QStringList> &place, bool *ok)
3584 const ushort LSQUARE = '[';
3585 const ushort RSQUARE = ']';
3586 const ushort LCURLY = '{';
3587 const ushort RCURLY = '}';
3588 const ushort LPAREN = '(';
3589 const ushort RPAREN = ')';
3590 const ushort DOLLAR = '$';
3591 const ushort SLASH = '\\';
3592 const ushort UNDERSCORE = '_';
3593 const ushort DOT = '.';
3594 const ushort SPACE = ' ';
3595 const ushort TAB = '\t';
3596 const ushort SINGLEQUOTE = '\'';
3597 const ushort DOUBLEQUOTE = '"';
3599 ushort unicode, quote = 0;
3600 const QChar *str_data = str.data();
3601 const int str_len = str.length();
3608 for(int i = 0; i < str_len; ++i) {
3609 unicode = str_data[i].unicode();
3610 const int start_var = i;
3611 if(unicode == DOLLAR && str_len > i+2) {
3612 unicode = str_data[++i].unicode();
3613 if(unicode == DOLLAR) {
3617 enum { VAR, ENVIRON, FUNCTION, PROPERTY } var_type = VAR;
3618 unicode = str_data[++i].unicode();
3619 if(unicode == LSQUARE) {
3620 unicode = str_data[++i].unicode();
3622 var_type = PROPERTY;
3623 } else if(unicode == LCURLY) {
3624 unicode = str_data[++i].unicode();
3627 } else if(unicode == LPAREN) {
3628 unicode = str_data[++i].unicode();
3633 if(!(unicode & (0xFF<<8)) &&
3634 unicode != DOT && unicode != UNDERSCORE &&
3635 //unicode != SINGLEQUOTE && unicode != DOUBLEQUOTE &&
3636 (unicode < 'a' || unicode > 'z') && (unicode < 'A' || unicode > 'Z') &&
3637 (unicode < '0' || unicode > '9') && (!term || unicode != '/'))
3639 var.append(QChar(unicode));
3642 unicode = str_data[i].unicode();
3643 // at this point, i points to either the 'term' or 'next' character (which is in unicode)
3645 if(var_type == VAR && unicode == LPAREN) {
3646 var_type = FUNCTION;
3651 unicode = str_data[i].unicode();
3652 if(unicode == LPAREN) {
3654 } else if(unicode == RPAREN) {
3659 args.append(QChar(unicode));
3662 unicode = str_data[i].unicode();
3665 // at this point i is pointing to the 'next' character (which is in unicode)
3666 // this might actually be a term character since you can do $${func()}
3669 if(unicode != term) {
3670 qmake_error_msg("Missing " + QString(term) + " terminator [found " + (unicode?QString(unicode):QString("end-of-line")) + "]");
3673 return QStringList();
3676 // move the 'cursor' back to the last char of the thing we were looking at
3679 // since i never points to the 'next' character, there is no reason for this to be set
3682 QStringList replacement;
3683 if(var_type == ENVIRON) {
3684 replacement = split_value_list(QString::fromLocal8Bit(qgetenv(var.toLatin1().constData())));
3685 } else if(var_type == PROPERTY) {
3686 if (var == "QMAKE_MKSPECS")
3687 replacement = split_value_list(qmake_mkspec_paths().join(Option::dirlist_sep));
3689 replacement = split_value_list(prop->value(var));
3690 } else if(var_type == FUNCTION) {
3691 replacement = doProjectExpand(var, args, place);
3692 } else if(var_type == VAR) {
3693 replacement = magicValues(var, place);
3695 if(!(replaced++) && start_var)
3696 current = str.left(start_var);
3697 if(!replacement.isEmpty()) {
3699 current += replacement.join(QString(Option::field_sep));
3701 current += replacement.takeFirst();
3702 if(!replacement.isEmpty()) {
3703 if(!current.isEmpty())
3704 ret.append(current);
3705 current = replacement.takeLast();
3706 if(!replacement.isEmpty())
3711 debug_msg(2, "Project Parser [var replace]: %s -> %s",
3712 str.toLatin1().constData(), var.toLatin1().constData(),
3713 replacement.join("::").toLatin1().constData());
3716 current.append("$");
3719 if(quote && unicode == quote) {
3722 } else if(unicode == SLASH) {
3723 bool escape = false;
3724 const char *symbols = "[]{}()$\\'\"";
3725 for(const char *s = symbols; *s; ++s) {
3726 if(str_data[i+1].unicode() == (ushort)*s) {
3730 current = str.left(start_var);
3731 current.append(str.at(i));
3735 if(!escape && !backslashWarned) {
3736 backslashWarned = true;
3737 warn_msg(WarnDeprecated, "%s:%d: Unescaped backslashes are deprecated.",
3738 parser.file.toLatin1().constData(), parser.line_no);
3740 if(escape || !replaced)
3742 } else if(!quote && (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE)) {
3745 if(!(replaced++) && i)
3746 current = str.left(i);
3747 } else if(!quote && (unicode == SPACE || unicode == TAB)) {
3749 if(!current.isEmpty()) {
3750 ret.append(current);
3754 if(replaced && unicode)
3755 current.append(QChar(unicode));
3758 ret = QStringList(str);
3759 else if(!current.isEmpty())
3760 ret.append(current);
3761 //qDebug() << "REPLACE" << str << ret;
3763 warn_msg(WarnDeprecated, "%s:%d: Unmatched quotes are deprecated.",
3764 parser.file.toLatin1().constData(), parser.line_no);
3768 QStringList QMakeProject::magicValues(const QString &_var, const QHash<QString, QStringList> &place) const
3770 QString var = varMap(_var);
3771 if (var == QLatin1String("_LINE_")) { //parser line number
3772 return QStringList(QString::number(parser.line_no));
3773 } else if(var == QLatin1String("_FILE_")) { //parser file
3774 return QStringList(parser.file);
3779 QStringList &QMakeProject::values(const QString &_var, QHash<QString, QStringList> &place)
3781 QString var = varMap(_var);
3785 bool QMakeProject::isEmpty(const QString &v) const
3787 QHash<QString, QStringList>::ConstIterator it = vars.constFind(v);
3788 return it == vars.constEnd() || it->isEmpty();
3792 QMakeProject::dump() const
3795 for (QHash<QString, QStringList>::ConstIterator it = vars.begin(); it != vars.end(); ++it) {
3796 if (!it.key().startsWith('.')) {
3797 QString str = it.key() + " =";
3798 foreach (const QString &v, it.value())
3799 str += ' ' + quoteValue(v);
3804 foreach (const QString &v, out)
3805 puts(qPrintable(v));