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
29using namespace llvm;
30
31namespace {
32// A list of supported preprocessing directives with their
33// internal token kinds and names.
34struct {
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
46TGLexer::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
63SMLoc 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.
69tgtok::TokKind TGLexer::ReturnError(SMLoc Loc, const Twine &Msg) {
70  PrintError(Loc, Msg);
71  return tgtok::Error;
72}
73
74tgtok::TokKind TGLexer::ReturnError(const char *Loc, const Twine &Msg) {
75  return ReturnError(SMLoc::getFromPointer(Loc), Msg);
76}
77
78bool 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
105int 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
132int TGLexer::peekNextChar(int Index) const {
133  return *(CurPtr + Index);
134}
135
136tgtok::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 "[^"]*"
254tgtok::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
306tgtok::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
320tgtok::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    .Case("defvar", tgtok::Defvar)
354    .Case("if", tgtok::If)
355    .Case("then", tgtok::Then)
356    .Case("else", tgtok::ElseKW)
357    .Default(tgtok::Id);
358
359  if (Kind == tgtok::Id)
360    CurStrVal.assign(Str.begin(), Str.end());
361  return Kind;
362}
363
364/// LexInclude - We just read the "include" token.  Get the string token that
365/// comes next and enter the include.
366bool TGLexer::LexInclude() {
367  // The token after the include must be a string.
368  tgtok::TokKind Tok = LexToken();
369  if (Tok == tgtok::Error) return true;
370  if (Tok != tgtok::StrVal) {
371    PrintError(getLoc(), "Expected filename after include");
372    return true;
373  }
374
375  // Get the string.
376  std::string Filename = CurStrVal;
377  std::string IncludedFile;
378
379  CurBuffer = SrcMgr.AddIncludeFile(Filename, SMLoc::getFromPointer(CurPtr),
380                                    IncludedFile);
381  if (!CurBuffer) {
382    PrintError(getLoc(), "Could not find include file '" + Filename + "'");
383    return true;
384  }
385
386  Dependencies.insert(IncludedFile);
387  // Save the line number and lex buffer of the includer.
388  CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
389  CurPtr = CurBuf.begin();
390
391  PrepIncludeStack.push_back(
392      std::make_unique<std::vector<PreprocessorControlDesc>>());
393  return false;
394}
395
396void TGLexer::SkipBCPLComment() {
397  ++CurPtr;  // skip the second slash.
398  while (true) {
399    switch (*CurPtr) {
400    case '\n':
401    case '\r':
402      return;  // Newline is end of comment.
403    case 0:
404      // If this is the end of the buffer, end the comment.
405      if (CurPtr == CurBuf.end())
406        return;
407      break;
408    }
409    // Otherwise, skip the character.
410    ++CurPtr;
411  }
412}
413
414/// SkipCComment - This skips C-style /**/ comments.  The only difference from C
415/// is that we allow nesting.
416bool TGLexer::SkipCComment() {
417  ++CurPtr;  // skip the star.
418  unsigned CommentDepth = 1;
419
420  while (true) {
421    int CurChar = getNextChar();
422    switch (CurChar) {
423    case EOF:
424      PrintError(TokStart, "Unterminated comment!");
425      return true;
426    case '*':
427      // End of the comment?
428      if (CurPtr[0] != '/') break;
429
430      ++CurPtr;   // End the */.
431      if (--CommentDepth == 0)
432        return false;
433      break;
434    case '/':
435      // Start of a nested comment?
436      if (CurPtr[0] != '*') break;
437      ++CurPtr;
438      ++CommentDepth;
439      break;
440    }
441  }
442}
443
444/// LexNumber - Lex:
445///    [-+]?[0-9]+
446///    0x[0-9a-fA-F]+
447///    0b[01]+
448tgtok::TokKind TGLexer::LexNumber() {
449  if (CurPtr[-1] == '0') {
450    if (CurPtr[0] == 'x') {
451      ++CurPtr;
452      const char *NumStart = CurPtr;
453      while (isxdigit(CurPtr[0]))
454        ++CurPtr;
455
456      // Requires at least one hex digit.
457      if (CurPtr == NumStart)
458        return ReturnError(TokStart, "Invalid hexadecimal number");
459
460      errno = 0;
461      CurIntVal = strtoll(NumStart, nullptr, 16);
462      if (errno == EINVAL)
463        return ReturnError(TokStart, "Invalid hexadecimal number");
464      if (errno == ERANGE) {
465        errno = 0;
466        CurIntVal = (int64_t)strtoull(NumStart, nullptr, 16);
467        if (errno == EINVAL)
468          return ReturnError(TokStart, "Invalid hexadecimal number");
469        if (errno == ERANGE)
470          return ReturnError(TokStart, "Hexadecimal number out of range");
471      }
472      return tgtok::IntVal;
473    } else if (CurPtr[0] == 'b') {
474      ++CurPtr;
475      const char *NumStart = CurPtr;
476      while (CurPtr[0] == '0' || CurPtr[0] == '1')
477        ++CurPtr;
478
479      // Requires at least one binary digit.
480      if (CurPtr == NumStart)
481        return ReturnError(CurPtr-2, "Invalid binary number");
482      CurIntVal = strtoll(NumStart, nullptr, 2);
483      return tgtok::BinaryIntVal;
484    }
485  }
486
487  // Check for a sign without a digit.
488  if (!isdigit(CurPtr[0])) {
489    if (CurPtr[-1] == '-')
490      return tgtok::minus;
491    else if (CurPtr[-1] == '+')
492      return tgtok::plus;
493  }
494
495  while (isdigit(CurPtr[0]))
496    ++CurPtr;
497  CurIntVal = strtoll(TokStart, nullptr, 10);
498  return tgtok::IntVal;
499}
500
501/// LexBracket - We just read '['.  If this is a code block, return it,
502/// otherwise return the bracket.  Match: '[' and '[{ ( [^}]+ | }[^]] )* }]'
503tgtok::TokKind TGLexer::LexBracket() {
504  if (CurPtr[0] != '{')
505    return tgtok::l_square;
506  ++CurPtr;
507  const char *CodeStart = CurPtr;
508  while (true) {
509    int Char = getNextChar();
510    if (Char == EOF) break;
511
512    if (Char != '}') continue;
513
514    Char = getNextChar();
515    if (Char == EOF) break;
516    if (Char == ']') {
517      CurStrVal.assign(CodeStart, CurPtr-2);
518      return tgtok::CodeFragment;
519    }
520  }
521
522  return ReturnError(CodeStart-2, "Unterminated Code Block");
523}
524
525/// LexExclaim - Lex '!' and '![a-zA-Z]+'.
526tgtok::TokKind TGLexer::LexExclaim() {
527  if (!isalpha(*CurPtr))
528    return ReturnError(CurPtr - 1, "Invalid \"!operator\"");
529
530  const char *Start = CurPtr++;
531  while (isalpha(*CurPtr))
532    ++CurPtr;
533
534  // Check to see which operator this is.
535  tgtok::TokKind Kind =
536    StringSwitch<tgtok::TokKind>(StringRef(Start, CurPtr - Start))
537    .Case("eq", tgtok::XEq)
538    .Case("ne", tgtok::XNe)
539    .Case("le", tgtok::XLe)
540    .Case("lt", tgtok::XLt)
541    .Case("ge", tgtok::XGe)
542    .Case("gt", tgtok::XGt)
543    .Case("if", tgtok::XIf)
544    .Case("cond", tgtok::XCond)
545    .Case("isa", tgtok::XIsA)
546    .Case("head", tgtok::XHead)
547    .Case("tail", tgtok::XTail)
548    .Case("size", tgtok::XSize)
549    .Case("con", tgtok::XConcat)
550    .Case("dag", tgtok::XDag)
551    .Case("add", tgtok::XADD)
552    .Case("mul", tgtok::XMUL)
553    .Case("and", tgtok::XAND)
554    .Case("or", tgtok::XOR)
555    .Case("shl", tgtok::XSHL)
556    .Case("sra", tgtok::XSRA)
557    .Case("srl", tgtok::XSRL)
558    .Case("cast", tgtok::XCast)
559    .Case("empty", tgtok::XEmpty)
560    .Case("subst", tgtok::XSubst)
561    .Case("foldl", tgtok::XFoldl)
562    .Case("foreach", tgtok::XForEach)
563    .Case("listconcat", tgtok::XListConcat)
564    .Case("listsplat", tgtok::XListSplat)
565    .Case("strconcat", tgtok::XStrConcat)
566    .Case("setop", tgtok::XSetOp)
567    .Case("getop", tgtok::XGetOp)
568    .Default(tgtok::Error);
569
570  return Kind != tgtok::Error ? Kind : ReturnError(Start-1, "Unknown operator");
571}
572
573bool TGLexer::prepExitInclude(bool IncludeStackMustBeEmpty) {
574  // Report an error, if preprocessor control stack for the current
575  // file is not empty.
576  if (!PrepIncludeStack.back()->empty()) {
577    prepReportPreprocessorStackError();
578
579    return false;
580  }
581
582  // Pop the preprocessing controls from the include stack.
583  if (PrepIncludeStack.empty()) {
584    PrintFatalError("Preprocessor include stack is empty");
585  }
586
587  PrepIncludeStack.pop_back();
588
589  if (IncludeStackMustBeEmpty) {
590    if (!PrepIncludeStack.empty())
591      PrintFatalError("Preprocessor include stack is not empty");
592  } else {
593    if (PrepIncludeStack.empty())
594      PrintFatalError("Preprocessor include stack is empty");
595  }
596
597  return true;
598}
599
600tgtok::TokKind TGLexer::prepIsDirective() const {
601  for (unsigned ID = 0; ID < llvm::array_lengthof(PreprocessorDirs); ++ID) {
602    int NextChar = *CurPtr;
603    bool Match = true;
604    unsigned I = 0;
605    for (; I < strlen(PreprocessorDirs[ID].Word); ++I) {
606      if (NextChar != PreprocessorDirs[ID].Word[I]) {
607        Match = false;
608        break;
609      }
610
611      NextChar = peekNextChar(I + 1);
612    }
613
614    // Check for whitespace after the directive.  If there is no whitespace,
615    // then we do not recognize it as a preprocessing directive.
616    if (Match) {
617      tgtok::TokKind Kind = PreprocessorDirs[ID].Kind;
618
619      // New line and EOF may follow only #else/#endif.  It will be reported
620      // as an error for #ifdef/#define after the call to prepLexMacroName().
621      if (NextChar == ' ' || NextChar == '\t' || NextChar == EOF ||
622          NextChar == '\n' ||
623          // It looks like TableGen does not support '\r' as the actual
624          // carriage return, e.g. getNextChar() treats a single '\r'
625          // as '\n'.  So we do the same here.
626          NextChar == '\r')
627        return Kind;
628
629      // Allow comments after some directives, e.g.:
630      //     #else// OR #else/**/
631      //     #endif// OR #endif/**/
632      //
633      // Note that we do allow comments after #ifdef/#define here, e.g.
634      //     #ifdef/**/ AND #ifdef//
635      //     #define/**/ AND #define//
636      //
637      // These cases will be reported as incorrect after calling
638      // prepLexMacroName().  We could have supported C-style comments
639      // after #ifdef/#define, but this would complicate the code
640      // for little benefit.
641      if (NextChar == '/') {
642        NextChar = peekNextChar(I + 1);
643
644        if (NextChar == '*' || NextChar == '/')
645          return Kind;
646
647        // Pretend that we do not recognize the directive.
648      }
649    }
650  }
651
652  return tgtok::Error;
653}
654
655bool TGLexer::prepEatPreprocessorDirective(tgtok::TokKind Kind) {
656  TokStart = CurPtr;
657
658  for (unsigned ID = 0; ID < llvm::array_lengthof(PreprocessorDirs); ++ID)
659    if (PreprocessorDirs[ID].Kind == Kind) {
660      // Advance CurPtr to the end of the preprocessing word.
661      CurPtr += strlen(PreprocessorDirs[ID].Word);
662      return true;
663    }
664
665  PrintFatalError("Unsupported preprocessing token in "
666                  "prepEatPreprocessorDirective()");
667  return false;
668}
669
670tgtok::TokKind TGLexer::lexPreprocessor(
671    tgtok::TokKind Kind, bool ReturnNextLiveToken) {
672
673  // We must be looking at a preprocessing directive.  Eat it!
674  if (!prepEatPreprocessorDirective(Kind))
675    PrintFatalError("lexPreprocessor() called for unknown "
676                    "preprocessor directive");
677
678  if (Kind == tgtok::Ifdef || Kind == tgtok::Ifndef) {
679    StringRef MacroName = prepLexMacroName();
680    StringRef IfTokName = Kind == tgtok::Ifdef ? "#ifdef" : "#ifndef";
681    if (MacroName.empty())
682      return ReturnError(TokStart, "Expected macro name after " + IfTokName);
683
684    bool MacroIsDefined = DefinedMacros.count(MacroName) != 0;
685
686    // Canonicalize ifndef to ifdef equivalent
687    if (Kind == tgtok::Ifndef) {
688      MacroIsDefined = !MacroIsDefined;
689      Kind = tgtok::Ifdef;
690    }
691
692    // Regardless of whether we are processing tokens or not,
693    // we put the #ifdef control on stack.
694    PrepIncludeStack.back()->push_back(
695        {Kind, MacroIsDefined, SMLoc::getFromPointer(TokStart)});
696
697    if (!prepSkipDirectiveEnd())
698      return ReturnError(CurPtr, "Only comments are supported after " +
699                                     IfTokName + " NAME");
700
701    // If we were not processing tokens before this #ifdef,
702    // then just return back to the lines skipping code.
703    if (!ReturnNextLiveToken)
704      return Kind;
705
706    // If we were processing tokens before this #ifdef,
707    // and the macro is defined, then just return the next token.
708    if (MacroIsDefined)
709      return LexToken();
710
711    // We were processing tokens before this #ifdef, and the macro
712    // is not defined, so we have to start skipping the lines.
713    // If the skipping is successful, it will return the token following
714    // either #else or #endif corresponding to this #ifdef.
715    if (prepSkipRegion(ReturnNextLiveToken))
716      return LexToken();
717
718    return tgtok::Error;
719  } else if (Kind == tgtok::Else) {
720    // Check if this #else is correct before calling prepSkipDirectiveEnd(),
721    // which will move CurPtr away from the beginning of #else.
722    if (PrepIncludeStack.back()->empty())
723      return ReturnError(TokStart, "#else without #ifdef or #ifndef");
724
725    PreprocessorControlDesc IfdefEntry = PrepIncludeStack.back()->back();
726
727    if (IfdefEntry.Kind != tgtok::Ifdef) {
728      PrintError(TokStart, "double #else");
729      return ReturnError(IfdefEntry.SrcPos, "Previous #else is here");
730    }
731
732    // Replace the corresponding #ifdef's control with its negation
733    // on the control stack.
734    PrepIncludeStack.back()->pop_back();
735    PrepIncludeStack.back()->push_back(
736        {Kind, !IfdefEntry.IsDefined, SMLoc::getFromPointer(TokStart)});
737
738    if (!prepSkipDirectiveEnd())
739      return ReturnError(CurPtr, "Only comments are supported after #else");
740
741    // If we were processing tokens before this #else,
742    // we have to start skipping lines until the matching #endif.
743    if (ReturnNextLiveToken) {
744      if (prepSkipRegion(ReturnNextLiveToken))
745        return LexToken();
746
747      return tgtok::Error;
748    }
749
750    // Return to the lines skipping code.
751    return Kind;
752  } else if (Kind == tgtok::Endif) {
753    // Check if this #endif is correct before calling prepSkipDirectiveEnd(),
754    // which will move CurPtr away from the beginning of #endif.
755    if (PrepIncludeStack.back()->empty())
756      return ReturnError(TokStart, "#endif without #ifdef");
757
758    auto &IfdefOrElseEntry = PrepIncludeStack.back()->back();
759
760    if (IfdefOrElseEntry.Kind != tgtok::Ifdef &&
761        IfdefOrElseEntry.Kind != tgtok::Else) {
762      PrintFatalError("Invalid preprocessor control on the stack");
763      return tgtok::Error;
764    }
765
766    if (!prepSkipDirectiveEnd())
767      return ReturnError(CurPtr, "Only comments are supported after #endif");
768
769    PrepIncludeStack.back()->pop_back();
770
771    // If we were processing tokens before this #endif, then
772    // we should continue it.
773    if (ReturnNextLiveToken) {
774      return LexToken();
775    }
776
777    // Return to the lines skipping code.
778    return Kind;
779  } else if (Kind == tgtok::Define) {
780    StringRef MacroName = prepLexMacroName();
781    if (MacroName.empty())
782      return ReturnError(TokStart, "Expected macro name after #define");
783
784    if (!DefinedMacros.insert(MacroName).second)
785      PrintWarning(getLoc(),
786                   "Duplicate definition of macro: " + Twine(MacroName));
787
788    if (!prepSkipDirectiveEnd())
789      return ReturnError(CurPtr,
790                         "Only comments are supported after #define NAME");
791
792    if (!ReturnNextLiveToken) {
793      PrintFatalError("#define must be ignored during the lines skipping");
794      return tgtok::Error;
795    }
796
797    return LexToken();
798  }
799
800  PrintFatalError("Preprocessing directive is not supported");
801  return tgtok::Error;
802}
803
804bool TGLexer::prepSkipRegion(bool MustNeverBeFalse) {
805  if (!MustNeverBeFalse)
806    PrintFatalError("Invalid recursion.");
807
808  do {
809    // Skip all symbols to the line end.
810    prepSkipToLineEnd();
811
812    // Find the first non-whitespace symbol in the next line(s).
813    if (!prepSkipLineBegin())
814      return false;
815
816    // If the first non-blank/comment symbol on the line is '#',
817    // it may be a start of preprocessing directive.
818    //
819    // If it is not '#' just go to the next line.
820    if (*CurPtr == '#')
821      ++CurPtr;
822    else
823      continue;
824
825    tgtok::TokKind Kind = prepIsDirective();
826
827    // If we did not find a preprocessing directive or it is #define,
828    // then just skip to the next line.  We do not have to do anything
829    // for #define in the line-skipping mode.
830    if (Kind == tgtok::Error || Kind == tgtok::Define)
831      continue;
832
833    tgtok::TokKind ProcessedKind = lexPreprocessor(Kind, false);
834
835    // If lexPreprocessor() encountered an error during lexing this
836    // preprocessor idiom, then return false to the calling lexPreprocessor().
837    // This will force tgtok::Error to be returned to the tokens processing.
838    if (ProcessedKind == tgtok::Error)
839      return false;
840
841    if (Kind != ProcessedKind)
842      PrintFatalError("prepIsDirective() and lexPreprocessor() "
843                      "returned different token kinds");
844
845    // If this preprocessing directive enables tokens processing,
846    // then return to the lexPreprocessor() and get to the next token.
847    // We can move from line-skipping mode to processing tokens only
848    // due to #else or #endif.
849    if (prepIsProcessingEnabled()) {
850      if (Kind != tgtok::Else && Kind != tgtok::Endif) {
851        PrintFatalError("Tokens processing was enabled by an unexpected "
852                        "preprocessing directive");
853        return false;
854      }
855
856      return true;
857    }
858  } while (CurPtr != CurBuf.end());
859
860  // We have reached the end of the file, but never left the lines-skipping
861  // mode.  This means there is no matching #endif.
862  prepReportPreprocessorStackError();
863  return false;
864}
865
866StringRef TGLexer::prepLexMacroName() {
867  // Skip whitespaces between the preprocessing directive and the macro name.
868  while (*CurPtr == ' ' || *CurPtr == '\t')
869    ++CurPtr;
870
871  TokStart = CurPtr;
872  // Macro names start with [a-zA-Z_].
873  if (*CurPtr != '_' && !isalpha(*CurPtr))
874    return "";
875
876  // Match the rest of the identifier regex: [0-9a-zA-Z_]*
877  while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
878    ++CurPtr;
879
880  return StringRef(TokStart, CurPtr - TokStart);
881}
882
883bool TGLexer::prepSkipLineBegin() {
884  while (CurPtr != CurBuf.end()) {
885    switch (*CurPtr) {
886    case ' ':
887    case '\t':
888    case '\n':
889    case '\r':
890      break;
891
892    case '/': {
893      int NextChar = peekNextChar(1);
894      if (NextChar == '*') {
895        // Skip C-style comment.
896        // Note that we do not care about skipping the C++-style comments.
897        // If the line contains "//", it may not contain any processable
898        // preprocessing directive.  Just return CurPtr pointing to
899        // the first '/' in this case.  We also do not care about
900        // incorrect symbols after the first '/' - we are in lines-skipping
901        // mode, so incorrect code is allowed to some extent.
902
903        // Set TokStart to the beginning of the comment to enable proper
904        // diagnostic printing in case of error in SkipCComment().
905        TokStart = CurPtr;
906
907        // CurPtr must point to '*' before call to SkipCComment().
908        ++CurPtr;
909        if (SkipCComment())
910          return false;
911      } else {
912        // CurPtr points to the non-whitespace '/'.
913        return true;
914      }
915
916      // We must not increment CurPtr after the comment was lexed.
917      continue;
918    }
919
920    default:
921      return true;
922    }
923
924    ++CurPtr;
925  }
926
927  // We have reached the end of the file.  Return to the lines skipping
928  // code, and allow it to handle the EOF as needed.
929  return true;
930}
931
932bool TGLexer::prepSkipDirectiveEnd() {
933  while (CurPtr != CurBuf.end()) {
934    switch (*CurPtr) {
935    case ' ':
936    case '\t':
937      break;
938
939    case '\n':
940    case '\r':
941      return true;
942
943    case '/': {
944      int NextChar = peekNextChar(1);
945      if (NextChar == '/') {
946        // Skip C++-style comment.
947        // We may just return true now, but let's skip to the line/buffer end
948        // to simplify the method specification.
949        ++CurPtr;
950        SkipBCPLComment();
951      } else if (NextChar == '*') {
952        // When we are skipping C-style comment at the end of a preprocessing
953        // directive, we can skip several lines.  If any meaningful TD token
954        // follows the end of the C-style comment on the same line, it will
955        // be considered as an invalid usage of TD token.
956        // For example, we want to forbid usages like this one:
957        //     #define MACRO class Class {}
958        // But with C-style comments we also disallow the following:
959        //     #define MACRO /* This macro is used
960        //                      to ... */ class Class {}
961        // One can argue that this should be allowed, but it does not seem
962        // to be worth of the complication.  Moreover, this matches
963        // the C preprocessor behavior.
964
965        // Set TokStart to the beginning of the comment to enable proper
966        // diagnostic printer in case of error in SkipCComment().
967        TokStart = CurPtr;
968        ++CurPtr;
969        if (SkipCComment())
970          return false;
971      } else {
972        TokStart = CurPtr;
973        PrintError(CurPtr, "Unexpected character");
974        return false;
975      }
976
977      // We must not increment CurPtr after the comment was lexed.
978      continue;
979    }
980
981    default:
982      // Do not allow any non-whitespaces after the directive.
983      TokStart = CurPtr;
984      return false;
985    }
986
987    ++CurPtr;
988  }
989
990  return true;
991}
992
993void TGLexer::prepSkipToLineEnd() {
994  while (*CurPtr != '\n' && *CurPtr != '\r' && CurPtr != CurBuf.end())
995    ++CurPtr;
996}
997
998bool TGLexer::prepIsProcessingEnabled() {
999  for (auto I = PrepIncludeStack.back()->rbegin(),
1000            E = PrepIncludeStack.back()->rend();
1001       I != E; ++I) {
1002    if (!I->IsDefined)
1003      return false;
1004  }
1005
1006  return true;
1007}
1008
1009void TGLexer::prepReportPreprocessorStackError() {
1010  if (PrepIncludeStack.back()->empty())
1011    PrintFatalError("prepReportPreprocessorStackError() called with "
1012                    "empty control stack");
1013
1014  auto &PrepControl = PrepIncludeStack.back()->back();
1015  PrintError(CurBuf.end(), "Reached EOF without matching #endif");
1016  PrintError(PrepControl.SrcPos, "The latest preprocessor control is here");
1017
1018  TokStart = CurPtr;
1019}
1020