tokenized_buffer.h 12 KB

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