tokenized_buffer.h 12 KB

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