1 //===- TGLexer.cpp - Lexer for TableGen -----------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // Implement the Lexer for TableGen.
11 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/Config/config.h" // for strtoull()/strtoll() define
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/SourceMgr.h"
22 #include "llvm/TableGen/Error.h"
33 // A list of supported preprocessing directives with their
34 // internal token kinds and names.
35 struct PreprocessorDir
{
39 } // end anonymous namespace
41 /// Returns true if `C` is a valid character in an identifier. If `First` is
42 /// true, returns true if `C` is a valid first character of an identifier,
43 /// else returns true if `C` is a valid non-first character of an identifier.
44 /// Identifiers match the following regular expression:
45 /// [a-zA-Z_][0-9a-zA-Z_]*
46 static bool isValidIDChar(char C
, bool First
) {
47 if (C
== '_' || isAlpha(C
))
49 return !First
&& isDigit(C
);
52 constexpr PreprocessorDir PreprocessorDirs
[] = {{tgtok::Ifdef
, "ifdef"},
53 {tgtok::Ifndef
, "ifndef"},
54 {tgtok::Else
, "else"},
55 {tgtok::Endif
, "endif"},
56 {tgtok::Define
, "define"}};
58 // Returns a pointer past the end of a valid macro name at the start of `Str`.
59 // Valid macro names match the regular expression [a-zA-Z_][0-9a-zA-Z_]*.
60 static const char *lexMacroName(StringRef Str
) {
63 // Macro names start with [a-zA-Z_].
64 const char *Next
= Str
.begin();
65 if (!isValidIDChar(*Next
, /*First=*/true))
67 // Eat the first character of the name.
70 // Match the rest of the identifier regex: [0-9a-zA-Z_]*
71 const char *End
= Str
.end();
72 while (Next
!= End
&& isValidIDChar(*Next
, /*First=*/false))
77 TGLexer::TGLexer(SourceMgr
&SM
, ArrayRef
<std::string
> Macros
) : SrcMgr(SM
) {
78 CurBuffer
= SrcMgr
.getMainFileID();
79 CurBuf
= SrcMgr
.getMemoryBuffer(CurBuffer
)->getBuffer();
80 CurPtr
= CurBuf
.begin();
83 // Pretend that we enter the "top-level" include file.
84 PrepIncludeStack
.emplace_back();
86 // Add all macros defined on the command line to the DefinedMacros set.
87 // Check invalid macro names and print fatal error if we find one.
88 for (StringRef MacroName
: Macros
) {
89 const char *End
= lexMacroName(MacroName
);
90 if (End
!= MacroName
.end())
91 PrintFatalError("invalid macro name `" + MacroName
+
92 "` specified on command line");
94 DefinedMacros
.insert(MacroName
);
98 SMLoc
TGLexer::getLoc() const {
99 return SMLoc::getFromPointer(TokStart
);
102 SMRange
TGLexer::getLocRange() const {
103 return {getLoc(), SMLoc::getFromPointer(CurPtr
)};
106 /// ReturnError - Set the error to the specified string at the specified
107 /// location. This is defined to always return tgtok::Error.
108 tgtok::TokKind
TGLexer::ReturnError(SMLoc Loc
, const Twine
&Msg
) {
109 PrintError(Loc
, Msg
);
113 tgtok::TokKind
TGLexer::ReturnError(const char *Loc
, const Twine
&Msg
) {
114 return ReturnError(SMLoc::getFromPointer(Loc
), Msg
);
117 bool TGLexer::processEOF() {
118 SMLoc ParentIncludeLoc
= SrcMgr
.getParentIncludeLoc(CurBuffer
);
119 if (ParentIncludeLoc
!= SMLoc()) {
120 // If prepExitInclude() detects a problem with the preprocessing
121 // control stack, it will return false. Pretend that we reached
122 // the final EOF and stop lexing more tokens by returning false
124 if (!prepExitInclude(false))
127 CurBuffer
= SrcMgr
.FindBufferContainingLoc(ParentIncludeLoc
);
128 CurBuf
= SrcMgr
.getMemoryBuffer(CurBuffer
)->getBuffer();
129 CurPtr
= ParentIncludeLoc
.getPointer();
130 // Make sure TokStart points into the parent file's buffer.
131 // LexToken() assigns to it before calling getNextChar(),
132 // so it is pointing into the included file now.
137 // Pretend that we exit the "top-level" include file.
138 // Note that in case of an error (e.g. control stack imbalance)
139 // the routine will issue a fatal error.
140 prepExitInclude(true);
144 int TGLexer::getNextChar() {
145 char CurChar
= *CurPtr
++;
148 return (unsigned char)CurChar
;
151 // A NUL character in the stream is either the end of the current buffer or
152 // a spurious NUL in the file. Disambiguate that here.
153 if (CurPtr
- 1 == CurBuf
.end()) {
154 --CurPtr
; // Arrange for another call to return EOF again.
158 "NUL character is invalid in source; treated as space");
164 // Handle the newline character by ignoring it and incrementing the line
165 // count. However, be careful about 'dos style' files with \n\r in them.
166 // Only treat a \n\r or \r\n as a single line.
167 if ((*CurPtr
== '\n' || (*CurPtr
== '\r')) &&
169 ++CurPtr
; // Eat the two char newline sequence.
174 int TGLexer::peekNextChar(int Index
) const {
175 return *(CurPtr
+ Index
);
178 tgtok::TokKind
TGLexer::LexToken(bool FileOrLineStart
) {
180 // This always consumes at least one character.
181 int CurChar
= getNextChar();
185 // Handle letters: [a-zA-Z_]
186 if (isValidIDChar(CurChar
, /*First=*/true))
187 return LexIdentifier();
189 // Unknown character, emit an error.
190 return ReturnError(TokStart
, "unexpected character");
192 // Lex next token, if we just left an include file.
193 // Note that leaving an include file means that the next
194 // symbol is located at the end of the 'include "..."'
195 // construct, so LexToken() is called with default
200 // Return EOF denoting the end of lexing.
203 case ':': return tgtok::colon
;
204 case ';': return tgtok::semi
;
205 case ',': return tgtok::comma
;
206 case '<': return tgtok::less
;
207 case '>': return tgtok::greater
;
208 case ']': return tgtok::r_square
;
209 case '{': return tgtok::l_brace
;
210 case '}': return tgtok::r_brace
;
211 case '(': return tgtok::l_paren
;
212 case ')': return tgtok::r_paren
;
213 case '=': return tgtok::equal
;
214 case '?': return tgtok::question
;
216 if (FileOrLineStart
) {
217 tgtok::TokKind Kind
= prepIsDirective();
218 if (Kind
!= tgtok::Error
)
219 return lexPreprocessor(Kind
);
224 // The period is a separate case so we can recognize the "..."
227 if (peekNextChar(0) == '.') {
228 ++CurPtr
; // Eat second dot.
229 if (peekNextChar(0) == '.') {
230 ++CurPtr
; // Eat third dot.
231 return tgtok::dotdotdot
;
233 return ReturnError(TokStart
, "invalid '..' punctuation");
238 PrintFatalError("getNextChar() must never return '\r'");
243 // Ignore whitespace.
244 return LexToken(FileOrLineStart
);
246 // Ignore whitespace, and identify the new line.
247 return LexToken(true);
249 // If this is the start of a // comment, skip until the end of the line or
250 // the end of the buffer.
253 else if (*CurPtr
== '*') {
256 } else // Otherwise, this is an error.
257 return ReturnError(TokStart
, "unexpected character");
258 return LexToken(FileOrLineStart
);
260 case '0': case '1': case '2': case '3': case '4': case '5': case '6':
261 case '7': case '8': case '9': {
263 if (isDigit(CurChar
)) {
264 // Allow identifiers to start with a number if it is followed by
265 // an identifier. This can happen with paste operations like
269 NextChar
= peekNextChar(i
++);
270 } while (isDigit(NextChar
));
272 if (NextChar
== 'x' || NextChar
== 'b') {
273 // If this is [0-9]b[01] or [0-9]x[0-9A-fa-f] this is most
275 int NextNextChar
= peekNextChar(i
);
276 switch (NextNextChar
) {
283 case '2': case '3': case '4': case '5':
284 case '6': case '7': case '8': case '9':
285 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
286 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
294 if (isValidIDChar(NextChar
, /*First=*/true))
295 return LexIdentifier();
299 case '"': return LexString();
300 case '$': return LexVarName();
301 case '[': return LexBracket();
302 case '!': return LexExclaim();
306 /// LexString - Lex "[^"]*"
307 tgtok::TokKind
TGLexer::LexString() {
308 const char *StrStart
= CurPtr
;
312 while (*CurPtr
!= '"') {
313 // If we hit the end of the buffer, report an error.
314 if (*CurPtr
== 0 && CurPtr
== CurBuf
.end())
315 return ReturnError(StrStart
, "end of file in string literal");
317 if (*CurPtr
== '\n' || *CurPtr
== '\r')
318 return ReturnError(StrStart
, "end of line in string literal");
320 if (*CurPtr
!= '\\') {
321 CurStrVal
+= *CurPtr
++;
328 case '\\': case '\'': case '"':
329 // These turn into their literal character.
330 CurStrVal
+= *CurPtr
++;
343 return ReturnError(CurPtr
, "escaped newlines not supported in tblgen");
345 // If we hit the end of the buffer, report an error.
347 if (CurPtr
== CurBuf
.end())
348 return ReturnError(StrStart
, "end of file in string literal");
351 return ReturnError(CurPtr
, "invalid escape in string literal");
356 return tgtok::StrVal
;
359 tgtok::TokKind
TGLexer::LexVarName() {
360 if (!isValidIDChar(CurPtr
[0], /*First=*/true))
361 return ReturnError(TokStart
, "invalid variable name");
363 // Otherwise, we're ok, consume the rest of the characters.
364 const char *VarNameStart
= CurPtr
++;
366 while (isValidIDChar(*CurPtr
, /*First=*/false))
369 CurStrVal
.assign(VarNameStart
, CurPtr
);
370 return tgtok::VarName
;
373 tgtok::TokKind
TGLexer::LexIdentifier() {
374 // The first letter is [a-zA-Z_].
375 const char *IdentStart
= TokStart
;
377 // Match the rest of the identifier regex: [0-9a-zA-Z_]*
378 while (isValidIDChar(*CurPtr
, /*First=*/false))
381 // Check to see if this identifier is a reserved keyword.
382 StringRef
Str(IdentStart
, CurPtr
-IdentStart
);
384 tgtok::TokKind Kind
= StringSwitch
<tgtok::TokKind
>(Str
)
385 .Case("int", tgtok::Int
)
386 .Case("bit", tgtok::Bit
)
387 .Case("bits", tgtok::Bits
)
388 .Case("string", tgtok::String
)
389 .Case("list", tgtok::List
)
390 .Case("code", tgtok::Code
)
391 .Case("dag", tgtok::Dag
)
392 .Case("class", tgtok::Class
)
393 .Case("def", tgtok::Def
)
394 .Case("true", tgtok::TrueVal
)
395 .Case("false", tgtok::FalseVal
)
396 .Case("foreach", tgtok::Foreach
)
397 .Case("defm", tgtok::Defm
)
398 .Case("defset", tgtok::Defset
)
399 .Case("deftype", tgtok::Deftype
)
400 .Case("multiclass", tgtok::MultiClass
)
401 .Case("field", tgtok::Field
)
402 .Case("let", tgtok::Let
)
403 .Case("in", tgtok::In
)
404 .Case("defvar", tgtok::Defvar
)
405 .Case("include", tgtok::Include
)
406 .Case("if", tgtok::If
)
407 .Case("then", tgtok::Then
)
408 .Case("else", tgtok::ElseKW
)
409 .Case("assert", tgtok::Assert
)
410 .Case("dump", tgtok::Dump
)
413 // A couple of tokens require special processing.
416 if (LexInclude()) return tgtok::Error
;
419 CurStrVal
.assign(Str
.begin(), Str
.end());
428 /// LexInclude - We just read the "include" token. Get the string token that
429 /// comes next and enter the include.
430 bool TGLexer::LexInclude() {
431 // The token after the include must be a string.
432 tgtok::TokKind Tok
= LexToken();
433 if (Tok
== tgtok::Error
) return true;
434 if (Tok
!= tgtok::StrVal
) {
435 PrintError(getLoc(), "expected filename after include");
440 std::string Filename
= CurStrVal
;
441 std::string IncludedFile
;
443 CurBuffer
= SrcMgr
.AddIncludeFile(Filename
, SMLoc::getFromPointer(CurPtr
),
446 PrintError(getLoc(), "could not find include file '" + Filename
+ "'");
450 Dependencies
.insert(IncludedFile
);
451 // Save the line number and lex buffer of the includer.
452 CurBuf
= SrcMgr
.getMemoryBuffer(CurBuffer
)->getBuffer();
453 CurPtr
= CurBuf
.begin();
455 PrepIncludeStack
.emplace_back();
459 /// SkipBCPLComment - Skip over the comment by finding the next CR or LF.
460 /// Or we may end up at the end of the buffer.
461 void TGLexer::SkipBCPLComment() {
462 ++CurPtr
; // skip the second slash.
463 auto EOLPos
= CurBuf
.find_first_of("\r\n", CurPtr
- CurBuf
.data());
464 CurPtr
= (EOLPos
== StringRef::npos
) ? CurBuf
.end() : CurBuf
.data() + EOLPos
;
467 /// SkipCComment - This skips C-style /**/ comments. The only difference from C
468 /// is that we allow nesting.
469 bool TGLexer::SkipCComment() {
470 ++CurPtr
; // skip the star.
471 unsigned CommentDepth
= 1;
474 int CurChar
= getNextChar();
477 PrintError(TokStart
, "unterminated comment");
480 // End of the comment?
481 if (CurPtr
[0] != '/') break;
483 ++CurPtr
; // End the */.
484 if (--CommentDepth
== 0)
488 // Start of a nested comment?
489 if (CurPtr
[0] != '*') break;
501 tgtok::TokKind
TGLexer::LexNumber() {
503 const char *NumStart
;
505 // Check if it's a hex or a binary value.
506 if (CurPtr
[-1] == '0') {
507 NumStart
= CurPtr
+ 1;
508 if (CurPtr
[0] == 'x') {
512 while (isHexDigit(CurPtr
[0]));
513 } else if (CurPtr
[0] == 'b') {
517 while (CurPtr
[0] == '0' || CurPtr
[0] == '1');
521 // For a hex or binary value, we always convert it to an unsigned value.
522 bool IsMinus
= false;
524 // Check if it's a decimal value.
526 // Check for a sign without a digit.
527 if (!isDigit(CurPtr
[0])) {
528 if (CurPtr
[-1] == '-')
530 else if (CurPtr
[-1] == '+')
536 IsMinus
= CurPtr
[-1] == '-';
538 while (isDigit(CurPtr
[0]))
542 // Requires at least one digit.
543 if (CurPtr
== NumStart
)
544 return ReturnError(TokStart
, "invalid number");
548 CurIntVal
= strtoll(NumStart
, nullptr, Base
);
550 CurIntVal
= strtoull(NumStart
, nullptr, Base
);
553 return ReturnError(TokStart
, "invalid number");
555 return ReturnError(TokStart
, "number out of range");
557 return Base
== 2 ? tgtok::BinaryIntVal
: tgtok::IntVal
;
560 /// LexBracket - We just read '['. If this is a code block, return it,
561 /// otherwise return the bracket. Match: '[' and '[{ ( [^}]+ | }[^]] )* }]'
562 tgtok::TokKind
TGLexer::LexBracket() {
563 if (CurPtr
[0] != '{')
564 return tgtok::l_square
;
566 const char *CodeStart
= CurPtr
;
568 int Char
= getNextChar();
569 if (Char
== EOF
) break;
571 if (Char
!= '}') continue;
573 Char
= getNextChar();
574 if (Char
== EOF
) break;
576 CurStrVal
.assign(CodeStart
, CurPtr
-2);
577 return tgtok::CodeFragment
;
581 return ReturnError(CodeStart
- 2, "unterminated code block");
584 /// LexExclaim - Lex '!' and '![a-zA-Z]+'.
585 tgtok::TokKind
TGLexer::LexExclaim() {
586 if (!isAlpha(*CurPtr
))
587 return ReturnError(CurPtr
- 1, "invalid \"!operator\"");
589 const char *Start
= CurPtr
++;
590 while (isAlpha(*CurPtr
))
593 // Check to see which operator this is.
594 tgtok::TokKind Kind
=
595 StringSwitch
<tgtok::TokKind
>(StringRef(Start
, CurPtr
- Start
))
596 .Case("eq", tgtok::XEq
)
597 .Case("ne", tgtok::XNe
)
598 .Case("le", tgtok::XLe
)
599 .Case("lt", tgtok::XLt
)
600 .Case("ge", tgtok::XGe
)
601 .Case("gt", tgtok::XGt
)
602 .Case("if", tgtok::XIf
)
603 .Case("cond", tgtok::XCond
)
604 .Case("isa", tgtok::XIsA
)
605 .Case("head", tgtok::XHead
)
606 .Case("tail", tgtok::XTail
)
607 .Case("size", tgtok::XSize
)
608 .Case("con", tgtok::XConcat
)
609 .Case("dag", tgtok::XDag
)
610 .Case("add", tgtok::XADD
)
611 .Case("sub", tgtok::XSUB
)
612 .Case("mul", tgtok::XMUL
)
613 .Case("div", tgtok::XDIV
)
614 .Case("not", tgtok::XNOT
)
615 .Case("logtwo", tgtok::XLOG2
)
616 .Case("and", tgtok::XAND
)
617 .Case("or", tgtok::XOR
)
618 .Case("xor", tgtok::XXOR
)
619 .Case("shl", tgtok::XSHL
)
620 .Case("sra", tgtok::XSRA
)
621 .Case("srl", tgtok::XSRL
)
622 .Case("cast", tgtok::XCast
)
623 .Case("empty", tgtok::XEmpty
)
624 .Case("subst", tgtok::XSubst
)
625 .Case("foldl", tgtok::XFoldl
)
626 .Case("foreach", tgtok::XForEach
)
627 .Case("filter", tgtok::XFilter
)
628 .Case("listconcat", tgtok::XListConcat
)
629 .Case("listflatten", tgtok::XListFlatten
)
630 .Case("listsplat", tgtok::XListSplat
)
631 .Case("listremove", tgtok::XListRemove
)
632 .Case("range", tgtok::XRange
)
633 .Case("strconcat", tgtok::XStrConcat
)
634 .Case("initialized", tgtok::XInitialized
)
635 .Case("interleave", tgtok::XInterleave
)
636 .Case("substr", tgtok::XSubstr
)
637 .Case("find", tgtok::XFind
)
638 .Cases("setdagop", "setop", tgtok::XSetDagOp
) // !setop is deprecated.
639 .Cases("getdagop", "getop", tgtok::XGetDagOp
) // !getop is deprecated.
640 .Case("getdagarg", tgtok::XGetDagArg
)
641 .Case("getdagname", tgtok::XGetDagName
)
642 .Case("setdagarg", tgtok::XSetDagArg
)
643 .Case("setdagname", tgtok::XSetDagName
)
644 .Case("exists", tgtok::XExists
)
645 .Case("tolower", tgtok::XToLower
)
646 .Case("toupper", tgtok::XToUpper
)
647 .Case("repr", tgtok::XRepr
)
648 .Default(tgtok::Error
);
650 return Kind
!= tgtok::Error
? Kind
651 : ReturnError(Start
- 1, "unknown operator");
654 bool TGLexer::prepExitInclude(bool IncludeStackMustBeEmpty
) {
655 // Report an error, if preprocessor control stack for the current
656 // file is not empty.
657 if (!PrepIncludeStack
.back().empty()) {
658 prepReportPreprocessorStackError();
663 // Pop the preprocessing controls from the include stack.
664 PrepIncludeStack
.pop_back();
666 if (IncludeStackMustBeEmpty
) {
667 if (!PrepIncludeStack
.empty())
668 PrintFatalError("preprocessor include stack is not empty");
670 if (PrepIncludeStack
.empty())
671 PrintFatalError("preprocessor include stack is empty");
677 tgtok::TokKind
TGLexer::prepIsDirective() const {
678 for (const auto [Kind
, Word
] : PreprocessorDirs
) {
679 if (StringRef(CurPtr
, Word
.size()) != Word
)
681 int NextChar
= peekNextChar(Word
.size());
683 // Check for whitespace after the directive. If there is no whitespace,
684 // then we do not recognize it as a preprocessing directive.
686 // New line and EOF may follow only #else/#endif. It will be reported
687 // as an error for #ifdef/#define after the call to prepLexMacroName().
688 if (NextChar
== ' ' || NextChar
== '\t' || NextChar
== EOF
||
690 // It looks like TableGen does not support '\r' as the actual
691 // carriage return, e.g. getNextChar() treats a single '\r'
692 // as '\n'. So we do the same here.
696 // Allow comments after some directives, e.g.:
697 // #else// OR #else/**/
698 // #endif// OR #endif/**/
700 // Note that we do allow comments after #ifdef/#define here, e.g.
701 // #ifdef/**/ AND #ifdef//
702 // #define/**/ AND #define//
704 // These cases will be reported as incorrect after calling
705 // prepLexMacroName(). We could have supported C-style comments
706 // after #ifdef/#define, but this would complicate the code
707 // for little benefit.
708 if (NextChar
== '/') {
709 NextChar
= peekNextChar(Word
.size() + 1);
711 if (NextChar
== '*' || NextChar
== '/')
714 // Pretend that we do not recognize the directive.
721 bool TGLexer::prepEatPreprocessorDirective(tgtok::TokKind Kind
) {
724 for (const auto [PKind
, PWord
] : PreprocessorDirs
)
726 // Advance CurPtr to the end of the preprocessing word.
727 CurPtr
+= PWord
.size();
731 PrintFatalError("unsupported preprocessing token in "
732 "prepEatPreprocessorDirective()");
736 tgtok::TokKind
TGLexer::lexPreprocessor(tgtok::TokKind Kind
,
737 bool ReturnNextLiveToken
) {
738 // We must be looking at a preprocessing directive. Eat it!
739 if (!prepEatPreprocessorDirective(Kind
))
740 PrintFatalError("lexPreprocessor() called for unknown "
741 "preprocessor directive");
743 if (Kind
== tgtok::Ifdef
|| Kind
== tgtok::Ifndef
) {
744 StringRef MacroName
= prepLexMacroName();
745 StringRef IfTokName
= Kind
== tgtok::Ifdef
? "#ifdef" : "#ifndef";
746 if (MacroName
.empty())
747 return ReturnError(TokStart
, "expected macro name after " + IfTokName
);
749 bool MacroIsDefined
= DefinedMacros
.count(MacroName
) != 0;
751 // Canonicalize ifndef's MacroIsDefined to its ifdef equivalent.
752 if (Kind
== tgtok::Ifndef
)
753 MacroIsDefined
= !MacroIsDefined
;
755 // Regardless of whether we are processing tokens or not,
756 // we put the #ifdef control on stack.
757 // Note that MacroIsDefined has been canonicalized against ifdef.
758 PrepIncludeStack
.back().push_back(
759 {tgtok::Ifdef
, MacroIsDefined
, SMLoc::getFromPointer(TokStart
)});
761 if (!prepSkipDirectiveEnd())
762 return ReturnError(CurPtr
, "only comments are supported after " +
763 IfTokName
+ " NAME");
765 // If we were not processing tokens before this #ifdef,
766 // then just return back to the lines skipping code.
767 if (!ReturnNextLiveToken
)
770 // If we were processing tokens before this #ifdef,
771 // and the macro is defined, then just return the next token.
775 // We were processing tokens before this #ifdef, and the macro
776 // is not defined, so we have to start skipping the lines.
777 // If the skipping is successful, it will return the token following
778 // either #else or #endif corresponding to this #ifdef.
779 if (prepSkipRegion(ReturnNextLiveToken
))
783 } else if (Kind
== tgtok::Else
) {
784 // Check if this #else is correct before calling prepSkipDirectiveEnd(),
785 // which will move CurPtr away from the beginning of #else.
786 if (PrepIncludeStack
.back().empty())
787 return ReturnError(TokStart
, "#else without #ifdef or #ifndef");
789 PreprocessorControlDesc IfdefEntry
= PrepIncludeStack
.back().back();
791 if (IfdefEntry
.Kind
!= tgtok::Ifdef
) {
792 PrintError(TokStart
, "double #else");
793 return ReturnError(IfdefEntry
.SrcPos
, "previous #else is here");
796 // Replace the corresponding #ifdef's control with its negation
797 // on the control stack.
798 PrepIncludeStack
.back().back() = {Kind
, !IfdefEntry
.IsDefined
,
799 SMLoc::getFromPointer(TokStart
)};
801 if (!prepSkipDirectiveEnd())
802 return ReturnError(CurPtr
, "only comments are supported after #else");
804 // If we were processing tokens before this #else,
805 // we have to start skipping lines until the matching #endif.
806 if (ReturnNextLiveToken
) {
807 if (prepSkipRegion(ReturnNextLiveToken
))
813 // Return to the lines skipping code.
815 } else if (Kind
== tgtok::Endif
) {
816 // Check if this #endif is correct before calling prepSkipDirectiveEnd(),
817 // which will move CurPtr away from the beginning of #endif.
818 if (PrepIncludeStack
.back().empty())
819 return ReturnError(TokStart
, "#endif without #ifdef");
821 auto &IfdefOrElseEntry
= PrepIncludeStack
.back().back();
823 if (IfdefOrElseEntry
.Kind
!= tgtok::Ifdef
&&
824 IfdefOrElseEntry
.Kind
!= tgtok::Else
) {
825 PrintFatalError("invalid preprocessor control on the stack");
829 if (!prepSkipDirectiveEnd())
830 return ReturnError(CurPtr
, "only comments are supported after #endif");
832 PrepIncludeStack
.back().pop_back();
834 // If we were processing tokens before this #endif, then
835 // we should continue it.
836 if (ReturnNextLiveToken
) {
840 // Return to the lines skipping code.
842 } else if (Kind
== tgtok::Define
) {
843 StringRef MacroName
= prepLexMacroName();
844 if (MacroName
.empty())
845 return ReturnError(TokStart
, "expected macro name after #define");
847 if (!DefinedMacros
.insert(MacroName
).second
)
848 PrintWarning(getLoc(),
849 "duplicate definition of macro: " + Twine(MacroName
));
851 if (!prepSkipDirectiveEnd())
852 return ReturnError(CurPtr
,
853 "only comments are supported after #define NAME");
855 if (!ReturnNextLiveToken
) {
856 PrintFatalError("#define must be ignored during the lines skipping");
863 PrintFatalError("preprocessing directive is not supported");
867 bool TGLexer::prepSkipRegion(bool MustNeverBeFalse
) {
868 if (!MustNeverBeFalse
)
869 PrintFatalError("invalid recursion.");
872 // Skip all symbols to the line end.
873 while (*CurPtr
!= '\n')
876 // Find the first non-whitespace symbol in the next line(s).
877 if (!prepSkipLineBegin())
880 // If the first non-blank/comment symbol on the line is '#',
881 // it may be a start of preprocessing directive.
883 // If it is not '#' just go to the next line.
889 tgtok::TokKind Kind
= prepIsDirective();
891 // If we did not find a preprocessing directive or it is #define,
892 // then just skip to the next line. We do not have to do anything
893 // for #define in the line-skipping mode.
894 if (Kind
== tgtok::Error
|| Kind
== tgtok::Define
)
897 tgtok::TokKind ProcessedKind
= lexPreprocessor(Kind
, false);
899 // If lexPreprocessor() encountered an error during lexing this
900 // preprocessor idiom, then return false to the calling lexPreprocessor().
901 // This will force tgtok::Error to be returned to the tokens processing.
902 if (ProcessedKind
== tgtok::Error
)
905 if (Kind
!= ProcessedKind
)
906 PrintFatalError("prepIsDirective() and lexPreprocessor() "
907 "returned different token kinds");
909 // If this preprocessing directive enables tokens processing,
910 // then return to the lexPreprocessor() and get to the next token.
911 // We can move from line-skipping mode to processing tokens only
912 // due to #else or #endif.
913 if (prepIsProcessingEnabled()) {
914 if (Kind
!= tgtok::Else
&& Kind
!= tgtok::Endif
) {
915 PrintFatalError("tokens processing was enabled by an unexpected "
916 "preprocessing directive");
922 } while (CurPtr
!= CurBuf
.end());
924 // We have reached the end of the file, but never left the lines-skipping
925 // mode. This means there is no matching #endif.
926 prepReportPreprocessorStackError();
930 StringRef
TGLexer::prepLexMacroName() {
931 // Skip whitespaces between the preprocessing directive and the macro name.
932 while (*CurPtr
== ' ' || *CurPtr
== '\t')
936 CurPtr
= lexMacroName(StringRef(CurPtr
, CurBuf
.end() - CurPtr
));
937 return StringRef(TokStart
, CurPtr
- TokStart
);
940 bool TGLexer::prepSkipLineBegin() {
941 while (CurPtr
!= CurBuf
.end()) {
950 int NextChar
= peekNextChar(1);
951 if (NextChar
== '*') {
952 // Skip C-style comment.
953 // Note that we do not care about skipping the C++-style comments.
954 // If the line contains "//", it may not contain any processable
955 // preprocessing directive. Just return CurPtr pointing to
956 // the first '/' in this case. We also do not care about
957 // incorrect symbols after the first '/' - we are in lines-skipping
958 // mode, so incorrect code is allowed to some extent.
960 // Set TokStart to the beginning of the comment to enable proper
961 // diagnostic printing in case of error in SkipCComment().
964 // CurPtr must point to '*' before call to SkipCComment().
969 // CurPtr points to the non-whitespace '/'.
973 // We must not increment CurPtr after the comment was lexed.
984 // We have reached the end of the file. Return to the lines skipping
985 // code, and allow it to handle the EOF as needed.
989 bool TGLexer::prepSkipDirectiveEnd() {
990 while (CurPtr
!= CurBuf
.end()) {
1001 int NextChar
= peekNextChar(1);
1002 if (NextChar
== '/') {
1003 // Skip C++-style comment.
1004 // We may just return true now, but let's skip to the line/buffer end
1005 // to simplify the method specification.
1008 } else if (NextChar
== '*') {
1009 // When we are skipping C-style comment at the end of a preprocessing
1010 // directive, we can skip several lines. If any meaningful TD token
1011 // follows the end of the C-style comment on the same line, it will
1012 // be considered as an invalid usage of TD token.
1013 // For example, we want to forbid usages like this one:
1014 // #define MACRO class Class {}
1015 // But with C-style comments we also disallow the following:
1016 // #define MACRO /* This macro is used
1017 // to ... */ class Class {}
1018 // One can argue that this should be allowed, but it does not seem
1019 // to be worth of the complication. Moreover, this matches
1020 // the C preprocessor behavior.
1022 // Set TokStart to the beginning of the comment to enable proper
1023 // diagnostic printer in case of error in SkipCComment().
1030 PrintError(CurPtr
, "unexpected character");
1034 // We must not increment CurPtr after the comment was lexed.
1039 // Do not allow any non-whitespaces after the directive.
1050 bool TGLexer::prepIsProcessingEnabled() {
1051 return all_of(PrepIncludeStack
.back(),
1052 [](const PreprocessorControlDesc
&I
) { return I
.IsDefined
; });
1055 void TGLexer::prepReportPreprocessorStackError() {
1056 if (PrepIncludeStack
.back().empty())
1057 PrintFatalError("prepReportPreprocessorStackError() called with "
1058 "empty control stack");
1060 auto &PrepControl
= PrepIncludeStack
.back().back();
1061 PrintError(CurBuf
.end(), "reached EOF without matching #endif");
1062 PrintError(PrepControl
.SrcPos
, "the latest preprocessor control is here");