tokenized_buffer.h 13 KB

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