tokenized_buffer.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. // The value of a real literal.
  162. //
  163. // This is either a dyadic fraction (mantissa * 2^exponent) or a decadic
  164. // fraction (mantissa * 10^exponent).
  165. //
  166. // The `TokenizedBuffer` must outlive any `RealLiteralValue`s referring to
  167. // its tokens.
  168. class RealLiteralValue {
  169. const TokenizedBuffer* buffer;
  170. int32_t literal_index;
  171. bool is_decimal;
  172. public:
  173. // The mantissa, represented as an unsigned integer.
  174. auto Mantissa() const -> const llvm::APInt& {
  175. return buffer->literal_int_storage[literal_index];
  176. }
  177. // The exponent, represented as a signed integer.
  178. auto Exponent() const -> const llvm::APInt& {
  179. return buffer->literal_int_storage[literal_index + 1];
  180. }
  181. // If false, the value is mantissa * 2^exponent.
  182. // If true, the value is mantissa * 10^exponent.
  183. auto IsDecimal() const -> bool { return is_decimal; }
  184. private:
  185. friend class TokenizedBuffer;
  186. RealLiteralValue(const TokenizedBuffer* buffer, int32_t literal_index,
  187. bool is_decimal)
  188. : buffer(buffer),
  189. literal_index(literal_index),
  190. is_decimal(is_decimal) {}
  191. };
  192. // Lexes a buffer of source code into a tokenized buffer.
  193. //
  194. // The provided source buffer must outlive any returned `TokenizedBuffer`
  195. // which will refer into the source.
  196. //
  197. // FIXME: Need to pass in some diagnostic machinery to report the details of
  198. // the error! Right now it prints to stderr.
  199. static auto Lex(SourceBuffer& source, DiagnosticEmitter& emitter)
  200. -> TokenizedBuffer;
  201. // Returns true if the buffer has errors that are detectable at lexing time.
  202. [[nodiscard]] auto HasErrors() const -> bool { return has_errors; }
  203. [[nodiscard]] auto Tokens() const -> llvm::iterator_range<TokenIterator> {
  204. return llvm::make_range(TokenIterator(Token(0)),
  205. TokenIterator(Token(token_infos.size())));
  206. }
  207. [[nodiscard]] auto Size() const -> int { return token_infos.size(); }
  208. [[nodiscard]] auto GetKind(Token token) const -> TokenKind;
  209. [[nodiscard]] auto GetLine(Token token) const -> Line;
  210. // Returns the 1-based line number.
  211. [[nodiscard]] auto GetLineNumber(Token token) const -> int;
  212. // Returns the 1-based column number.
  213. [[nodiscard]] auto GetColumnNumber(Token token) const -> int;
  214. // Returns the source text lexed into this token.
  215. [[nodiscard]] auto GetTokenText(Token token) const -> llvm::StringRef;
  216. // Returns the identifier associated with this token. The token kind must be
  217. // an `Identifier`.
  218. [[nodiscard]] auto GetIdentifier(Token token) const -> Identifier;
  219. // Returns the value of an `IntegerLiteral()` token.
  220. [[nodiscard]] auto GetIntegerLiteral(Token token) const -> const llvm::APInt&;
  221. // Returns the value of an `RealLiteral()` token.
  222. [[nodiscard]] auto GetRealLiteral(Token token) const -> RealLiteralValue;
  223. // Returns the closing token matched with the given opening token.
  224. //
  225. // The given token must be an opening token kind.
  226. [[nodiscard]] auto GetMatchedClosingToken(Token opening_token) const -> Token;
  227. // Returns the opening token matched with the given closing token.
  228. //
  229. // The given token must be a closing token kind.
  230. [[nodiscard]] auto GetMatchedOpeningToken(Token closing_token) const -> Token;
  231. // Returns whether the token was created as part of an error recovery effort.
  232. //
  233. // For example, a closing paren inserted to match an unmatched paren.
  234. [[nodiscard]] auto IsRecoveryToken(Token token) const -> bool;
  235. // Returns the 1-based line number.
  236. [[nodiscard]] auto GetLineNumber(Line line) const -> int;
  237. // Returns the 1-based indentation column number.
  238. [[nodiscard]] auto GetIndentColumnNumber(Line line) const -> int;
  239. // Returns the text for an identifier.
  240. [[nodiscard]] auto GetIdentifierText(Identifier id) const -> llvm::StringRef;
  241. // Prints a description of the tokenized stream to the provided `raw_ostream`.
  242. //
  243. // It prints one line of information for each token in the buffer, including
  244. // the kind of token, where it occurs within the source file, indentation for
  245. // the associated line, the spelling of the token in source, and any
  246. // additional information tracked such as which unique identifier it is or any
  247. // matched grouping token.
  248. //
  249. // Each line is formatted as a YAML record:
  250. //
  251. // clang-format off
  252. // ```
  253. // token: { index: 0, kind: 'Semi', line: 1, column: 1, indent: 1, spelling: ';' }
  254. // ```
  255. // clang-format on
  256. //
  257. // This can be parsed as YAML using tools like `python-yq` combined with `jq`
  258. // on the command line. The format is also reasonably amenable to other
  259. // line-oriented shell tools from `grep` to `awk`.
  260. auto Print(llvm::raw_ostream& output_stream) const -> void;
  261. // Prints a description of a single token. See `print` for details on the
  262. // format.
  263. auto PrintToken(llvm::raw_ostream& output_stream, Token token) const -> void;
  264. private:
  265. // Implementation detail struct implementing the actual lexer logic.
  266. class Lexer;
  267. friend Lexer;
  268. // Specifies minimum widths to use when printing a token's fields via
  269. // `printToken`.
  270. struct PrintWidths {
  271. // Widens `this` to the maximum of `this` and `new_width` for each
  272. // dimension.
  273. auto Widen(const PrintWidths& new_width) -> void;
  274. int index;
  275. int kind;
  276. int column;
  277. int line;
  278. int indent;
  279. };
  280. struct TokenInfo {
  281. TokenKind kind;
  282. // Whether the token was injected artificially during error recovery.
  283. bool is_recovery = false;
  284. // Line on which the Token starts.
  285. Line token_line;
  286. // Zero-based byte offset of the token within its line.
  287. int32_t column;
  288. // We may have up to 32 bits of payload, based on the kind of token.
  289. union {
  290. static_assert(
  291. sizeof(Token) <= sizeof(int32_t),
  292. "Unable to pack token and identifier index into the same space!");
  293. Identifier id;
  294. int32_t literal_index;
  295. Token closing_token;
  296. Token opening_token;
  297. int32_t error_length;
  298. };
  299. };
  300. struct LineInfo {
  301. // Zero-based byte offset of the start of the line within the source buffer
  302. // provided.
  303. int64_t start;
  304. // The byte length of the line. Does not include the newline character (or a
  305. // null terminator or EOF).
  306. int32_t length;
  307. // The byte offset from the start of the line of the first non-whitespace
  308. // character.
  309. int32_t indent;
  310. };
  311. struct IdentifierInfo {
  312. llvm::StringRef text;
  313. };
  314. // The constructor is merely responsible for trivial initialization of
  315. // members. A working object of this type is built with the `lex` function
  316. // above so that its return can indicate if an error was encountered while
  317. // lexing.
  318. explicit TokenizedBuffer(SourceBuffer& source) : source(&source) {}
  319. auto GetLineInfo(Line line) -> LineInfo&;
  320. [[nodiscard]] auto GetLineInfo(Line line) const -> const LineInfo&;
  321. auto AddLine(LineInfo info) -> Line;
  322. auto GetTokenInfo(Token token) -> TokenInfo&;
  323. [[nodiscard]] auto GetTokenInfo(Token token) const -> const TokenInfo&;
  324. auto AddToken(TokenInfo info) -> Token;
  325. [[nodiscard]] auto GetTokenPrintWidths(Token token) const -> PrintWidths;
  326. auto PrintToken(llvm::raw_ostream& output_stream, Token token,
  327. PrintWidths widths) const -> void;
  328. SourceBuffer* source;
  329. llvm::SmallVector<TokenInfo, 16> token_infos;
  330. llvm::SmallVector<LineInfo, 16> line_infos;
  331. llvm::SmallVector<IdentifierInfo, 16> identifier_infos;
  332. // Storage for integers that form part of the value of a numeric literal.
  333. llvm::SmallVector<llvm::APInt, 16> literal_int_storage;
  334. llvm::DenseMap<llvm::StringRef, Identifier> identifier_map;
  335. bool has_errors = false;
  336. };
  337. } // namespace Carbon
  338. #endif // LEXER_TOKENIZED_BUFFER_H_