tokenized_buffer.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 line and 1-based column number of the first character after
  123. // this token.
  124. auto GetEndLocation(TokenIndex token) const -> std::pair<LineIndex, int>;
  125. // Returns the source text lexed into this token.
  126. auto GetTokenText(TokenIndex token) const -> llvm::StringRef;
  127. // Returns the identifier associated with this token. The token kind must be
  128. // an `Identifier`.
  129. auto GetIdentifier(TokenIndex token) const -> IdentifierId;
  130. // Returns the value of an `IntLiteral()` token.
  131. auto GetIntLiteral(TokenIndex token) const -> IntId;
  132. // Returns the value of an `RealLiteral()` token.
  133. auto GetRealLiteral(TokenIndex token) const -> RealId;
  134. // Returns the value of a `StringLiteral()` token.
  135. auto GetStringLiteralValue(TokenIndex token) const -> StringLiteralValueId;
  136. // Returns the size specified in a `*TypeLiteral()` token.
  137. auto GetTypeLiteralSize(TokenIndex token) const -> const llvm::APInt&;
  138. // Returns the closing token matched with the given opening token.
  139. //
  140. // The given token must be an opening token kind.
  141. auto GetMatchedClosingToken(TokenIndex opening_token) const -> TokenIndex;
  142. // Returns the opening token matched with the given closing token.
  143. //
  144. // The given token must be a closing token kind.
  145. auto GetMatchedOpeningToken(TokenIndex closing_token) const -> TokenIndex;
  146. // Returns whether the given token has leading whitespace.
  147. auto HasLeadingWhitespace(TokenIndex token) const -> bool;
  148. // Returns whether the given token has trailing whitespace.
  149. auto HasTrailingWhitespace(TokenIndex token) const -> bool;
  150. // Returns whether the token was created as part of an error recovery effort.
  151. //
  152. // For example, a closing paren inserted to match an unmatched paren.
  153. auto IsRecoveryToken(TokenIndex token) const -> bool;
  154. // Returns the 1-based line number.
  155. auto GetLineNumber(LineIndex line) const -> int;
  156. // Returns the 1-based indentation column number.
  157. auto GetIndentColumnNumber(LineIndex line) const -> int;
  158. // Returns the next line handle.
  159. auto GetNextLine(LineIndex line) const -> LineIndex;
  160. // Returns the previous line handle.
  161. auto GetPrevLine(LineIndex line) const -> LineIndex;
  162. // Prints a description of the tokenized stream to the provided `raw_ostream`.
  163. //
  164. // It prints one line of information for each token in the buffer, including
  165. // the kind of token, where it occurs within the source file, indentation for
  166. // the associated line, the spelling of the token in source, and any
  167. // additional information tracked such as which unique identifier it is or any
  168. // matched grouping token.
  169. //
  170. // Each line is formatted as a YAML record:
  171. //
  172. // clang-format off
  173. // ```
  174. // token: { index: 0, kind: 'Semi', line: 1, column: 1, indent: 1, spelling: ';' }
  175. // ```
  176. // clang-format on
  177. //
  178. // This can be parsed as YAML using tools like `python-yq` combined with `jq`
  179. // on the command line. The format is also reasonably amenable to other
  180. // line-oriented shell tools from `grep` to `awk`.
  181. auto Print(llvm::raw_ostream& output_stream) const -> void;
  182. // Prints a description of a single token. See `Print` for details on the
  183. // format.
  184. auto PrintToken(llvm::raw_ostream& output_stream, TokenIndex token) const
  185. -> void;
  186. // Returns true if the buffer has errors that were detected at lexing time.
  187. auto has_errors() const -> bool { return has_errors_; }
  188. auto tokens() const -> llvm::iterator_range<TokenIterator> {
  189. return llvm::make_range(TokenIterator(TokenIndex(0)),
  190. TokenIterator(TokenIndex(token_infos_.size())));
  191. }
  192. auto size() const -> int { return token_infos_.size(); }
  193. auto expected_parse_tree_size() const -> int {
  194. return expected_parse_tree_size_;
  195. }
  196. auto source() const -> const SourceBuffer& { return *source_; }
  197. private:
  198. friend class Lexer;
  199. friend class TokenLocationTranslator;
  200. // A diagnostic location translator that maps token locations into source
  201. // buffer locations.
  202. class SourceBufferLocationTranslator
  203. : public DiagnosticLocationTranslator<const char*> {
  204. public:
  205. explicit SourceBufferLocationTranslator(const TokenizedBuffer* buffer)
  206. : buffer_(buffer) {}
  207. // Map the given position within the source buffer into a diagnostic
  208. // location.
  209. auto GetLocation(const char* loc) -> DiagnosticLocation override;
  210. private:
  211. const TokenizedBuffer* buffer_;
  212. };
  213. // Specifies minimum widths to use when printing a token's fields via
  214. // `printToken`.
  215. struct PrintWidths {
  216. // Widens `this` to the maximum of `this` and `new_width` for each
  217. // dimension.
  218. auto Widen(const PrintWidths& widths) -> void;
  219. int index;
  220. int kind;
  221. int line;
  222. int column;
  223. int indent;
  224. };
  225. struct TokenInfo {
  226. TokenKind kind;
  227. // Whether the token has trailing whitespace.
  228. bool has_trailing_space = false;
  229. // Whether the token was injected artificially during error recovery.
  230. bool is_recovery = false;
  231. // LineIndex on which the TokenIndex starts.
  232. LineIndex token_line;
  233. // Zero-based byte offset of the token within its line.
  234. int32_t column;
  235. // We may have up to 32 bits of payload, based on the kind of token.
  236. union {
  237. static_assert(
  238. sizeof(TokenIndex) <= sizeof(int32_t),
  239. "Unable to pack token and identifier index into the same space!");
  240. IdentifierId ident_id = IdentifierId::Invalid;
  241. StringLiteralValueId string_literal_id;
  242. IntId int_id;
  243. RealId real_id;
  244. TokenIndex closing_token;
  245. TokenIndex opening_token;
  246. int32_t error_length;
  247. };
  248. };
  249. struct LineInfo {
  250. // The length will always be assigned later. Indent may be assigned if
  251. // non-zero.
  252. explicit LineInfo(int64_t start)
  253. : start(start),
  254. length(static_cast<int32_t>(llvm::StringRef::npos)),
  255. indent(0) {}
  256. explicit LineInfo(int64_t start, int32_t length)
  257. : start(start), length(length), indent(0) {}
  258. // Zero-based byte offset of the start of the line within the source buffer
  259. // provided.
  260. int64_t start;
  261. // The byte length of the line. Does not include the newline character (or a
  262. // nul-terminator or EOF).
  263. int32_t length;
  264. // The byte offset from the start of the line of the first non-whitespace
  265. // character.
  266. int32_t indent;
  267. };
  268. // The constructor is merely responsible for trivial initialization of
  269. // members. A working object of this type is built with `Lex::Lex` so that its
  270. // return can indicate if an error was encountered while lexing.
  271. explicit TokenizedBuffer(SharedValueStores& value_stores,
  272. SourceBuffer& source)
  273. : value_stores_(&value_stores), source_(&source) {}
  274. auto GetLineInfo(LineIndex line) -> LineInfo&;
  275. auto GetLineInfo(LineIndex line) const -> const LineInfo&;
  276. auto AddLine(LineInfo info) -> LineIndex;
  277. auto GetTokenInfo(TokenIndex token) -> TokenInfo&;
  278. auto GetTokenInfo(TokenIndex token) const -> const TokenInfo&;
  279. auto AddToken(TokenInfo info) -> TokenIndex;
  280. auto GetTokenPrintWidths(TokenIndex token) const -> PrintWidths;
  281. auto PrintToken(llvm::raw_ostream& output_stream, TokenIndex token,
  282. PrintWidths widths) const -> void;
  283. // Used to allocate computed string literals.
  284. llvm::BumpPtrAllocator allocator_;
  285. SharedValueStores* value_stores_;
  286. SourceBuffer* source_;
  287. llvm::SmallVector<TokenInfo> token_infos_;
  288. llvm::SmallVector<LineInfo> line_infos_;
  289. // Stores the computed value of string literals so that StringRefs are
  290. // durable.
  291. llvm::SmallVector<std::unique_ptr<std::string>> computed_strings_;
  292. // The number of parse tree nodes that we expect to be created for the tokens
  293. // in this buffer.
  294. int expected_parse_tree_size_ = 0;
  295. bool has_errors_ = false;
  296. };
  297. // A diagnostic emitter that uses positions within a source buffer's text as
  298. // its source of location information.
  299. using LexerDiagnosticEmitter = DiagnosticEmitter<const char*>;
  300. // A diagnostic emitter that uses tokens as its source of location information.
  301. using TokenDiagnosticEmitter = DiagnosticEmitter<TokenIndex>;
  302. } // namespace Carbon::Lex
  303. #endif // CARBON_TOOLCHAIN_LEX_TOKENIZED_BUFFER_H_