TGLexer.cpp 31 KB

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