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