tokenized_buffer.h 14 KB

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