tokenized_buffer.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 CARBON_TOOLCHAIN_LEXER_TOKENIZED_BUFFER_H_
  5. #define CARBON_TOOLCHAIN_LEXER_TOKENIZED_BUFFER_H_
  6. #include <cstdint>
  7. #include <iterator>
  8. #include <optional>
  9. #include "common/ostream.h"
  10. #include "llvm/ADT/APInt.h"
  11. #include "llvm/ADT/DenseMap.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/ADT/iterator.h"
  15. #include "llvm/ADT/iterator_range.h"
  16. #include "llvm/Support/raw_ostream.h"
  17. #include "toolchain/common/index_base.h"
  18. #include "toolchain/diagnostics/diagnostic_emitter.h"
  19. #include "toolchain/lexer/token_kind.h"
  20. #include "toolchain/source/source_buffer.h"
  21. namespace Carbon {
  22. class TokenizedBuffer;
  23. // A buffer of tokenized Carbon source code.
  24. //
  25. // This is constructed by lexing the source code text into a series of tokens.
  26. // The buffer provides lightweight handles to tokens and other lexed entities,
  27. // as well as iterations to walk the sequence of tokens found in the buffer.
  28. //
  29. // Lexing errors result in a potentially incomplete sequence of tokens and
  30. // `HasError` returning true.
  31. class TokenizedBuffer {
  32. public:
  33. // A lightweight handle to a lexed token in a `TokenizedBuffer`.
  34. //
  35. // `Token` objects are designed to be passed by value, not reference or
  36. // pointer. They are also designed to be small and efficient to store in data
  37. // structures.
  38. //
  39. // `Token` objects from the same `TokenizedBuffer` can be compared with each
  40. // other, both for being the same token within the buffer, and to establish
  41. // relative position within the token stream that has been lexed out of the
  42. // buffer. `Token` objects from different `TokenizedBuffer`s cannot be
  43. // meaningfully compared.
  44. //
  45. // All other APIs to query a `Token` are on the `TokenizedBuffer`.
  46. struct Token : public ComparableIndexBase {
  47. using ComparableIndexBase::ComparableIndexBase;
  48. };
  49. // A lightweight handle to a lexed line in a `TokenizedBuffer`.
  50. //
  51. // `Line` objects are designed to be passed by value, not reference or
  52. // pointer. They are also designed to be small and efficient to store in data
  53. // structures.
  54. //
  55. // Each `Line` object refers to a specific line in the source code that was
  56. // lexed. They can be compared directly to establish that they refer to the
  57. // same line or the relative position of different lines within the source.
  58. //
  59. // All other APIs to query a `Line` are on the `TokenizedBuffer`.
  60. struct Line : public ComparableIndexBase {
  61. using ComparableIndexBase::ComparableIndexBase;
  62. };
  63. // A lightweight handle to a lexed identifier in a `TokenizedBuffer`.
  64. //
  65. // `Identifier` 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 identifier lexed is canonicalized to a single entry in the identifier
  70. // table. `Identifier` objects will compare equal if they refer to the same
  71. // identifier spelling. Where the identifier was written is not preserved.
  72. //
  73. // All other APIs to query a `Identifier` are on the `TokenizedBuffer`.
  74. struct Identifier : public IndexBase {
  75. using IndexBase::IndexBase;
  76. };
  77. // Random-access iterator over tokens within the buffer.
  78. class TokenIterator
  79. : public llvm::iterator_facade_base<
  80. TokenIterator, std::random_access_iterator_tag, const Token, int> {
  81. public:
  82. TokenIterator() = default;
  83. explicit TokenIterator(Token token) : token_(token) {}
  84. auto operator==(const TokenIterator& rhs) const -> bool {
  85. return token_ == rhs.token_;
  86. }
  87. auto operator<(const TokenIterator& rhs) const -> bool {
  88. return token_ < rhs.token_;
  89. }
  90. auto operator*() const -> const Token& { return token_; }
  91. using iterator_facade_base::operator-;
  92. auto operator-(const TokenIterator& rhs) const -> int {
  93. return token_.index - rhs.token_.index;
  94. }
  95. auto operator+=(int n) -> TokenIterator& {
  96. token_.index += n;
  97. return *this;
  98. }
  99. auto operator-=(int n) -> TokenIterator& {
  100. token_.index -= n;
  101. return *this;
  102. }
  103. // Prints the raw token index.
  104. auto Print(llvm::raw_ostream& output) const -> void;
  105. private:
  106. friend class TokenizedBuffer;
  107. Token token_;
  108. };
  109. // The value of a real literal.
  110. //
  111. // This is either a dyadic fraction (mantissa * 2^exponent) or a decadic
  112. // fraction (mantissa * 10^exponent).
  113. //
  114. // The `TokenizedBuffer` must outlive any `RealLiteralValue`s referring to
  115. // its tokens.
  116. class RealLiteralValue {
  117. public:
  118. // The mantissa, represented as an unsigned integer.
  119. [[nodiscard]] auto Mantissa() const -> const llvm::APInt& {
  120. return buffer_->literal_int_storage_[literal_index_];
  121. }
  122. // The exponent, represented as a signed integer.
  123. [[nodiscard]] auto Exponent() const -> const llvm::APInt& {
  124. return buffer_->literal_int_storage_[literal_index_ + 1];
  125. }
  126. // If false, the value is mantissa * 2^exponent.
  127. // If true, the value is mantissa * 10^exponent.
  128. [[nodiscard]] auto IsDecimal() const -> bool { return is_decimal_; }
  129. auto Print(llvm::raw_ostream& output_stream) const -> void {
  130. output_stream << Mantissa() << "*" << (is_decimal_ ? "10" : "2") << "^"
  131. << Exponent();
  132. }
  133. private:
  134. friend class TokenizedBuffer;
  135. RealLiteralValue(const TokenizedBuffer* buffer, int32_t literal_index,
  136. bool is_decimal)
  137. : buffer_(buffer),
  138. literal_index_(literal_index),
  139. is_decimal_(is_decimal) {}
  140. const TokenizedBuffer* buffer_;
  141. int32_t literal_index_;
  142. bool is_decimal_;
  143. };
  144. // A diagnostic location translator that maps token locations into source
  145. // buffer locations.
  146. class TokenLocationTranslator : public DiagnosticLocationTranslator<Token> {
  147. public:
  148. explicit TokenLocationTranslator(const TokenizedBuffer* buffer,
  149. int* last_line_lexed_to_column)
  150. : buffer_(buffer),
  151. last_line_lexed_to_column_(last_line_lexed_to_column) {}
  152. // Map the given token into a diagnostic location.
  153. auto GetLocation(Token token) -> DiagnosticLocation override;
  154. private:
  155. const TokenizedBuffer* buffer_;
  156. // Passed to SourceBufferLocationTranslator.
  157. int* last_line_lexed_to_column_;
  158. };
  159. // Lexes a buffer of source code into a tokenized buffer.
  160. //
  161. // The provided source buffer must outlive any returned `TokenizedBuffer`
  162. // which will refer into the source.
  163. static auto Lex(SourceBuffer& source, DiagnosticConsumer& consumer)
  164. -> TokenizedBuffer;
  165. [[nodiscard]] auto GetKind(Token token) const -> TokenKind;
  166. [[nodiscard]] auto GetLine(Token token) const -> Line;
  167. // Returns the 1-based line number.
  168. [[nodiscard]] auto GetLineNumber(Token token) const -> int;
  169. // Returns the 1-based column number.
  170. [[nodiscard]] auto GetColumnNumber(Token token) const -> int;
  171. // Returns the source text lexed into this token.
  172. [[nodiscard]] auto GetTokenText(Token token) const -> llvm::StringRef;
  173. // Returns the identifier associated with this token. The token kind must be
  174. // an `Identifier`.
  175. [[nodiscard]] auto GetIdentifier(Token token) const -> Identifier;
  176. // Returns the value of an `IntegerLiteral()` token.
  177. [[nodiscard]] auto GetIntegerLiteral(Token token) const -> const llvm::APInt&;
  178. // Returns the value of an `RealLiteral()` token.
  179. [[nodiscard]] auto GetRealLiteral(Token token) const -> RealLiteralValue;
  180. // Returns the value of a `StringLiteral()` token.
  181. [[nodiscard]] auto GetStringLiteral(Token token) const -> llvm::StringRef;
  182. // Returns the size specified in a `*TypeLiteral()` token.
  183. [[nodiscard]] auto GetTypeLiteralSize(Token token) const
  184. -> const llvm::APInt&;
  185. // Returns the closing token matched with the given opening token.
  186. //
  187. // The given token must be an opening token kind.
  188. [[nodiscard]] auto GetMatchedClosingToken(Token opening_token) const -> Token;
  189. // Returns the opening token matched with the given closing token.
  190. //
  191. // The given token must be a closing token kind.
  192. [[nodiscard]] auto GetMatchedOpeningToken(Token closing_token) const -> Token;
  193. // Returns whether the given token has leading whitespace.
  194. [[nodiscard]] auto HasLeadingWhitespace(Token token) const -> bool;
  195. // Returns whether the given token has trailing whitespace.
  196. [[nodiscard]] auto HasTrailingWhitespace(Token token) const -> bool;
  197. // Returns whether the token was created as part of an error recovery effort.
  198. //
  199. // For example, a closing paren inserted to match an unmatched paren.
  200. [[nodiscard]] auto IsRecoveryToken(Token token) const -> bool;
  201. // Returns the 1-based line number.
  202. [[nodiscard]] auto GetLineNumber(Line line) const -> int;
  203. // Returns the 1-based indentation column number.
  204. [[nodiscard]] auto GetIndentColumnNumber(Line line) const -> int;
  205. // Returns the text for an identifier.
  206. [[nodiscard]] auto GetIdentifierText(Identifier id) const -> llvm::StringRef;
  207. // Prints a description of the tokenized stream to the provided `raw_ostream`.
  208. //
  209. // It prints one line of information for each token in the buffer, including
  210. // the kind of token, where it occurs within the source file, indentation for
  211. // the associated line, the spelling of the token in source, and any
  212. // additional information tracked such as which unique identifier it is or any
  213. // matched grouping token.
  214. //
  215. // Each line is formatted as a YAML record:
  216. //
  217. // clang-format off
  218. // ```
  219. // token: { index: 0, kind: 'Semi', line: 1, column: 1, indent: 1, spelling: ';' }
  220. // ```
  221. // clang-format on
  222. //
  223. // This can be parsed as YAML using tools like `python-yq` combined with `jq`
  224. // on the command line. The format is also reasonably amenable to other
  225. // line-oriented shell tools from `grep` to `awk`.
  226. auto Print(llvm::raw_ostream& output_stream) const -> void;
  227. // Prints a description of a single token. See `Print` for details on the
  228. // format.
  229. auto PrintToken(llvm::raw_ostream& output_stream, Token token) const -> void;
  230. // Returns true if the buffer has errors that are detectable at lexing time.
  231. [[nodiscard]] auto has_errors() const -> bool { return has_errors_; }
  232. [[nodiscard]] auto tokens() const -> llvm::iterator_range<TokenIterator> {
  233. return llvm::make_range(TokenIterator(Token(0)),
  234. TokenIterator(Token(token_infos_.size())));
  235. }
  236. [[nodiscard]] auto size() const -> int { return token_infos_.size(); }
  237. private:
  238. // Implementation detail struct implementing the actual lexer logic.
  239. class Lexer;
  240. friend Lexer;
  241. // A diagnostic location translator that maps token locations into source
  242. // buffer locations.
  243. class SourceBufferLocationTranslator
  244. : public DiagnosticLocationTranslator<const char*> {
  245. public:
  246. explicit SourceBufferLocationTranslator(const TokenizedBuffer* buffer,
  247. int* last_line_lexed_to_column)
  248. : buffer_(buffer),
  249. last_line_lexed_to_column_(last_line_lexed_to_column) {}
  250. // Map the given position within the source buffer into a diagnostic
  251. // location.
  252. auto GetLocation(const char* loc) -> DiagnosticLocation override;
  253. private:
  254. const TokenizedBuffer* buffer_;
  255. // The last lexed column, for determining whether the last line should be
  256. // checked for unlexed newlines. May be null after lexing is complete.
  257. int* last_line_lexed_to_column_;
  258. };
  259. // Specifies minimum widths to use when printing a token's fields via
  260. // `printToken`.
  261. struct PrintWidths {
  262. // Widens `this` to the maximum of `this` and `new_width` for each
  263. // dimension.
  264. auto Widen(const PrintWidths& widths) -> void;
  265. int index;
  266. int kind;
  267. int line;
  268. int column;
  269. int indent;
  270. };
  271. struct TokenInfo {
  272. TokenKind kind;
  273. // Whether the token has trailing whitespace.
  274. bool has_trailing_space = false;
  275. // Whether the token was injected artificially during error recovery.
  276. bool is_recovery = false;
  277. // Line on which the Token starts.
  278. Line token_line;
  279. // Zero-based byte offset of the token within its line.
  280. int32_t column;
  281. // We may have up to 32 bits of payload, based on the kind of token.
  282. union {
  283. static_assert(
  284. sizeof(Token) <= sizeof(int32_t),
  285. "Unable to pack token and identifier index into the same space!");
  286. Identifier id;
  287. int32_t literal_index;
  288. Token closing_token;
  289. Token opening_token;
  290. int32_t error_length;
  291. };
  292. };
  293. struct LineInfo {
  294. // Zero-based byte offset of the start of the line within the source buffer
  295. // provided.
  296. int64_t start;
  297. // The byte length of the line. Does not include the newline character (or a
  298. // nul-terminator or EOF).
  299. int32_t length;
  300. // The byte offset from the start of the line of the first non-whitespace
  301. // character.
  302. int32_t indent;
  303. };
  304. struct IdentifierInfo {
  305. llvm::StringRef text;
  306. };
  307. // The constructor is merely responsible for trivial initialization of
  308. // members. A working object of this type is built with the `lex` function
  309. // above so that its return can indicate if an error was encountered while
  310. // lexing.
  311. explicit TokenizedBuffer(SourceBuffer& source) : source_(&source) {}
  312. auto GetLineInfo(Line line) -> LineInfo&;
  313. [[nodiscard]] auto GetLineInfo(Line line) const -> const LineInfo&;
  314. auto AddLine(LineInfo info) -> Line;
  315. auto GetTokenInfo(Token token) -> TokenInfo&;
  316. [[nodiscard]] auto GetTokenInfo(Token token) const -> const TokenInfo&;
  317. auto AddToken(TokenInfo info) -> Token;
  318. [[nodiscard]] auto GetTokenPrintWidths(Token token) const -> PrintWidths;
  319. auto PrintToken(llvm::raw_ostream& output_stream, Token token,
  320. PrintWidths widths) const -> void;
  321. SourceBuffer* source_;
  322. llvm::SmallVector<TokenInfo, 16> token_infos_;
  323. llvm::SmallVector<LineInfo, 16> line_infos_;
  324. llvm::SmallVector<IdentifierInfo, 16> identifier_infos_;
  325. // Storage for integers that form part of the value of a numeric or type
  326. // literal.
  327. llvm::SmallVector<llvm::APInt, 16> literal_int_storage_;
  328. llvm::SmallVector<std::string, 16> literal_string_storage_;
  329. llvm::DenseMap<llvm::StringRef, Identifier> identifier_map_;
  330. bool has_errors_ = false;
  331. };
  332. // A diagnostic emitter that uses positions within a source buffer's text as
  333. // its source of location information.
  334. using LexerDiagnosticEmitter = DiagnosticEmitter<const char*>;
  335. // A diagnostic emitter that uses tokens as its source of location information.
  336. using TokenDiagnosticEmitter = DiagnosticEmitter<TokenizedBuffer::Token>;
  337. } // namespace Carbon
  338. #endif // CARBON_TOOLCHAIN_LEXER_TOKENIZED_BUFFER_H_