TGLexer.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. //===- TGLexer.h - Lexer for TableGen Files ---------------------*- C++ -*-===//
  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. // This class represents the Lexer for tablegen files.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_LIB_TABLEGEN_TGLEXER_H
  13. #define LLVM_LIB_TABLEGEN_TGLEXER_H
  14. #include "llvm/ADT/StringRef.h"
  15. #include "llvm/ADT/StringSet.h"
  16. #include "llvm/Support/DataTypes.h"
  17. #include "llvm/Support/SMLoc.h"
  18. #include <cassert>
  19. #include <memory>
  20. #include <set>
  21. #include <string>
  22. #include <vector>
  23. namespace llvm {
  24. template <typename T> class ArrayRef;
  25. class SourceMgr;
  26. class Twine;
  27. namespace tgtok {
  28. enum TokKind {
  29. // Markers
  30. Eof, Error,
  31. // Tokens with no info.
  32. minus, plus, // - +
  33. l_square, r_square, // [ ]
  34. l_brace, r_brace, // { }
  35. l_paren, r_paren, // ( )
  36. less, greater, // < >
  37. colon, semi, // : ;
  38. comma, dot, // , .
  39. equal, question, // = ?
  40. paste, // #
  41. dotdotdot, // ...
  42. // Reserved keywords. ('ElseKW' is named to distinguish it from the
  43. // existing 'Else' that means the preprocessor #else.)
  44. Assert, Bit, Bits, Class, Code, Dag, Def, Defm, Defset, Defvar, ElseKW,
  45. FalseKW, Field, Foreach, If, In, Include, Int, Let, List, MultiClass,
  46. String, Then, TrueKW,
  47. // Bang operators.
  48. XConcat, XADD, XSUB, XMUL, XNOT, XAND, XOR, XXOR, XSRA, XSRL, XSHL,
  49. XListConcat, XListSplat, XStrConcat, XInterleave, XSubstr, XCast,
  50. XSubst, XForEach, XFilter, XFoldl, XHead, XTail, XSize, XEmpty, XIf,
  51. XCond, XEq, XIsA, XDag, XNe, XLe, XLt, XGe, XGt, XSetDagOp, XGetDagOp,
  52. // Boolean literals.
  53. TrueVal, FalseVal,
  54. // Integer value.
  55. IntVal,
  56. // Binary constant. Note that these are sized according to the number of
  57. // bits given.
  58. BinaryIntVal,
  59. // String valued tokens.
  60. Id, StrVal, VarName, CodeFragment,
  61. // Preprocessing tokens for internal usage by the lexer.
  62. // They are never returned as a result of Lex().
  63. Ifdef, Ifndef, Else, Endif, Define
  64. };
  65. }
  66. /// TGLexer - TableGen Lexer class.
  67. class TGLexer {
  68. SourceMgr &SrcMgr;
  69. const char *CurPtr = nullptr;
  70. StringRef CurBuf;
  71. // Information about the current token.
  72. const char *TokStart = nullptr;
  73. tgtok::TokKind CurCode = tgtok::TokKind::Eof;
  74. std::string CurStrVal; // This is valid for Id, StrVal, VarName, CodeFragment
  75. int64_t CurIntVal = 0; // This is valid for IntVal.
  76. /// CurBuffer - This is the current buffer index we're lexing from as managed
  77. /// by the SourceMgr object.
  78. unsigned CurBuffer = 0;
  79. public:
  80. typedef std::set<std::string> DependenciesSetTy;
  81. private:
  82. /// Dependencies - This is the list of all included files.
  83. DependenciesSetTy Dependencies;
  84. public:
  85. TGLexer(SourceMgr &SrcMgr, ArrayRef<std::string> Macros);
  86. tgtok::TokKind Lex() {
  87. return CurCode = LexToken(CurPtr == CurBuf.begin());
  88. }
  89. const DependenciesSetTy &getDependencies() const {
  90. return Dependencies;
  91. }
  92. tgtok::TokKind getCode() const { return CurCode; }
  93. const std::string &getCurStrVal() const {
  94. assert((CurCode == tgtok::Id || CurCode == tgtok::StrVal ||
  95. CurCode == tgtok::VarName || CurCode == tgtok::CodeFragment) &&
  96. "This token doesn't have a string value");
  97. return CurStrVal;
  98. }
  99. int64_t getCurIntVal() const {
  100. assert(CurCode == tgtok::IntVal && "This token isn't an integer");
  101. return CurIntVal;
  102. }
  103. std::pair<int64_t, unsigned> getCurBinaryIntVal() const {
  104. assert(CurCode == tgtok::BinaryIntVal &&
  105. "This token isn't a binary integer");
  106. return std::make_pair(CurIntVal, (CurPtr - TokStart)-2);
  107. }
  108. SMLoc getLoc() const;
  109. private:
  110. /// LexToken - Read the next token and return its code.
  111. tgtok::TokKind LexToken(bool FileOrLineStart = false);
  112. tgtok::TokKind ReturnError(SMLoc Loc, const Twine &Msg);
  113. tgtok::TokKind ReturnError(const char *Loc, const Twine &Msg);
  114. int getNextChar();
  115. int peekNextChar(int Index) const;
  116. void SkipBCPLComment();
  117. bool SkipCComment();
  118. tgtok::TokKind LexIdentifier();
  119. bool LexInclude();
  120. tgtok::TokKind LexString();
  121. tgtok::TokKind LexVarName();
  122. tgtok::TokKind LexNumber();
  123. tgtok::TokKind LexBracket();
  124. tgtok::TokKind LexExclaim();
  125. // Process EOF encountered in LexToken().
  126. // If EOF is met in an include file, then the method will update
  127. // CurPtr, CurBuf and preprocessing include stack, and return true.
  128. // If EOF is met in the top-level file, then the method will
  129. // update and check the preprocessing include stack, and return false.
  130. bool processEOF();
  131. // *** Structures and methods for preprocessing support ***
  132. // A set of macro names that are defined either via command line or
  133. // by using:
  134. // #define NAME
  135. StringSet<> DefinedMacros;
  136. // Each of #ifdef and #else directives has a descriptor associated
  137. // with it.
  138. //
  139. // An ordered list of preprocessing controls defined by #ifdef/#else
  140. // directives that are in effect currently is called preprocessing
  141. // control stack. It is represented as a vector of PreprocessorControlDesc's.
  142. //
  143. // The control stack is updated according to the following rules:
  144. //
  145. // For each #ifdef we add an element to the control stack.
  146. // For each #else we replace the top element with a descriptor
  147. // with an inverted IsDefined value.
  148. // For each #endif we pop the top element from the control stack.
  149. //
  150. // When CurPtr reaches the current buffer's end, the control stack
  151. // must be empty, i.e. #ifdef and the corresponding #endif
  152. // must be located in the same file.
  153. struct PreprocessorControlDesc {
  154. // Either tgtok::Ifdef or tgtok::Else.
  155. tgtok::TokKind Kind;
  156. // True, if the condition for this directive is true, false - otherwise.
  157. // Examples:
  158. // #ifdef NAME : true, if NAME is defined, false - otherwise.
  159. // ...
  160. // #else : false, if NAME is defined, true - otherwise.
  161. bool IsDefined;
  162. // Pointer into CurBuf to the beginning of the preprocessing directive
  163. // word, e.g.:
  164. // #ifdef NAME
  165. // ^ - SrcPos
  166. SMLoc SrcPos;
  167. };
  168. // We want to disallow code like this:
  169. // file1.td:
  170. // #define NAME
  171. // #ifdef NAME
  172. // include "file2.td"
  173. // EOF
  174. // file2.td:
  175. // #endif
  176. // EOF
  177. //
  178. // To do this, we clear the preprocessing control stack on entry
  179. // to each of the included file. PrepIncludeStack is used to store
  180. // preprocessing control stacks for the current file and all its
  181. // parent files. The back() element is the preprocessing control
  182. // stack for the current file.
  183. std::vector<std::unique_ptr<std::vector<PreprocessorControlDesc>>>
  184. PrepIncludeStack;
  185. // Validate that the current preprocessing control stack is empty,
  186. // since we are about to exit a file, and pop the include stack.
  187. //
  188. // If IncludeStackMustBeEmpty is true, the include stack must be empty
  189. // after the popping, otherwise, the include stack must not be empty
  190. // after the popping. Basically, the include stack must be empty
  191. // only if we exit the "top-level" file (i.e. finish lexing).
  192. //
  193. // The method returns false, if the current preprocessing control stack
  194. // is not empty (e.g. there is an unterminated #ifdef/#else),
  195. // true - otherwise.
  196. bool prepExitInclude(bool IncludeStackMustBeEmpty);
  197. // Look ahead for a preprocessing directive starting from CurPtr. The caller
  198. // must only call this method, if *(CurPtr - 1) is '#'. If the method matches
  199. // a preprocessing directive word followed by a whitespace, then it returns
  200. // one of the internal token kinds, i.e. Ifdef, Else, Endif, Define.
  201. //
  202. // CurPtr is not adjusted by this method.
  203. tgtok::TokKind prepIsDirective() const;
  204. // Given a preprocessing token kind, adjusts CurPtr to the end
  205. // of the preprocessing directive word. Returns true, unless
  206. // an unsupported token kind is passed in.
  207. //
  208. // We use look-ahead prepIsDirective() and prepEatPreprocessorDirective()
  209. // to avoid adjusting CurPtr before we are sure that '#' is followed
  210. // by a preprocessing directive. If it is not, then we fall back to
  211. // tgtok::paste interpretation of '#'.
  212. bool prepEatPreprocessorDirective(tgtok::TokKind Kind);
  213. // The main "exit" point from the token parsing to preprocessor.
  214. //
  215. // The method is called for CurPtr, when prepIsDirective() returns
  216. // true. The first parameter matches the result of prepIsDirective(),
  217. // denoting the actual preprocessor directive to be processed.
  218. //
  219. // If the preprocessing directive disables the tokens processing, e.g.:
  220. // #ifdef NAME // NAME is undefined
  221. // then lexPreprocessor() enters the lines-skipping mode.
  222. // In this mode, it does not parse any tokens, because the code under
  223. // the #ifdef may not even be a correct tablegen code. The preprocessor
  224. // looks for lines containing other preprocessing directives, which
  225. // may be prepended with whitespaces and C-style comments. If the line
  226. // does not contain a preprocessing directive, it is skipped completely.
  227. // Otherwise, the preprocessing directive is processed by recursively
  228. // calling lexPreprocessor(). The processing of the encountered
  229. // preprocessing directives includes updating preprocessing control stack
  230. // and adding new macros into DefinedMacros set.
  231. //
  232. // The second parameter controls whether lexPreprocessor() is called from
  233. // LexToken() (true) or recursively from lexPreprocessor() (false).
  234. //
  235. // If ReturnNextLiveToken is true, the method returns the next
  236. // LEX token following the current directive or following the end
  237. // of the disabled preprocessing region corresponding to this directive.
  238. // If ReturnNextLiveToken is false, the method returns the first parameter,
  239. // unless there were errors encountered in the disabled preprocessing
  240. // region - in this case, it returns tgtok::Error.
  241. tgtok::TokKind lexPreprocessor(tgtok::TokKind Kind,
  242. bool ReturnNextLiveToken = true);
  243. // Worker method for lexPreprocessor() to skip lines after some
  244. // preprocessing directive up to the buffer end or to the directive
  245. // that re-enables token processing. The method returns true
  246. // upon processing the next directive that re-enables tokens
  247. // processing. False is returned if an error was encountered.
  248. //
  249. // Note that prepSkipRegion() calls lexPreprocessor() to process
  250. // encountered preprocessing directives. In this case, the second
  251. // parameter to lexPreprocessor() is set to false. Being passed
  252. // false ReturnNextLiveToken, lexPreprocessor() must never call
  253. // prepSkipRegion(). We assert this by passing ReturnNextLiveToken
  254. // to prepSkipRegion() and checking that it is never set to false.
  255. bool prepSkipRegion(bool MustNeverBeFalse);
  256. // Lex name of the macro after either #ifdef or #define. We could have used
  257. // LexIdentifier(), but it has special handling of "include" word, which
  258. // could result in awkward diagnostic errors. Consider:
  259. // ----
  260. // #ifdef include
  261. // class ...
  262. // ----
  263. // LexIdentifier() will engage LexInclude(), which will complain about
  264. // missing file with name "class". Instead, prepLexMacroName() will treat
  265. // "include" as a normal macro name.
  266. //
  267. // On entry, CurPtr points to the end of a preprocessing directive word.
  268. // The method allows for whitespaces between the preprocessing directive
  269. // and the macro name. The allowed whitespaces are ' ' and '\t'.
  270. //
  271. // If the first non-whitespace symbol after the preprocessing directive
  272. // is a valid start symbol for an identifier (i.e. [a-zA-Z_]), then
  273. // the method updates TokStart to the position of the first non-whitespace
  274. // symbol, sets CurPtr to the position of the macro name's last symbol,
  275. // and returns a string reference to the macro name. Otherwise,
  276. // TokStart is set to the first non-whitespace symbol after the preprocessing
  277. // directive, and the method returns an empty string reference.
  278. //
  279. // In all cases, TokStart may be used to point to the word following
  280. // the preprocessing directive.
  281. StringRef prepLexMacroName();
  282. // Skip any whitespaces starting from CurPtr. The method is used
  283. // only in the lines-skipping mode to find the first non-whitespace
  284. // symbol after or at CurPtr. Allowed whitespaces are ' ', '\t', '\n'
  285. // and '\r'. The method skips C-style comments as well, because
  286. // it is used to find the beginning of the preprocessing directive.
  287. // If we do not handle C-style comments the following code would
  288. // result in incorrect detection of a preprocessing directive:
  289. // /*
  290. // #ifdef NAME
  291. // */
  292. // As long as we skip C-style comments, the following code is correctly
  293. // recognized as a preprocessing directive:
  294. // /* first line comment
  295. // second line comment */ #ifdef NAME
  296. //
  297. // The method returns true upon reaching the first non-whitespace symbol
  298. // or EOF, CurPtr is set to point to this symbol. The method returns false,
  299. // if an error occured during skipping of a C-style comment.
  300. bool prepSkipLineBegin();
  301. // Skip any whitespaces or comments after a preprocessing directive.
  302. // The method returns true upon reaching either end of the line
  303. // or end of the file. If there is a multiline C-style comment
  304. // after the preprocessing directive, the method skips
  305. // the comment, so the final CurPtr may point to one of the next lines.
  306. // The method returns false, if an error occured during skipping
  307. // C- or C++-style comment, or a non-whitespace symbol appears
  308. // after the preprocessing directive.
  309. //
  310. // The method maybe called both during lines-skipping and tokens
  311. // processing. It actually verifies that only whitespaces or/and
  312. // comments follow a preprocessing directive.
  313. //
  314. // After the execution of this mehod, CurPtr points either to new line
  315. // symbol, buffer end or non-whitespace symbol following the preprocesing
  316. // directive.
  317. bool prepSkipDirectiveEnd();
  318. // Skip all symbols to the end of the line/file.
  319. // The method adjusts CurPtr, so that it points to either new line
  320. // symbol in the current line or the buffer end.
  321. void prepSkipToLineEnd();
  322. // Return true, if the current preprocessor control stack is such that
  323. // we should allow lexer to process the next token, false - otherwise.
  324. //
  325. // In particular, the method returns true, if all the #ifdef/#else
  326. // controls on the stack have their IsDefined member set to true.
  327. bool prepIsProcessingEnabled();
  328. // Report an error, if we reach EOF with non-empty preprocessing control
  329. // stack. This means there is no matching #endif for the previous
  330. // #ifdef/#else.
  331. void prepReportPreprocessorStackError();
  332. };
  333. } // end namespace llvm
  334. #endif