Files
qt-creator/src/shared/proparser/profileevaluator.cpp

3479 lines
125 KiB
C++
Raw Normal View History

/**************************************************************************
2008-12-02 12:01:29 +01:00
**
** This file is part of Qt Creator
**
2010-03-05 11:25:49 +01:00
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
2008-12-02 12:01:29 +01:00
**
** Contact: Nokia Corporation (qt-info@nokia.com)
2008-12-02 12:01:29 +01:00
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
2009-08-14 09:30:56 +02:00
** contact the sales department at http://qt.nokia.com/contact.
2008-12-02 12:01:29 +01:00
**
**************************************************************************/
2008-12-02 12:01:29 +01:00
#include "profileevaluator.h"
#include "proitems.h"
#include "ioutils.h"
2008-12-02 12:01:29 +01:00
#include <QtCore/QByteArray>
#include <QtCore/QDateTime>
2008-12-02 12:01:29 +01:00
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QList>
#include <QtCore/QRegExp>
#include <QtCore/QSet>
#include <QtCore/QStack>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QTextStream>
#ifdef PROPARSER_THREAD_SAFE
# include <QtCore/QThreadPool>
#endif
2008-12-02 12:01:29 +01:00
#ifdef Q_OS_UNIX
#include <unistd.h>
#include <sys/utsname.h>
#else
#include <Windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
2008-12-02 12:01:29 +01:00
#ifdef Q_OS_WIN32
#define QT_POPEN _popen
#define QT_PCLOSE _pclose
2008-12-02 12:01:29 +01:00
#else
#define QT_POPEN popen
#define QT_PCLOSE pclose
2008-12-02 12:01:29 +01:00
#endif
using namespace ProFileEvaluatorInternal;
2008-12-02 12:01:29 +01:00
QT_BEGIN_NAMESPACE
static void refFunctions(QHash<QString, ProFunctionDef *> *defs)
{
foreach (ProFunctionDef *itm, *defs)
itm->ref();
}
static void clearFunctions(QHash<QString, ProFunctionDef *> *defs)
{
foreach (ProFunctionDef *itm, *defs)
itm->deref();
defs->clear();
}
static void clearFunctions(ProFileEvaluator::FunctionDefs *defs)
{
clearFunctions(&defs->replaceFunctions);
clearFunctions(&defs->testFunctions);
}
///////////////////////////////////////////////////////////////////////
//
// ProFileCache
//
///////////////////////////////////////////////////////////////////////
ProFileCache::~ProFileCache()
{
foreach (const Entry &ent, parsed_files)
if (ent.pro)
ent.pro->deref();
}
void ProFileCache::discardFile(const QString &fileName)
{
#ifdef PROPARSER_THREAD_SAFE
QMutexLocker lck(&mutex);
#endif
QHash<QString, Entry>::Iterator it = parsed_files.find(fileName);
if (it != parsed_files.end()) {
if (it->pro)
it->pro->deref();
parsed_files.erase(it);
}
}
void ProFileCache::discardFiles(const QString &prefix)
{
#ifdef PROPARSER_THREAD_SAFE
QMutexLocker lck(&mutex);
#endif
QHash<QString, Entry>::Iterator
it = parsed_files.begin(),
end = parsed_files.end();
while (it != end)
if (it.key().startsWith(prefix)) {
if (it->pro)
it->pro->deref();
it = parsed_files.erase(it);
} else {
++it;
}
}
///////////////////////////////////////////////////////////////////////
//
// ProFileOption
//
///////////////////////////////////////////////////////////////////////
ProFileOption::ProFileOption()
{
#ifdef Q_OS_WIN
dirlist_sep = QLatin1Char(';');
dir_sep = QLatin1Char('\\');
#else
dirlist_sep = QLatin1Char(':');
dir_sep = QLatin1Char('/');
#endif
qmakespec = QString::fromLatin1(qgetenv("QMAKESPEC").data());
#if defined(Q_OS_WIN32)
target_mode = TARG_WIN_MODE;
#elif defined(Q_OS_MAC)
target_mode = TARG_MACX_MODE;
#elif defined(Q_OS_QNX6)
target_mode = TARG_QNX6_MODE;
#else
target_mode = TARG_UNIX_MODE;
#endif
cache = 0;
}
ProFileOption::~ProFileOption()
{
clearFunctions(&base_functions);
}
2008-12-02 12:01:29 +01:00
///////////////////////////////////////////////////////////////////////
//
// ProFileEvaluator::Private
//
///////////////////////////////////////////////////////////////////////
class ProFileEvaluator::Private
2008-12-02 12:01:29 +01:00
{
public:
static void initStatics();
Private(ProFileEvaluator *q_, ProFileOption *option);
~Private();
2008-12-02 12:01:29 +01:00
ProFileEvaluator *q;
int m_lineNo; // Error reporting
bool m_verbose;
/////////////// Reading pro file
struct BlockCursor {
BlockCursor() : cursor(0) {}
BlockCursor(BlockCursor &other) : cursor(other.cursor) { other.cursor = 0; }
BlockCursor(ProItem **itp) : cursor(itp) {}
~BlockCursor() { if (cursor) *cursor = 0; }
BlockCursor &operator=(BlockCursor &other) { cursor = other.cursor; other.cursor = 0; return *this; }
void set(ProItem **itp) { if (cursor) *cursor = 0; cursor = itp; }
void reset() { if (cursor) { *cursor = 0; cursor = 0; } }
void append(ProItem *item) { *cursor = item; cursor = item->nextRef(); }
bool isValid() const { return cursor != 0; }
private:
ProItem **cursor;
};
struct BlockScope {
BlockScope() : braceLevel(0), special(false) {}
BlockScope(BlockScope &other) :
cursor(other.cursor), elseCursor(other.elseCursor),
braceLevel(other.braceLevel), special(other.special) {}
BlockCursor cursor; // Current appending position
BlockCursor elseCursor; // Appending position for else branch of last conditional in scope
int braceLevel; // Nesting of braces in scope
bool special; // Single-line conditionals cannot have else branches
};
enum ScopeState {
StNew, // Fresh scope
StCtrl, // Control statement (for or else) met on current line
StCond // Conditionals met on current line
};
2008-12-02 12:01:29 +01:00
bool read(ProFile *pro);
bool read(ProFile *pro, const QString &content);
bool read(ProItem **itp, const QString &content);
bool readInternal(ProItem **itp, const QString &content, ushort *buf);
2008-12-02 12:01:29 +01:00
void updateItem(ushort *uc, ushort *ptr);
ProVariable *startVariable(ushort *uc, ushort *ptr);
void finalizeVariable(ProVariable *var, ushort *uc, ushort *ptr);
void insertOperator(ProItem::ProItemKind opkind);
void enterScope(BlockCursor &cursor, bool special, ScopeState state);
void enterScope(ProItem **itp, bool special, ScopeState state)
{ BlockCursor curs(itp); enterScope(curs, special, state); }
void flushCond();
void flushScopes();
QStack<BlockScope> m_blockstack;
ScopeState m_state;
bool m_canElse; // Conditionals met on previous line, but no scope was opened
bool m_invert; // Pending conditional is negated
enum { NoOperator, AndOperator, OrOperator } m_operator; // Pending conditional is ORed/ANDed
/////////////// Evaluating pro file contents
ProItem::ProItemReturn visitProFile(ProFile *pro);
ProItem::ProItemReturn visitProBlock(ProItem *items);
ProItem::ProItemReturn visitProLoop(ProLoop *loop);
void visitProFunctionDef(ProFunctionDef *def);
void visitProVariable(ProVariable *variable);
ProItem::ProItemReturn visitProCondition(ProCondition *condition);
2008-12-02 12:01:29 +01:00
static inline QString map(const QString &var);
QHash<QString, QStringList> *findValues(const QString &variableName,
QHash<QString, QStringList>::Iterator *it);
QStringList &valuesRef(const QString &variableName);
QStringList valuesDirect(const QString &variableName) const;
2008-12-02 12:01:29 +01:00
QStringList values(const QString &variableName) const;
QString propertyValue(const QString &val, bool complain = true) const;
2008-12-02 12:01:29 +01:00
static QStringList split_value_list(const QString &vals);
2008-12-02 12:01:29 +01:00
bool isActiveConfig(const QString &config, bool regex = false);
QStringList expandVariableReferences(const QString &value, int *pos = 0, bool joined = false);
2008-12-02 12:01:29 +01:00
QStringList evaluateExpandFunction(const QString &function, const QString &arguments);
QString format(const char *format) const;
void logMessage(const QString &msg) const;
void errorMessage(const QString &msg) const;
void fileMessage(const QString &msg) const;
2008-12-02 12:01:29 +01:00
QString currentFileName() const;
QString currentDirectory() const;
2008-12-02 12:01:29 +01:00
ProFile *currentProFile() const;
QString resolvePath(const QString &fileName) const
{ return IoUtils::resolvePath(currentDirectory(), fileName); }
2008-12-02 12:01:29 +01:00
ProItem::ProItemReturn evaluateConditionalFunction(const QString &function, const QString &arguments);
ProFile *parsedProFile(const QString &fileName, bool cache,
const QString &contents = QString());
bool evaluateFile(const QString &fileName);
bool evaluateFeatureFile(const QString &fileName,
QHash<QString, QStringList> *values = 0, FunctionDefs *defs = 0);
bool evaluateFileInto(const QString &fileName,
QHash<QString, QStringList> *values, FunctionDefs *defs);
2008-12-02 12:01:29 +01:00
static inline ProItem::ProItemReturn returnBool(bool b)
{ return b ? ProItem::ReturnTrue : ProItem::ReturnFalse; }
QList<QStringList> prepareFunctionArgs(const QString &arguments);
QStringList evaluateFunction(ProFunctionDef *func, const QList<QStringList> &argumentsList, bool *ok);
QStringList qmakeMkspecPaths() const;
QStringList qmakeFeaturePaths() const;
2008-12-02 12:01:29 +01:00
int m_skipLevel;
int m_loopLevel; // To report unexpected break() and next()s
bool m_cumulative;
2008-12-02 12:01:29 +01:00
QStack<ProFile*> m_profileStack; // To handle 'include(a.pri), so we can track back to 'a.pro' when finished with 'a.pri'
QString m_outputDir;
2008-12-02 12:01:29 +01:00
int m_listCount;
FunctionDefs m_functionDefs;
QStringList m_returnValue;
QStack<QHash<QString, QStringList> > m_valuemapStack; // VariableName must be us-ascii, the content however can be non-us-ascii.
QHash<const ProFile*, QHash<QString, QStringList> > m_filevaluemap; // Variables per include file
QStringList m_addUserConfigCmdArgs;
QStringList m_removeUserConfigCmdArgs;
bool m_parsePreAndPostFiles;
ProFileOption *m_option;
enum ExpandFunc {
2010-04-28 11:37:51 +02:00
E_MEMBER=1, E_FIRST, E_LAST, E_SIZE, E_CAT, E_FROMFILE, E_EVAL, E_LIST,
E_SPRINTF, E_JOIN, E_SPLIT, E_BASENAME, E_DIRNAME, E_SECTION,
E_FIND, E_SYSTEM, E_UNIQUE, E_QUOTE, E_ESCAPE_EXPAND,
E_UPPER, E_LOWER, E_FILES, E_PROMPT, E_RE_ESCAPE,
E_REPLACE
};
enum TestFunc {
T_REQUIRES=1, T_GREATERTHAN, T_LESSTHAN, T_EQUALS,
T_EXISTS, T_EXPORT, T_CLEAR, T_UNSET, T_EVAL, T_CONFIG, T_SYSTEM,
T_RETURN, T_BREAK, T_NEXT, T_DEFINED, T_CONTAINS, T_INFILE,
T_COUNT, T_ISEMPTY, T_INCLUDE, T_LOAD, T_DEBUG, T_MESSAGE, T_IF
};
enum VarName {
V_LITERAL_DOLLAR, V_LITERAL_HASH, V_LITERAL_WHITESPACE,
V_DIRLIST_SEPARATOR, V_DIR_SEPARATOR,
V_OUT_PWD, V_PWD, V_IN_PWD,
V__FILE_, V__LINE_, V__PRO_FILE_, V__PRO_FILE_PWD_,
V_QMAKE_HOST_arch, V_QMAKE_HOST_name, V_QMAKE_HOST_os,
V_QMAKE_HOST_version, V_QMAKE_HOST_version_string,
V__DATE_, V__QMAKE_CACHE_
};
2008-12-02 12:01:29 +01:00
};
#if !defined(__GNUC__) || __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3)
Q_DECLARE_TYPEINFO(ProFileEvaluator::Private::BlockCursor, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(ProFileEvaluator::Private::BlockScope, Q_MOVABLE_TYPE);
#endif
static struct {
QString field_sep;
QString strelse;
QString strtrue;
QString strfalse;
QString strunix;
QString strmacx;
QString strqnx6;
QString strmac9;
QString strmac;
QString strwin32;
QString strCONFIG;
QString strARGS;
QString strDot;
QString strDotDot;
QString strfor;
QString strever;
QString strforever;
QString strdefineTest;
QString strdefineReplace;
QString strTEMPLATE;
QString strQMAKE_DIR_SEP;
QHash<QString, int> expands;
QHash<QString, int> functions;
QHash<QString, int> varList;
QHash<QString, QString> varMap;
QRegExp reg_variableName;
QStringList fakeValue;
} statics;
void ProFileEvaluator::Private::initStatics()
{
if (!statics.field_sep.isNull())
return;
statics.field_sep = QLatin1String(" ");
statics.strelse = QLatin1String("else");
statics.strtrue = QLatin1String("true");
statics.strfalse = QLatin1String("false");
statics.strunix = QLatin1String("unix");
statics.strmacx = QLatin1String("macx");
statics.strqnx6 = QLatin1String("qnx6");
statics.strmac9 = QLatin1String("mac9");
statics.strmac = QLatin1String("mac");
statics.strwin32 = QLatin1String("win32");
statics.strCONFIG = QLatin1String("CONFIG");
statics.strARGS = QLatin1String("ARGS");
statics.strDot = QLatin1String(".");
statics.strDotDot = QLatin1String("..");
statics.strfor = QLatin1String("for");
statics.strever = QLatin1String("ever");
statics.strforever = QLatin1String("forever");
statics.strdefineTest = QLatin1String("defineTest");
statics.strdefineReplace = QLatin1String("defineReplace");
statics.strTEMPLATE = QLatin1String("TEMPLATE");
statics.strQMAKE_DIR_SEP = QLatin1String("QMAKE_DIR_SEP");
statics.reg_variableName.setPattern(QLatin1String("\\$\\(.*\\)"));
statics.reg_variableName.setMinimal(true);
statics.fakeValue.detach(); // It has to have a unique begin() value
static const struct {
const char * const name;
const ExpandFunc func;
} expandInits[] = {
{ "member", E_MEMBER },
{ "first", E_FIRST },
{ "last", E_LAST },
2010-04-28 11:37:51 +02:00
{ "size", E_SIZE },
{ "cat", E_CAT },
{ "fromfile", E_FROMFILE },
{ "eval", E_EVAL },
{ "list", E_LIST },
{ "sprintf", E_SPRINTF },
{ "join", E_JOIN },
{ "split", E_SPLIT },
{ "basename", E_BASENAME },
{ "dirname", E_DIRNAME },
{ "section", E_SECTION },
{ "find", E_FIND },
{ "system", E_SYSTEM },
{ "unique", E_UNIQUE },
{ "quote", E_QUOTE },
{ "escape_expand", E_ESCAPE_EXPAND },
{ "upper", E_UPPER },
{ "lower", E_LOWER },
{ "re_escape", E_RE_ESCAPE },
{ "files", E_FILES },
{ "prompt", E_PROMPT }, // interactive, so cannot be implemented
{ "replace", E_REPLACE }
};
for (unsigned i = 0; i < sizeof(expandInits)/sizeof(expandInits[0]); ++i)
statics.expands.insert(QLatin1String(expandInits[i].name), expandInits[i].func);
static const struct {
const char * const name;
const TestFunc func;
} testInits[] = {
{ "requires", T_REQUIRES },
{ "greaterThan", T_GREATERTHAN },
{ "lessThan", T_LESSTHAN },
{ "equals", T_EQUALS },
{ "isEqual", T_EQUALS },
{ "exists", T_EXISTS },
{ "export", T_EXPORT },
{ "clear", T_CLEAR },
{ "unset", T_UNSET },
{ "eval", T_EVAL },
{ "CONFIG", T_CONFIG },
{ "if", T_IF },
{ "isActiveConfig", T_CONFIG },
{ "system", T_SYSTEM },
{ "return", T_RETURN },
{ "break", T_BREAK },
{ "next", T_NEXT },
{ "defined", T_DEFINED },
{ "contains", T_CONTAINS },
{ "infile", T_INFILE },
{ "count", T_COUNT },
{ "isEmpty", T_ISEMPTY },
{ "load", T_LOAD },
{ "include", T_INCLUDE },
{ "debug", T_DEBUG },
{ "message", T_MESSAGE },
{ "warning", T_MESSAGE },
{ "error", T_MESSAGE },
};
for (unsigned i = 0; i < sizeof(testInits)/sizeof(testInits[0]); ++i)
statics.functions.insert(QLatin1String(testInits[i].name), testInits[i].func);
static const char * const names[] = {
"LITERAL_DOLLAR", "LITERAL_HASH", "LITERAL_WHITESPACE",
"DIRLIST_SEPARATOR", "DIR_SEPARATOR",
"OUT_PWD", "PWD", "IN_PWD",
"_FILE_", "_LINE_", "_PRO_FILE_", "_PRO_FILE_PWD_",
"QMAKE_HOST.arch", "QMAKE_HOST.name", "QMAKE_HOST.os",
"QMAKE_HOST.version", "QMAKE_HOST.version_string",
"_DATE_", "_QMAKE_CACHE_"
};
for (unsigned i = 0; i < sizeof(names)/sizeof(names[0]); ++i)
statics.varList.insert(QLatin1String(names[i]), i);
static const struct {
const char * const oldname, * const newname;
} mapInits[] = {
{ "INTERFACES", "FORMS" },
{ "QMAKE_POST_BUILD", "QMAKE_POST_LINK" },
{ "TARGETDEPS", "POST_TARGETDEPS" },
{ "LIBPATH", "QMAKE_LIBDIR" },
{ "QMAKE_EXT_MOC", "QMAKE_EXT_CPP_MOC" },
{ "QMAKE_MOD_MOC", "QMAKE_H_MOD_MOC" },
{ "QMAKE_LFLAGS_SHAPP", "QMAKE_LFLAGS_APP" },
{ "PRECOMPH", "PRECOMPILED_HEADER" },
{ "PRECOMPCPP", "PRECOMPILED_SOURCE" },
{ "INCPATH", "INCLUDEPATH" },
{ "QMAKE_EXTRA_WIN_COMPILERS", "QMAKE_EXTRA_COMPILERS" },
{ "QMAKE_EXTRA_UNIX_COMPILERS", "QMAKE_EXTRA_COMPILERS" },
{ "QMAKE_EXTRA_WIN_TARGETS", "QMAKE_EXTRA_TARGETS" },
{ "QMAKE_EXTRA_UNIX_TARGETS", "QMAKE_EXTRA_TARGETS" },
{ "QMAKE_EXTRA_UNIX_INCLUDES", "QMAKE_EXTRA_INCLUDES" },
{ "QMAKE_EXTRA_UNIX_VARIABLES", "QMAKE_EXTRA_VARIABLES" },
{ "QMAKE_RPATH", "QMAKE_LFLAGS_RPATH" },
{ "QMAKE_FRAMEWORKDIR", "QMAKE_FRAMEWORKPATH" },
{ "QMAKE_FRAMEWORKDIR_FLAGS", "QMAKE_FRAMEWORKPATH_FLAGS" }
};
for (unsigned i = 0; i < sizeof(mapInits)/sizeof(mapInits[0]); ++i)
statics.varMap.insert(QLatin1String(mapInits[i].oldname),
QLatin1String(mapInits[i].newname));
}
QString ProFileEvaluator::Private::map(const QString &var)
{
return statics.varMap.value(var, var);
}
ProFileEvaluator::Private::Private(ProFileEvaluator *q_, ProFileOption *option)
: q(q_), m_option(option)
2008-12-02 12:01:29 +01:00
{
// So that single-threaded apps don't have to call initialize() for now.
initStatics();
// Configuration, more or less
2008-12-02 12:01:29 +01:00
m_verbose = true;
m_cumulative = true;
m_parsePreAndPostFiles = true;
// Evaluator state
m_skipLevel = 0;
m_loopLevel = 0;
m_listCount = 0;
m_valuemapStack.push(QHash<QString, QStringList>());
2008-12-02 12:01:29 +01:00
}
ProFileEvaluator::Private::~Private()
{
clearFunctions(&m_functionDefs);
}
////////// Parser ///////////
2008-12-02 12:01:29 +01:00
bool ProFileEvaluator::Private::read(ProFile *pro)
{
QFile file(pro->fileName());
if (!file.open(QIODevice::ReadOnly)) {
if (IoUtils::exists(pro->fileName()))
errorMessage(format("%1 not readable.").arg(pro->fileName()));
2008-12-02 12:01:29 +01:00
return false;
}
QString content(QString::fromLatin1(file.readAll())); // yes, really latin1
file.close();
2009-10-02 17:37:02 +02:00
m_lineNo = 1;
m_profileStack.push(pro);
bool ret = readInternal(pro->itemsRef(), content, (ushort*)content.data());
m_profileStack.pop();
return ret;
}
bool ProFileEvaluator::Private::read(ProFile *pro, const QString &content)
{
QString buf;
buf.reserve(content.size());
2009-10-02 17:37:02 +02:00
m_lineNo = 1;
m_profileStack.push(pro);
bool ret = readInternal(pro->itemsRef(), content, (ushort*)buf.data());
m_profileStack.pop();
return ret;
}
bool ProFileEvaluator::Private::read(ProItem **itp, const QString &content)
{
QString buf;
buf.reserve(content.size());
m_lineNo = 0;
return readInternal(itp, content, (ushort*)buf.data());
}
// We know that the buffer cannot grow larger than the input string,
// and the read() functions rely on it.
bool ProFileEvaluator::Private::readInternal(ProItem **itp, const QString &in, ushort *buf)
{
// Parser state
m_blockstack.resize(m_blockstack.size() + 1);
m_blockstack.top().cursor.set(itp);
2008-12-02 12:01:29 +01:00
// We rely on QStrings being null-terminated, so don't maintain a global end pointer.
const ushort *cur = (const ushort *)in.unicode();
m_canElse = false;
freshLine:
m_state = StNew;
m_invert = false;
m_operator = NoOperator;
ProVariable *currAssignment = 0;
ushort *ptr = buf;
int parens = 0;
bool inError = false;
bool putSpace = false;
ushort quote = 0;
forever {
ushort c;
// First, skip leading whitespace
for (;; ++cur) {
c = *cur;
if (c == '\n' || !c) { // Entirely empty line (sans whitespace)
if (currAssignment) {
finalizeVariable(currAssignment, buf, ptr);
currAssignment = 0;
} else {
updateItem(buf, ptr);
}
if (c) {
++cur;
++m_lineNo;
goto freshLine;
}
2010-05-11 12:09:39 +02:00
if (m_blockstack.size() > 1)
logMessage(format("Missing closing brace(s)."));
return true;
2008-12-02 12:01:29 +01:00
}
if (c != ' ' && c != '\t' && c != '\r')
break;
}
// Then strip comments. Yep - no escaping is possible.
const ushort *end; // End of this line
const ushort *cptr; // Start of next line
for (cptr = cur;; ++cptr) {
c = *cptr;
if (c == '#') {
for (end = cptr; (c = *++cptr);) {
if (c == '\n') {
++cptr;
break;
}
}
if (end == cur) { // Line with only a comment (sans whitespace)
// Qmake bizarreness: such lines do not affect line continuations
goto ignore;
}
break;
}
if (!c) {
end = cptr;
break;
}
if (c == '\n') {
end = cptr++;
break;
}
}
// Then look for line continuations. Yep - no escaping here as well.
bool lineCont;
forever {
// We don't have to check for underrun here, as we already determined
// that the line is non-empty.
ushort ec = *(end - 1);
if (ec == '\\') {
--end;
lineCont = true;
break;
}
if (ec != ' ' && ec != '\t' && ec != '\r') {
lineCont = false;
break;
}
--end;
}
if (!inError) {
// Finally, do the tokenization
if (!currAssignment) {
newItem:
do {
if (cur == end)
goto lineEnd;
c = *cur++;
} while (c == ' ' || c == '\t');
forever {
if (c == '"') {
quote = '"' - quote;
} else if (c == '!' && ptr == buf) {
m_invert ^= true;
goto nextItem;
} else if (!quote) {
if (c == '(') {
++parens;
} else if (c == ')') {
--parens;
} else if (!parens) {
if (c == ':') {
updateItem(buf, ptr);
if (m_state == StNew)
logMessage(format("And operator without prior condition."));
else
m_operator = AndOperator;
nextItem:
ptr = buf;
putSpace = false;
goto newItem;
}
if (c == '|') {
updateItem(buf, ptr);
if (m_state != StCond)
logMessage(format("Or operator without prior condition."));
else
m_operator = OrOperator;
goto nextItem;
}
if (c == '{') {
updateItem(buf, ptr);
flushCond();
++m_blockstack.top().braceLevel;
goto nextItem;
}
if (c == '}') {
updateItem(buf, ptr);
flushScopes();
if (!m_blockstack.top().braceLevel)
errorMessage(format("Excess closing brace."));
else if (!--m_blockstack.top().braceLevel
&& m_blockstack.count() != 1) {
m_blockstack.resize(m_blockstack.size() - 1);
m_state = StNew;
m_canElse = false;
}
goto nextItem;
}
if (c == '=') {
if ((currAssignment = startVariable(buf, ptr))) {
ptr = buf;
putSpace = false;
break;
}
ptr = buf;
inError = true;
goto skip;
}
}
}
if (putSpace) {
putSpace = false;
*ptr++ = ' ';
}
*ptr++ = c;
forever {
if (cur == end)
goto lineEnd;
c = *cur++;
if (c != ' ' && c != '\t')
break;
putSpace = true;
}
}
} // !currAssignment
do {
if (cur == end)
goto lineEnd;
c = *cur++;
} while (c == ' ' || c == '\t');
forever {
if (putSpace) {
putSpace = false;
*ptr++ = ' ';
}
*ptr++ = c;
forever {
if (cur == end)
goto lineEnd;
c = *cur++;
if (c != ' ' && c != '\t')
break;
putSpace = true;
}
}
lineEnd:
if (lineCont) {
putSpace = (ptr != buf);
} else {
if (currAssignment) {
finalizeVariable(currAssignment, buf, ptr);
currAssignment = 0;
} else {
updateItem(buf, ptr);
}
ptr = buf;
putSpace = false;
}
} // !inError
skip:
if (!lineCont) {
cur = cptr;
++m_lineNo;
goto freshLine;
}
ignore:
cur = cptr;
++m_lineNo;
2008-12-02 12:01:29 +01:00
}
}
ProVariable *ProFileEvaluator::Private::startVariable(ushort *uc, ushort *ptr)
2008-12-02 12:01:29 +01:00
{
flushCond();
2008-12-02 12:01:29 +01:00
if (ptr == uc) // Line starting with '=', like a conflict marker
return 0;
ProVariable::VariableOperator opkind;
switch (*(ptr - 1)) {
2008-12-02 12:01:29 +01:00
case '+':
--ptr;
2008-12-02 12:01:29 +01:00
opkind = ProVariable::AddOperator;
break;
case '-':
--ptr;
2008-12-02 12:01:29 +01:00
opkind = ProVariable::RemoveOperator;
break;
case '*':
--ptr;
2008-12-02 12:01:29 +01:00
opkind = ProVariable::UniqueAddOperator;
break;
case '~':
--ptr;
2008-12-02 12:01:29 +01:00
opkind = ProVariable::ReplaceOperator;
break;
default:
opkind = ProVariable::SetOperator;
goto skipTrunc;
2008-12-02 12:01:29 +01:00
}
if (ptr == uc) // Line starting with manipulation operator
return 0;
if (*(ptr - 1) == ' ')
--ptr;
skipTrunc:
ProVariable *variable = new ProVariable(map(QString((QChar*)uc, ptr - uc)));
2008-12-02 12:01:29 +01:00
variable->setLineNumber(m_lineNo);
variable->setVariableOperator(opkind);
return variable;
}
2008-12-02 12:01:29 +01:00
void ProFileEvaluator::Private::finalizeVariable(ProVariable *variable, ushort *uc, ushort *ptr)
{
variable->setValue(QString((QChar*)uc, ptr - uc));
m_blockstack.top().cursor.append(variable);
2008-12-02 12:01:29 +01:00
}
void ProFileEvaluator::Private::enterScope(BlockCursor &cursor, bool special, ScopeState state)
2008-12-02 12:01:29 +01:00
{
m_blockstack.resize(m_blockstack.size() + 1);
m_blockstack.top().cursor = cursor;
m_blockstack.top().special = special;
m_state = state;
m_canElse = false;
2008-12-02 12:01:29 +01:00
}
void ProFileEvaluator::Private::flushScopes()
2008-12-02 12:01:29 +01:00
{
if (m_state == StNew) {
while (!m_blockstack.top().braceLevel && m_blockstack.size() > 1)
m_blockstack.resize(m_blockstack.size() - 1);
m_blockstack.top().elseCursor.reset();
m_canElse = false;
}
}
void ProFileEvaluator::Private::flushCond()
{
if (m_state == StCond) {
ProBranch *blk = new ProBranch();
blk->setLineNumber(m_lineNo);
BlockScope &top = m_blockstack.top();
top.cursor.append(blk);
if (!top.special || top.braceLevel) {
top.elseCursor.set(blk->elseItemsRef());
} else {
*blk->elseItemsRef() = 0;
// elseCursor was either never set in this scope
// or the last flushScopes reset it.
}
enterScope(blk->thenItemsRef(), false, StNew);
} else {
flushScopes();
}
2008-12-02 12:01:29 +01:00
}
void ProFileEvaluator::Private::insertOperator(ProItem::ProItemKind opkind)
2008-12-02 12:01:29 +01:00
{
ProItem *proOp = new ProItem(opkind);
proOp->setLineNumber(m_lineNo);
m_blockstack.top().cursor.append(proOp);
2008-12-02 12:01:29 +01:00
}
static bool get_next_arg(const QString &params, int *pos, QString *out)
2008-12-02 12:01:29 +01:00
{
int quote = 0;
int parens = 0;
const ushort *uc = (const ushort *)params.constData();
const ushort *params_start = uc + *pos;
if (*params_start == ' ')
++params_start;
const ushort *params_data = params_start;
const ushort *params_next = 0;
for (;; params_data++) {
ushort unicode = *params_data;
if (!unicode) { // Huh?
params_next = params_data;
break;
} else if (unicode == '(') {
++parens;
} else if (unicode == ')') {
if (--parens < 0) {
params_next = params_data;
break;
}
} else if (quote && unicode == quote) {
quote = 0;
} else if (!quote && (unicode == '\'' || unicode == '"')) {
quote = unicode;
}
if (!parens && !quote && unicode == ',') {
params_next = params_data + 1;
break;
}
}
if (params_data == params_start)
return false;
if (out) {
if (params_data[-1] == ' ')
--params_data;
*out = params.mid(params_start - uc, params_data - params_start);
}
*pos = params_next - uc;
return true;
}
static bool isKeyFunc(const QString &str, const QString &key, int *pos)
{
if (!str.startsWith(key))
return false;
const ushort *uc = (const ushort *)str.constData() + key.length();
if (*uc == ' ')
uc++;
if (*uc != '(')
return false;
*pos = uc - (const ushort *)str.constData() + 1;
return true;
2008-12-02 12:01:29 +01:00
}
void ProFileEvaluator::Private::updateItem(ushort *uc, ushort *ptr)
2008-12-02 12:01:29 +01:00
{
if (ptr == uc)
2008-12-02 12:01:29 +01:00
return;
QString str((QChar*)uc, ptr - uc);
int pos;
const QString *defName;
ProFunctionDef::FunctionType defType;
if (!str.compare(statics.strelse, Qt::CaseInsensitive)) {
if (m_invert || m_operator != NoOperator) {
logMessage(format("Unexpected operator in front of else."));
return;
}
BlockScope &top = m_blockstack.top();
if (m_canElse && (!top.special || top.braceLevel)) {
ProBranch *blk = new ProBranch();
blk->setLineNumber(m_lineNo);
*blk->thenItemsRef() = 0;
top.cursor.append(blk);
enterScope(blk->elseItemsRef(), false, StCtrl);
return;
}
forever {
BlockScope &top = m_blockstack.top();
if (top.elseCursor.isValid()) {
BlockCursor cursor(top.elseCursor); // ref into stack becomes stale
enterScope(cursor, false, StCtrl);
return;
}
if (top.braceLevel || m_blockstack.size() == 1)
break;
m_blockstack.resize(m_blockstack.size() - 1);
}
errorMessage(format("Unexpected 'else'."));
} else if (isKeyFunc(str, statics.strfor, &pos)) {
flushCond();
if (m_invert || m_operator == OrOperator) {
// '|' could actually work reasonably, but qmake does nonsense here.
logMessage(format("Unexpected operator in front of for()."));
return;
}
QString var, expr;
if (!get_next_arg(str, &pos, &var)
|| (get_next_arg(str, &pos, &expr) && get_next_arg(str, &pos, 0))) {
logMessage(format("Syntax is for(var, list), for(var, forever) or for(ever)."));
return;
}
if (expr.isEmpty()) {
expr = var;
var.clear();
}
ProLoop *loop = new ProLoop(var, expr);
m_blockstack.top().cursor.append(loop);
enterScope(loop->itemsRef(), true, StCtrl);
} else if (isKeyFunc(str, statics.strdefineReplace, &pos)) {
defName = &statics.strdefineReplace;
defType = ProFunctionDef::ReplaceFunction;
goto deffunc;
} else if (isKeyFunc(str, statics.strdefineTest, &pos)) {
defName = &statics.strdefineTest;
defType = ProFunctionDef::TestFunction;
deffunc:
flushScopes();
if (m_invert) {
logMessage(format("Unexpected operator in front of function definition."));
return;
}
QString func;
if (!get_next_arg(str, &pos, &func) || get_next_arg(str, &pos, 0)) {
logMessage(format("%s(function) requires one argument.").arg(*defName));
return;
}
if (m_operator != NoOperator) {
insertOperator(m_operator == AndOperator ? ProItem::OpAndKind : ProItem::OpOrKind);
m_operator = NoOperator;
}
ProFunctionDef *def = new ProFunctionDef(func, defType);
m_blockstack.top().cursor.append(def);
enterScope(def->itemsRef(), true, StCtrl);
} else {
flushScopes();
if (m_operator != NoOperator) {
insertOperator(m_operator == AndOperator ? ProItem::OpAndKind : ProItem::OpOrKind);
m_operator = NoOperator;
}
if (m_invert) {
insertOperator(ProItem::OpNotKind);
m_invert = false;
}
ProItem *item = new ProCondition(str);
item->setLineNumber(m_lineNo);
m_blockstack.top().cursor.append(item);
m_state = StCond;
m_canElse = true;
}
2008-12-02 12:01:29 +01:00
}
//////// Evaluator tools /////////
QStringList ProFileEvaluator::Private::split_value_list(const QString &vals)
{
QString build;
QStringList ret;
QStack<char> quote;
const ushort SPACE = ' ';
const ushort LPAREN = '(';
const ushort RPAREN = ')';
const ushort SINGLEQUOTE = '\'';
const ushort DOUBLEQUOTE = '"';
const ushort BACKSLASH = '\\';
ushort unicode;
const QChar *vals_data = vals.data();
const int vals_len = vals.length();
for (int x = 0, parens = 0; x < vals_len; x++) {
unicode = vals_data[x].unicode();
if (x != (int)vals_len-1 && unicode == BACKSLASH &&
(vals_data[x+1].unicode() == SINGLEQUOTE || vals_data[x+1].unicode() == DOUBLEQUOTE)) {
build += vals_data[x++]; //get that 'escape'
} else if (!quote.isEmpty() && unicode == quote.top()) {
quote.pop();
} else if (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE) {
quote.push(unicode);
} else if (unicode == RPAREN) {
--parens;
} else if (unicode == LPAREN) {
++parens;
}
if (!parens && quote.isEmpty() && vals_data[x] == SPACE) {
ret << build;
build.clear();
} else {
build += vals_data[x];
}
}
if (!build.isEmpty())
ret << build;
return ret;
}
static void insertUnique(QStringList *varlist, const QStringList &value)
{
foreach (const QString &str, value)
if (!varlist->contains(str))
varlist->append(str);
}
static void removeEach(QStringList *varlist, const QStringList &value)
{
foreach (const QString &str, value)
varlist->removeAll(str);
}
static void replaceInList(QStringList *varlist,
const QRegExp &regexp, const QString &replace, bool global)
{
for (QStringList::Iterator varit = varlist->begin(); varit != varlist->end(); ) {
if ((*varit).contains(regexp)) {
(*varit).replace(regexp, replace);
if ((*varit).isEmpty())
varit = varlist->erase(varit);
else
++varit;
if (!global)
break;
} else {
++varit;
}
}
}
static QString expandEnvVars(const QString &str)
{
QString string = str;
int rep;
QRegExp reg_variableName = statics.reg_variableName; // Copy for thread safety
while ((rep = reg_variableName.indexIn(string)) != -1)
string.replace(rep, reg_variableName.matchedLength(),
QString::fromLocal8Bit(qgetenv(string.mid(rep + 2, reg_variableName.matchedLength() - 3).toLatin1().constData()).constData()));
return string;
}
static QStringList expandEnvVars(const QStringList &x)
{
QStringList ret;
foreach (const QString &str, x)
ret << expandEnvVars(str);
return ret;
}
// This is braindead, but we want qmake compat
static QString fixPathToLocalOS(const QString &str)
{
QString string = expandEnvVars(str);
2009-08-04 20:51:49 +02:00
if (string.length() > 2 && string.at(0).isLetter() && string.at(1) == QLatin1Char(':'))
string[0] = string[0].toLower();
#if defined(Q_OS_WIN32)
string.replace(QLatin1Char('/'), QLatin1Char('\\'));
#else
string.replace(QLatin1Char('\\'), QLatin1Char('/'));
#endif
return string;
}
2010-04-29 17:46:57 +02:00
static bool isTrue(const QString &str)
{
return !str.compare(statics.strtrue, Qt::CaseInsensitive) || str.toInt();
}
//////// Evaluator /////////
2008-12-02 12:01:29 +01:00
ProItem::ProItemReturn ProFileEvaluator::Private::visitProBlock(ProItem *items)
{
bool okey = true, or_op = false, invert = false;
ProItem::ProItemReturn ret = ProItem::ReturnTrue;
for (ProItem *itm = items; itm; itm = itm->next()) {
switch (itm->kind()) {
case ProItem::VariableKind:
visitProVariable(static_cast<ProVariable*>(itm));
continue;
case ProItem::BranchKind:
if (m_cumulative) {
if (!okey)
m_skipLevel++;
ret = visitProBlock(static_cast<ProBranch*>(itm)->thenItems());
if (!okey)
m_skipLevel--;
else
m_skipLevel++;
if (ret == ProItem::ReturnTrue || ret == ProItem::ReturnFalse)
ret = visitProBlock(static_cast<ProBranch*>(itm)->elseItems());
if (okey)
m_skipLevel--;
} else {
ret = visitProBlock(okey ? static_cast<ProBranch*>(itm)->thenItems()
: static_cast<ProBranch*>(itm)->elseItems());
}
okey = true, or_op = false; // force next evaluation
break;
case ProItem::LoopKind:
if (m_cumulative) // This is a no-win situation, so just pretend it's no loop
ret = visitProBlock(static_cast<ProLoop*>(itm)->items());
else if (okey != or_op)
ret = visitProLoop(static_cast<ProLoop*>(itm));
okey = true, or_op = false; // force next evaluation
break;
case ProItem::FunctionDefKind:
if (m_cumulative || okey != or_op)
visitProFunctionDef(static_cast<ProFunctionDef *>(itm));
okey = true, or_op = false; // force next evaluation
continue;
case ProItem::OpNotKind:
invert ^= true;
break;
case ProItem::OpAndKind:
or_op = false;
break;
case ProItem::OpOrKind:
or_op = true;
break;
case ProItem::ConditionKind:
if (!m_skipLevel && okey != or_op) {
ret = visitProCondition(static_cast<ProCondition*>(itm));
switch (ret) {
case ProItem::ReturnTrue: okey = true; break;
case ProItem::ReturnFalse: okey = false; break;
default: return ret;
}
okey ^= invert;
} else if (m_cumulative) {
m_skipLevel++;
visitProCondition(static_cast<ProCondition*>(itm));
m_skipLevel--;
}
or_op = !okey; // tentatively force next evaluation
invert = false;
break;
default: Q_ASSERT_X(false, "visitProBlock", "unexpected item type");
}
if (ret != ProItem::ReturnTrue && ret != ProItem::ReturnFalse)
break;
}
return ret;
}
void ProFileEvaluator::Private::visitProFunctionDef(ProFunctionDef *def)
2008-12-02 12:01:29 +01:00
{
QHash<QString, ProFunctionDef *> *hash =
(def->type() == ProFunctionDef::TestFunction
? &m_functionDefs.testFunctions
: &m_functionDefs.replaceFunctions);
if (ProFunctionDef *xdef = hash->value(def->name()))
xdef->deref();
hash->insert(def->name(), def);
def->ref();
}
ProItem::ProItemReturn ProFileEvaluator::Private::visitProLoop(ProLoop *loop)
{
ProItem::ProItemReturn ret = ProItem::ReturnTrue;
bool infinite = false;
int index = 0;
QString variable;
QStringList oldVarVal;
QString it_list = expandVariableReferences(loop->expression(), 0, true).first();
if (loop->variable().isEmpty()) {
if (it_list != statics.strever) {
logMessage(format("Invalid loop expression."));
return ProItem::ReturnFalse;
}
it_list = statics.strforever;
} else {
variable = map(loop->variable());
oldVarVal = valuesDirect(variable);
it_list = map(it_list);
2008-12-02 12:01:29 +01:00
}
QStringList list = valuesDirect(it_list);
if (list.isEmpty()) {
if (it_list == statics.strforever) {
infinite = true;
} else {
int dotdot = it_list.indexOf(statics.strDotDot);
if (dotdot != -1) {
bool ok;
int start = it_list.left(dotdot).toInt(&ok);
if (ok) {
int end = it_list.mid(dotdot+2).toInt(&ok);
if (ok) {
if (start < end) {
for (int i = start; i <= end; i++)
list << QString::number(i);
} else {
for (int i = start; i >= end; i--)
list << QString::number(i);
}
}
}
}
2008-12-16 10:48:49 +01:00
}
}
2008-12-02 12:01:29 +01:00
m_loopLevel++;
forever {
if (infinite) {
if (!variable.isEmpty())
m_valuemapStack.top()[variable] = QStringList(QString::number(index++));
if (index > 1000) {
errorMessage(format("ran into infinite loop (> 1000 iterations)."));
break;
}
} else {
QString val;
do {
if (index >= list.count())
goto do_break;
val = list.at(index++);
} while (val.isEmpty()); // stupid, but qmake is like that
m_valuemapStack.top()[variable] = QStringList(val);
}
ret = visitProBlock(loop->items());
switch (ret) {
case ProItem::ReturnTrue:
case ProItem::ReturnFalse:
break;
case ProItem::ReturnNext:
ret = ProItem::ReturnTrue;
break;
case ProItem::ReturnBreak:
ret = ProItem::ReturnTrue;
goto do_break;
default:
goto do_break;
}
}
do_break:
m_loopLevel--;
if (!variable.isEmpty())
m_valuemapStack.top()[variable] = oldVarVal;
return ret;
}
void ProFileEvaluator::Private::visitProVariable(ProVariable *var)
2008-12-02 12:01:29 +01:00
{
m_lineNo = var->lineNumber();
const QString &varName = var->variable();
2008-12-02 12:01:29 +01:00
if (var->variableOperator() == ProVariable::ReplaceOperator) { // ~=
// DEFINES ~= s/a/b/?[gqi]
QString val = expandVariableReferences(var->value(), 0, true).first();
if (val.length() < 4 || val.at(0) != QLatin1Char('s')) {
logMessage(format("the ~= operator can handle only the s/// function."));
return;
}
QChar sep = val.at(1);
QStringList func = val.split(sep);
if (func.count() < 3 || func.count() > 4) {
logMessage(format("the s/// function expects 3 or 4 arguments."));
return;
}
bool global = false, quote = false, case_sense = false;
if (func.count() == 4) {
global = func[3].indexOf(QLatin1Char('g')) != -1;
case_sense = func[3].indexOf(QLatin1Char('i')) == -1;
quote = func[3].indexOf(QLatin1Char('q')) != -1;
}
QString pattern = func[1];
QString replace = func[2];
if (quote)
pattern = QRegExp::escape(pattern);
QRegExp regexp(pattern, case_sense ? Qt::CaseSensitive : Qt::CaseInsensitive);
if (!m_skipLevel || m_cumulative) {
// We could make a union of modified and unmodified values,
// but this will break just as much as it fixes, so leave it as is.
replaceInList(&valuesRef(varName), regexp, replace, global);
replaceInList(&m_filevaluemap[currentProFile()][varName], regexp, replace, global);
}
} else {
QStringList varVal = expandVariableReferences(var->value());
switch (var->variableOperator()) {
default: // ReplaceOperator - cannot happen
case ProVariable::SetOperator: // =
if (!m_cumulative) {
if (!m_skipLevel) {
m_valuemapStack.top()[varName] = varVal;
m_filevaluemap[currentProFile()][varName] = varVal;
}
} else {
// We are greedy for values.
valuesRef(varName) += varVal;
m_filevaluemap[currentProFile()][varName] += varVal;
}
break;
case ProVariable::UniqueAddOperator: // *=
if (!m_skipLevel || m_cumulative) {
insertUnique(&valuesRef(varName), varVal);
insertUnique(&m_filevaluemap[currentProFile()][varName], varVal);
}
break;
case ProVariable::AddOperator: // +=
if (!m_skipLevel || m_cumulative) {
valuesRef(varName) += varVal;
m_filevaluemap[currentProFile()][varName] += varVal;
}
break;
case ProVariable::RemoveOperator: // -=
if (!m_cumulative) {
if (!m_skipLevel) {
removeEach(&valuesRef(varName), varVal);
removeEach(&m_filevaluemap[currentProFile()][varName], varVal);
}
} else {
// We are stingy with our values, too.
}
break;
}
}
2008-12-02 12:01:29 +01:00
}
ProItem::ProItemReturn ProFileEvaluator::Private::visitProCondition(ProCondition *cond)
2008-12-02 12:01:29 +01:00
{
if (cond->text().endsWith(QLatin1Char(')'))) {
if (!m_cumulative && m_skipLevel)
return ProItem::ReturnTrue;
int lparen = cond->text().indexOf(QLatin1Char('('));
QString arguments = cond->text().mid(lparen + 1, cond->text().length() - lparen - 2);
QString funcName = cond->text().left(lparen).trimmed();
m_lineNo = cond->lineNumber();
return evaluateConditionalFunction(funcName, arguments);
} else {
if (m_skipLevel)
return ProItem::ReturnTrue;
return returnBool(isActiveConfig(cond->text(), true));
2008-12-02 12:01:29 +01:00
}
}
ProItem::ProItemReturn ProFileEvaluator::Private::visitProFile(ProFile *pro)
2008-12-02 12:01:29 +01:00
{
m_profileStack.push(pro);
if (m_profileStack.count() == 1) {
// Do this only for the initial profile we visit, since
2008-12-02 12:01:29 +01:00
// that is *the* profile. All the other times we reach this function will be due to
// include(file) or load(file)
if (m_parsePreAndPostFiles) {
if (m_option->base_valuemap.isEmpty()) {
// ### init QMAKE_QMAKE, QMAKE_SH
// ### init QMAKE_EXT_{C,H,CPP,OBJ}
// ### init TEMPLATE_PREFIX
QString qmake_cache = m_option->cachefile;
if (qmake_cache.isEmpty() && !m_outputDir.isEmpty()) { //find it as it has not been specified
QDir dir(m_outputDir);
forever {
qmake_cache = dir.path() + QLatin1String("/.qmake.cache");
if (IoUtils::exists(qmake_cache))
break;
if (!dir.cdUp() || dir.isRoot()) {
qmake_cache.clear();
break;
}
}
}
if (!qmake_cache.isEmpty()) {
qmake_cache = resolvePath(qmake_cache);
QHash<QString, QStringList> cache_valuemap;
if (evaluateFileInto(qmake_cache, &cache_valuemap, 0)) {
if (m_option->qmakespec.isEmpty()) {
const QStringList &vals = cache_valuemap.value(QLatin1String("QMAKESPEC"));
if (!vals.isEmpty())
m_option->qmakespec = vals.first();
}
} else {
qmake_cache.clear();
}
}
m_option->cachefile = qmake_cache;
QStringList mkspec_roots = qmakeMkspecPaths();
QString qmakespec = expandEnvVars(m_option->qmakespec);
if (qmakespec.isEmpty()) {
foreach (const QString &root, mkspec_roots) {
QString mkspec = root + QLatin1String("/default");
if (IoUtils::fileType(mkspec) == IoUtils::FileIsDir) {
qmakespec = mkspec;
break;
}
}
if (qmakespec.isEmpty()) {
errorMessage(format("Could not find qmake configuration directory"));
// Unlike in qmake, not finding the spec is not critical ...
}
}
if (IoUtils::isRelativePath(qmakespec)) {
if (IoUtils::exists(currentDirectory() + QLatin1Char('/') + qmakespec
+ QLatin1String("/qmake.conf"))) {
qmakespec = currentDirectory() + QLatin1Char('/') + qmakespec;
} else if (!m_outputDir.isEmpty()
&& IoUtils::exists(m_outputDir + QLatin1Char('/') + qmakespec
+ QLatin1String("/qmake.conf"))) {
qmakespec = m_outputDir + QLatin1Char('/') + qmakespec;
} else {
foreach (const QString &root, mkspec_roots) {
QString mkspec = root + QLatin1Char('/') + qmakespec;
if (IoUtils::exists(mkspec)) {
qmakespec = mkspec;
goto cool;
}
}
errorMessage(format("Could not find qmake configuration file"));
// Unlike in qmake, a missing config is not critical ...
qmakespec.clear();
cool: ;
}
}
if (!qmakespec.isEmpty()) {
m_option->qmakespec = QDir::cleanPath(qmakespec);
QString spec = m_option->qmakespec + QLatin1String("/qmake.conf");
if (!evaluateFileInto(spec,
&m_option->base_valuemap, &m_option->base_functions)) {
errorMessage(format("Could not read qmake configuration file %1").arg(spec));
} else if (!m_option->cachefile.isEmpty()) {
evaluateFileInto(m_option->cachefile,
&m_option->base_valuemap, &m_option->base_functions);
}
m_option->qmakespec_name = IoUtils::fileName(m_option->qmakespec).toString();
if (m_option->qmakespec_name == QLatin1String("default")) {
#ifdef Q_OS_UNIX
char buffer[1024];
int l = ::readlink(m_option->qmakespec.toLatin1().constData(), buffer, 1024);
if (l != -1)
m_option->qmakespec_name =
IoUtils::fileName(QString::fromLatin1(buffer, l)).toString();
#else
// We can't resolve symlinks as they do on Unix, so configure.exe puts
// the source of the qmake.conf at the end of the default/qmake.conf in
// the QMAKESPEC_ORG variable.
const QStringList &spec_org =
m_option->base_valuemap.value(QLatin1String("QMAKESPEC_ORIGINAL"));
if (!spec_org.isEmpty())
m_option->qmakespec_name =
IoUtils::fileName(spec_org.first()).toString();
#endif
}
}
evaluateFeatureFile(QLatin1String("default_pre.prf"),
&m_option->base_valuemap, &m_option->base_functions);
}
m_valuemapStack.top() = m_option->base_valuemap;
clearFunctions(&m_functionDefs);
m_functionDefs = m_option->base_functions;
refFunctions(&m_functionDefs.testFunctions);
refFunctions(&m_functionDefs.replaceFunctions);
QStringList &tgt = m_valuemapStack.top()[QLatin1String("TARGET")];
if (tgt.isEmpty())
tgt.append(QFileInfo(pro->fileName()).baseName());
QStringList &tmp = m_valuemapStack.top()[QLatin1String("CONFIG")];
tmp.append(m_addUserConfigCmdArgs);
foreach (const QString &remove, m_removeUserConfigCmdArgs)
tmp.removeAll(remove);
2008-12-02 12:01:29 +01:00
}
}
visitProBlock(pro->items());
if (m_profileStack.count() == 1) {
if (m_parsePreAndPostFiles) {
evaluateFeatureFile(QLatin1String("default_post.prf"));
QSet<QString> processed;
forever {
bool finished = true;
QStringList configs = valuesDirect(statics.strCONFIG);
for (int i = configs.size() - 1; i >= 0; --i) {
2009-08-04 20:51:49 +02:00
const QString config = configs.at(i).toLower();
if (!processed.contains(config)) {
processed.insert(config);
if (evaluateFeatureFile(config)) {
finished = false;
break;
2008-12-02 12:01:29 +01:00
}
}
}
if (finished)
break;
2008-12-02 12:01:29 +01:00
}
}
}
m_profileStack.pop();
return ProItem::ReturnTrue;
2008-12-02 12:01:29 +01:00
}
QStringList ProFileEvaluator::Private::qmakeMkspecPaths() const
{
QStringList ret;
const QString concat = QLatin1String("/mkspecs");
QByteArray qmakepath = qgetenv("QMAKEPATH");
if (!qmakepath.isEmpty())
foreach (const QString &it, QString::fromLocal8Bit(qmakepath).split(m_option->dirlist_sep))
ret << QDir::cleanPath(it) + concat;
QString builtIn = propertyValue(QLatin1String("QT_INSTALL_DATA")) + concat;
if (!ret.contains(builtIn))
ret << builtIn;
return ret;
}
QStringList ProFileEvaluator::Private::qmakeFeaturePaths() const
2008-12-02 12:01:29 +01:00
{
QString mkspecs_concat = QLatin1String("/mkspecs");
QString features_concat = QLatin1String("/features");
2008-12-02 12:01:29 +01:00
QStringList concat;
switch (m_option->target_mode) {
case ProFileOption::TARG_MACX_MODE:
concat << QLatin1String("/features/mac");
concat << QLatin1String("/features/macx");
concat << QLatin1String("/features/unix");
break;
case ProFileOption::TARG_UNIX_MODE:
concat << QLatin1String("/features/unix");
break;
case ProFileOption::TARG_WIN_MODE:
concat << QLatin1String("/features/win32");
break;
case ProFileOption::TARG_MAC9_MODE:
concat << QLatin1String("/features/mac");
concat << QLatin1String("/features/mac9");
break;
case ProFileOption::TARG_QNX6_MODE:
concat << QLatin1String("/features/qnx6");
concat << QLatin1String("/features/unix");
break;
2008-12-02 12:01:29 +01:00
}
concat << features_concat;
2008-12-02 12:01:29 +01:00
QStringList feature_roots;
2008-12-02 12:01:29 +01:00
QByteArray mkspec_path = qgetenv("QMAKEFEATURES");
if (!mkspec_path.isEmpty())
foreach (const QString &f, QString::fromLocal8Bit(mkspec_path).split(m_option->dirlist_sep))
feature_roots += resolvePath(f);
feature_roots += propertyValue(QLatin1String("QMAKEFEATURES"), false).split(
m_option->dirlist_sep, QString::SkipEmptyParts);
if (!m_option->cachefile.isEmpty()) {
QString path = m_option->cachefile.left(m_option->cachefile.lastIndexOf((ushort)'/'));
2008-12-02 12:01:29 +01:00
foreach (const QString &concat_it, concat)
feature_roots << (path + concat_it);
}
QByteArray qmakepath = qgetenv("QMAKEPATH");
if (!qmakepath.isNull()) {
const QStringList lst = QString::fromLocal8Bit(qmakepath).split(m_option->dirlist_sep);
2008-12-02 12:01:29 +01:00
foreach (const QString &item, lst) {
QString citem = resolvePath(item);
2008-12-02 12:01:29 +01:00
foreach (const QString &concat_it, concat)
feature_roots << (citem + mkspecs_concat + concat_it);
}
}
if (!m_option->qmakespec.isEmpty()) {
QString qmakespec = resolvePath(m_option->qmakespec);
feature_roots << (qmakespec + features_concat);
QDir specdir(qmakespec);
while (!specdir.isRoot()) {
if (!specdir.cdUp() || specdir.isRoot())
break;
if (IoUtils::exists(specdir.path() + features_concat)) {
foreach (const QString &concat_it, concat)
feature_roots << (specdir.path() + concat_it);
break;
}
2008-12-02 12:01:29 +01:00
}
}
2008-12-02 12:01:29 +01:00
foreach (const QString &concat_it, concat)
feature_roots << (propertyValue(QLatin1String("QT_INSTALL_PREFIX")) +
mkspecs_concat + concat_it);
foreach (const QString &concat_it, concat)
feature_roots << (propertyValue(QLatin1String("QT_INSTALL_DATA")) +
mkspecs_concat + concat_it);
for (int i = 0; i < feature_roots.count(); ++i)
if (!feature_roots.at(i).endsWith((ushort)'/'))
feature_roots[i].append((ushort)'/');
feature_roots.removeDuplicates();
2008-12-02 12:01:29 +01:00
return feature_roots;
}
QString ProFileEvaluator::Private::propertyValue(const QString &name, bool complain) const
2008-12-02 12:01:29 +01:00
{
if (m_option->properties.contains(name))
return m_option->properties.value(name);
2008-12-02 12:01:29 +01:00
if (name == QLatin1String("QMAKE_MKSPECS"))
return qmakeMkspecPaths().join(m_option->dirlist_sep);
2008-12-02 12:01:29 +01:00
if (name == QLatin1String("QMAKE_VERSION"))
return QLatin1String("1.0"); //### FIXME
if (complain)
logMessage(format("Querying unknown property %1").arg(name));
return QString();
2008-12-02 12:01:29 +01:00
}
ProFile *ProFileEvaluator::Private::currentProFile() const
{
if (m_profileStack.count() > 0)
return m_profileStack.top();
return 0;
}
QString ProFileEvaluator::Private::currentFileName() const
{
ProFile *pro = currentProFile();
if (pro)
return pro->fileName();
return QString();
}
QString ProFileEvaluator::Private::currentDirectory() const
2008-12-02 12:01:29 +01:00
{
ProFile *cur = m_profileStack.top();
2008-12-19 21:35:10 +01:00
return cur->directoryName();
2008-12-02 12:01:29 +01:00
}
// Be fast even for debug builds
#ifdef __GNUC__
# define ALWAYS_INLINE __attribute__((always_inline))
#else
# define ALWAYS_INLINE
#endif
// The (QChar*)current->constData() constructs below avoid pointless detach() calls
static inline void ALWAYS_INLINE appendChar(ushort unicode,
QString *current, QChar **ptr, QString *pending)
{
if (!pending->isEmpty()) {
int len = pending->size();
current->resize(current->size() + len);
::memcpy((QChar*)current->constData(), pending->constData(), len * 2);
pending->clear();
*ptr = (QChar*)current->constData() + len;
}
*(*ptr)++ = QChar(unicode);
}
static void appendString(const QString &string,
QString *current, QChar **ptr, QString *pending)
{
if (string.isEmpty())
return;
QChar *uc = (QChar*)current->constData();
int len;
if (*ptr != uc) {
len = *ptr - uc;
current->resize(current->size() + string.size());
} else if (!pending->isEmpty()) {
len = pending->size();
current->resize(current->size() + len + string.size());
::memcpy((QChar*)current->constData(), pending->constData(), len * 2);
pending->clear();
} else {
*pending = string;
return;
}
*ptr = (QChar*)current->constData() + len;
::memcpy(*ptr, string.data(), string.size() * 2);
*ptr += string.size();
}
static void flushCurrent(QStringList *ret,
QString *current, QChar **ptr, QString *pending, bool joined)
{
QChar *uc = (QChar*)current->constData();
int len = *ptr - uc;
if (len) {
ret->append(QString(uc, len));
*ptr = uc;
} else if (!pending->isEmpty()) {
ret->append(*pending);
pending->clear();
} else if (joined) {
ret->append(QString());
}
}
static inline void flushFinal(QStringList *ret,
const QString &current, const QChar *ptr, const QString &pending,
const QString &str, bool replaced, bool joined)
{
int len = ptr - current.data();
if (len) {
if (!replaced && len == str.size())
ret->append(str);
else
ret->append(QString(current.data(), len));
} else if (!pending.isEmpty()) {
ret->append(pending);
} else if (joined) {
ret->append(QString());
}
}
QStringList ProFileEvaluator::Private::expandVariableReferences(
const QString &str, int *pos, bool joined)
2008-12-02 12:01:29 +01:00
{
QStringList ret;
// if (ok)
// *ok = true;
if (str.isEmpty() && !pos)
2008-12-02 12:01:29 +01:00
return ret;
const ushort LSQUARE = '[';
const ushort RSQUARE = ']';
const ushort LCURLY = '{';
const ushort RCURLY = '}';
const ushort LPAREN = '(';
const ushort RPAREN = ')';
const ushort DOLLAR = '$';
const ushort BACKSLASH = '\\';
const ushort UNDERSCORE = '_';
const ushort DOT = '.';
const ushort SPACE = ' ';
const ushort TAB = '\t';
const ushort COMMA = ',';
const ushort SINGLEQUOTE = '\'';
const ushort DOUBLEQUOTE = '"';
2008-12-02 12:01:29 +01:00
ushort unicode, quote = 0, parens = 0;
const ushort *str_data = (const ushort *)str.data();
2008-12-02 12:01:29 +01:00
const int str_len = str.length();
QString var, args;
bool replaced = false;
bool putSpace = false;
QString current; // Buffer for successively assembled string segments
current.resize(str.size());
QChar *ptr = current.data();
QString pending; // Buffer for string segments from variables
// Only one of the above buffers can be filled at a given time.
for (int i = pos ? *pos : 0; i < str_len; ++i) {
unicode = str_data[i];
if (unicode == DOLLAR) {
if (str_len > i+2 && str_data[i+1] == DOLLAR) {
++i;
ushort term = 0;
2008-12-02 12:01:29 +01:00
enum { VAR, ENVIRON, FUNCTION, PROPERTY } var_type = VAR;
unicode = str_data[++i];
if (unicode == LSQUARE) {
unicode = str_data[++i];
2008-12-02 12:01:29 +01:00
term = RSQUARE;
var_type = PROPERTY;
} else if (unicode == LCURLY) {
unicode = str_data[++i];
2008-12-02 12:01:29 +01:00
var_type = VAR;
term = RCURLY;
} else if (unicode == LPAREN) {
unicode = str_data[++i];
2008-12-02 12:01:29 +01:00
var_type = ENVIRON;
term = RPAREN;
}
int name_start = i;
forever {
if (!(unicode & (0xFF<<8)) &&
unicode != DOT && unicode != UNDERSCORE &&
//unicode != SINGLEQUOTE && unicode != DOUBLEQUOTE &&
(unicode < 'a' || unicode > 'z') && (unicode < 'A' || unicode > 'Z') &&
(unicode < '0' || unicode > '9'))
2008-12-02 12:01:29 +01:00
break;
if (++i == str_len)
break;
unicode = str_data[i];
// at this point, i points to either the 'term' or 'next' character (which is in unicode)
2008-12-02 12:01:29 +01:00
}
var = QString::fromRawData((QChar*)str_data + name_start, i - name_start);
if (var_type == VAR && unicode == LPAREN) {
2008-12-02 12:01:29 +01:00
var_type = FUNCTION;
name_start = i + 1;
2008-12-02 12:01:29 +01:00
int depth = 0;
forever {
2008-12-02 12:01:29 +01:00
if (++i == str_len)
break;
unicode = str_data[i];
if (unicode == LPAREN) {
2008-12-02 12:01:29 +01:00
depth++;
} else if (unicode == RPAREN) {
2008-12-02 12:01:29 +01:00
if (!depth)
break;
--depth;
}
}
args = QString((QChar*)str_data + name_start, i - name_start);
if (++i < str_len)
unicode = str_data[i];
2008-12-02 12:01:29 +01:00
else
unicode = 0;
// at this point i is pointing to the 'next' character (which is in unicode)
// this might actually be a term character since you can do $${func()}
2008-12-02 12:01:29 +01:00
}
if (term) {
if (unicode != term) {
logMessage(format("Missing %1 terminator [found %2]")
.arg(QChar(term))
.arg(unicode ? QString(unicode) : QString::fromLatin1(("end-of-line"))));
// if (ok)
// *ok = false;
if (pos)
*pos = str_len;
2008-12-02 12:01:29 +01:00
return QStringList();
}
} else {
// move the 'cursor' back to the last char of the thing we were looking at
--i;
2008-12-02 12:01:29 +01:00
}
QStringList replacement;
if (var_type == ENVIRON) {
replacement = split_value_list(QString::fromLocal8Bit(qgetenv(var.toLatin1().constData())));
2008-12-02 12:01:29 +01:00
} else if (var_type == PROPERTY) {
replacement << propertyValue(var);
} else if (var_type == FUNCTION) {
replacement << evaluateExpandFunction(var, args);
} else if (var_type == VAR) {
replacement = values(map(var));
2008-12-02 12:01:29 +01:00
}
if (!replacement.isEmpty()) {
if (quote || joined) {
if (putSpace) {
putSpace = false;
if (!replacement.at(0).isEmpty()) // Bizarre, indeed
appendChar(' ', &current, &ptr, &pending);
}
appendString(replacement.join(statics.field_sep),
&current, &ptr, &pending);
} else {
appendString(replacement.at(0), &current, &ptr, &pending);
if (replacement.size() > 1) {
flushCurrent(&ret, &current, &ptr, &pending, false);
int j = 1;
if (replacement.size() > 2) {
// FIXME: ret.reserve(ret.size() + replacement.size() - 2);
for (; j < replacement.size() - 1; ++j)
ret << replacement.at(j);
}
pending = replacement.at(j);
}
2008-12-02 12:01:29 +01:00
}
replaced = true;
2008-12-02 12:01:29 +01:00
}
continue;
2008-12-02 12:01:29 +01:00
}
} else if (unicode == BACKSLASH) {
static const char symbols[] = "[]{}()$\\'\"";
ushort unicode2 = str_data[i+1];
if (!(unicode2 & 0xff00) && strchr(symbols, unicode2)) {
unicode = unicode2;
++i;
}
} else if (quote) {
if (unicode == quote) {
quote = 0;
continue;
}
} else {
if (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE) {
quote = unicode;
continue;
} else if (unicode == SPACE || unicode == TAB) {
if (!joined)
flushCurrent(&ret, &current, &ptr, &pending, false);
else if ((ptr - (QChar*)current.constData()) || !pending.isEmpty())
putSpace = true;
continue;
} else if (pos) {
if (unicode == LPAREN) {
++parens;
} else if (unicode == RPAREN) {
--parens;
} else if (!parens && unicode == COMMA) {
if (!joined) {
*pos = i + 1;
flushFinal(&ret, current, ptr, pending, str, replaced, false);
return ret;
}
flushCurrent(&ret, &current, &ptr, &pending, true);
putSpace = false;
continue;
}
}
}
if (putSpace) {
putSpace = false;
appendChar(' ', &current, &ptr, &pending);
}
appendChar(unicode, &current, &ptr, &pending);
}
if (pos)
*pos = str_len;
flushFinal(&ret, current, ptr, pending, str, replaced, joined);
2008-12-02 12:01:29 +01:00
return ret;
}
bool ProFileEvaluator::Private::isActiveConfig(const QString &config, bool regex)
{
// magic types for easy flipping
if (config == statics.strtrue)
2008-12-02 12:01:29 +01:00
return true;
if (config == statics.strfalse)
2008-12-02 12:01:29 +01:00
return false;
// mkspecs
if ((m_option->target_mode == m_option->TARG_MACX_MODE
|| m_option->target_mode == m_option->TARG_QNX6_MODE
|| m_option->target_mode == m_option->TARG_UNIX_MODE)
&& config == statics.strunix)
2008-12-02 12:01:29 +01:00
return true;
if (m_option->target_mode == m_option->TARG_MACX_MODE && config == statics.strmacx)
2008-12-02 12:01:29 +01:00
return true;
if (m_option->target_mode == m_option->TARG_QNX6_MODE && config == statics.strqnx6)
2008-12-02 12:01:29 +01:00
return true;
if (m_option->target_mode == m_option->TARG_MAC9_MODE && config == statics.strmac9)
2008-12-02 12:01:29 +01:00
return true;
if ((m_option->target_mode == m_option->TARG_MAC9_MODE
|| m_option->target_mode == m_option->TARG_MACX_MODE)
&& config == statics.strmac)
2008-12-02 12:01:29 +01:00
return true;
if (m_option->target_mode == m_option->TARG_WIN_MODE && config == statics.strwin32)
2008-12-02 12:01:29 +01:00
return true;
if (regex && (config.contains(QLatin1Char('*')) || config.contains(QLatin1Char('?')))) {
QRegExp re(config, Qt::CaseSensitive, QRegExp::Wildcard);
if (re.exactMatch(m_option->qmakespec_name))
return true;
// CONFIG variable
foreach (const QString &configValue, valuesDirect(statics.strCONFIG)) {
if (re.exactMatch(configValue))
return true;
}
} else {
// mkspecs
if (m_option->qmakespec_name == config)
return true;
// CONFIG variable
if (valuesDirect(statics.strCONFIG).contains(config))
return true;
}
2008-12-02 12:01:29 +01:00
return false;
}
QList<QStringList> ProFileEvaluator::Private::prepareFunctionArgs(const QString &arguments)
{
QList<QStringList> args_list;
for (int pos = 0; pos < arguments.length(); )
args_list << expandVariableReferences(arguments, &pos);
return args_list;
}
QStringList ProFileEvaluator::Private::evaluateFunction(
ProFunctionDef *funcPtr, const QList<QStringList> &argumentsList, bool *ok)
{
bool oki;
QStringList ret;
if (m_valuemapStack.count() >= 100) {
errorMessage(format("ran into infinite recursion (depth > 100)."));
2009-06-03 19:04:10 +02:00
oki = false;
} else {
m_valuemapStack.push(QHash<QString, QStringList>());
int loopLevel = m_loopLevel;
m_loopLevel = 0;
QStringList args;
for (int i = 0; i < argumentsList.count(); ++i) {
args += argumentsList[i];
m_valuemapStack.top()[QString::number(i+1)] = argumentsList[i];
}
m_valuemapStack.top()[statics.strARGS] = args;
oki = (visitProBlock(funcPtr->items()) != ProItem::ReturnFalse); // True || Return
ret = m_returnValue;
m_returnValue.clear();
m_loopLevel = loopLevel;
m_valuemapStack.pop();
}
if (ok)
*ok = oki;
if (oki)
return ret;
return QStringList();
}
2008-12-02 12:01:29 +01:00
QStringList ProFileEvaluator::Private::evaluateExpandFunction(const QString &func, const QString &arguments)
{
if (ProFunctionDef *funcPtr = m_functionDefs.replaceFunctions.value(func, 0))
return evaluateFunction(funcPtr, prepareFunctionArgs(arguments), 0);
//why don't the builtin functions just use args_list? --Sam
int pos = 0;
QStringList args = expandVariableReferences(arguments, &pos, true);
ExpandFunc func_t = ExpandFunc(statics.expands.value(func.toLower()));
2008-12-02 12:01:29 +01:00
QStringList ret;
switch (func_t) {
case E_BASENAME:
case E_DIRNAME:
case E_SECTION: {
bool regexp = false;
QString sep, var;
int beg = 0;
int end = -1;
if (func_t == E_SECTION) {
if (args.count() != 3 && args.count() != 4) {
logMessage(format("%1(var) section(var, sep, begin, end) "
"requires three or four arguments.").arg(func));
2008-12-02 12:01:29 +01:00
} else {
var = args[0];
sep = args[1];
beg = args[2].toInt();
if (args.count() == 4)
end = args[3].toInt();
}
} else {
if (args.count() != 1) {
logMessage(format("%1(var) requires one argument.").arg(func));
2008-12-02 12:01:29 +01:00
} else {
var = args[0];
regexp = true;
sep = QLatin1String("[\\\\/]");
if (func_t == E_DIRNAME)
end = -2;
else
beg = -1;
}
}
if (!var.isNull()) {
if (regexp) {
QRegExp sepRx(sep);
foreach (const QString &str, values(map(var)))
ret += str.section(sepRx, beg, end);
} else {
foreach (const QString &str, values(map(var)))
2008-12-02 12:01:29 +01:00
ret += str.section(sep, beg, end);
}
}
break;
}
case E_SPRINTF:
if(args.count() < 1) {
logMessage(format("sprintf(format, ...) requires at least one argument"));
} else {
QString tmp = args.at(0);
for (int i = 1; i < args.count(); ++i)
tmp = tmp.arg(args.at(i));
ret = split_value_list(tmp);
}
break;
2008-12-02 12:01:29 +01:00
case E_JOIN: {
if (args.count() < 1 || args.count() > 4) {
logMessage(format("join(var, glue, before, after) requires one to four arguments."));
2008-12-02 12:01:29 +01:00
} else {
QString glue, before, after;
if (args.count() >= 2)
glue = args[1];
if (args.count() >= 3)
before = args[2];
if (args.count() == 4)
after = args[3];
const QStringList &var = values(map(args.first()));
2008-12-02 12:01:29 +01:00
if (!var.isEmpty())
ret.append(before + var.join(glue) + after);
}
break;
}
2009-08-12 13:42:29 +02:00
case E_SPLIT:
if (args.count() != 2) {
logMessage(format("split(var, sep) requires one or two arguments"));
2008-12-02 12:01:29 +01:00
} else {
const QString &sep = (args.count() == 2) ? args[1] : statics.field_sep;
foreach (const QString &var, values(map(args.first())))
2008-12-02 12:01:29 +01:00
foreach (const QString &splt, var.split(sep))
ret.append(splt);
}
break;
2009-08-12 13:42:29 +02:00
case E_MEMBER:
2008-12-02 12:01:29 +01:00
if (args.count() < 1 || args.count() > 3) {
logMessage(format("member(var, start, end) requires one to three arguments."));
2008-12-02 12:01:29 +01:00
} else {
bool ok = true;
const QStringList &var = values(map(args.first()));
2008-12-02 12:01:29 +01:00
int start = 0, end = 0;
if (args.count() >= 2) {
QString start_str = args[1];
start = start_str.toInt(&ok);
if (!ok) {
if (args.count() == 2) {
int dotdot = start_str.indexOf(statics.strDotDot);
2008-12-02 12:01:29 +01:00
if (dotdot != -1) {
start = start_str.left(dotdot).toInt(&ok);
if (ok)
end = start_str.mid(dotdot+2).toInt(&ok);
}
}
if (!ok)
logMessage(format("member() argument 2 (start) '%2' invalid.")
2008-12-02 12:01:29 +01:00
.arg(start_str));
} else {
end = start;
if (args.count() == 3)
end = args[2].toInt(&ok);
if (!ok)
logMessage(format("member() argument 3 (end) '%2' invalid.\n")
2008-12-02 12:01:29 +01:00
.arg(args[2]));
}
}
if (ok) {
if (start < 0)
start += var.count();
if (end < 0)
end += var.count();
if (start < 0 || start >= var.count() || end < 0 || end >= var.count()) {
//nothing
} else if (start < end) {
for (int i = start; i <= end && var.count() >= i; i++)
ret.append(var[i]);
} else {
for (int i = start; i >= end && var.count() >= i && i >= 0; i--)
ret += var[i];
}
}
}
break;
case E_FIRST:
2009-08-12 13:42:29 +02:00
case E_LAST:
2008-12-02 12:01:29 +01:00
if (args.count() != 1) {
logMessage(format("%1(var) requires one argument.").arg(func));
2008-12-02 12:01:29 +01:00
} else {
const QStringList var = values(map(args.first()));
2008-12-02 12:01:29 +01:00
if (!var.isEmpty()) {
if (func_t == E_FIRST)
ret.append(var[0]);
else
ret.append(var.last());
}
}
break;
2010-04-28 11:37:51 +02:00
case E_SIZE:
if(args.count() != 1)
logMessage(format("size(var) requires one argument."));
else
ret.append(QString::number(values(map(args.at(0))).size()));
break;
case E_CAT:
if (args.count() < 1 || args.count() > 2) {
logMessage(format("cat(file, singleline=true) requires one or two arguments."));
} else {
QString file = args[0];
bool singleLine = true;
if (args.count() > 1)
2010-04-29 17:46:57 +02:00
singleLine = isTrue(args.at(1));
QFile qfile(resolvePath(expandEnvVars(file)));
if (qfile.open(QIODevice::ReadOnly)) {
QTextStream stream(&qfile);
while (!stream.atEnd()) {
ret += split_value_list(stream.readLine().trimmed());
if (!singleLine)
ret += QLatin1String("\n");
}
qfile.close();
}
}
break;
case E_FROMFILE:
if (args.count() != 2) {
logMessage(format("fromfile(file, variable) requires two arguments."));
} else {
2009-09-23 18:19:09 +02:00
QHash<QString, QStringList> vars;
if (evaluateFileInto(resolvePath(expandEnvVars(args.at(0))), &vars, 0))
2009-09-23 18:19:09 +02:00
ret = vars.value(args.at(1));
}
break;
2009-08-12 13:42:29 +02:00
case E_EVAL:
if (args.count() != 1) {
logMessage(format("eval(variable) requires one argument"));
} else {
ret += values(map(args.at(0)));
}
2009-08-12 13:42:29 +02:00
break;
case E_LIST: {
QString tmp;
tmp.sprintf(".QMAKE_INTERNAL_TMP_variableName_%d", m_listCount++);
ret = QStringList(tmp);
QStringList lst;
foreach (const QString &arg, args)
lst += split_value_list(arg);
m_valuemapStack.top()[tmp] = lst;
break; }
case E_FIND:
if (args.count() != 2) {
logMessage(format("find(var, str) requires two arguments."));
} else {
QRegExp regx(args[1]);
foreach (const QString &val, values(map(args.first())))
if (regx.indexIn(val) != -1)
ret += val;
}
break;
case E_SYSTEM:
if (!m_skipLevel) {
2008-12-02 12:01:29 +01:00
if (args.count() < 1 || args.count() > 2) {
logMessage(format("system(execute) requires one or two arguments."));
2008-12-02 12:01:29 +01:00
} else {
char buff[256];
FILE *proc = QT_POPEN((QLatin1String("cd ")
+ IoUtils::shellQuote(currentDirectory())
+ QLatin1String(" && ") + args[0]).toLatin1(), "r");
2008-12-02 12:01:29 +01:00
bool singleLine = true;
if (args.count() > 1)
2010-04-29 17:46:57 +02:00
singleLine = isTrue(args.at(1));
2008-12-02 12:01:29 +01:00
QString output;
while (proc && !feof(proc)) {
int read_in = int(fread(buff, 1, 255, proc));
if (!read_in)
break;
for (int i = 0; i < read_in; i++) {
if ((singleLine && buff[i] == '\n') || buff[i] == '\t')
buff[i] = ' ';
}
buff[read_in] = '\0';
output += QLatin1String(buff);
}
ret += split_value_list(output);
if (proc)
QT_PCLOSE(proc);
2008-12-02 12:01:29 +01:00
}
}
break;
case E_UNIQUE:
if(args.count() != 1) {
logMessage(format("unique(var) requires one argument."));
} else {
ret = values(map(args.first()));
2010-02-04 10:47:55 +01:00
ret.removeDuplicates();
}
break;
2008-12-02 12:01:29 +01:00
case E_QUOTE:
2010-04-29 17:58:47 +02:00
ret += args;
2008-12-02 12:01:29 +01:00
break;
case E_ESCAPE_EXPAND:
for (int i = 0; i < args.size(); ++i) {
QChar *i_data = args[i].data();
int i_len = args[i].length();
for (int x = 0; x < i_len; ++x) {
if (*(i_data+x) == QLatin1Char('\\') && x < i_len-1) {
if (*(i_data+x+1) == QLatin1Char('\\')) {
++x;
} else {
struct {
char in, out;
} mapped_quotes[] = {
{ 'n', '\n' },
{ 't', '\t' },
{ 'r', '\r' },
{ 0, 0 }
};
for (int i = 0; mapped_quotes[i].in; ++i) {
if (*(i_data+x+1) == QLatin1Char(mapped_quotes[i].in)) {
*(i_data+x) = QLatin1Char(mapped_quotes[i].out);
if (x < i_len-2)
memmove(i_data+x+1, i_data+x+2, (i_len-x-2)*sizeof(QChar));
--i_len;
break;
}
}
}
}
}
ret.append(QString(i_data, i_len));
}
break;
case E_RE_ESCAPE:
for (int i = 0; i < args.size(); ++i)
ret += QRegExp::escape(args[i]);
break;
case E_UPPER:
case E_LOWER:
for (int i = 0; i < args.count(); ++i)
if (func_t == E_UPPER)
ret += args[i].toUpper();
else
ret += args[i].toLower();
break;
case E_FILES:
if (args.count() != 1 && args.count() != 2) {
logMessage(format("files(pattern, recursive=false) requires one or two arguments"));
} else {
bool recursive = false;
if (args.count() == 2)
2010-04-29 17:46:57 +02:00
recursive = isTrue(args.at(1));
QStringList dirs;
QString r = fixPathToLocalOS(args[0]);
QString pfx;
if (IoUtils::isRelativePath(r)) {
pfx = currentDirectory();
if (!pfx.endsWith(QLatin1Char('/')))
pfx += QLatin1Char('/');
}
int slash = r.lastIndexOf(QDir::separator());
if (slash != -1) {
2010-02-10 16:20:16 +01:00
dirs.append(r.left(slash+1));
r = r.mid(slash+1);
} else {
dirs.append(QString());
}
const QRegExp regex(r, Qt::CaseSensitive, QRegExp::Wildcard);
for (int d = 0; d < dirs.count(); d++) {
QString dir = dirs[d];
QDir qdir(pfx + dir);
for (int i = 0; i < (int)qdir.count(); ++i) {
if (qdir[i] == statics.strDot || qdir[i] == statics.strDotDot)
continue;
QString fname = dir + qdir[i];
if (IoUtils::fileType(pfx + fname) == IoUtils::FileIsDir) {
if (recursive)
2010-02-10 16:20:16 +01:00
dirs.append(fname + QDir::separator());
}
if (regex.exactMatch(qdir[i]))
ret += fname;
}
}
}
break;
case E_REPLACE:
if(args.count() != 3 ) {
logMessage(format("replace(var, before, after) requires three arguments"));
} else {
const QRegExp before(args[1]);
const QString after(args[2]);
foreach (QString val, values(map(args.first())))
ret += val.replace(before, after);
}
break;
2008-12-02 12:01:29 +01:00
case 0:
logMessage(format("'%1' is not a recognized replace function").arg(func));
2008-12-02 12:01:29 +01:00
break;
default:
logMessage(format("Function '%1' is not implemented").arg(func));
2008-12-02 12:01:29 +01:00
break;
}
return ret;
}
ProItem::ProItemReturn ProFileEvaluator::Private::evaluateConditionalFunction(
const QString &function, const QString &arguments)
2008-12-02 12:01:29 +01:00
{
if (ProFunctionDef *funcPtr = m_functionDefs.testFunctions.value(function, 0)) {
bool ok;
QStringList ret = evaluateFunction(funcPtr, prepareFunctionArgs(arguments), &ok);
if (ok) {
if (ret.isEmpty()) {
return ProItem::ReturnTrue;
} else {
if (ret.first() != statics.strfalse) {
if (ret.first() == statics.strtrue) {
return ProItem::ReturnTrue;
} else {
bool ok;
int val = ret.first().toInt(&ok);
if (ok) {
if (val)
return ProItem::ReturnTrue;
} else {
logMessage(format("Unexpected return value from test '%1': %2")
.arg(function).arg(ret.join(QLatin1String(" :: "))));
}
}
}
}
}
return ProItem::ReturnFalse;
}
//why don't the builtin functions just use args_list? --Sam
int pos = 0;
QStringList args = expandVariableReferences(arguments, &pos, true);
2008-12-02 12:01:29 +01:00
TestFunc func_t = (TestFunc)statics.functions.value(function);
2008-12-02 12:01:29 +01:00
switch (func_t) {
case T_DEFINED:
if (args.count() < 1 || args.count() > 2) {
logMessage(format("defined(function, [\"test\"|\"replace\"])"
" requires one or two arguments."));
return ProItem::ReturnFalse;
}
if (args.count() > 1) {
if (args[1] == QLatin1String("test"))
return returnBool(m_functionDefs.testFunctions.contains(args[0]));
else if (args[1] == QLatin1String("replace"))
return returnBool(m_functionDefs.replaceFunctions.contains(args[0]));
logMessage(format("defined(function, type):"
" unexpected type [%1].\n").arg(args[1]));
return ProItem::ReturnFalse;
}
return returnBool(m_functionDefs.replaceFunctions.contains(args[0])
|| m_functionDefs.testFunctions.contains(args[0]));
case T_RETURN:
m_returnValue = args;
// It is "safe" to ignore returns - due to qmake brokeness
// they cannot be used to terminate loops anyway.
if (m_skipLevel || m_cumulative)
return ProItem::ReturnTrue;
if (m_valuemapStack.isEmpty()) {
logMessage(format("unexpected return()."));
return ProItem::ReturnFalse;
}
return ProItem::ReturnReturn;
case T_EXPORT: {
if (m_skipLevel && !m_cumulative)
return ProItem::ReturnTrue;
if (args.count() != 1) {
logMessage(format("export(variable) requires one argument."));
return ProItem::ReturnFalse;
}
const QString &var = map(args.at(0));
for (int i = m_valuemapStack.size(); --i > 0; ) {
QHash<QString, QStringList>::Iterator it = m_valuemapStack[i].find(var);
if (it != m_valuemapStack.at(i).end()) {
if (it->constBegin() == statics.fakeValue.constBegin()) {
// This is stupid, but qmake doesn't propagate deletions
m_valuemapStack[0][var] = QStringList();
} else {
m_valuemapStack[0][var] = *it;
}
m_valuemapStack[i].erase(it);
while (--i)
m_valuemapStack[i].remove(var);
break;
}
}
return ProItem::ReturnTrue;
}
case T_INFILE:
2009-09-23 18:19:09 +02:00
if (args.count() < 2 || args.count() > 3) {
logMessage(format("infile(file, var, [values]) requires two or three arguments."));
} else {
QHash<QString, QStringList> vars;
if (!evaluateFileInto(resolvePath(expandEnvVars(args.at(0))), &vars, 0))
2009-09-23 18:19:09 +02:00
return ProItem::ReturnFalse;
if (args.count() == 2)
return returnBool(vars.contains(args.at(1)));
QRegExp regx;
const QString &qry = args.at(2);
if (qry != QRegExp::escape(qry))
regx.setPattern(qry);
2009-09-23 18:19:09 +02:00
foreach (const QString &s, vars.value(args.at(1)))
if ((!regx.isEmpty() && regx.exactMatch(s)) || s == qry)
2009-09-23 18:19:09 +02:00
return ProItem::ReturnTrue;
}
return ProItem::ReturnFalse;
#if 0
case T_REQUIRES:
#endif
2009-10-02 17:37:02 +02:00
case T_EVAL: {
ProItem *pro;
QString buf = args.join(QLatin1String(" "));
if (!readInternal(&pro, buf, (ushort*)buf.data()))
return ProItem::ReturnFalse;
ProItem::ProItemReturn ret = visitProBlock(pro);
ProItem::disposeItems(pro);
return ret;
}
case T_BREAK:
if (m_skipLevel)
return ProItem::ReturnFalse;
if (m_loopLevel)
return ProItem::ReturnBreak;
logMessage(format("unexpected break()."));
return ProItem::ReturnFalse;
case T_NEXT:
if (m_skipLevel)
return ProItem::ReturnFalse;
if (m_loopLevel)
return ProItem::ReturnNext;
logMessage(format("unexpected next()."));
return ProItem::ReturnFalse;
2009-05-18 15:42:45 +02:00
case T_IF: {
if (m_skipLevel && !m_cumulative)
return ProItem::ReturnFalse;
2009-05-18 15:42:45 +02:00
if (args.count() != 1) {
logMessage(format("if(condition) requires one argument."));
2009-05-18 15:42:45 +02:00
return ProItem::ReturnFalse;
}
QString cond = args.first();
bool quoted = false;
bool ret = true;
bool orOp = false;
bool invert = false;
bool isFunc = false;
int parens = 0;
QString test;
test.reserve(20);
QString args;
args.reserve(50);
const QChar *d = cond.unicode();
const QChar *ed = d + cond.length();
while (d < ed) {
ushort c = (d++)->unicode();
bool isOp = false;
2009-05-18 15:42:45 +02:00
if (quoted) {
if (c == '"')
quoted = false;
else if (c == '!' && test.isEmpty())
invert = true;
else
test += c;
} else if (c == '(') {
isFunc = true;
if (parens)
args += c;
++parens;
} else if (c == ')') {
--parens;
if (parens)
args += c;
} else if (!parens) {
if (c == '"')
quoted = true;
else if (c == ':' || c == '|')
isOp = true;
else if (c == '!' && test.isEmpty())
invert = true;
else
test += c;
2009-05-18 15:42:45 +02:00
} else {
args += c;
}
if (!quoted && !parens && (isOp || d == ed)) {
if (m_cumulative || (orOp != ret)) {
if (isFunc)
ret = evaluateConditionalFunction(test, args);
2009-05-18 15:42:45 +02:00
else
ret = isActiveConfig(test, true);
ret ^= invert;
2009-05-18 15:42:45 +02:00
}
orOp = (c == '|');
invert = false;
isFunc = false;
test.clear();
args.clear();
2009-05-18 15:42:45 +02:00
}
}
return returnBool(ret);
}
case T_CONFIG: {
2008-12-02 12:01:29 +01:00
if (args.count() < 1 || args.count() > 2) {
logMessage(format("CONFIG(config) requires one or two arguments."));
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
if (args.count() == 1)
return returnBool(isActiveConfig(args.first()));
2008-12-02 12:01:29 +01:00
const QStringList mutuals = args[1].split(QLatin1Char('|'));
const QStringList &configs = valuesDirect(statics.strCONFIG);
for (int i = configs.size() - 1; i >= 0; i--) {
2008-12-02 12:01:29 +01:00
for (int mut = 0; mut < mutuals.count(); mut++) {
if (configs[i] == mutuals[mut].trimmed()) {
return returnBool(configs[i] == args[0]);
2008-12-02 12:01:29 +01:00
}
}
}
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
case T_CONTAINS: {
2008-12-02 12:01:29 +01:00
if (args.count() < 2 || args.count() > 3) {
logMessage(format("contains(var, val) requires two or three arguments."));
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
const QString &qry = args.at(1);
QRegExp regx;
if (qry != QRegExp::escape(qry))
regx.setPattern(qry);
const QStringList &l = values(map(args.first()));
2008-12-02 12:01:29 +01:00
if (args.count() == 2) {
for (int i = 0; i < l.size(); ++i) {
const QString val = l[i];
if ((!regx.isEmpty() && regx.exactMatch(val)) || val == qry)
return ProItem::ReturnTrue;
2008-12-02 12:01:29 +01:00
}
} else {
const QStringList mutuals = args[2].split(QLatin1Char('|'));
for (int i = l.size() - 1; i >= 0; i--) {
const QString val = l[i];
for (int mut = 0; mut < mutuals.count(); mut++) {
if (val == mutuals[mut].trimmed()) {
return returnBool((!regx.isEmpty() && regx.exactMatch(val))
|| val == qry);
2008-12-02 12:01:29 +01:00
}
}
}
}
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
2010-02-11 15:53:35 +01:00
case T_COUNT: {
2008-12-02 12:01:29 +01:00
if (args.count() != 2 && args.count() != 3) {
logMessage(format("count(var, count, op=\"equals\") requires two or three arguments."));
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
int cnt = values(map(args.first())).count();
2008-12-02 12:01:29 +01:00
if (args.count() == 3) {
QString comp = args[2];
if (comp == QLatin1String(">") || comp == QLatin1String("greaterThan")) {
2010-02-11 15:53:35 +01:00
return returnBool(cnt > args[1].toInt());
2008-12-02 12:01:29 +01:00
} else if (comp == QLatin1String(">=")) {
2010-02-11 15:53:35 +01:00
return returnBool(cnt >= args[1].toInt());
2008-12-02 12:01:29 +01:00
} else if (comp == QLatin1String("<") || comp == QLatin1String("lessThan")) {
2010-02-11 15:53:35 +01:00
return returnBool(cnt < args[1].toInt());
2008-12-02 12:01:29 +01:00
} else if (comp == QLatin1String("<=")) {
2010-02-11 15:53:35 +01:00
return returnBool(cnt <= args[1].toInt());
} else if (comp == QLatin1String("equals") || comp == QLatin1String("isEqual")
|| comp == QLatin1String("=") || comp == QLatin1String("==")) {
2010-02-11 15:53:35 +01:00
return returnBool(cnt == args[1].toInt());
2008-12-02 12:01:29 +01:00
} else {
logMessage(format("unexpected modifier to count(%2)").arg(comp));
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
}
2010-02-11 15:53:35 +01:00
return returnBool(cnt == args[1].toInt());
}
case T_GREATERTHAN:
case T_LESSTHAN: {
if (args.count() != 2) {
logMessage(format("%1(variable, value) requires two arguments.").arg(function));
return ProItem::ReturnFalse;
}
QString rhs(args[1]), lhs(values(map(args.at(0))).join(statics.field_sep));
bool ok;
int rhs_int = rhs.toInt(&ok);
if (ok) { // do integer compare
int lhs_int = lhs.toInt(&ok);
if (ok) {
if (func_t == T_GREATERTHAN)
return returnBool(lhs_int > rhs_int);
return returnBool(lhs_int < rhs_int);
}
}
if (func_t == T_GREATERTHAN)
return returnBool(lhs > rhs);
return returnBool(lhs < rhs);
}
case T_EQUALS:
if (args.count() != 2) {
logMessage(format("%1(variable, value) requires two arguments.").arg(function));
return ProItem::ReturnFalse;
}
return returnBool(values(map(args.at(0))).join(statics.field_sep) == args.at(1));
case T_CLEAR: {
if (m_skipLevel && !m_cumulative)
return ProItem::ReturnFalse;
if (args.count() != 1) {
logMessage(format("%1(variable) requires one argument.").arg(function));
return ProItem::ReturnFalse;
}
QHash<QString, QStringList> *hsh;
QHash<QString, QStringList>::Iterator it;
const QString &var = map(args.at(0));
if (!(hsh = findValues(var, &it)))
return ProItem::ReturnFalse;
if (hsh == &m_valuemapStack.top())
it->clear();
else
m_valuemapStack.top()[var].clear();
return ProItem::ReturnTrue;
}
case T_UNSET: {
if (m_skipLevel && !m_cumulative)
return ProItem::ReturnFalse;
if (args.count() != 1) {
logMessage(format("%1(variable) requires one argument.").arg(function));
return ProItem::ReturnFalse;
}
QHash<QString, QStringList> *hsh;
QHash<QString, QStringList>::Iterator it;
const QString &var = map(args.at(0));
if (!(hsh = findValues(var, &it)))
return ProItem::ReturnFalse;
if (m_valuemapStack.size() == 1)
hsh->erase(it);
else if (hsh == &m_valuemapStack.top())
*it = statics.fakeValue;
else
m_valuemapStack.top()[var] = statics.fakeValue;
return ProItem::ReturnTrue;
}
case T_INCLUDE: {
if (m_skipLevel && !m_cumulative)
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
QString parseInto;
// the third optional argument to include() controls warnings
// and is not used here
if ((args.count() == 2) || (args.count() == 3) ) {
2008-12-02 12:01:29 +01:00
parseInto = args[1];
} else if (args.count() != 1) {
2010-02-11 14:13:59 +01:00
logMessage(format("include(file, into, silent) requires one, two or three arguments."));
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
2010-02-11 14:13:59 +01:00
QString fn = resolvePath(expandEnvVars(args.first()));
bool ok;
if (parseInto.isEmpty()) {
ok = evaluateFile(fn);
} else {
QHash<QString, QStringList> symbols;
if ((ok = evaluateFileInto(fn, &symbols, 0))) {
QHash<QString, QStringList> newMap;
for (QHash<QString, QStringList>::ConstIterator
it = m_valuemapStack.top().constBegin(),
end = m_valuemapStack.top().constEnd();
it != end; ++it)
if (!(it.key().startsWith(parseInto) &&
(it.key().length() == parseInto.length()
|| it.key().at(parseInto.length()) == QLatin1Char('.'))))
newMap[it.key()] = it.value();
2010-02-11 14:13:59 +01:00
for (QHash<QString, QStringList>::ConstIterator it = symbols.constBegin();
it != symbols.constEnd(); ++it)
if (!it.key().startsWith(QLatin1Char('.')))
newMap.insert(parseInto + QLatin1Char('.') + it.key(), it.value());
m_valuemapStack.top() = newMap;
}
2010-02-11 14:13:59 +01:00
}
return returnBool(ok);
2008-12-02 12:01:29 +01:00
}
case T_LOAD: {
if (m_skipLevel && !m_cumulative)
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
bool ignore_error = false;
if (args.count() == 2) {
2010-04-29 17:46:57 +02:00
ignore_error = isTrue(args.at(1));
2008-12-02 12:01:29 +01:00
} else if (args.count() != 1) {
logMessage(format("load(feature) requires one or two arguments."));
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
// XXX ignore_error unused
return returnBool(evaluateFeatureFile(expandEnvVars(args.first())));
2008-12-02 12:01:29 +01:00
}
case T_DEBUG:
// Yup - do nothing. Nothing is going to enable debug output anyway.
return ProItem::ReturnFalse;
case T_MESSAGE: {
2008-12-02 12:01:29 +01:00
if (args.count() != 1) {
logMessage(format("%1(message) requires one argument.").arg(function));
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
QString msg = expandEnvVars(args.first());
fileMessage(QString::fromLatin1("Project %1: %2").arg(function.toUpper(), msg));
2009-05-20 14:35:00 +02:00
// ### Consider real termination in non-cumulative mode
return returnBool(function != QLatin1String("error"));
2008-12-02 12:01:29 +01:00
}
#if 0 // Way too dangerous to enable.
case T_SYSTEM: {
2008-12-02 12:01:29 +01:00
if (args.count() != 1) {
logMessage(format("system(exec) requires one argument."));
ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
return returnBool(system((QLatin1String("cd ")
+ IoUtils::shellQuote(currentDirectory())
+ QLatin1String(" && ") + args.first()).toLatin1().constData()) == 0);
2008-12-02 12:01:29 +01:00
}
#endif
case T_ISEMPTY: {
2008-12-02 12:01:29 +01:00
if (args.count() != 1) {
logMessage(format("isEmpty(var) requires one argument."));
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
QStringList sl = values(map(args.first()));
2008-12-02 12:01:29 +01:00
if (sl.count() == 0) {
return ProItem::ReturnTrue;
2008-12-02 12:01:29 +01:00
} else if (sl.count() > 0) {
QString var = sl.first();
if (var.isEmpty())
return ProItem::ReturnTrue;
2008-12-02 12:01:29 +01:00
}
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
case T_EXISTS: {
2008-12-02 12:01:29 +01:00
if (args.count() != 1) {
logMessage(format("exists(file) requires one argument."));
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
QString file = resolvePath(expandEnvVars(args.first()));
2008-12-02 12:01:29 +01:00
if (IoUtils::exists(file)) {
return ProItem::ReturnTrue;
2008-12-02 12:01:29 +01:00
}
2010-02-11 12:41:16 +01:00
int slsh = file.lastIndexOf(QLatin1Char('/'));
QString fn = file.mid(slsh+1);
if (fn.contains(QLatin1Char('*')) || fn.contains(QLatin1Char('?'))) {
QString dirstr = file.left(slsh+1);
if (!QDir(dirstr).entryList(QStringList(fn)).isEmpty())
return ProItem::ReturnTrue;
2010-02-11 12:41:16 +01:00
}
2008-12-02 12:01:29 +01:00
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
case 0:
logMessage(format("'%1' is not a recognized test function").arg(function));
return ProItem::ReturnFalse;
default:
logMessage(format("Function '%1' is not implemented").arg(function));
return ProItem::ReturnFalse;
2008-12-02 12:01:29 +01:00
}
}
QHash<QString, QStringList> *ProFileEvaluator::Private::findValues(
const QString &variableName, QHash<QString, QStringList>::Iterator *rit)
{
for (int i = m_valuemapStack.size(); --i >= 0; ) {
QHash<QString, QStringList>::Iterator it = m_valuemapStack[i].find(variableName);
if (it != m_valuemapStack[i].end()) {
if (it->constBegin() == statics.fakeValue.constBegin())
return 0;
*rit = it;
return &m_valuemapStack[i];
}
}
return 0;
}
QStringList &ProFileEvaluator::Private::valuesRef(const QString &variableName)
{
QHash<QString, QStringList>::Iterator it = m_valuemapStack.top().find(variableName);
if (it != m_valuemapStack.top().end())
return *it;
for (int i = m_valuemapStack.size() - 1; --i >= 0; ) {
QHash<QString, QStringList>::ConstIterator it = m_valuemapStack.at(i).constFind(variableName);
if (it != m_valuemapStack.at(i).constEnd()) {
QStringList &ret = m_valuemapStack.top()[variableName];
ret = *it;
return ret;
}
}
return m_valuemapStack.top()[variableName];
}
QStringList ProFileEvaluator::Private::valuesDirect(const QString &variableName) const
{
for (int i = m_valuemapStack.size(); --i >= 0; ) {
QHash<QString, QStringList>::ConstIterator it = m_valuemapStack.at(i).constFind(variableName);
if (it != m_valuemapStack.at(i).constEnd()) {
if (it->constBegin() == statics.fakeValue.constBegin())
break;
return *it;
}
}
return QStringList();
}
QStringList ProFileEvaluator::Private::values(const QString &variableName) const
2008-12-02 12:01:29 +01:00
{
QHash<QString, int>::ConstIterator vli = statics.varList.find(variableName);
if (vli != statics.varList.constEnd()) {
int vlidx = *vli;
QString ret;
switch ((VarName)vlidx) {
case V_LITERAL_WHITESPACE: ret = QLatin1String("\t"); break;
case V_LITERAL_DOLLAR: ret = QLatin1String("$"); break;
case V_LITERAL_HASH: ret = QLatin1String("#"); break;
case V_OUT_PWD: //the outgoing dir
ret = m_outputDir;
break;
case V_PWD: //current working dir (of _FILE_)
case V_IN_PWD:
ret = currentDirectory();
break;
case V_DIR_SEPARATOR:
ret = m_option->dir_sep;
break;
case V_DIRLIST_SEPARATOR:
ret = m_option->dirlist_sep;
break;
case V__LINE_: //parser line number
ret = QString::number(m_lineNo);
break;
case V__FILE_: //parser file; qmake is a bit weird here
ret = m_profileStack.size() == 1 ? currentFileName() : currentProFile()->displayFileName();
break;
case V__DATE_: //current date/time
ret = QDateTime::currentDateTime().toString();
break;
case V__PRO_FILE_:
ret = m_profileStack.first()->fileName();
break;
case V__PRO_FILE_PWD_:
ret = m_profileStack.first()->directoryName();
break;
case V__QMAKE_CACHE_:
ret = m_option->cachefile;
break;
#if defined(Q_OS_WIN32)
case V_QMAKE_HOST_os: ret = QLatin1String("Windows"); break;
case V_QMAKE_HOST_name: {
DWORD name_length = 1024;
TCHAR name[1024];
if (GetComputerName(name, &name_length))
ret = QString::fromUtf16((ushort*)name, name_length);
break;
}
case V_QMAKE_HOST_version:
ret = QString::number(QSysInfo::WindowsVersion);
break;
case V_QMAKE_HOST_version_string:
switch (QSysInfo::WindowsVersion) {
case QSysInfo::WV_Me: ret = QLatin1String("WinMe"); break;
case QSysInfo::WV_95: ret = QLatin1String("Win95"); break;
case QSysInfo::WV_98: ret = QLatin1String("Win98"); break;
case QSysInfo::WV_NT: ret = QLatin1String("WinNT"); break;
case QSysInfo::WV_2000: ret = QLatin1String("Win2000"); break;
case QSysInfo::WV_2003: ret = QLatin1String("Win2003"); break;
case QSysInfo::WV_XP: ret = QLatin1String("WinXP"); break;
case QSysInfo::WV_VISTA: ret = QLatin1String("WinVista"); break;
default: ret = QLatin1String("Unknown"); break;
}
break;
case V_QMAKE_HOST_arch:
SYSTEM_INFO info;
GetSystemInfo(&info);
switch(info.wProcessorArchitecture) {
#ifdef PROCESSOR_ARCHITECTURE_AMD64
case PROCESSOR_ARCHITECTURE_AMD64:
ret = QLatin1String("x86_64");
break;
#endif
case PROCESSOR_ARCHITECTURE_INTEL:
ret = QLatin1String("x86");
break;
case PROCESSOR_ARCHITECTURE_IA64:
#ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64
case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
#endif
ret = QLatin1String("IA64");
break;
default:
ret = QLatin1String("Unknown");
break;
}
break;
#elif defined(Q_OS_UNIX)
case V_QMAKE_HOST_os:
case V_QMAKE_HOST_name:
case V_QMAKE_HOST_version:
case V_QMAKE_HOST_version_string:
case V_QMAKE_HOST_arch:
{
struct utsname name;
const char *what;
if (!uname(&name)) {
switch (vlidx) {
case V_QMAKE_HOST_os: what = name.sysname; break;
case V_QMAKE_HOST_name: what = name.nodename; break;
case V_QMAKE_HOST_version: what = name.release; break;
case V_QMAKE_HOST_version_string: what = name.version; break;
case V_QMAKE_HOST_arch: what = name.machine; break;
}
ret = QString::fromLatin1(what);
}
}
#endif
}
return QStringList(ret);
}
QStringList result = valuesDirect(variableName);
if (result.isEmpty()) {
if (variableName == statics.strTEMPLATE) {
result.append(QLatin1String("app"));
} else if (variableName == statics.strQMAKE_DIR_SEP) {
result.append(m_option->dirlist_sep);
}
2008-12-02 12:01:29 +01:00
}
return result;
}
ProFile *ProFileEvaluator::Private::parsedProFile(const QString &fileName, bool cache,
const QString &contents)
2008-12-02 12:01:29 +01:00
{
ProFile *pro;
if (cache && m_option->cache) {
ProFileCache::Entry *ent;
#ifdef PROPARSER_THREAD_SAFE
QMutexLocker locker(&m_option->cache->mutex);
#endif
QHash<QString, ProFileCache::Entry>::Iterator it =
m_option->cache->parsed_files.find(fileName);
if (it != m_option->cache->parsed_files.end()) {
ent = &*it;
#ifdef PROPARSER_THREAD_SAFE
if (ent->locker && !ent->locker->done) {
++ent->locker->waiters;
QThreadPool::globalInstance()->releaseThread();
ent->locker->cond.wait(locker.mutex());
QThreadPool::globalInstance()->reserveThread();
if (!--ent->locker->waiters) {
delete ent->locker;
ent->locker = 0;
}
}
#endif
if ((pro = ent->pro))
pro->ref();
} else {
ent = &m_option->cache->parsed_files[fileName];
#ifdef PROPARSER_THREAD_SAFE
ent->locker = new ProFileCache::Entry::Locker;
locker.unlock();
#endif
pro = new ProFile(fileName);
if (!(contents.isNull() ? read(pro) : read(pro, contents))) {
delete pro;
pro = 0;
} else {
pro->ref();
}
ent->pro = pro;
#ifdef PROPARSER_THREAD_SAFE
locker.relock();
if (ent->locker->waiters) {
ent->locker->done = true;
ent->locker->cond.wakeAll();
} else {
delete ent->locker;
ent->locker = 0;
}
#endif
}
} else {
pro = new ProFile(fileName);
if (!(contents.isNull() ? read(pro) : read(pro, contents))) {
delete pro;
2010-02-26 12:50:57 +01:00
pro = 0;
}
}
return pro;
2008-12-02 12:01:29 +01:00
}
bool ProFileEvaluator::Private::evaluateFile(const QString &fileName)
2008-12-02 12:01:29 +01:00
{
if (fileName.isEmpty())
return false;
foreach (const ProFile *pf, m_profileStack)
if (pf->fileName() == fileName) {
errorMessage(format("circular inclusion of %1").arg(fileName));
return false;
}
if (ProFile *pro = parsedProFile(fileName, true)) {
q->aboutToEval(pro);
bool ok = (visitProFile(pro) == ProItem::ReturnTrue);
pro->deref();
return ok;
2008-12-02 12:01:29 +01:00
} else {
return false;
2008-12-02 12:01:29 +01:00
}
}
bool ProFileEvaluator::Private::evaluateFeatureFile(
const QString &fileName, QHash<QString, QStringList> *values, FunctionDefs *funcs)
2008-12-02 12:01:29 +01:00
{
QString fn = fileName;
if (!fn.endsWith(QLatin1String(".prf")))
fn += QLatin1String(".prf");
if (!fileName.contains((ushort)'/') || !IoUtils::exists(resolvePath(fn))) {
if (m_option->feature_roots.isEmpty())
m_option->feature_roots = qmakeFeaturePaths();
int start_root = 0;
QString currFn = currentFileName();
if (IoUtils::fileName(currFn) == IoUtils::fileName(fn)) {
for (int root = 0; root < m_option->feature_roots.size(); ++root)
if (currFn == m_option->feature_roots.at(root) + fn) {
start_root = root + 1;
break;
}
}
for (int root = start_root; root < m_option->feature_roots.size(); ++root) {
QString fname = m_option->feature_roots.at(root) + fn;
if (IoUtils::exists(fname)) {
fn = fname;
goto cool;
}
2008-12-02 12:01:29 +01:00
}
return false;
cool:
// It's beyond me why qmake has this inside this if ...
QStringList &already = valuesRef(QLatin1String("QMAKE_INTERNAL_INCLUDED_FEATURES"));
if (already.contains(fn))
return true;
already.append(fn);
} else {
fn = resolvePath(fn);
}
if (values) {
return evaluateFileInto(fn, values, funcs);
} else {
bool cumulative = m_cumulative;
m_cumulative = false;
// Don't use evaluateFile() here to avoid calling aboutToEval().
// The path is fully normalized already.
bool ok = false;
if (ProFile *pro = parsedProFile(fn, true)) {
ok = (visitProFile(pro) == ProItem::ReturnTrue);
pro->deref();
}
m_cumulative = cumulative;
return ok;
2008-12-02 12:01:29 +01:00
}
}
bool ProFileEvaluator::Private::evaluateFileInto(
const QString &fileName, QHash<QString, QStringList> *values, FunctionDefs *funcs)
{
ProFileEvaluator visitor(m_option);
visitor.d->m_cumulative = false;
visitor.d->m_parsePreAndPostFiles = false;
visitor.d->m_verbose = m_verbose;
visitor.d->m_valuemapStack.top() = *values;
if (funcs)
visitor.d->m_functionDefs = *funcs;
if (!visitor.d->evaluateFile(fileName))
return false;
*values = visitor.d->m_valuemapStack.top();
if (funcs) {
*funcs = visitor.d->m_functionDefs;
// So they are not unref'd
visitor.d->m_functionDefs.testFunctions.clear();
visitor.d->m_functionDefs.replaceFunctions.clear();
}
return true;
2008-12-02 12:01:29 +01:00
}
QString ProFileEvaluator::Private::format(const char *fmt) const
{
ProFile *pro = currentProFile();
QString fileName = pro ? pro->fileName() : QLatin1String("Not a file");
int lineNumber = pro ? m_lineNo : 0;
return QString::fromLatin1("%1(%2):").arg(fileName).arg(lineNumber) + QString::fromAscii(fmt);
}
void ProFileEvaluator::Private::logMessage(const QString &message) const
{
if (m_verbose && !m_skipLevel)
q->logMessage(message);
}
void ProFileEvaluator::Private::fileMessage(const QString &message) const
{
if (!m_skipLevel)
q->fileMessage(message);
}
void ProFileEvaluator::Private::errorMessage(const QString &message) const
{
if (!m_skipLevel)
q->errorMessage(message);
}
2008-12-02 12:01:29 +01:00
///////////////////////////////////////////////////////////////////////
//
// ProFileEvaluator
//
///////////////////////////////////////////////////////////////////////
void ProFileEvaluator::initialize()
{
Private::initStatics();
}
ProFileEvaluator::ProFileEvaluator(ProFileOption *option)
: d(new Private(this, option))
2008-12-02 12:01:29 +01:00
{
}
ProFileEvaluator::~ProFileEvaluator()
{
delete d;
}
bool ProFileEvaluator::contains(const QString &variableName) const
{
return d->m_valuemapStack.top().contains(variableName);
2008-12-02 12:01:29 +01:00
}
QStringList ProFileEvaluator::values(const QString &variableName) const
{
return expandEnvVars(d->values(variableName));
2008-12-02 12:01:29 +01:00
}
QStringList ProFileEvaluator::values(const QString &variableName, const ProFile *pro) const
{
// It makes no sense to put any kind of magic into expanding these
return expandEnvVars(d->m_filevaluemap.value(pro).value(variableName));
2008-12-02 12:01:29 +01:00
}
QStringList ProFileEvaluator::absolutePathValues(
const QString &variable, const QString &baseDirectory) const
{
QStringList result;
foreach (const QString &el, values(variable)) {
QString absEl = IoUtils::resolvePath(baseDirectory, el);
if (IoUtils::fileType(absEl) == IoUtils::FileIsDir)
result << QDir::cleanPath(absEl);
}
return result;
}
QStringList ProFileEvaluator::absoluteFileValues(
const QString &variable, const QString &baseDirectory, const QStringList &searchDirs,
const ProFile *pro) const
{
QStringList result;
foreach (const QString &el, pro ? values(variable, pro) : values(variable)) {
QString absEl;
if (IoUtils::isAbsolutePath(el)) {
if (IoUtils::exists(el)) {
result << QDir::cleanPath(el);
goto next;
}
absEl = el;
} else {
foreach (const QString &dir, searchDirs) {
QString fn = dir + QLatin1Char('/') + el;
if (IoUtils::exists(fn)) {
result << QDir::cleanPath(fn);
goto next;
}
}
if (baseDirectory.isEmpty())
goto next;
absEl = baseDirectory + QLatin1Char('/') + el;
}
{
absEl = QDir::cleanPath(absEl);
int nameOff = absEl.lastIndexOf(QLatin1Char('/'));
QString absDir = QString::fromRawData(absEl.constData(), nameOff);
if (IoUtils::exists(absDir)) {
QString wildcard = QString::fromRawData(absEl.constData() + nameOff + 1,
absEl.length() - nameOff - 1);
if (wildcard.contains(QLatin1Char('*')) || wildcard.contains(QLatin1Char('?'))) {
QDir theDir(absDir);
foreach (const QString &fn, theDir.entryList(QStringList(wildcard)))
if (fn != statics.strDot && fn != statics.strDotDot)
result << absDir + QLatin1Char('/') + fn;
} // else if (acceptMissing)
}
}
next: ;
}
return result;
}
2008-12-02 12:01:29 +01:00
ProFileEvaluator::TemplateType ProFileEvaluator::templateType()
{
QStringList templ = values(statics.strTEMPLATE);
2008-12-02 12:01:29 +01:00
if (templ.count() >= 1) {
const QString &t = templ.last();
if (!t.compare(QLatin1String("app"), Qt::CaseInsensitive))
2008-12-02 12:01:29 +01:00
return TT_Application;
if (!t.compare(QLatin1String("lib"), Qt::CaseInsensitive))
2008-12-02 12:01:29 +01:00
return TT_Library;
if (!t.compare(QLatin1String("script"), Qt::CaseInsensitive))
2008-12-02 12:01:29 +01:00
return TT_Script;
if (!t.compare(QLatin1String("subdirs"), Qt::CaseInsensitive))
2008-12-02 12:01:29 +01:00
return TT_Subdirs;
}
return TT_Unknown;
}
ProFile *ProFileEvaluator::parsedProFile(const QString &fileName, const QString &contents)
2008-12-02 12:01:29 +01:00
{
return d->parsedProFile(fileName, false, contents);
}
2008-12-02 12:01:29 +01:00
bool ProFileEvaluator::accept(ProFile *pro)
{
return d->visitProFile(pro);
2008-12-02 12:01:29 +01:00
}
QString ProFileEvaluator::propertyValue(const QString &name) const
{
return d->propertyValue(name);
}
void ProFileEvaluator::aboutToEval(ProFile *)
{
}
2008-12-02 12:01:29 +01:00
void ProFileEvaluator::logMessage(const QString &message)
{
qWarning("%s", qPrintable(message));
2008-12-02 12:01:29 +01:00
}
void ProFileEvaluator::fileMessage(const QString &message)
{
qWarning("%s", qPrintable(message));
2008-12-02 12:01:29 +01:00
}
void ProFileEvaluator::errorMessage(const QString &message)
{
qWarning("%s", qPrintable(message));
2008-12-02 12:01:29 +01:00
}
void ProFileEvaluator::setVerbose(bool on)
{
d->m_verbose = on;
}
void ProFileEvaluator::setCumulative(bool on)
{
d->m_cumulative = on;
}
void ProFileEvaluator::setOutputDir(const QString &dir)
{
d->m_outputDir = dir;
}
void ProFileEvaluator::setConfigCommandLineArguments(const QStringList &addUserConfigCmdArgs, const QStringList &removeUserConfigCmdArgs)
{
d->m_addUserConfigCmdArgs = addUserConfigCmdArgs;
d->m_removeUserConfigCmdArgs = removeUserConfigCmdArgs;
}
void ProFileEvaluator::setParsePreAndPostFiles(bool on)
{
d->m_parsePreAndPostFiles = on;
}
2008-12-02 12:01:29 +01:00
QT_END_NAMESPACE