7#include <qstringlist.h>
11#include <qvarlengtharray.h>
15using namespace QtMiscUtils;
26 result.resize(input.size());
27 const char *data = input.constData();
28 const char *end = input.constData() + input.size();
29 char *output = result.data();
35 bool takeLine = (*data ==
'#');
36 if (*data ==
'%' && *(data+1) ==
':') {
43 do ++data;
while (data != end &&
is_space(*data
));
48 if (*(data + 1) ==
'\r') {
51 if (data != end && (*(data + 1) ==
'\n' || (*data) ==
'\r')) {
54 if (data != end && *data !=
'\r')
58 }
else if (*data ==
'\r' && *(data + 1) ==
'\n') {
84 result.resize(output - result.constData());
91 while(index < symbols.size() - 1 && symbols.at(index).token != PP_ENDIF){
92 switch (symbols.at(index).token) {
108 while (index < symbols.size() - 1
109 && (symbols.at(index).token != PP_ENDIF
110 && symbols.at(index).token != PP_ELIF
111 && symbols.at(index).token != PP_ELSE)
113 switch (symbols.at(index).token) {
125 return (index < symbols.size() - 1);
136 symbols.reserve(input.size() / 16);
137 const char *begin = input.constData();
138 const char *data = begin;
143 const char *lexem = data;
145 Token token = NOTOKEN;
147 if (
static_cast<
signed char>(*data) < 0) {
151 int nextindex = keywords[state]
.next;
153 if (*data == keywords[state]
.defchar)
155 else if (!state || nextindex)
160 token = keywords[state]
.token;
166 token = keywords[state]
.ident;
168 if (token == NOTOKEN) {
180 if (token > SPECIAL_TREATMENT_MARK) {
184 token = STRING_LITERAL;
188 && !symbols.isEmpty()
189 && symbols.constLast().token == STRING_LITERAL) {
191 const QByteArray newString
193 + symbols.constLast().unquotedLexemView()
194 + input.mid(lexem - begin + 1, data - lexem - 2)
196 symbols.last() =
Symbol(symbols.constLast().lineNum,
203 while (*data && (*data !=
'\''
205 && *(data-2)!=
'\\')))
209 token = CHARACTER_LITERAL;
218 bool hasSeenTokenSeparator =
false;;
219 while (isAsciiDigit(*data) || (hasSeenTokenSeparator = *data ==
'\''))
221 if (!*data || *data !=
'.') {
222 token = INTEGER_LITERAL;
223 if (data - lexem == 1 &&
224 (*data ==
'x' || *data ==
'X'
225 || *data ==
'b' || *data ==
'B')
228 while (isHexDigit(*data) || (hasSeenTokenSeparator = *data ==
'\''))
230 }
else if (*data ==
'L')
232 if (!hasSeenTokenSeparator) {
240 token = FLOATING_LITERAL;
244 case FLOATING_LITERAL:
245 while (isAsciiDigit(*data) || *data ==
'\'')
247 if (*data ==
'+' || *data ==
'-')
249 if (*data ==
'e' || *data ==
'E') {
251 while (isAsciiDigit(*data) || *data ==
'\'')
254 if (*data ==
'f' || *data ==
'F'
255 || *data ==
'l' || *data ==
'L')
261 while (*data && (*data ==
' ' || *data ==
'\t'))
282 const char *rewind = data;
283 while (*data && (*data ==
' ' || *data ==
'\t'))
285 if (*data && *data ==
'\n') {
307 while (*data && (*(data-1) !=
'/' || *(data-2) !=
'*')) {
317 while (*data && (*data ==
' ' || *data ==
'\t'))
323 while (*data && *data !=
'\n')
330 symbols +=
Symbol(lineNum, token, input, lexem-begin, data-lexem);
334 const char *lexem = data;
336 Token token = NOTOKEN;
342 if (
static_cast<
signed char>(*data) < 0) {
346 int nextindex = pp_keywords[state]
.next;
348 if (*data == pp_keywords[state]
.defchar)
350 else if (!state || nextindex)
355 token = pp_keywords[state]
.token;
360 token = pp_keywords[state]
.ident;
380 case PP_INCLUDE_NEXT:
385 token = PP_STRING_LITERAL;
388 while (*data && (*data !=
'\''
390 && *(data-2)!=
'\\')))
394 token = PP_CHARACTER_LITERAL;
397 while (isAsciiDigit(*data) || *data ==
'\'')
399 if (!*data || *data !=
'.') {
400 token = PP_INTEGER_LITERAL;
401 if (data - lexem == 1 &&
402 (*data ==
'x' || *data ==
'X')
405 while (isHexDigit(*data) || *data ==
'\'')
407 }
else if (*data ==
'L')
411 token = PP_FLOATING_LITERAL;
414 case PP_FLOATING_LITERAL:
415 while (isAsciiDigit(*data) || *data ==
'\'')
417 if (*data ==
'+' || *data ==
'-')
419 if (*data ==
'e' || *data ==
'E') {
421 while (isAsciiDigit(*data) || *data ==
'\'')
424 if (*data ==
'f' || *data ==
'F'
425 || *data ==
'l' || *data ==
'L')
437 token = PP_IDENTIFIER;
440 symbols +=
Symbol(lineNum, token, input, lexem-begin, data-lexem);
461 while (*data && (*(data-1) !=
'/' || *(data-2) !=
'*')) {
466 token = PP_WHITESPACE;
469 while (*data && (*data ==
' ' || *data ==
'\t'))
473 while (*data && *data !=
'\n')
482 const char *rewind = data;
483 while (*data && (*data ==
' ' || *data ==
'\t'))
485 if (*data && *data ==
'\n') {
494 token = PP_STRING_LITERAL;
495 while (*data && *data !=
'\n' && *(data-1) !=
'>')
503 symbols +=
Symbol(lineNum, token, input, lexem-begin, data-lexem);
511 int lineNum,
bool one,
const QSet<QByteArray> &excludeSymbols)
516 sf.symbols = toExpand;
518 sf.excludedSymbols = excludeSymbols;
519 symbols.push(
std::move(sf));
521 if (toExpand.isEmpty())
526 Symbols newSyms = macroExpandIdentifier(that, symbols, lineNum, ¯o);
528 if (macro.isEmpty()) {
535 sf.symbols = newSyms;
537 sf.expandedMacro = macro;
538 symbols.push(
std::move(sf));
540 if (!symbols
.hasNext() || (one && symbols.size() == 1))
546 index = symbols.top().index;
548 index = toExpand.size();
557 if (s
.token != PP_IDENTIFIER || !that
->macros.contains(s) || symbols.dontReplaceSymbol(s.lexem())) {
562 *macroName = s.lexem();
566 expansion = macro.symbols;
568 bool haveSpace =
false;
569 while (symbols
.test(PP_WHITESPACE
)) { haveSpace =
true; }
570 if (!symbols
.test(PP_LPAREN
)) {
571 *macroName = QByteArray();
576 syms.last().lineNum = lineNum;
583 while (symbols
.test(PP_WHITESPACE
)) {}
585 bool vararg = macro
.isVariadic && (arguments.size() == macro.arguments.size() - 1);
588 if (t == PP_LPAREN) {
590 }
else if (t == PP_RPAREN) {
594 }
else if (t == PP_COMMA && nesting == 0) {
600 arguments += argument;
605 that->error(
"missing ')' in macro usage");
609 if (macro
.isVariadic && arguments.size() == macro.arguments.size() - 1)
610 arguments += Symbols();
619 const auto end = macro.symbols.cend();
620 auto it = macro.symbols.cbegin();
621 const auto lastSym =
std::prev(macro.symbols.cend(), !macro.symbols.isEmpty() ? 1 : 0);
622 for (; it != end; ++it) {
625 mode = (s
.token == HASH ? Hash : HashHash);
628 const qsizetype index = macro.arguments.indexOf(s);
629 if (mode == Normal) {
630 if (index >= 0 && index < arguments.size()) {
632 if (it == lastSym ||
std::next(it)->token != PP_HASHHASH) {
633 Symbols arg = arguments.at(index);
635 macroExpand(&expansion, that, arg, idx, lineNum,
false, symbols.excludeSymbols());
637 expansion += arguments.at(index);
642 }
else if (mode == Hash) {
644 that->error(
"'#' is not followed by a macro parameter");
646 }
else if (index >= arguments.size()) {
647 that->error(
"Macro invoked with too few parameters for a use of '#'");
651 const Symbols &arg = arguments.at(index);
652 QByteArray stringified;
654 stringified = arg.front().lexem();
655 for (
auto it = arg.cbegin();
std::next(it) != arg.cend(); ++it) {
656 const auto next =
std::next(it);
657 if (next->from - (it->from + it->len) > 0)
658 stringified +=
' ' + next->lexem();
660 stringified += next->lexem();
663 stringified.replace(
'"',
"\\\"");
664 stringified.prepend(
'"');
665 stringified.append(
'"');
668 expansion +=
Symbol(lineNum, STRING_LITERAL, stringified);
669 }
else if (mode == HashHash){
670 if (s
.token == WHITESPACE)
673 while (expansion.size() && expansion.constLast().token == PP_WHITESPACE)
674 expansion.pop_back();
677 if (index >= 0 && index < arguments.size()) {
678 const Symbols &arg = arguments.at(index);
679 if (arg.size() == 0) {
686 if (!expansion.isEmpty() && expansion.constLast().token == s
.token
687 && expansion.constLast().token != STRING_LITERAL) {
688 Symbol last = expansion.takeLast();
690 QByteArray lexem = last.lexem() + next.lexem();
696 if (index >= 0 && index < arguments.size()) {
697 const Symbols &arg = arguments.at(index);
699 expansion.append(arg.cbegin() + 1, arg.cend());
705 that->error(
"'#' or '##' found at the end of a macro argument");
715 Token token = next();
716 if (token == PP_IDENTIFIER) {
717 macroExpand(&substituted,
this, symbols, index, symbol().lineNum,
true);
718 }
else if (token == PP_DEFINED) {
719 bool braces = test(PP_LPAREN);
720 if (test(PP_HAS_INCLUDE) || test(PP_HAS_INCLUDE_NEXT)) {
722 Symbol definedOrNotDefined = symbol();
723 definedOrNotDefined
.token = PP_MOC_TRUE;
724 substituted += definedOrNotDefined;
727 Symbol definedOrNotDefined = symbol();
728 definedOrNotDefined
.token =
macros.contains(definedOrNotDefined)? PP_MOC_TRUE : PP_MOC_FALSE;
729 substituted += definedOrNotDefined;
734 }
else if (token == PP_NEWLINE) {
735 substituted += symbol();
737 }
else if (token == PP_HAS_INCLUDE || token == PP_HAS_INCLUDE_NEXT) {
738 const bool isIncludeNext = (token == PP_HAS_INCLUDE_NEXT);
741 bool usesAngleInclude =
false;
742 QByteArray includeAsString;
744 if (tok == PP_LANGLE) {
745 usesAngleInclude =
true;
748 Symbol currentSymbol = symbol();
749 includeAsString += currentSymbol.lexem();
750 if (currentSymbol
.token == PP_IDENTIFIER)
751 macroExpand(&innerSymbols,
this, symbols, index, symbol().lineNum,
true);
753 innerSymbols.append(currentSymbol);
754 }
while (next() != PP_RANGLE);
756 includeAsString = unquotedLexem();
759 const qsizetype startIndex = isIncludeNext ? includeNextStartIndex() : 0;
760 const auto exists = [&](
const QByteArray &include) {
762 return !resolveIncludeNext(include, startIndex).isNull();
763 const QByteArray &relative = usesAngleInclude ? QByteArray() : currentFilenames.top();
764 return !resolveInclude(include, relative).isNull();
766 bool result = exists(includeAsString);
767 if (usesAngleInclude && !result) {
769 includeAsString = {};
770 for (
const auto &innerSymbol: innerSymbols)
771 includeAsString.append(innerSymbol.lexem());
772 result = exists(includeAsString);
774 Symbol definedOrNotDefined = symbol();
775 definedOrNotDefined
.token = result ? PP_MOC_TRUE : PP_MOC_FALSE;
776 substituted += definedOrNotDefined;
778 substituted += symbol();
809 if (test(PP_QUESTION)) {
812 return value ? alt1 : alt2;
934 return remainder ? value % remainder : 0;
939 return div ? value / div : 0;
982 if (test(PP_LPAREN)) {
987 auto lexView = lexemView();
988 if (lexView.endsWith(
'L'))
990 value = lexView.toInt(
nullptr, 0);
998 return (t == PP_IDENTIFIER
999 || t == PP_INTEGER_LITERAL
1000 || t == PP_FLOATING_LITERAL
1002 || t == PP_MOC_FALSE
1009 expression.currentFilenames = currentFilenames;
1018 const qint64 size = file->size();
1019 char *rawInput =
reinterpret_cast<
char*>(file->map(0, size));
1020 return rawInput ? QByteArray::fromRawData(rawInput, size) : file->readAll();
1026 Q_ASSERT(from + len <= lex.size());
1027 Q_ASSERT(next.len >= 2);
1028 Q_ASSERT(next.from + next.len <= next.lex.size());
1030 if (len != lex.size()) {
1032 QByteArray l = lexemView().chopped(1) % next.lexemView().sliced(1);
1037 const auto unquoted = next.unquotedLexemView();
1038 lex.insert(from + len - 1,
1048 const auto mergeable = [](
const Symbol &lhs,
const Symbol &rhs) {
1049 return lhs
.token == STRING_LITERAL && rhs
.token == STRING_LITERAL;
1052 auto end = symbols.end();
1053 auto it =
std::adjacent_find(symbols.begin(), symbols.end(), mergeable);
1063 lit->mergeStringLiteral(*it);
1065 while (++it != end) {
1071 if (it->token == STRING_LITERAL) {
1073 lit->mergeStringLiteral(*it);
1075 *++dst =
std::move(*it);
1079 *++dst =
std::move(*it);
1085 symbols.erase(dst, end);
1092 const QByteArray &include,
1093 qsizetype startIndex,
1094 const bool debugIncludes)
1097 qsizetype foundIndex = -1;
1099 if (Q_UNLIKELY(debugIncludes)) {
1100 fprintf(stderr,
"debug-includes: searching for '%s'\n", include.constData());
1103 for (qsizetype i = startIndex; i < includepaths.size(); ++i) {
1104 const Parser::IncludePath &p = includepaths.at(i);
1108 if (p.isFrameworkPath) {
1109 const qsizetype slashPos = include.indexOf(
'/');
1110 if (slashPos >= 0) {
1111 fi.setFile(QString::fromLocal8Bit(p.path +
'/' + include.left(slashPos) +
".framework/Headers/"),
1112 QString::fromLocal8Bit(include.mid(slashPos + 1)));
1113 }
else if (!include.contains(
'.')) {
1115 fi.setFile(QString::fromLocal8Bit(p.path +
'/' + include +
".framework/Headers/"),
1116 QString::fromLocal8Bit(include));
1119 fi.setFile(QString::fromLocal8Bit(p.path), QString::fromLocal8Bit(include));
1122 if (Q_UNLIKELY(debugIncludes)) {
1123 const auto candidate = fi.filePath().toLocal8Bit();
1124 fprintf(stderr,
"debug-includes: considering '%s'\n", candidate.constData());
1136 if (!fi.exists() || fi.isDir()) {
1137 if (Q_UNLIKELY(debugIncludes)) {
1138 fprintf(stderr,
"debug-includes: can't find '%s'\n", include.constData());
1143 const auto result = fi.canonicalFilePath().toLocal8Bit();
1145 if (Q_UNLIKELY(debugIncludes)) {
1146 fprintf(stderr,
"debug-includes: found '%s'\n", result.constData());
1149 return { result, foundIndex };
1153 qsizetype *foundIndex)
1158 if (!relativeTo.isEmpty()) {
1160 fi.setFile(QFileInfo(QString::fromLocal8Bit(relativeTo)).dir(), QString::fromLocal8Bit(include));
1161 if (fi.exists() && !fi.isDir()) {
1166 if (foundIndex && !currentIncludeDirIndex.empty())
1167 *foundIndex = currentIncludeDirIndex.top();
1168 return fi.canonicalFilePath().toLocal8Bit();
1172 auto it = nonlocalIncludePathResolutionCache.find(include);
1173 if (it == nonlocalIncludePathResolutionCache.end())
1174 it = nonlocalIncludePathResolutionCache.insert(include,
1181 *foundIndex = it.value().foundIndex;
1182 return it.value().path;
1186 qsizetype *foundIndex)
1190 const IncludeResolution resolution = searchIncludePaths(includes, include, startIndex, debugIncludes);
1192 *foundIndex = resolution.foundIndex;
1193 return resolution.path;
1202 const qsizetype currentDirIndex = currentIncludeDirIndex.top();
1203 if (currentDirIndex < 0) {
1204 warning(
"#include_next in primary source file; "
1205 "will search from start of include path");
1208 return currentDirIndex + 1;
1211void Preprocessor::preprocess(
const QByteArray &filename,
Symbols &preprocessed, qsizetype includeDirIndex)
1213 currentFilenames.push(filename);
1214 currentIncludeDirIndex.push(includeDirIndex);
1215 preprocessed.reserve(preprocessed.size() + symbols.size());
1217 Token token = next();
1221 case PP_INCLUDE_NEXT:
1223 const bool includeNext = (token == PP_INCLUDE_NEXT);
1224 int lineNum = symbol().lineNum;
1227 if (test(PP_STRING_LITERAL)) {
1228 local = lexemView().startsWith(
'\"');
1229 include = unquotedLexem();
1234 qsizetype foundIndex = -1;
1236 include = resolveIncludeNext(include, includeNextStartIndex(), &foundIndex);
1238 include = resolveInclude(include, local ? filename : QByteArray(), &foundIndex);
1239 if (include.isNull())
1242 if (Preprocessor::preprocessedIncludes.contains(include))
1244 Preprocessor::preprocessedIncludes.insert(include);
1246 QFile file(QString::fromLocal8Bit(include.constData()));
1247 if (!file.open(QFile::ReadOnly))
1250 QByteArray input = readOrMapFile(&file);
1253 if (input.isEmpty())
1256 Symbols saveSymbols = symbols;
1257 qsizetype saveIndex = index;
1260 input = cleaned(input);
1263 symbols = tokenize(input);
1269 preprocessed +=
Symbol(0, MOC_INCLUDE_BEGIN, include);
1270 preprocess(include, preprocessed, foundIndex);
1271 preprocessed +=
Symbol(lineNum, MOC_INCLUDE_END, include);
1273 symbols = saveSymbols;
1280 QByteArray name = lexem();
1281 if (name.isEmpty() || !is_ident_start(name[0]))
1292 qsizetype start = index;
1294 macro.symbols.reserve(index - start - 1);
1298 Token lastToken = HASH;
1299 for (qsizetype i = start; i < index - 1; ++i) {
1300 Token token = symbols.at(i).token;
1301 if (token == WHITESPACE) {
1302 if (lastToken == PP_HASH || lastToken == HASH ||
1303 lastToken == PP_HASHHASH ||
1304 lastToken == WHITESPACE)
1306 }
else if (token == PP_HASHHASH) {
1307 if (!macro.symbols.isEmpty() &&
1308 lastToken == WHITESPACE)
1309 macro.symbols.pop_back();
1311 macro.symbols.append(symbols.at(i));
1315 while (!macro.symbols.isEmpty() &&
1316 (macro.symbols.constLast().token == PP_WHITESPACE || macro.symbols.constLast().token == WHITESPACE))
1317 macro.symbols.pop_back();
1319 if (!macro.symbols.isEmpty()) {
1320 if (macro.symbols.constFirst().token == PP_HASHHASH ||
1321 macro.symbols.constLast().token == PP_HASHHASH) {
1322 error(
"'##' cannot appear at either end of a macro expansion");
1325 macros.insert(name, macro);
1330 QByteArray name = lexem();
1335 case PP_IDENTIFIER: {
1337 macroExpand(&preprocessed,
this, symbols, index, symbol().lineNum,
true);
1349 if (test(PP_ELIF)) {
1368 if (
macros.contains(
"QT_NO_KEYWORDS"))
1371 sym
.token = (token == SIGNALS ? Q_SIGNALS_TOKEN : Q_SLOTS_TOKEN);
1372 preprocessed += sym;
1377 preprocessed += symbol();
1380 currentIncludeDirIndex.pop();
1381 currentFilenames.pop();
1386 QByteArray input = readOrMapFile(file);
1388 if (input.isEmpty())
1392 input = cleaned(input);
1396 symbols = tokenize(input);
1399 for (
int j = 0; j < symbols.size(); ++j)
1400 fprintf(stderr,
"line %d: %s(%s)\n",
1402 symbols[j].lexem().constData(),
1403 tokenTypeName(symbols[j].token));
1411 result.reserve(file->size() / 300000);
1412 preprocess(filename, result);
1413 mergeStringLiterals(result);
1416 for (
int j = 0; j < result.size(); ++j)
1417 fprintf(stderr,
"line %d: %s(%s)\n",
1419 result[j].lexem().constData(),
1420 tokenTypeName(result[j].token));
1430 while (test(PP_WHITESPACE)) {}
1434 if (t != PP_IDENTIFIER) {
1435 QByteArrayView l = lexemView();
1438 arguments +=
Symbol(symbol().lineNum, PP_IDENTIFIER,
"__VA_ARGS__");
1439 while (test(PP_WHITESPACE)) {}
1440 if (!test(PP_RPAREN))
1441 error(
"missing ')' in macro argument list");
1443 }
else if (!is_identifier(l.constData(), l.size())) {
1444 error(
"Unexpected character in macro argument list.");
1449 if (arguments.contains(arg))
1450 error(
"Duplicate macro parameter.");
1451 arguments += symbol();
1453 while (test(PP_WHITESPACE)) {}
1459 if (lexemView() ==
"...") {
1463 while (test(PP_WHITESPACE)) {}
1464 if (!test(PP_RPAREN))
1465 error(
"missing ')' in macro argument list");
1468 error(
"Unexpected character in macro argument list.");
1470 m->arguments = arguments;
1471 while (test(PP_WHITESPACE)) {}
1476 while(hasNext() && next() != t)
1482 debugIncludes = value;
int relational_expression()
int exclusive_OR_expression()
bool unary_expression_lookup()
int logical_OR_expression()
int equality_expression()
int logical_AND_expression()
int additive_expression()
int multiplicative_expression()
int conditional_expression()
bool primary_expression_lookup()
int inclusive_OR_expression()
QByteArray resolveIncludeNext(const QByteArray &filename, qsizetype startIndex, qsizetype *foundIndex=nullptr)
void setDebugIncludes(bool value)
void parseDefineArguments(Macro *m)
Symbols preprocessed(const QByteArray &filename, QFile *device)
void substituteUntilNewline(Symbols &substituted)
static bool preprocessOnly
QByteArray resolveInclude(const QByteArray &filename, const QByteArray &relativeTo, qsizetype *foundIndex=nullptr)
@ PreparePreprocessorStatement
@ TokenizePreprocessorStatement
const Symbol & symbol() const
static const short keyword_trans[][128]
Combined button and popup list for selecting options.
static const short pp_keyword_trans[][128]
static QByteArray readOrMapFile(QFile *file)
static IncludeResolution searchIncludePaths(const QList< Parser::IncludePath > &includepaths, const QByteArray &include, qsizetype startIndex, const bool debugIncludes)
static QByteArray cleaned(const QByteArray &input)
static void mergeStringLiterals(Symbols &symbols)
Simple structure used by the Doc and DocParser classes.
Symbol(int lineNum, Token token)
void mergeStringLiteral(const Symbol &next)