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