1 //===- TGLexer.cpp - Lexer for TableGen -----------------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Implement the Lexer for TableGen.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TGLexer.h"
14 #include "llvm/ADT/StringSwitch.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/Config/config.h" // for strtoull()/strtoll() define
17 #include "llvm/Support/Compiler.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 #include "llvm/Support/SourceMgr.h"
20 #include "llvm/TableGen/Error.h"
21 #include <algorithm>
22 #include <cctype>
23 #include <cerrno>
24 #include <cstdint>
25 #include <cstdio>
26 #include <cstdlib>
27 #include <cstring>
28 
29 using namespace llvm;
30 
31 namespace {
32 // A list of supported preprocessing directives with their
33 // internal token kinds and names.
34 struct {
35   tgtok::TokKind Kind;
36   const char *Word;
37 } PreprocessorDirs[] = {
38   { tgtok::Ifdef, "ifdef" },
39   { tgtok::Ifndef, "ifndef" },
40   { tgtok::Else, "else" },
41   { tgtok::Endif, "endif" },
42   { tgtok::Define, "define" }
43 };
44 } // end anonymous namespace
45 
46 TGLexer::TGLexer(SourceMgr &SM, ArrayRef<std::string> Macros) : SrcMgr(SM) {
47   CurBuffer = SrcMgr.getMainFileID();
48   CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
49   CurPtr = CurBuf.begin();
50   TokStart = nullptr;
51 
52   // Pretend that we enter the "top-level" include file.
53   PrepIncludeStack.push_back(
54       std::make_unique<std::vector<PreprocessorControlDesc>>());
55 
56   // Put all macros defined in the command line into the DefinedMacros set.
57   std::for_each(Macros.begin(), Macros.end(),
58                 [this](const std::string &MacroName) {
59                   DefinedMacros.insert(MacroName);
60                 });
61 }
62 
63 SMLoc TGLexer::getLoc() const {
64   return SMLoc::getFromPointer(TokStart);
65 }
66 
67 /// ReturnError - Set the error to the specified string at the specified
68 /// location.  This is defined to always return tgtok::Error.
69 tgtok::TokKind TGLexer::ReturnError(SMLoc Loc, const Twine &Msg) {
70   PrintError(Loc, Msg);
71   return tgtok::Error;
72 }
73 
74 tgtok::TokKind TGLexer::ReturnError(const char *Loc, const Twine &Msg) {
75   return ReturnError(SMLoc::getFromPointer(Loc), Msg);
76 }
77 
78 bool TGLexer::processEOF() {
79   SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
80   if (ParentIncludeLoc != SMLoc()) {
81     // If prepExitInclude() detects a problem with the preprocessing
82     // control stack, it will return false.  Pretend that we reached
83     // the final EOF and stop lexing more tokens by returning false
84     // to LexToken().
85     if (!prepExitInclude(false))
86       return false;
87 
88     CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
89     CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
90     CurPtr = ParentIncludeLoc.getPointer();
91     // Make sure TokStart points into the parent file's buffer.
92     // LexToken() assigns to it before calling getNextChar(),
93     // so it is pointing into the included file now.
94     TokStart = CurPtr;
95     return true;
96   }
97 
98   // Pretend that we exit the "top-level" include file.
99   // Note that in case of an error (e.g. control stack imbalance)
100   // the routine will issue a fatal error.
101   prepExitInclude(true);
102   return false;
103 }
104 
105 int TGLexer::getNextChar() {
106   char CurChar = *CurPtr++;
107   switch (CurChar) {
108   default:
109     return (unsigned char)CurChar;
110   case 0: {
111     // A nul character in the stream is either the end of the current buffer or
112     // a random nul in the file.  Disambiguate that here.
113     if (CurPtr-1 != CurBuf.end())
114       return 0;  // Just whitespace.
115 
116     // Otherwise, return end of file.
117     --CurPtr;  // Another call to lex will return EOF again.
118     return EOF;
119   }
120   case '\n':
121   case '\r':
122     // Handle the newline character by ignoring it and incrementing the line
123     // count.  However, be careful about 'dos style' files with \n\r in them.
124     // Only treat a \n\r or \r\n as a single line.
125     if ((*CurPtr == '\n' || (*CurPtr == '\r')) &&
126         *CurPtr != CurChar)
127       ++CurPtr;  // Eat the two char newline sequence.
128     return '\n';
129   }
130 }
131 
132 int TGLexer::peekNextChar(int Index) const {
133   return *(CurPtr + Index);
134 }
135 
136 tgtok::TokKind TGLexer::LexToken(bool FileOrLineStart) {
137   TokStart = CurPtr;
138   // This always consumes at least one character.
139   int CurChar = getNextChar();
140 
141   switch (CurChar) {
142   default:
143     // Handle letters: [a-zA-Z_]
144     if (isalpha(CurChar) || CurChar == '_')
145       return LexIdentifier();
146 
147     // Unknown character, emit an error.
148     return ReturnError(TokStart, "Unexpected character");
149   case EOF:
150     // Lex next token, if we just left an include file.
151     // Note that leaving an include file means that the next
152     // symbol is located at the end of 'include "..."'
153     // construct, so LexToken() is called with default
154     // false parameter.
155     if (processEOF())
156       return LexToken();
157 
158     // Return EOF denoting the end of lexing.
159     return tgtok::Eof;
160 
161   case ':': return tgtok::colon;
162   case ';': return tgtok::semi;
163   case '.': return tgtok::period;
164   case ',': return tgtok::comma;
165   case '<': return tgtok::less;
166   case '>': return tgtok::greater;
167   case ']': return tgtok::r_square;
168   case '{': return tgtok::l_brace;
169   case '}': return tgtok::r_brace;
170   case '(': return tgtok::l_paren;
171   case ')': return tgtok::r_paren;
172   case '=': return tgtok::equal;
173   case '?': return tgtok::question;
174   case '#':
175     if (FileOrLineStart) {
176       tgtok::TokKind Kind = prepIsDirective();
177       if (Kind != tgtok::Error)
178         return lexPreprocessor(Kind);
179     }
180 
181     return tgtok::paste;
182 
183   case '\r':
184     PrintFatalError("getNextChar() must never return '\r'");
185     return tgtok::Error;
186 
187   case 0:
188   case ' ':
189   case '\t':
190     // Ignore whitespace.
191     return LexToken(FileOrLineStart);
192   case '\n':
193     // Ignore whitespace, and identify the new line.
194     return LexToken(true);
195   case '/':
196     // If this is the start of a // comment, skip until the end of the line or
197     // the end of the buffer.
198     if (*CurPtr == '/')
199       SkipBCPLComment();
200     else if (*CurPtr == '*') {
201       if (SkipCComment())
202         return tgtok::Error;
203     } else // Otherwise, this is an error.
204       return ReturnError(TokStart, "Unexpected character");
205     return LexToken(FileOrLineStart);
206   case '-': case '+':
207   case '0': case '1': case '2': case '3': case '4': case '5': case '6':
208   case '7': case '8': case '9': {
209     int NextChar = 0;
210     if (isdigit(CurChar)) {
211       // Allow identifiers to start with a number if it is followed by
212       // an identifier.  This can happen with paste operations like
213       // foo#8i.
214       int i = 0;
215       do {
216         NextChar = peekNextChar(i++);
217       } while (isdigit(NextChar));
218 
219       if (NextChar == 'x' || NextChar == 'b') {
220         // If this is [0-9]b[01] or [0-9]x[0-9A-fa-f] this is most
221         // likely a number.
222         int NextNextChar = peekNextChar(i);
223         switch (NextNextChar) {
224         default:
225           break;
226         case '0': case '1':
227           if (NextChar == 'b')
228             return LexNumber();
229           LLVM_FALLTHROUGH;
230         case '2': case '3': case '4': case '5':
231         case '6': case '7': case '8': case '9':
232         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
233         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
234           if (NextChar == 'x')
235             return LexNumber();
236           break;
237         }
238       }
239     }
240 
241     if (isalpha(NextChar) || NextChar == '_')
242       return LexIdentifier();
243 
244     return LexNumber();
245   }
246   case '"': return LexString();
247   case '$': return LexVarName();
248   case '[': return LexBracket();
249   case '!': return LexExclaim();
250   }
251 }
252 
253 /// LexString - Lex "[^"]*"
254 tgtok::TokKind TGLexer::LexString() {
255   const char *StrStart = CurPtr;
256 
257   CurStrVal = "";
258 
259   while (*CurPtr != '"') {
260     // If we hit the end of the buffer, report an error.
261     if (*CurPtr == 0 && CurPtr == CurBuf.end())
262       return ReturnError(StrStart, "End of file in string literal");
263 
264     if (*CurPtr == '\n' || *CurPtr == '\r')
265       return ReturnError(StrStart, "End of line in string literal");
266 
267     if (*CurPtr != '\\') {
268       CurStrVal += *CurPtr++;
269       continue;
270     }
271 
272     ++CurPtr;
273 
274     switch (*CurPtr) {
275     case '\\': case '\'': case '"':
276       // These turn into their literal character.
277       CurStrVal += *CurPtr++;
278       break;
279     case 't':
280       CurStrVal += '\t';
281       ++CurPtr;
282       break;
283     case 'n':
284       CurStrVal += '\n';
285       ++CurPtr;
286       break;
287 
288     case '\n':
289     case '\r':
290       return ReturnError(CurPtr, "escaped newlines not supported in tblgen");
291 
292     // If we hit the end of the buffer, report an error.
293     case '\0':
294       if (CurPtr == CurBuf.end())
295         return ReturnError(StrStart, "End of file in string literal");
296       LLVM_FALLTHROUGH;
297     default:
298       return ReturnError(CurPtr, "invalid escape in string literal");
299     }
300   }
301 
302   ++CurPtr;
303   return tgtok::StrVal;
304 }
305 
306 tgtok::TokKind TGLexer::LexVarName() {
307   if (!isalpha(CurPtr[0]) && CurPtr[0] != '_')
308     return ReturnError(TokStart, "Invalid variable name");
309 
310   // Otherwise, we're ok, consume the rest of the characters.
311   const char *VarNameStart = CurPtr++;
312 
313   while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
314     ++CurPtr;
315 
316   CurStrVal.assign(VarNameStart, CurPtr);
317   return tgtok::VarName;
318 }
319 
320 tgtok::TokKind TGLexer::LexIdentifier() {
321   // The first letter is [a-zA-Z_].
322   const char *IdentStart = TokStart;
323 
324   // Match the rest of the identifier regex: [0-9a-zA-Z_]*
325   while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
326     ++CurPtr;
327 
328   // Check to see if this identifier is a keyword.
329   StringRef Str(IdentStart, CurPtr-IdentStart);
330 
331   if (Str == "include") {
332     if (LexInclude()) return tgtok::Error;
333     return Lex();
334   }
335 
336   tgtok::TokKind Kind = StringSwitch<tgtok::TokKind>(Str)
337     .Case("int", tgtok::Int)
338     .Case("bit", tgtok::Bit)
339     .Case("bits", tgtok::Bits)
340     .Case("string", tgtok::String)
341     .Case("list", tgtok::List)
342     .Case("code", tgtok::Code)
343     .Case("dag", tgtok::Dag)
344     .Case("class", tgtok::Class)
345     .Case("def", tgtok::Def)
346     .Case("foreach", tgtok::Foreach)
347     .Case("defm", tgtok::Defm)
348     .Case("defset", tgtok::Defset)
349     .Case("multiclass", tgtok::MultiClass)
350     .Case("field", tgtok::Field)
351     .Case("let", tgtok::Let)
352     .Case("in", tgtok::In)
353     .Default(tgtok::Id);
354 
355   if (Kind == tgtok::Id)
356     CurStrVal.assign(Str.begin(), Str.end());
357   return Kind;
358 }
359 
360 /// LexInclude - We just read the "include" token.  Get the string token that
361 /// comes next and enter the include.
362 bool TGLexer::LexInclude() {
363   // The token after the include must be a string.
364   tgtok::TokKind Tok = LexToken();
365   if (Tok == tgtok::Error) return true;
366   if (Tok != tgtok::StrVal) {
367     PrintError(getLoc(), "Expected filename after include");
368     return true;
369   }
370 
371   // Get the string.
372   std::string Filename = CurStrVal;
373   std::string IncludedFile;
374 
375   CurBuffer = SrcMgr.AddIncludeFile(Filename, SMLoc::getFromPointer(CurPtr),
376                                     IncludedFile);
377   if (!CurBuffer) {
378     PrintError(getLoc(), "Could not find include file '" + Filename + "'");
379     return true;
380   }
381 
382   Dependencies.insert(IncludedFile);
383   // Save the line number and lex buffer of the includer.
384   CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
385   CurPtr = CurBuf.begin();
386 
387   PrepIncludeStack.push_back(
388       std::make_unique<std::vector<PreprocessorControlDesc>>());
389   return false;
390 }
391 
392 void TGLexer::SkipBCPLComment() {
393   ++CurPtr;  // skip the second slash.
394   while (true) {
395     switch (*CurPtr) {
396     case '\n':
397     case '\r':
398       return;  // Newline is end of comment.
399     case 0:
400       // If this is the end of the buffer, end the comment.
401       if (CurPtr == CurBuf.end())
402         return;
403       break;
404     }
405     // Otherwise, skip the character.
406     ++CurPtr;
407   }
408 }
409 
410 /// SkipCComment - This skips C-style /**/ comments.  The only difference from C
411 /// is that we allow nesting.
412 bool TGLexer::SkipCComment() {
413   ++CurPtr;  // skip the star.
414   unsigned CommentDepth = 1;
415 
416   while (true) {
417     int CurChar = getNextChar();
418     switch (CurChar) {
419     case EOF:
420       PrintError(TokStart, "Unterminated comment!");
421       return true;
422     case '*':
423       // End of the comment?
424       if (CurPtr[0] != '/') break;
425 
426       ++CurPtr;   // End the */.
427       if (--CommentDepth == 0)
428         return false;
429       break;
430     case '/':
431       // Start of a nested comment?
432       if (CurPtr[0] != '*') break;
433       ++CurPtr;
434       ++CommentDepth;
435       break;
436     }
437   }
438 }
439 
440 /// LexNumber - Lex:
441 ///    [-+]?[0-9]+
442 ///    0x[0-9a-fA-F]+
443 ///    0b[01]+
444 tgtok::TokKind TGLexer::LexNumber() {
445   if (CurPtr[-1] == '0') {
446     if (CurPtr[0] == 'x') {
447       ++CurPtr;
448       const char *NumStart = CurPtr;
449       while (isxdigit(CurPtr[0]))
450         ++CurPtr;
451 
452       // Requires at least one hex digit.
453       if (CurPtr == NumStart)
454         return ReturnError(TokStart, "Invalid hexadecimal number");
455 
456       errno = 0;
457       CurIntVal = strtoll(NumStart, nullptr, 16);
458       if (errno == EINVAL)
459         return ReturnError(TokStart, "Invalid hexadecimal number");
460       if (errno == ERANGE) {
461         errno = 0;
462         CurIntVal = (int64_t)strtoull(NumStart, nullptr, 16);
463         if (errno == EINVAL)
464           return ReturnError(TokStart, "Invalid hexadecimal number");
465         if (errno == ERANGE)
466           return ReturnError(TokStart, "Hexadecimal number out of range");
467       }
468       return tgtok::IntVal;
469     } else if (CurPtr[0] == 'b') {
470       ++CurPtr;
471       const char *NumStart = CurPtr;
472       while (CurPtr[0] == '0' || CurPtr[0] == '1')
473         ++CurPtr;
474 
475       // Requires at least one binary digit.
476       if (CurPtr == NumStart)
477         return ReturnError(CurPtr-2, "Invalid binary number");
478       CurIntVal = strtoll(NumStart, nullptr, 2);
479       return tgtok::BinaryIntVal;
480     }
481   }
482 
483   // Check for a sign without a digit.
484   if (!isdigit(CurPtr[0])) {
485     if (CurPtr[-1] == '-')
486       return tgtok::minus;
487     else if (CurPtr[-1] == '+')
488       return tgtok::plus;
489   }
490 
491   while (isdigit(CurPtr[0]))
492     ++CurPtr;
493   CurIntVal = strtoll(TokStart, nullptr, 10);
494   return tgtok::IntVal;
495 }
496 
497 /// LexBracket - We just read '['.  If this is a code block, return it,
498 /// otherwise return the bracket.  Match: '[' and '[{ ( [^}]+ | }[^]] )* }]'
499 tgtok::TokKind TGLexer::LexBracket() {
500   if (CurPtr[0] != '{')
501     return tgtok::l_square;
502   ++CurPtr;
503   const char *CodeStart = CurPtr;
504   while (true) {
505     int Char = getNextChar();
506     if (Char == EOF) break;
507 
508     if (Char != '}') continue;
509 
510     Char = getNextChar();
511     if (Char == EOF) break;
512     if (Char == ']') {
513       CurStrVal.assign(CodeStart, CurPtr-2);
514       return tgtok::CodeFragment;
515     }
516   }
517 
518   return ReturnError(CodeStart-2, "Unterminated Code Block");
519 }
520 
521 /// LexExclaim - Lex '!' and '![a-zA-Z]+'.
522 tgtok::TokKind TGLexer::LexExclaim() {
523   if (!isalpha(*CurPtr))
524     return ReturnError(CurPtr - 1, "Invalid \"!operator\"");
525 
526   const char *Start = CurPtr++;
527   while (isalpha(*CurPtr))
528     ++CurPtr;
529 
530   // Check to see which operator this is.
531   tgtok::TokKind Kind =
532     StringSwitch<tgtok::TokKind>(StringRef(Start, CurPtr - Start))
533     .Case("eq", tgtok::XEq)
534     .Case("ne", tgtok::XNe)
535     .Case("le", tgtok::XLe)
536     .Case("lt", tgtok::XLt)
537     .Case("ge", tgtok::XGe)
538     .Case("gt", tgtok::XGt)
539     .Case("if", tgtok::XIf)
540     .Case("cond", tgtok::XCond)
541     .Case("isa", tgtok::XIsA)
542     .Case("head", tgtok::XHead)
543     .Case("tail", tgtok::XTail)
544     .Case("size", tgtok::XSize)
545     .Case("con", tgtok::XConcat)
546     .Case("dag", tgtok::XDag)
547     .Case("add", tgtok::XADD)
548     .Case("mul", tgtok::XMUL)
549     .Case("and", tgtok::XAND)
550     .Case("or", tgtok::XOR)
551     .Case("shl", tgtok::XSHL)
552     .Case("sra", tgtok::XSRA)
553     .Case("srl", tgtok::XSRL)
554     .Case("cast", tgtok::XCast)
555     .Case("empty", tgtok::XEmpty)
556     .Case("subst", tgtok::XSubst)
557     .Case("foldl", tgtok::XFoldl)
558     .Case("foreach", tgtok::XForEach)
559     .Case("listconcat", tgtok::XListConcat)
560     .Case("listsplat", tgtok::XListSplat)
561     .Case("strconcat", tgtok::XStrConcat)
562     .Case("setop", tgtok::XSetOp)
563     .Case("getop", tgtok::XGetOp)
564     .Default(tgtok::Error);
565 
566   return Kind != tgtok::Error ? Kind : ReturnError(Start-1, "Unknown operator");
567 }
568 
569 bool TGLexer::prepExitInclude(bool IncludeStackMustBeEmpty) {
570   // Report an error, if preprocessor control stack for the current
571   // file is not empty.
572   if (!PrepIncludeStack.back()->empty()) {
573     prepReportPreprocessorStackError();
574 
575     return false;
576   }
577 
578   // Pop the preprocessing controls from the include stack.
579   if (PrepIncludeStack.empty()) {
580     PrintFatalError("Preprocessor include stack is empty");
581   }
582 
583   PrepIncludeStack.pop_back();
584 
585   if (IncludeStackMustBeEmpty) {
586     if (!PrepIncludeStack.empty())
587       PrintFatalError("Preprocessor include stack is not empty");
588   } else {
589     if (PrepIncludeStack.empty())
590       PrintFatalError("Preprocessor include stack is empty");
591   }
592 
593   return true;
594 }
595 
596 tgtok::TokKind TGLexer::prepIsDirective() const {
597   for (unsigned ID = 0; ID < llvm::array_lengthof(PreprocessorDirs); ++ID) {
598     int NextChar = *CurPtr;
599     bool Match = true;
600     unsigned I = 0;
601     for (; I < strlen(PreprocessorDirs[ID].Word); ++I) {
602       if (NextChar != PreprocessorDirs[ID].Word[I]) {
603         Match = false;
604         break;
605       }
606 
607       NextChar = peekNextChar(I + 1);
608     }
609 
610     // Check for whitespace after the directive.  If there is no whitespace,
611     // then we do not recognize it as a preprocessing directive.
612     if (Match) {
613       tgtok::TokKind Kind = PreprocessorDirs[ID].Kind;
614 
615       // New line and EOF may follow only #else/#endif.  It will be reported
616       // as an error for #ifdef/#define after the call to prepLexMacroName().
617       if (NextChar == ' ' || NextChar == '\t' || NextChar == EOF ||
618           NextChar == '\n' ||
619           // It looks like TableGen does not support '\r' as the actual
620           // carriage return, e.g. getNextChar() treats a single '\r'
621           // as '\n'.  So we do the same here.
622           NextChar == '\r')
623         return Kind;
624 
625       // Allow comments after some directives, e.g.:
626       //     #else// OR #else/**/
627       //     #endif// OR #endif/**/
628       //
629       // Note that we do allow comments after #ifdef/#define here, e.g.
630       //     #ifdef/**/ AND #ifdef//
631       //     #define/**/ AND #define//
632       //
633       // These cases will be reported as incorrect after calling
634       // prepLexMacroName().  We could have supported C-style comments
635       // after #ifdef/#define, but this would complicate the code
636       // for little benefit.
637       if (NextChar == '/') {
638         NextChar = peekNextChar(I + 1);
639 
640         if (NextChar == '*' || NextChar == '/')
641           return Kind;
642 
643         // Pretend that we do not recognize the directive.
644       }
645     }
646   }
647 
648   return tgtok::Error;
649 }
650 
651 bool TGLexer::prepEatPreprocessorDirective(tgtok::TokKind Kind) {
652   TokStart = CurPtr;
653 
654   for (unsigned ID = 0; ID < llvm::array_lengthof(PreprocessorDirs); ++ID)
655     if (PreprocessorDirs[ID].Kind == Kind) {
656       // Advance CurPtr to the end of the preprocessing word.
657       CurPtr += strlen(PreprocessorDirs[ID].Word);
658       return true;
659     }
660 
661   PrintFatalError("Unsupported preprocessing token in "
662                   "prepEatPreprocessorDirective()");
663   return false;
664 }
665 
666 tgtok::TokKind TGLexer::lexPreprocessor(
667     tgtok::TokKind Kind, bool ReturnNextLiveToken) {
668 
669   // We must be looking at a preprocessing directive.  Eat it!
670   if (!prepEatPreprocessorDirective(Kind))
671     PrintFatalError("lexPreprocessor() called for unknown "
672                     "preprocessor directive");
673 
674   if (Kind == tgtok::Ifdef || Kind == tgtok::Ifndef) {
675     StringRef MacroName = prepLexMacroName();
676     StringRef IfTokName = Kind == tgtok::Ifdef ? "#ifdef" : "#ifndef";
677     if (MacroName.empty())
678       return ReturnError(TokStart, "Expected macro name after " + IfTokName);
679 
680     bool MacroIsDefined = DefinedMacros.count(MacroName) != 0;
681 
682     // Canonicalize ifndef to ifdef equivalent
683     if (Kind == tgtok::Ifndef) {
684       MacroIsDefined = !MacroIsDefined;
685       Kind = tgtok::Ifdef;
686     }
687 
688     // Regardless of whether we are processing tokens or not,
689     // we put the #ifdef control on stack.
690     PrepIncludeStack.back()->push_back(
691         {Kind, MacroIsDefined, SMLoc::getFromPointer(TokStart)});
692 
693     if (!prepSkipDirectiveEnd())
694       return ReturnError(CurPtr, "Only comments are supported after " +
695                                      IfTokName + " NAME");
696 
697     // If we were not processing tokens before this #ifdef,
698     // then just return back to the lines skipping code.
699     if (!ReturnNextLiveToken)
700       return Kind;
701 
702     // If we were processing tokens before this #ifdef,
703     // and the macro is defined, then just return the next token.
704     if (MacroIsDefined)
705       return LexToken();
706 
707     // We were processing tokens before this #ifdef, and the macro
708     // is not defined, so we have to start skipping the lines.
709     // If the skipping is successful, it will return the token following
710     // either #else or #endif corresponding to this #ifdef.
711     if (prepSkipRegion(ReturnNextLiveToken))
712       return LexToken();
713 
714     return tgtok::Error;
715   } else if (Kind == tgtok::Else) {
716     // Check if this #else is correct before calling prepSkipDirectiveEnd(),
717     // which will move CurPtr away from the beginning of #else.
718     if (PrepIncludeStack.back()->empty())
719       return ReturnError(TokStart, "#else without #ifdef or #ifndef");
720 
721     PreprocessorControlDesc IfdefEntry = PrepIncludeStack.back()->back();
722 
723     if (IfdefEntry.Kind != tgtok::Ifdef) {
724       PrintError(TokStart, "double #else");
725       return ReturnError(IfdefEntry.SrcPos, "Previous #else is here");
726     }
727 
728     // Replace the corresponding #ifdef's control with its negation
729     // on the control stack.
730     PrepIncludeStack.back()->pop_back();
731     PrepIncludeStack.back()->push_back(
732         {Kind, !IfdefEntry.IsDefined, SMLoc::getFromPointer(TokStart)});
733 
734     if (!prepSkipDirectiveEnd())
735       return ReturnError(CurPtr, "Only comments are supported after #else");
736 
737     // If we were processing tokens before this #else,
738     // we have to start skipping lines until the matching #endif.
739     if (ReturnNextLiveToken) {
740       if (prepSkipRegion(ReturnNextLiveToken))
741         return LexToken();
742 
743       return tgtok::Error;
744     }
745 
746     // Return to the lines skipping code.
747     return Kind;
748   } else if (Kind == tgtok::Endif) {
749     // Check if this #endif is correct before calling prepSkipDirectiveEnd(),
750     // which will move CurPtr away from the beginning of #endif.
751     if (PrepIncludeStack.back()->empty())
752       return ReturnError(TokStart, "#endif without #ifdef");
753 
754     auto &IfdefOrElseEntry = PrepIncludeStack.back()->back();
755 
756     if (IfdefOrElseEntry.Kind != tgtok::Ifdef &&
757         IfdefOrElseEntry.Kind != tgtok::Else) {
758       PrintFatalError("Invalid preprocessor control on the stack");
759       return tgtok::Error;
760     }
761 
762     if (!prepSkipDirectiveEnd())
763       return ReturnError(CurPtr, "Only comments are supported after #endif");
764 
765     PrepIncludeStack.back()->pop_back();
766 
767     // If we were processing tokens before this #endif, then
768     // we should continue it.
769     if (ReturnNextLiveToken) {
770       return LexToken();
771     }
772 
773     // Return to the lines skipping code.
774     return Kind;
775   } else if (Kind == tgtok::Define) {
776     StringRef MacroName = prepLexMacroName();
777     if (MacroName.empty())
778       return ReturnError(TokStart, "Expected macro name after #define");
779 
780     if (!DefinedMacros.insert(MacroName).second)
781       PrintWarning(getLoc(),
782                    "Duplicate definition of macro: " + Twine(MacroName));
783 
784     if (!prepSkipDirectiveEnd())
785       return ReturnError(CurPtr,
786                          "Only comments are supported after #define NAME");
787 
788     if (!ReturnNextLiveToken) {
789       PrintFatalError("#define must be ignored during the lines skipping");
790       return tgtok::Error;
791     }
792 
793     return LexToken();
794   }
795 
796   PrintFatalError("Preprocessing directive is not supported");
797   return tgtok::Error;
798 }
799 
800 bool TGLexer::prepSkipRegion(bool MustNeverBeFalse) {
801   if (!MustNeverBeFalse)
802     PrintFatalError("Invalid recursion.");
803 
804   do {
805     // Skip all symbols to the line end.
806     prepSkipToLineEnd();
807 
808     // Find the first non-whitespace symbol in the next line(s).
809     if (!prepSkipLineBegin())
810       return false;
811 
812     // If the first non-blank/comment symbol on the line is '#',
813     // it may be a start of preprocessing directive.
814     //
815     // If it is not '#' just go to the next line.
816     if (*CurPtr == '#')
817       ++CurPtr;
818     else
819       continue;
820 
821     tgtok::TokKind Kind = prepIsDirective();
822 
823     // If we did not find a preprocessing directive or it is #define,
824     // then just skip to the next line.  We do not have to do anything
825     // for #define in the line-skipping mode.
826     if (Kind == tgtok::Error || Kind == tgtok::Define)
827       continue;
828 
829     tgtok::TokKind ProcessedKind = lexPreprocessor(Kind, false);
830 
831     // If lexPreprocessor() encountered an error during lexing this
832     // preprocessor idiom, then return false to the calling lexPreprocessor().
833     // This will force tgtok::Error to be returned to the tokens processing.
834     if (ProcessedKind == tgtok::Error)
835       return false;
836 
837     if (Kind != ProcessedKind)
838       PrintFatalError("prepIsDirective() and lexPreprocessor() "
839                       "returned different token kinds");
840 
841     // If this preprocessing directive enables tokens processing,
842     // then return to the lexPreprocessor() and get to the next token.
843     // We can move from line-skipping mode to processing tokens only
844     // due to #else or #endif.
845     if (prepIsProcessingEnabled()) {
846       if (Kind != tgtok::Else && Kind != tgtok::Endif) {
847         PrintFatalError("Tokens processing was enabled by an unexpected "
848                         "preprocessing directive");
849         return false;
850       }
851 
852       return true;
853     }
854   } while (CurPtr != CurBuf.end());
855 
856   // We have reached the end of the file, but never left the lines-skipping
857   // mode.  This means there is no matching #endif.
858   prepReportPreprocessorStackError();
859   return false;
860 }
861 
862 StringRef TGLexer::prepLexMacroName() {
863   // Skip whitespaces between the preprocessing directive and the macro name.
864   while (*CurPtr == ' ' || *CurPtr == '\t')
865     ++CurPtr;
866 
867   TokStart = CurPtr;
868   // Macro names start with [a-zA-Z_].
869   if (*CurPtr != '_' && !isalpha(*CurPtr))
870     return "";
871 
872   // Match the rest of the identifier regex: [0-9a-zA-Z_]*
873   while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
874     ++CurPtr;
875 
876   return StringRef(TokStart, CurPtr - TokStart);
877 }
878 
879 bool TGLexer::prepSkipLineBegin() {
880   while (CurPtr != CurBuf.end()) {
881     switch (*CurPtr) {
882     case ' ':
883     case '\t':
884     case '\n':
885     case '\r':
886       break;
887 
888     case '/': {
889       int NextChar = peekNextChar(1);
890       if (NextChar == '*') {
891         // Skip C-style comment.
892         // Note that we do not care about skipping the C++-style comments.
893         // If the line contains "//", it may not contain any processable
894         // preprocessing directive.  Just return CurPtr pointing to
895         // the first '/' in this case.  We also do not care about
896         // incorrect symbols after the first '/' - we are in lines-skipping
897         // mode, so incorrect code is allowed to some extent.
898 
899         // Set TokStart to the beginning of the comment to enable proper
900         // diagnostic printing in case of error in SkipCComment().
901         TokStart = CurPtr;
902 
903         // CurPtr must point to '*' before call to SkipCComment().
904         ++CurPtr;
905         if (SkipCComment())
906           return false;
907       } else {
908         // CurPtr points to the non-whitespace '/'.
909         return true;
910       }
911 
912       // We must not increment CurPtr after the comment was lexed.
913       continue;
914     }
915 
916     default:
917       return true;
918     }
919 
920     ++CurPtr;
921   }
922 
923   // We have reached the end of the file.  Return to the lines skipping
924   // code, and allow it to handle the EOF as needed.
925   return true;
926 }
927 
928 bool TGLexer::prepSkipDirectiveEnd() {
929   while (CurPtr != CurBuf.end()) {
930     switch (*CurPtr) {
931     case ' ':
932     case '\t':
933       break;
934 
935     case '\n':
936     case '\r':
937       return true;
938 
939     case '/': {
940       int NextChar = peekNextChar(1);
941       if (NextChar == '/') {
942         // Skip C++-style comment.
943         // We may just return true now, but let's skip to the line/buffer end
944         // to simplify the method specification.
945         ++CurPtr;
946         SkipBCPLComment();
947       } else if (NextChar == '*') {
948         // When we are skipping C-style comment at the end of a preprocessing
949         // directive, we can skip several lines.  If any meaningful TD token
950         // follows the end of the C-style comment on the same line, it will
951         // be considered as an invalid usage of TD token.
952         // For example, we want to forbid usages like this one:
953         //     #define MACRO class Class {}
954         // But with C-style comments we also disallow the following:
955         //     #define MACRO /* This macro is used
956         //                      to ... */ class Class {}
957         // One can argue that this should be allowed, but it does not seem
958         // to be worth of the complication.  Moreover, this matches
959         // the C preprocessor behavior.
960 
961         // Set TokStart to the beginning of the comment to enable proper
962         // diagnostic printer in case of error in SkipCComment().
963         TokStart = CurPtr;
964         ++CurPtr;
965         if (SkipCComment())
966           return false;
967       } else {
968         TokStart = CurPtr;
969         PrintError(CurPtr, "Unexpected character");
970         return false;
971       }
972 
973       // We must not increment CurPtr after the comment was lexed.
974       continue;
975     }
976 
977     default:
978       // Do not allow any non-whitespaces after the directive.
979       TokStart = CurPtr;
980       return false;
981     }
982 
983     ++CurPtr;
984   }
985 
986   return true;
987 }
988 
989 void TGLexer::prepSkipToLineEnd() {
990   while (*CurPtr != '\n' && *CurPtr != '\r' && CurPtr != CurBuf.end())
991     ++CurPtr;
992 }
993 
994 bool TGLexer::prepIsProcessingEnabled() {
995   for (auto I = PrepIncludeStack.back()->rbegin(),
996             E = PrepIncludeStack.back()->rend();
997        I != E; ++I) {
998     if (!I->IsDefined)
999       return false;
1000   }
1001 
1002   return true;
1003 }
1004 
1005 void TGLexer::prepReportPreprocessorStackError() {
1006   if (PrepIncludeStack.back()->empty())
1007     PrintFatalError("prepReportPreprocessorStackError() called with "
1008                     "empty control stack");
1009 
1010   auto &PrepControl = PrepIncludeStack.back()->back();
1011   PrintError(CurBuf.end(), "Reached EOF without matching #endif");
1012   PrintError(PrepControl.SrcPos, "The latest preprocessor control is here");
1013 
1014   TokStart = CurPtr;
1015 }
1016