Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
preprocessor.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// Copyright (C) 2014 Olivier Goffart <ogoffart@woboq.org>
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
4
5#include "preprocessor.h"
6#include "utils.h"
7#include <qstringlist.h>
8#include <qfile.h>
9#include <qdir.h>
10#include <qfileinfo.h>
11#include <qvarlengtharray.h>
12
14
15using namespace QtMiscUtils;
16
17#include "ppkeywords.cpp"
18#include "keywords.cpp"
19
20// transform \r\n into \n
21// \r into \n (os9 style)
22// backslash-newlines into newlines
23static QByteArray cleaned(const QByteArray &input)
24{
25 QByteArray result;
26 result.resize(input.size());
27 const char *data = input.constData();
28 const char *end = input.constData() + input.size();
29 char *output = result.data();
30
31 int newlines = 0;
32 while (data != end) {
33 while (data != end && is_space(*data))
34 ++data;
35 bool takeLine = (*data == '#');
36 if (*data == '%' && *(data+1) == ':') {
37 takeLine = true;
38 ++data;
39 }
40 if (takeLine) {
41 *output = '#';
42 ++output;
43 do ++data; while (data != end && is_space(*data));
44 }
45 while (data != end) {
46 // handle \\\n, \\\r\n and \\\r
47 if (*data == '\\') {
48 if (*(data + 1) == '\r') {
49 ++data;
50 }
51 if (data != end && (*(data + 1) == '\n' || (*data) == '\r')) {
52 ++newlines;
53 data += 1;
54 if (data != end && *data != '\r')
55 data += 1;
56 continue;
57 }
58 } else if (*data == '\r' && *(data + 1) == '\n') { // reduce \r\n to \n
59 ++data;
60 }
61 if (data == end)
62 break;
63
64 char ch = *data;
65 if (ch == '\r') // os9: replace \r with \n
66 ch = '\n';
67 *output = ch;
68 ++output;
69
70 if (*data == '\n') {
71 // output additional newlines to keep the correct line-numbering
72 // for the lines following the backslash-newline sequence(s)
73 while (newlines) {
74 *output = '\n';
75 ++output;
76 --newlines;
77 }
78 ++data;
79 break;
80 }
81 ++data;
82 }
83 }
84 result.resize(output - result.constData());
85 return result;
86}
87
88bool Preprocessor::preprocessOnly = false;
90{
91 while(index < symbols.size() - 1 && symbols.at(index).token != PP_ENDIF){
92 switch (symbols.at(index).token) {
93 case PP_IF:
94 case PP_IFDEF:
95 case PP_IFNDEF:
96 ++index;
98 break;
99 default:
100 ;
101 }
102 ++index;
103 }
104}
105
107{
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)
112 ){
113 switch (symbols.at(index).token) {
114 case PP_IF:
115 case PP_IFDEF:
116 case PP_IFNDEF:
117 ++index;
119 break;
120 default:
121 ;
122 }
123 ++index;
124 }
125 return (index < symbols.size() - 1);
126}
127
128
129Symbols Preprocessor::tokenize(const QByteArray& input, int lineNum, Preprocessor::TokenizeMode mode)
130{
131 Symbols symbols;
132 // Preallocate some space to speed up the code below.
133 // The magic divisor value was found by calculating the average ratio between
134 // input size and the final size of symbols.
135 // This yielded a value of 16.x when compiling Qt Base.
136 symbols.reserve(input.size() / 16);
137 const char *begin = input.constData();
138 const char *data = begin;
139 while (*data) {
140 if (mode == TokenizeCpp || mode == TokenizeDefine) {
141 int column = 0;
142
143 const char *lexem = data;
144 int state = 0;
145 Token token = NOTOKEN;
146 for (;;) {
147 if (static_cast<signed char>(*data) < 0) {
148 ++data;
149 continue;
150 }
151 int nextindex = keywords[state].next;
152 int next = 0;
153 if (*data == keywords[state].defchar)
154 next = keywords[state].defnext;
155 else if (!state || nextindex)
156 next = keyword_trans[nextindex][(int)*data];
157 if (!next)
158 break;
159 state = next;
160 token = keywords[state].token;
161 ++data;
162 }
163
164 // suboptimal, is_ident_char should use a table
165 if (keywords[state].ident && is_ident_char(*data))
166 token = keywords[state].ident;
167
168 if (token == NOTOKEN) {
169 if (*data)
170 ++data;
171 // an error really, but let's ignore this input
172 // to not confuse moc later. However in pre-processor
173 // only mode let's continue.
175 continue;
176 }
177
178 ++column;
179
180 if (token > SPECIAL_TREATMENT_MARK) {
181 switch (token) {
182 case QUOTE:
183 data = skipQuote(data);
184 token = STRING_LITERAL;
185 // concatenate multi-line strings for easier
186 // STRING_LITERAL handling in moc
188 && !symbols.isEmpty()
189 && symbols.constLast().token == STRING_LITERAL) {
190
191 const QByteArray newString
192 = '\"'
193 + symbols.constLast().unquotedLexemView()
194 + input.mid(lexem - begin + 1, data - lexem - 2)
195 + '\"';
196 symbols.last() = Symbol(symbols.constLast().lineNum,
197 STRING_LITERAL,
198 newString);
199 continue;
200 }
201 break;
202 case SINGLEQUOTE:
203 while (*data && (*data != '\''
204 || (*(data-1)=='\\'
205 && *(data-2)!='\\')))
206 ++data;
207 if (*data)
208 ++data;
209 token = CHARACTER_LITERAL;
210 break;
211 case LANGLE_SCOPE:
212 // split <:: into two tokens, < and ::
213 token = LANGLE;
214 data -= 2;
215 break;
216 case DIGIT:
217 {
218 bool hasSeenTokenSeparator = false;;
219 while (isAsciiDigit(*data) || (hasSeenTokenSeparator = *data == '\''))
220 ++data;
221 if (!*data || *data != '.') {
222 token = INTEGER_LITERAL;
223 if (data - lexem == 1 &&
224 (*data == 'x' || *data == 'X'
225 || *data == 'b' || *data == 'B')
226 && *lexem == '0') {
227 ++data;
228 while (isHexDigit(*data) || (hasSeenTokenSeparator = *data == '\''))
229 ++data;
230 } else if (*data == 'L') // TODO: handle other suffixes
231 ++data;
232 if (!hasSeenTokenSeparator) {
233 while (is_ident_char(*data)) {
234 ++data;
235 token = IDENTIFIER;
236 }
237 }
238 break;
239 }
240 token = FLOATING_LITERAL;
241 ++data;
242 Q_FALLTHROUGH();
243 }
244 case FLOATING_LITERAL:
245 while (isAsciiDigit(*data) || *data == '\'')
246 ++data;
247 if (*data == '+' || *data == '-')
248 ++data;
249 if (*data == 'e' || *data == 'E') {
250 ++data;
251 while (isAsciiDigit(*data) || *data == '\'')
252 ++data;
253 }
254 if (*data == 'f' || *data == 'F'
255 || *data == 'l' || *data == 'L')
256 ++data;
257 break;
258 case HASH:
259 if (column == 1 && mode == TokenizeCpp) {
261 while (*data && (*data == ' ' || *data == '\t'))
262 ++data;
263 if (is_ident_char(*data))
265 continue;
266 }
267 break;
268 case PP_HASHHASH:
269 if (mode == TokenizeCpp)
270 continue;
271 break;
272 case NEWLINE:
273 ++lineNum;
274 if (mode == TokenizeDefine) {
275 mode = TokenizeCpp;
276 // emit the newline token
277 break;
278 }
279 continue;
280 case BACKSLASH:
281 {
282 const char *rewind = data;
283 while (*data && (*data == ' ' || *data == '\t'))
284 ++data;
285 if (*data && *data == '\n') {
286 ++data;
287 continue;
288 }
289 data = rewind;
290 } break;
291 case CHARACTER:
292 while (is_ident_char(*data))
293 ++data;
294 token = IDENTIFIER;
295 break;
296 case C_COMMENT:
297 if (*data) {
298 if (*data == '\n')
299 ++lineNum;
300 ++data;
301 if (*data) {
302 if (*data == '\n')
303 ++lineNum;
304 ++data;
305 }
306 }
307 while (*data && (*(data-1) != '/' || *(data-2) != '*')) {
308 if (*data == '\n')
309 ++lineNum;
310 ++data;
311 }
312 token = WHITESPACE; // one comment, one whitespace
313 Q_FALLTHROUGH();
314 case WHITESPACE:
315 if (column == 1)
316 column = 0;
317 while (*data && (*data == ' ' || *data == '\t'))
318 ++data;
319 if (Preprocessor::preprocessOnly) // tokenize whitespace
320 break;
321 continue;
322 case CPP_COMMENT:
323 while (*data && *data != '\n')
324 ++data;
325 continue; // ignore safely, the newline is a separator
326 default:
327 continue; //ignore
328 }
329 }
330 symbols += Symbol(lineNum, token, input, lexem-begin, data-lexem);
331
332 } else { // Preprocessor
333
334 const char *lexem = data;
335 int state = 0;
336 Token token = NOTOKEN;
337 if (mode == TokenizePreprocessorStatement) {
338 state = pp_keyword_trans[0][(int)'#'];
340 }
341 for (;;) {
342 if (static_cast<signed char>(*data) < 0) {
343 ++data;
344 continue;
345 }
346 int nextindex = pp_keywords[state].next;
347 int next = 0;
348 if (*data == pp_keywords[state].defchar)
349 next = pp_keywords[state].defnext;
350 else if (!state || nextindex)
351 next = pp_keyword_trans[nextindex][(int)*data];
352 if (!next)
353 break;
354 state = next;
355 token = pp_keywords[state].token;
356 ++data;
357 }
358 // suboptimal, is_ident_char should use a table
359 if (pp_keywords[state].ident && is_ident_char(*data))
360 token = pp_keywords[state].ident;
361
362 switch (token) {
363 case NOTOKEN:
364 if (*data)
365 ++data;
366 break;
367 case PP_DEFINE:
368 mode = PrepareDefine;
369 break;
370 case PP_IFDEF:
371 symbols += Symbol(lineNum, PP_IF);
372 symbols += Symbol(lineNum, PP_DEFINED);
373 continue;
374 case PP_IFNDEF:
375 symbols += Symbol(lineNum, PP_IF);
376 symbols += Symbol(lineNum, PP_NOT);
377 symbols += Symbol(lineNum, PP_DEFINED);
378 continue;
379 case PP_INCLUDE:
380 case PP_INCLUDE_NEXT:
381 mode = TokenizeInclude;
382 break;
383 case PP_QUOTE:
384 data = skipQuote(data);
385 token = PP_STRING_LITERAL;
386 break;
387 case PP_SINGLEQUOTE:
388 while (*data && (*data != '\''
389 || (*(data-1)=='\\'
390 && *(data-2)!='\\')))
391 ++data;
392 if (*data)
393 ++data;
394 token = PP_CHARACTER_LITERAL;
395 break;
396 case PP_DIGIT:
397 while (isAsciiDigit(*data) || *data == '\'')
398 ++data;
399 if (!*data || *data != '.') {
400 token = PP_INTEGER_LITERAL;
401 if (data - lexem == 1 &&
402 (*data == 'x' || *data == 'X')
403 && *lexem == '0') {
404 ++data;
405 while (isHexDigit(*data) || *data == '\'')
406 ++data;
407 } else if (*data == 'L') // TODO: handle other suffixes
408 ++data;
409 break;
410 }
411 token = PP_FLOATING_LITERAL;
412 ++data;
413 Q_FALLTHROUGH();
414 case PP_FLOATING_LITERAL:
415 while (isAsciiDigit(*data) || *data == '\'')
416 ++data;
417 if (*data == '+' || *data == '-')
418 ++data;
419 if (*data == 'e' || *data == 'E') {
420 ++data;
421 while (isAsciiDigit(*data) || *data == '\'')
422 ++data;
423 }
424 if (*data == 'f' || *data == 'F'
425 || *data == 'l' || *data == 'L')
426 ++data;
427 break;
428 case PP_CHARACTER:
429 if (mode == PreparePreprocessorStatement) {
430 // rewind entire token to begin
431 data = lexem;
433 continue;
434 }
435 while (is_ident_char(*data))
436 ++data;
437 token = PP_IDENTIFIER;
438
439 if (mode == PrepareDefine) {
440 symbols += Symbol(lineNum, token, input, lexem-begin, data-lexem);
441 // make sure we explicitly add the whitespace here if the next char
442 // is not an opening brace, so we can distinguish correctly between
443 // regular and function macros
444 if (*data != '(')
445 symbols += Symbol(lineNum, WHITESPACE);
446 mode = TokenizeDefine;
447 continue;
448 }
449 break;
450 case PP_C_COMMENT:
451 if (*data) {
452 if (*data == '\n')
453 ++lineNum;
454 ++data;
455 if (*data) {
456 if (*data == '\n')
457 ++lineNum;
458 ++data;
459 }
460 }
461 while (*data && (*(data-1) != '/' || *(data-2) != '*')) {
462 if (*data == '\n')
463 ++lineNum;
464 ++data;
465 }
466 token = PP_WHITESPACE; // one comment, one whitespace
467 Q_FALLTHROUGH();
468 case PP_WHITESPACE:
469 while (*data && (*data == ' ' || *data == '\t'))
470 ++data;
471 continue; // the preprocessor needs no whitespace
472 case PP_CPP_COMMENT:
473 while (*data && *data != '\n')
474 ++data;
475 continue; // ignore safely, the newline is a separator
476 case PP_NEWLINE:
477 ++lineNum;
478 mode = TokenizeCpp;
479 break;
480 case PP_BACKSLASH:
481 {
482 const char *rewind = data;
483 while (*data && (*data == ' ' || *data == '\t'))
484 ++data;
485 if (*data && *data == '\n') {
486 ++data;
487 continue;
488 }
489 data = rewind;
490 } break;
491 case PP_LANGLE:
492 if (mode != TokenizeInclude)
493 break;
494 token = PP_STRING_LITERAL;
495 while (*data && *data != '\n' && *(data-1) != '>')
496 ++data;
497 break;
498 default:
499 break;
500 }
502 continue;
503 symbols += Symbol(lineNum, token, input, lexem-begin, data-lexem);
504 }
505 }
506 symbols += Symbol(); // eof symbol
507 return symbols;
508}
509
510void Preprocessor::macroExpand(Symbols *into, Preprocessor *that, const Symbols &toExpand, qsizetype &index,
511 int lineNum, bool one, const QSet<QByteArray> &excludeSymbols)
512{
513 SymbolStack symbols;
514 symbols.reserve(8);
515 SafeSymbols sf;
516 sf.symbols = toExpand;
517 sf.index = index;
518 sf.excludedSymbols = excludeSymbols;
519 symbols.push(std::move(sf));
520
521 if (toExpand.isEmpty())
522 return;
523
524 for (;;) {
525 QByteArray macro;
526 Symbols newSyms = macroExpandIdentifier(that, symbols, lineNum, &macro);
527
528 if (macro.isEmpty()) {
529 // not a macro
530 Symbol s = symbols.symbol();
531 s.lineNum = lineNum;
532 *into += s;
533 } else {
534 SafeSymbols sf;
535 sf.symbols = newSyms;
536 sf.index = 0;
537 sf.expandedMacro = macro;
538 symbols.push(std::move(sf));
539 }
540 if (!symbols.hasNext() || (one && symbols.size() == 1))
541 break;
542 symbols.next();
543 }
544
545 if (symbols.size())
546 index = symbols.top().index;
547 else
548 index = toExpand.size();
549}
550
551
552Symbols Preprocessor::macroExpandIdentifier(Preprocessor *that, SymbolStack &symbols, int lineNum, QByteArray *macroName)
553{
554 Symbol s = symbols.symbol();
555
556 // not a macro
557 if (s.token != PP_IDENTIFIER || !that->macros.contains(s) || symbols.dontReplaceSymbol(s.lexem())) {
558 return Symbols();
559 }
560
561 const Macro &macro = that->macros.value(s);
562 *macroName = s.lexem();
563
564 Symbols expansion;
565 if (!macro.isFunction) {
566 expansion = macro.symbols;
567 } else {
568 bool haveSpace = false;
569 while (symbols.test(PP_WHITESPACE)) { haveSpace = true; }
570 if (!symbols.test(PP_LPAREN)) {
571 *macroName = QByteArray();
572 Symbols syms;
573 if (haveSpace)
574 syms += Symbol(lineNum, PP_WHITESPACE);
575 syms += s;
576 syms.last().lineNum = lineNum;
577 return syms;
578 }
579 QVarLengthArray<Symbols, 5> arguments;
580 while (symbols.hasNext()) {
581 Symbols argument;
582 // strip leading space
583 while (symbols.test(PP_WHITESPACE)) {}
584 int nesting = 0;
585 bool vararg = macro.isVariadic && (arguments.size() == macro.arguments.size() - 1);
586 while (symbols.hasNext()) {
587 Token t = symbols.next();
588 if (t == PP_LPAREN) {
589 ++nesting;
590 } else if (t == PP_RPAREN) {
591 --nesting;
592 if (nesting < 0)
593 break;
594 } else if (t == PP_COMMA && nesting == 0) {
595 if (!vararg)
596 break;
597 }
598 argument += symbols.symbol();
599 }
600 arguments += argument;
601
602 if (nesting < 0)
603 break;
604 else if (!symbols.hasNext())
605 that->error("missing ')' in macro usage");
606 }
607
608 // empty VA_ARGS
609 if (macro.isVariadic && arguments.size() == macro.arguments.size() - 1)
610 arguments += Symbols();
611
612 // now replace the macro arguments with the expanded arguments
613 enum Mode {
614 Normal,
615 Hash,
616 HashHash
617 } mode = Normal;
618
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) {
623 const Symbol &s = *it;
624 if (s.token == HASH || s.token == PP_HASHHASH) {
625 mode = (s.token == HASH ? Hash : HashHash);
626 continue;
627 }
628 const qsizetype index = macro.arguments.indexOf(s);
629 if (mode == Normal) {
630 if (index >= 0 && index < arguments.size()) {
631 // each argument undoergoes macro expansion if it's not used as part of a # or ##
632 if (it == lastSym || std::next(it)->token != PP_HASHHASH) {
633 Symbols arg = arguments.at(index);
634 qsizetype idx = 1;
635 macroExpand(&expansion, that, arg, idx, lineNum, false, symbols.excludeSymbols());
636 } else {
637 expansion += arguments.at(index);
638 }
639 } else {
640 expansion += s;
641 }
642 } else if (mode == Hash) {
643 if (index < 0) {
644 that->error("'#' is not followed by a macro parameter");
645 continue;
646 } else if (index >= arguments.size()) {
647 that->error("Macro invoked with too few parameters for a use of '#'");
648 continue;
649 }
650
651 const Symbols &arg = arguments.at(index);
652 QByteArray stringified;
653 if (!arg.empty()) {
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();
659 else
660 stringified += next->lexem();
661 }
662
663 stringified.replace('"', "\\\"");
664 stringified.prepend('"');
665 stringified.append('"');
666 }
667
668 expansion += Symbol(lineNum, STRING_LITERAL, stringified);
669 } else if (mode == HashHash){
670 if (s.token == WHITESPACE)
671 continue;
672
673 while (expansion.size() && expansion.constLast().token == PP_WHITESPACE)
674 expansion.pop_back();
675
676 Symbol next = s;
677 if (index >= 0 && index < arguments.size()) {
678 const Symbols &arg = arguments.at(index);
679 if (arg.size() == 0) {
680 mode = Normal;
681 continue;
682 }
683 next = arg.at(0);
684 }
685
686 if (!expansion.isEmpty() && expansion.constLast().token == s.token
687 && expansion.constLast().token != STRING_LITERAL) {
688 Symbol last = expansion.takeLast();
689
690 QByteArray lexem = last.lexem() + next.lexem();
691 expansion += Symbol(lineNum, last.token, lexem);
692 } else {
693 expansion += next;
694 }
695
696 if (index >= 0 && index < arguments.size()) {
697 const Symbols &arg = arguments.at(index);
698 if (!arg.isEmpty())
699 expansion.append(arg.cbegin() + 1, arg.cend());
700 }
701 }
702 mode = Normal;
703 }
704 if (mode != Normal)
705 that->error("'#' or '##' found at the end of a macro argument");
706
707 }
708
709 return expansion;
710}
711
713{
714 while (hasNext()) {
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)) {
721 // __has_include / __has_include_next are always supported
722 Symbol definedOrNotDefined = symbol();
723 definedOrNotDefined.token = PP_MOC_TRUE;
724 substituted += definedOrNotDefined;
725 } else {
726 next(PP_IDENTIFIER);
727 Symbol definedOrNotDefined = symbol();
728 definedOrNotDefined.token = macros.contains(definedOrNotDefined)? PP_MOC_TRUE : PP_MOC_FALSE;
729 substituted += definedOrNotDefined;
730 }
731 if (braces)
732 test(PP_RPAREN);
733 continue;
734 } else if (token == PP_NEWLINE) {
735 substituted += symbol();
736 break;
737 } else if (token == PP_HAS_INCLUDE || token == PP_HAS_INCLUDE_NEXT) {
738 const bool isIncludeNext = (token == PP_HAS_INCLUDE_NEXT);
739 next(LPAREN);
740 Token tok = next(); // quote or LANGLE
741 bool usesAngleInclude = false;
742 QByteArray includeAsString;
743 Symbols innerSymbols;
744 if (tok == PP_LANGLE) {
745 usesAngleInclude = true;
746 next();
747 do {
748 Symbol currentSymbol = symbol();
749 includeAsString += currentSymbol.lexem();
750 if (currentSymbol.token == PP_IDENTIFIER)
751 macroExpand(&innerSymbols, this, symbols, index, symbol().lineNum, true);
752 else
753 innerSymbols.append(currentSymbol);
754 } while (next() != PP_RANGLE);
755 } else {
756 includeAsString = unquotedLexem();
757 }
758 next(RPAREN);
759 const qsizetype startIndex = isIncludeNext ? includeNextStartIndex() : 0;
760 const auto exists = [&](const QByteArray &include) {
761 if (isIncludeNext)
762 return !resolveIncludeNext(include, startIndex).isNull();
763 const QByteArray &relative = usesAngleInclude ? QByteArray() : currentFilenames.top();
764 return !resolveInclude(include, relative).isNull();
765 };
766 bool result = exists(includeAsString);
767 if (usesAngleInclude && !result) {
768 // try with expansion
769 includeAsString = {};
770 for (const auto &innerSymbol: innerSymbols)
771 includeAsString.append(innerSymbol.lexem());
772 result = exists(includeAsString);
773 }
774 Symbol definedOrNotDefined = symbol();
775 definedOrNotDefined.token = result ? PP_MOC_TRUE : PP_MOC_FALSE;
776 substituted += definedOrNotDefined;
777 } else {
778 substituted += symbol();
779 }
780 }
781}
782
783
805
807{
808 int value = logical_OR_expression();
809 if (test(PP_QUESTION)) {
810 int alt1 = conditional_expression();
811 int alt2 = test(PP_COLON) ? conditional_expression() : 0;
812 return value ? alt1 : alt2;
813 }
814 return value;
815}
816
818{
819 int value = logical_AND_expression();
820 if (test(PP_OROR))
821 return logical_OR_expression() || value;
822 return value;
823}
824
826{
827 int value = inclusive_OR_expression();
828 if (test(PP_ANDAND))
829 return logical_AND_expression() && value;
830 return value;
831}
832
834{
835 int value = exclusive_OR_expression();
836 if (test(PP_OR))
837 return value | inclusive_OR_expression();
838 return value;
839}
840
842{
843 int value = AND_expression();
844 if (test(PP_HAT))
845 return value ^ exclusive_OR_expression();
846 return value;
847}
848
850{
851 int value = equality_expression();
852 if (test(PP_AND))
853 return value & AND_expression();
854 return value;
855}
856
858{
859 int value = relational_expression();
860 switch (next()) {
861 case PP_EQEQ:
862 return value == equality_expression();
863 case PP_NE:
864 return value != equality_expression();
865 default:
866 prev();
867 return value;
868 }
869}
870
872{
873 int value = shift_expression();
874 switch (next()) {
875 case PP_LANGLE:
876 return value < relational_expression();
877 case PP_RANGLE:
878 return value > relational_expression();
879 case PP_LE:
880 return value <= relational_expression();
881 case PP_GE:
882 return value >= relational_expression();
883 default:
884 prev();
885 return value;
886 }
887}
888
890{
891 int value = additive_expression();
892 switch (next()) {
893 case PP_LTLT:
894 return value << shift_expression();
895 case PP_GTGT:
896 return value >> shift_expression();
897 default:
898 prev();
899 return value;
900 }
901}
902
904{
905 int value = multiplicative_expression();
906 switch (next()) {
907 case PP_PLUS:
908 return value + additive_expression();
909 case PP_MINUS:
910 return value - additive_expression();
911 default:
912 prev();
913 return value;
914 }
915}
916
918{
919 int value = unary_expression();
920 switch (next()) {
921 case PP_STAR:
922 {
923 // get well behaved overflow behavior by converting to long
924 // and then back to int
925 // NOTE: A conformant preprocessor would need to work intmax_t/
926 // uintmax_t according to [cpp.cond], 19.1 §10
927 // But we're not compliant anyway
928 qint64 result = qint64(value) * qint64(multiplicative_expression());
929 return int(result);
930 }
931 case PP_PERCENT:
932 {
933 int remainder = multiplicative_expression();
934 return remainder ? value % remainder : 0;
935 }
936 case PP_SLASH:
937 {
939 return div ? value / div : 0;
940 }
941 default:
942 prev();
943 return value;
944 };
945}
946
948{
949 switch (next()) {
950 case PP_PLUS:
951 return unary_expression();
952 case PP_MINUS:
953 return -unary_expression();
954 case PP_NOT:
955 return !unary_expression();
956 case PP_TILDE:
957 return ~unary_expression();
958 case PP_MOC_TRUE:
959 return 1;
960 case PP_MOC_FALSE:
961 return 0;
962 default:
963 prev();
965 }
966}
967
969{
970 Token t = lookup();
972 || t == PP_PLUS
973 || t == PP_MINUS
974 || t == PP_NOT
975 || t == PP_TILDE
976 || t == PP_DEFINED);
977}
978
980{
981 int value;
982 if (test(PP_LPAREN)) {
984 test(PP_RPAREN);
985 } else {
986 next();
987 auto lexView = lexemView();
988 if (lexView.endsWith('L'))
989 lexView.chop(1);
990 value = lexView.toInt(nullptr, 0);
991 }
992 return value;
993}
994
996{
997 Token t = lookup();
998 return (t == PP_IDENTIFIER
999 || t == PP_INTEGER_LITERAL
1000 || t == PP_FLOATING_LITERAL
1001 || t == PP_MOC_TRUE
1002 || t == PP_MOC_FALSE
1003 || t == PP_LPAREN);
1004}
1005
1007{
1008 PP_Expression expression;
1009 expression.currentFilenames = currentFilenames;
1010
1011 substituteUntilNewline(expression.symbols);
1012
1013 return expression.value();
1014}
1015
1016static QByteArray readOrMapFile(QFile *file)
1017{
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();
1021}
1022
1024{
1025 Q_ASSERT(len >= 2); // at least `""`
1026 Q_ASSERT(from + len <= lex.size());
1027 Q_ASSERT(next.len >= 2); // at least `""`
1028 Q_ASSERT(next.from + next.len <= next.lex.size());
1029
1030 if (len != lex.size()) {
1031 // "rubbish" around lexem() in `lex`: clean up (`lex` may be the whole file)
1032 QByteArray l = lexemView().chopped(1) % next.lexemView().sliced(1);
1033 lex = std::move(l); // lexemView() aliases `lex`; only clobber it now
1034 from = 0;
1035 } else {
1036 // like QByteArray::append(), but dealing with the "" around each lexem:
1037 const auto unquoted = next.unquotedLexemView();
1038 lex.insert(from + len - 1, // before closing `"`
1039 unquoted);
1040 }
1041 len = lex.size();
1042}
1043
1044static void mergeStringLiterals(Symbols &symbols)
1045{
1046 // like std::unique, but merges instead of skips adjacent STRING_LITERALs:
1047
1048 const auto mergeable = [](const Symbol &lhs, const Symbol &rhs) {
1049 return lhs.token == STRING_LITERAL && rhs.token == STRING_LITERAL;
1050 };
1051
1052 auto end = symbols.end();
1053 auto it = std::adjacent_find(symbols.begin(), symbols.end(), mergeable);
1054 if (it == end) // none found
1055 return;
1056
1057 // we know `it`, `it + 1` are both STRING_LITERAL (adjacent_find post-condition)
1058 // in particular: it + 1 < end
1059
1060 auto dst = it;
1061 auto lit = dst;
1062 ++it;
1063 lit->mergeStringLiteral(*it);
1064
1065 while (++it != end) {
1066 // Loop Invariants:
1067 // - [begin(), dst] is already processed
1068 // - `lit` is the last string literal
1069 // - we can merge if lit == dst
1070 // - [it, end[ still to be checked
1071 if (it->token == STRING_LITERAL) {
1072 if (lit == dst) { // can merge
1073 lit->mergeStringLiteral(*it);
1074 } else { // can't merge: not adjacent to previous STRING_LITERAL
1075 *++dst = std::move(*it);
1076 lit = dst; // remember that this was a literal
1077 }
1078 } else {
1079 *++dst = std::move(*it);
1080 }
1081 }
1082
1083 ++dst;
1084
1085 symbols.erase(dst, end);
1086}
1087
1088// Searches the include path list for \a include, starting at \a startIndex.
1089// For a plain #include startIndex is 0 (search the whole list); for
1090// #include_next it is one past the directory the current file was found in.
1091static IncludeResolution searchIncludePaths(const QList<Parser::IncludePath> &includepaths,
1092 const QByteArray &include,
1093 qsizetype startIndex,
1094 const bool debugIncludes)
1095{
1096 QFileInfo fi;
1097 qsizetype foundIndex = -1;
1098
1099 if (Q_UNLIKELY(debugIncludes)) {
1100 fprintf(stderr, "debug-includes: searching for '%s'\n", include.constData());
1101 }
1102
1103 for (qsizetype i = startIndex; i < includepaths.size(); ++i) {
1104 const Parser::IncludePath &p = includepaths.at(i);
1105 if (fi.exists())
1106 break;
1107
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('.')) {
1114 // Possible umbrella header
1115 fi.setFile(QString::fromLocal8Bit(p.path + '/' + include + ".framework/Headers/"),
1116 QString::fromLocal8Bit(include));
1117 }
1118 } else {
1119 fi.setFile(QString::fromLocal8Bit(p.path), QString::fromLocal8Bit(include));
1120 }
1121
1122 if (Q_UNLIKELY(debugIncludes)) {
1123 const auto candidate = fi.filePath().toLocal8Bit();
1124 fprintf(stderr, "debug-includes: considering '%s'\n", candidate.constData());
1125 }
1126
1127 // try again, maybe there's a file later in the include paths with the same name
1128 // (186067)
1129 if (fi.isDir()) {
1130 fi = QFileInfo();
1131 continue;
1132 }
1133 foundIndex = i;
1134 }
1135
1136 if (!fi.exists() || fi.isDir()) {
1137 if (Q_UNLIKELY(debugIncludes)) {
1138 fprintf(stderr, "debug-includes: can't find '%s'\n", include.constData());
1139 }
1140 return {};
1141 }
1142
1143 const auto result = fi.canonicalFilePath().toLocal8Bit();
1144
1145 if (Q_UNLIKELY(debugIncludes)) {
1146 fprintf(stderr, "debug-includes: found '%s'\n", result.constData());
1147 }
1148
1149 return { result, foundIndex };
1150}
1151
1152QByteArray Preprocessor::resolveInclude(const QByteArray &include, const QByteArray &relativeTo,
1153 qsizetype *foundIndex)
1154{
1155 if (foundIndex)
1156 *foundIndex = -1;
1157
1158 if (!relativeTo.isEmpty()) {
1159 QFileInfo fi;
1160 fi.setFile(QFileInfo(QString::fromLocal8Bit(relativeTo)).dir(), QString::fromLocal8Bit(include));
1161 if (fi.exists() && !fi.isDir()) {
1162 // Found next to the including file, not via the search path. Inherit
1163 // the includer's include-path position so a later #include_next
1164 // resumes after that directory instead of being mistaken for one in
1165 // the primary source file (e.g. GCC's syslimits.h via limits.h).
1166 if (foundIndex && !currentIncludeDirIndex.empty())
1167 *foundIndex = currentIncludeDirIndex.top();
1168 return fi.canonicalFilePath().toLocal8Bit();
1169 }
1170 }
1171
1172 auto it = nonlocalIncludePathResolutionCache.find(include);
1173 if (it == nonlocalIncludePathResolutionCache.end())
1174 it = nonlocalIncludePathResolutionCache.insert(include,
1175 searchIncludePaths(
1176 includes,
1177 include,
1178 0,
1179 debugIncludes));
1180 if (foundIndex)
1181 *foundIndex = it.value().foundIndex;
1182 return it.value().path;
1183}
1184
1185QByteArray Preprocessor::resolveIncludeNext(const QByteArray &include, qsizetype startIndex,
1186 qsizetype *foundIndex)
1187{
1188 // #include_next never resolves relative to the including file, and its
1189 // result depends on the start index, so it bypasses the resolution cache.
1190 const IncludeResolution resolution = searchIncludePaths(includes, include, startIndex, debugIncludes);
1191 if (foundIndex)
1192 *foundIndex = resolution.foundIndex;
1193 return resolution.path;
1194}
1195
1196qsizetype Preprocessor::includeNextStartIndex()
1197{
1198 // #include_next continues the search after the directory the current file
1199 // was found in. If the current file was not found via the include path
1200 // (e.g. the primary source file), warn and search from the start of the
1201 // path, matching GCC/Clang.
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");
1206 return 0;
1207 }
1208 return currentDirIndex + 1;
1209}
1210
1211void Preprocessor::preprocess(const QByteArray &filename, Symbols &preprocessed, qsizetype includeDirIndex)
1212{
1213 currentFilenames.push(filename);
1214 currentIncludeDirIndex.push(includeDirIndex);
1215 preprocessed.reserve(preprocessed.size() + symbols.size());
1216 while (hasNext()) {
1217 Token token = next();
1218
1219 switch (token) {
1220 case PP_INCLUDE:
1221 case PP_INCLUDE_NEXT:
1222 {
1223 const bool includeNext = (token == PP_INCLUDE_NEXT);
1224 int lineNum = symbol().lineNum;
1225 QByteArray include;
1226 bool local = false;
1227 if (test(PP_STRING_LITERAL)) {
1228 local = lexemView().startsWith('\"');
1229 include = unquotedLexem();
1230 } else
1231 continue;
1232 until(PP_NEWLINE);
1233
1234 qsizetype foundIndex = -1;
1235 if (includeNext)
1236 include = resolveIncludeNext(include, includeNextStartIndex(), &foundIndex);
1237 else
1238 include = resolveInclude(include, local ? filename : QByteArray(), &foundIndex);
1239 if (include.isNull())
1240 continue;
1241
1242 if (Preprocessor::preprocessedIncludes.contains(include))
1243 continue;
1244 Preprocessor::preprocessedIncludes.insert(include);
1245
1246 QFile file(QString::fromLocal8Bit(include.constData()));
1247 if (!file.open(QFile::ReadOnly))
1248 continue;
1249
1250 QByteArray input = readOrMapFile(&file);
1251
1252 file.close();
1253 if (input.isEmpty())
1254 continue;
1255
1256 Symbols saveSymbols = symbols;
1257 qsizetype saveIndex = index;
1258
1259 // phase 1: get rid of backslash-newlines
1260 input = cleaned(input);
1261
1262 // phase 2: tokenize for the preprocessor
1263 symbols = tokenize(input);
1264 input.clear();
1265
1266 index = 0;
1267
1268 // phase 3: preprocess conditions and substitute macros
1269 preprocessed += Symbol(0, MOC_INCLUDE_BEGIN, include);
1270 preprocess(include, preprocessed, foundIndex);
1271 preprocessed += Symbol(lineNum, MOC_INCLUDE_END, include);
1272
1273 symbols = saveSymbols;
1274 index = saveIndex;
1275 continue;
1276 }
1277 case PP_DEFINE:
1278 {
1279 next();
1280 QByteArray name = lexem();
1281 if (name.isEmpty() || !is_ident_start(name[0]))
1282 error();
1283 Macro macro;
1284 macro.isVariadic = false;
1285 if (test(LPAREN)) {
1286 // we have a function macro
1287 macro.isFunction = true;
1289 } else {
1290 macro.isFunction = false;
1291 }
1292 qsizetype start = index;
1293 until(PP_NEWLINE);
1294 macro.symbols.reserve(index - start - 1);
1295
1296 // remove whitespace where there shouldn't be any:
1297 // Before and after the macro, after a # and around ##
1298 Token lastToken = HASH; // skip shitespace at the beginning
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)
1305 continue;
1306 } else if (token == PP_HASHHASH) {
1307 if (!macro.symbols.isEmpty() &&
1308 lastToken == WHITESPACE)
1309 macro.symbols.pop_back();
1310 }
1311 macro.symbols.append(symbols.at(i));
1312 lastToken = token;
1313 }
1314 // remove trailing whitespace
1315 while (!macro.symbols.isEmpty() &&
1316 (macro.symbols.constLast().token == PP_WHITESPACE || macro.symbols.constLast().token == WHITESPACE))
1317 macro.symbols.pop_back();
1318
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");
1323 }
1324 }
1325 macros.insert(name, macro);
1326 continue;
1327 }
1328 case PP_UNDEF: {
1329 next();
1330 QByteArray name = lexem();
1331 until(PP_NEWLINE);
1332 macros.remove(name);
1333 continue;
1334 }
1335 case PP_IDENTIFIER: {
1336 // substitute macros
1337 macroExpand(&preprocessed, this, symbols, index, symbol().lineNum, true);
1338 continue;
1339 }
1340 case PP_HASH:
1341 until(PP_NEWLINE);
1342 continue; // skip unknown preprocessor statement
1343 case PP_IFDEF:
1344 case PP_IFNDEF:
1345 case PP_IF:
1346 while (!evaluateCondition()) {
1347 if (!skipBranch())
1348 break;
1349 if (test(PP_ELIF)) {
1350 } else {
1351 until(PP_NEWLINE);
1352 break;
1353 }
1354 }
1355 continue;
1356 case PP_ELIF:
1357 case PP_ELSE:
1359 Q_FALLTHROUGH();
1360 case PP_ENDIF:
1361 until(PP_NEWLINE);
1362 continue;
1363 case PP_NEWLINE:
1364 continue;
1365 case SIGNALS:
1366 case SLOTS: {
1367 Symbol sym = symbol();
1368 if (macros.contains("QT_NO_KEYWORDS"))
1369 sym.token = IDENTIFIER;
1370 else
1371 sym.token = (token == SIGNALS ? Q_SIGNALS_TOKEN : Q_SLOTS_TOKEN);
1372 preprocessed += sym;
1373 } continue;
1374 default:
1375 break;
1376 }
1377 preprocessed += symbol();
1378 }
1379
1380 currentIncludeDirIndex.pop();
1381 currentFilenames.pop();
1382}
1383
1384Symbols Preprocessor::preprocessed(const QByteArray &filename, QFile *file)
1385{
1386 QByteArray input = readOrMapFile(file);
1387
1388 if (input.isEmpty())
1389 return symbols;
1390
1391 // phase 1: get rid of backslash-newlines
1392 input = cleaned(input);
1393
1394 // phase 2: tokenize for the preprocessor
1395 index = 0;
1396 symbols = tokenize(input);
1397
1398#if 0
1399 for (int j = 0; j < symbols.size(); ++j)
1400 fprintf(stderr, "line %d: %s(%s)\n",
1401 symbols[j].lineNum,
1402 symbols[j].lexem().constData(),
1403 tokenTypeName(symbols[j].token));
1404#endif
1405
1406 // phase 3: preprocess conditions and substitute macros
1407 Symbols result;
1408 // Preallocate some space to speed up the code below.
1409 // The magic value was found by logging the final size
1410 // and calculating an average when running moc over FOSS projects.
1411 result.reserve(file->size() / 300000);
1412 preprocess(filename, result);
1413 mergeStringLiterals(result);
1414
1415#if 0
1416 for (int j = 0; j < result.size(); ++j)
1417 fprintf(stderr, "line %d: %s(%s)\n",
1418 result[j].lineNum,
1419 result[j].lexem().constData(),
1420 tokenTypeName(result[j].token));
1421#endif
1422
1423 return result;
1424}
1425
1427{
1428 Symbols arguments;
1429 while (hasNext()) {
1430 while (test(PP_WHITESPACE)) {}
1431 Token t = next();
1432 if (t == PP_RPAREN)
1433 break;
1434 if (t != PP_IDENTIFIER) {
1435 QByteArrayView l = lexemView();
1436 if (l == "...") {
1437 m->isVariadic = true;
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");
1442 break;
1443 } else if (!is_identifier(l.constData(), l.size())) {
1444 error("Unexpected character in macro argument list.");
1445 }
1446 }
1447
1448 Symbol arg = symbol();
1449 if (arguments.contains(arg))
1450 error("Duplicate macro parameter.");
1451 arguments += symbol();
1452
1453 while (test(PP_WHITESPACE)) {}
1454 t = next();
1455 if (t == PP_RPAREN)
1456 break;
1457 if (t == PP_COMMA)
1458 continue;
1459 if (lexemView() == "...") {
1460 //GCC extension: #define FOO(x, y...) x(y)
1461 // The last argument was already parsed. Just mark the macro as variadic.
1462 m->isVariadic = true;
1463 while (test(PP_WHITESPACE)) {}
1464 if (!test(PP_RPAREN))
1465 error("missing ')' in macro argument list");
1466 break;
1467 }
1468 error("Unexpected character in macro argument list.");
1469 }
1470 m->arguments = arguments;
1471 while (test(PP_WHITESPACE)) {}
1472}
1473
1474void Preprocessor::until(Token t)
1475{
1476 while(hasNext() && next() != t)
1477 ;
1478}
1479
1481{
1482 debugIncludes = value;
1483}
1484
1485
1486QT_END_NAMESPACE
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)
void skipUntilEndif()
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
Definition qlist.h:81
const Symbol & symbol() const
Definition symbols.h:102
bool hasNext()
Definition symbols.h:89
Token next()
Definition symbols.h:94
bool test(Token)
Definition symbols.h:111
short defnext
Definition keywords.cpp:455
static const short keyword_trans[][128]
Definition keywords.cpp:7
Token token
Definition keywords.cpp:452
Token ident
Definition keywords.cpp:456
short next
Definition keywords.cpp:453
char defchar
Definition keywords.cpp:454
Combined button and popup list for selecting options.
short next
static const short pp_keyword_trans[][128]
Definition ppkeywords.cpp:7
PP_Token ident
short defnext
PP_Token token
char defchar
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)
bool is_ident_char(char s)
Definition utils.h:30
const char * skipQuote(const char *data)
Definition utils.h:42
bool is_space(char s)
Definition utils.h:19
Simple structure used by the Doc and DocParser classes.
bool isVariadic
bool isFunction
Symbol(int lineNum, Token token)
Definition symbols.h:48
Token token
Definition symbols.h:58
void mergeStringLiteral(const Symbol &next)
int lineNum
Definition symbols.h:57
Symbol()=default
QList< Symbol > Symbols
Definition symbols.h:75