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