TGLexer.cpp 31 KB

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