TGLexer.cpp 31 KB

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