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