tokenized_buffer.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef LEXER_TOKENIZED_BUFFER_H_
  5. #define LEXER_TOKENIZED_BUFFER_H_
  6. #include <cstdint>
  7. #include <iterator>
  8. #include "diagnostics/diagnostic_emitter.h"
  9. #include "lexer/token_kind.h"
  10. #include "llvm/ADT/APInt.h"
  11. #include "llvm/ADT/DenseMap.h"
  12. #include "llvm/ADT/Optional.h"
  13. #include "llvm/ADT/SmallVector.h"
  14. #include "llvm/ADT/StringRef.h"
  15. #include "llvm/ADT/iterator.h"
  16. #include "llvm/ADT/iterator_range.h"
  17. #include "source/source_buffer.h"
  18. namespace Carbon {
  19. // A buffer of tokenized Carbon source code.
  20. //
  21. // This is constructed by lexing the source code text into a series of tokens.
  22. // The buffer provides lightweight handles to tokens and other lexed entities,
  23. // as well as iterations to walk the sequence of tokens found in the buffer.
  24. //
  25. // Lexing errors result in a potentially incomplete sequence of tokens and
  26. // `HasError` returning true.
  27. class TokenizedBuffer {
  28. public:
  29. // A lightweight handle to a lexed token in a `TokenizedBuffer`.
  30. //
  31. // `Token` objects are designed to be passed by value, not reference or
  32. // pointer. They are also designed to be small and efficient to store in data
  33. // structures.
  34. //
  35. // `Token` objects from the same `TokenizedBuffer` can be compared with each
  36. // other, both for being the same token within the buffer, and to establish
  37. // relative position within the token stream that has been lexed out of the
  38. // buffer.
  39. //
  40. // All other APIs to query a `Token` are on the `TokenizedBuffer`.
  41. class Token {
  42. public:
  43. Token() = default;
  44. auto operator==(const Token& rhs) const -> bool {
  45. return index == rhs.index;
  46. }
  47. auto operator!=(const Token& rhs) const -> bool {
  48. return index != rhs.index;
  49. }
  50. auto operator<(const Token& rhs) const -> bool { return index < rhs.index; }
  51. auto operator<=(const Token& rhs) const -> bool {
  52. return index <= rhs.index;
  53. }
  54. auto operator>(const Token& rhs) const -> bool { return index > rhs.index; }
  55. auto operator>=(const Token& rhs) const -> bool {
  56. return index >= rhs.index;
  57. }
  58. private:
  59. friend class TokenizedBuffer;
  60. explicit Token(int index) : index(index) {}
  61. int32_t index;
  62. };
  63. // A lightweight handle to a lexed line in a `TokenizedBuffer`.
  64. //
  65. // `Line` objects are designed to be passed by value, not reference or
  66. // pointer. They are also designed to be small and efficient to store in data
  67. // structures.
  68. //
  69. // Each `Line` object refers to a specific line in the source code that was
  70. // lexed. They can be compared directly to establish that they refer to the
  71. // same line or the relative position of different lines within the source.
  72. //
  73. // All other APIs to query a `Line` are on the `TokenizedBuffer`.
  74. class Line {
  75. public:
  76. Line() = default;
  77. auto operator==(const Line& rhs) const -> bool {
  78. return index == rhs.index;
  79. }
  80. auto operator!=(const Line& rhs) const -> bool {
  81. return index != rhs.index;
  82. }
  83. auto operator<(const Line& rhs) const -> bool { return index < rhs.index; }
  84. auto operator<=(const Line& rhs) const -> bool {
  85. return index <= rhs.index;
  86. }
  87. auto operator>(const Line& rhs) const -> bool { return index > rhs.index; }
  88. auto operator>=(const Line& rhs) const -> bool {
  89. return index >= rhs.index;
  90. }
  91. private:
  92. friend class TokenizedBuffer;
  93. explicit Line(int index) : index(index) {}
  94. int32_t index;
  95. };
  96. // A lightweight handle to a lexed identifier in a `TokenizedBuffer`.
  97. //
  98. // `Identifier` objects are designed to be passed by value, not reference or
  99. // pointer. They are also designed to be small and efficient to store in data
  100. // structures.
  101. //
  102. // Each identifier lexed is canonicalized to a single entry in the identifier
  103. // table. `Identifier` objects will compare equal if they refer to the same
  104. // identifier spelling. Where the identifier was written is not preserved.
  105. //
  106. // All other APIs to query a `Identifier` are on the `TokenizedBuffer`.
  107. class Identifier {
  108. public:
  109. Identifier() = default;
  110. // Most normal APIs are provided by the `TokenizedBuffer`, we just support
  111. // basic comparison operations.
  112. auto operator==(const Identifier& rhs) const -> bool {
  113. return index == rhs.index;
  114. }
  115. auto operator!=(const Identifier& rhs) const -> bool {
  116. return index != rhs.index;
  117. }
  118. private:
  119. friend class TokenizedBuffer;
  120. explicit Identifier(int index) : index(index) {}
  121. int32_t index;
  122. };
  123. // Random-access iterator over tokens within the buffer.
  124. class TokenIterator
  125. : public llvm::iterator_facade_base<
  126. TokenIterator, std::random_access_iterator_tag, Token, int> {
  127. public:
  128. TokenIterator() = default;
  129. explicit TokenIterator(Token token) : token(token) {}
  130. auto operator==(const TokenIterator& rhs) const -> bool {
  131. return token == rhs.token;
  132. }
  133. auto operator<(const TokenIterator& rhs) const -> bool {
  134. return token < rhs.token;
  135. }
  136. auto operator*() const -> const Token& { return token; }
  137. auto operator*() -> Token& { return token; }
  138. auto operator-(const TokenIterator& rhs) const -> int {
  139. return token.index - rhs.token.index;
  140. }
  141. auto operator+=(int n) -> TokenIterator& {
  142. token.index += n;
  143. return *this;
  144. }
  145. auto operator-=(int n) -> TokenIterator& {
  146. token.index -= n;
  147. return *this;
  148. }
  149. private:
  150. friend class TokenizedBuffer;
  151. Token token;
  152. };
  153. // Lexes a buffer of source code into a tokenized buffer.
  154. //
  155. // The provided source buffer must outlive any returned `TokenizedBuffer`
  156. // which will refer into the source.
  157. //
  158. // FIXME: Need to pass in some diagnostic machinery to report the details of
  159. // the error! Right now it prints to stderr.
  160. static auto Lex(SourceBuffer& source, DiagnosticEmitter& emitter)
  161. -> TokenizedBuffer;
  162. // Returns true if the buffer has errors that are detectable at lexing time.
  163. [[nodiscard]] auto HasErrors() const -> bool { return has_errors; }
  164. [[nodiscard]] auto Tokens() const -> llvm::iterator_range<TokenIterator> {
  165. return llvm::make_range(TokenIterator(Token(0)),
  166. TokenIterator(Token(token_infos.size())));
  167. }
  168. [[nodiscard]] auto Size() const -> int { return token_infos.size(); }
  169. [[nodiscard]] auto GetKind(Token token) const -> TokenKind;
  170. [[nodiscard]] auto GetLine(Token token) const -> Line;
  171. // Returns the 1-based line number.
  172. [[nodiscard]] auto GetLineNumber(Token token) const -> int;
  173. // Returns the 1-based column number.
  174. [[nodiscard]] auto GetColumnNumber(Token token) const -> int;
  175. // Returns the source text lexed into this token.
  176. [[nodiscard]] auto GetTokenText(Token token) const -> llvm::StringRef;
  177. // Returns the identifier associated with this token. The token kind must be
  178. // an `Identifier`.
  179. [[nodiscard]] auto GetIdentifier(Token token) const -> Identifier;
  180. // Returns the value of an `IntegerLiteral()` token.
  181. auto GetIntegerLiteral(Token token) const -> llvm::APInt;
  182. // Returns the closing token matched with the given opening token.
  183. //
  184. // The given token must be an opening token kind.
  185. [[nodiscard]] auto GetMatchedClosingToken(Token opening_token) const -> Token;
  186. // Returns the opening token matched with the given closing token.
  187. //
  188. // The given token must be a closing token kind.
  189. [[nodiscard]] auto GetMatchedOpeningToken(Token closing_token) const -> Token;
  190. // Returns whether the token was created as part of an error recovery effort.
  191. //
  192. // For example, a closing paren inserted to match an unmatched paren.
  193. [[nodiscard]] auto IsRecoveryToken(Token token) const -> bool;
  194. // Returns the 1-based line number.
  195. [[nodiscard]] auto GetLineNumber(Line line) const -> int;
  196. // Returns the 1-based indentation column number.
  197. [[nodiscard]] auto GetIndentColumnNumber(Line line) const -> int;
  198. // Returns the text for an identifier.
  199. [[nodiscard]] auto GetIdentifierText(Identifier id) const -> llvm::StringRef;
  200. // Prints a description of the tokenized stream to the provided `raw_ostream`.
  201. //
  202. // It prints one line of information for each token in the buffer, including
  203. // the kind of token, where it occurs within the source file, indentation for
  204. // the associated line, the spelling of the token in source, and any
  205. // additional information tracked such as which unique identifier it is or any
  206. // matched grouping token.
  207. //
  208. // Each line is formatted as a YAML record:
  209. //
  210. // clang-format off
  211. // ```
  212. // token: { index: 0, kind: 'Semi', line: 1, column: 1, indent: 1, spelling: ';' }
  213. // ```
  214. // clang-format on
  215. //
  216. // This can be parsed as YAML using tools like `python-yq` combined with `jq`
  217. // on the command line. The format is also reasonably amenable to other
  218. // line-oriented shell tools from `grep` to `awk`.
  219. auto Print(llvm::raw_ostream& output_stream) const -> void;
  220. // Prints a description of a single token. See `print` for details on the
  221. // format.
  222. auto PrintToken(llvm::raw_ostream& output_stream, Token token) const -> void;
  223. private:
  224. // Implementation detail struct implementing the actual lexer logic.
  225. class Lexer;
  226. friend Lexer;
  227. // Specifies minimum widths to use when printing a token's fields via
  228. // `printToken`.
  229. struct PrintWidths {
  230. int index;
  231. int kind;
  232. int column;
  233. int line;
  234. int indent;
  235. // Widens `this` to the maximum of `this` and `new_width` for each
  236. // dimension.
  237. void Widen(const PrintWidths& new_width);
  238. };
  239. struct TokenInfo {
  240. TokenKind kind;
  241. // Whether the token was injected artificially during error recovery.
  242. bool is_recovery = false;
  243. // Line on which the Token starts.
  244. Line token_line;
  245. // Zero-based byte offset of the token within its line.
  246. int32_t column;
  247. // We may have up to 32 bits of payload, based on the kind of token.
  248. union {
  249. static_assert(
  250. sizeof(Token) <= sizeof(int32_t),
  251. "Unable to pack token and identifier index into the same space!");
  252. Identifier id;
  253. int32_t literal_index;
  254. Token closing_token;
  255. Token opening_token;
  256. int32_t error_length;
  257. };
  258. };
  259. struct LineInfo {
  260. // Zero-based byte offset of the start of the line within the source buffer
  261. // provided.
  262. int64_t start;
  263. // The byte length of the line. Does not include the newline character (or a
  264. // null terminator or EOF).
  265. int32_t length;
  266. // The byte offset from the start of the line of the first non-whitespace
  267. // character.
  268. int32_t indent;
  269. };
  270. struct IdentifierInfo {
  271. llvm::StringRef text;
  272. };
  273. // The constructor is merely responsible for trivial initialization of
  274. // members. A working object of this type is built with the `lex` function
  275. // above so that its return can indicate if an error was encountered while
  276. // lexing.
  277. explicit TokenizedBuffer(SourceBuffer& source) : source(&source) {}
  278. auto GetLineInfo(Line line) -> LineInfo&;
  279. [[nodiscard]] auto GetLineInfo(Line line) const -> const LineInfo&;
  280. auto AddLine(LineInfo info) -> Line;
  281. auto GetTokenInfo(Token token) -> TokenInfo&;
  282. [[nodiscard]] auto GetTokenInfo(Token token) const -> const TokenInfo&;
  283. auto AddToken(TokenInfo info) -> Token;
  284. [[nodiscard]] auto GetTokenPrintWidths(Token token) const -> PrintWidths;
  285. auto PrintToken(llvm::raw_ostream& output_stream, Token token,
  286. PrintWidths widths) const -> void;
  287. SourceBuffer* source;
  288. llvm::SmallVector<TokenInfo, 16> token_infos;
  289. llvm::SmallVector<LineInfo, 16> line_infos;
  290. llvm::SmallVector<IdentifierInfo, 16> identifier_infos;
  291. llvm::SmallVector<llvm::APInt, 16> int_literals;
  292. llvm::DenseMap<llvm::StringRef, Identifier> identifier_map;
  293. bool has_errors = false;
  294. };
  295. } // namespace Carbon
  296. #endif // LEXER_TOKENIZED_BUFFER_H_