tokenized_buffer.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 "common/ostream.h"
  8. #include "llvm/ADT/APInt.h"
  9. #include "llvm/ADT/SmallVector.h"
  10. #include "llvm/ADT/StringRef.h"
  11. #include "llvm/ADT/iterator_range.h"
  12. #include "llvm/Support/Allocator.h"
  13. #include "llvm/Support/raw_ostream.h"
  14. #include "toolchain/base/index_base.h"
  15. #include "toolchain/base/mem_usage.h"
  16. #include "toolchain/base/value_store.h"
  17. #include "toolchain/diagnostics/diagnostic_emitter.h"
  18. #include "toolchain/lex/token_index.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 line in a `TokenizedBuffer`.
  24. //
  25. // `LineIndex` 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. // Each `LineIndex` object refers to a specific line in the source code that was
  30. // lexed. They can be compared directly to establish that they refer to the
  31. // same line or the relative position of different lines within the source.
  32. //
  33. // All other APIs to query a `LineIndex` are on the `TokenizedBuffer`.
  34. struct LineIndex : public IndexBase {
  35. static const LineIndex Invalid;
  36. using IndexBase::IndexBase;
  37. };
  38. constexpr LineIndex LineIndex::Invalid(InvalidIndex);
  39. // Indices for comments within the buffer.
  40. struct CommentIndex : public IndexBase {
  41. static const CommentIndex Invalid;
  42. using IndexBase::IndexBase;
  43. };
  44. constexpr CommentIndex CommentIndex::Invalid(InvalidIndex);
  45. // Random-access iterator over comments within the buffer.
  46. using CommentIterator = IndexIterator<CommentIndex>;
  47. // Random-access iterator over tokens within the buffer.
  48. using TokenIterator = IndexIterator<TokenIndex>;
  49. // A diagnostic location converter that maps token locations into source
  50. // buffer locations.
  51. class TokenDiagnosticConverter : public DiagnosticConverter<TokenIndex> {
  52. public:
  53. explicit TokenDiagnosticConverter(const TokenizedBuffer* buffer)
  54. : buffer_(buffer) {}
  55. // Map the given token into a diagnostic location.
  56. auto ConvertLoc(TokenIndex token, ContextFnT context_fn) const
  57. -> DiagnosticLoc override;
  58. private:
  59. const TokenizedBuffer* buffer_;
  60. };
  61. // A buffer of tokenized Carbon source code.
  62. //
  63. // This is constructed by lexing the source code text into a series of tokens.
  64. // The buffer provides lightweight handles to tokens and other lexed entities,
  65. // as well as iterations to walk the sequence of tokens found in the buffer.
  66. //
  67. // Lexing errors result in a potentially incomplete sequence of tokens and
  68. // `HasError` returning true.
  69. class TokenizedBuffer : public Printable<TokenizedBuffer> {
  70. public:
  71. // The maximum number of tokens that can be stored in the buffer, including
  72. // the FileStart and FileEnd tokens.
  73. static constexpr int MaxTokens = 1 << 23;
  74. // A comment, which can be a block of lines.
  75. //
  76. // This is the API version of `CommentData`.
  77. struct CommentInfo {
  78. // The comment's full text, including `//` symbols. This may have several
  79. // lines for block comments.
  80. llvm::StringRef text;
  81. // The comment's indent.
  82. int32_t indent;
  83. // The first line of the comment.
  84. LineIndex start_line;
  85. };
  86. auto GetKind(TokenIndex token) const -> TokenKind;
  87. auto GetLine(TokenIndex token) const -> LineIndex;
  88. // Returns the 1-based line number.
  89. auto GetLineNumber(TokenIndex token) const -> int;
  90. // Returns the 1-based column number.
  91. auto GetColumnNumber(TokenIndex token) const -> int;
  92. // Returns the line and 1-based column number of the first character after
  93. // this token.
  94. auto GetEndLoc(TokenIndex token) const -> std::pair<LineIndex, int>;
  95. // Returns the source text lexed into this token.
  96. auto GetTokenText(TokenIndex token) const -> llvm::StringRef;
  97. // Returns the identifier associated with this token. The token kind must be
  98. // an `Identifier`.
  99. auto GetIdentifier(TokenIndex token) const -> IdentifierId;
  100. // Returns the value of an `IntLiteral()` token.
  101. auto GetIntLiteral(TokenIndex token) const -> IntId;
  102. // Returns the value of an `RealLiteral()` token.
  103. auto GetRealLiteral(TokenIndex token) const -> RealId;
  104. // Returns the value of a `StringLiteral()` token.
  105. auto GetStringLiteralValue(TokenIndex token) const -> StringLiteralValueId;
  106. // Returns the size specified in a `*TypeLiteral()` token.
  107. auto GetTypeLiteralSize(TokenIndex token) const -> IntId;
  108. // Returns the closing token matched with the given opening token.
  109. //
  110. // The given token must be an opening token kind.
  111. auto GetMatchedClosingToken(TokenIndex opening_token) const -> TokenIndex;
  112. // Returns the opening token matched with the given closing token.
  113. //
  114. // The given token must be a closing token kind.
  115. auto GetMatchedOpeningToken(TokenIndex closing_token) const -> TokenIndex;
  116. // Returns whether the given token has leading whitespace.
  117. auto HasLeadingWhitespace(TokenIndex token) const -> bool;
  118. // Returns whether the given token has trailing whitespace.
  119. auto HasTrailingWhitespace(TokenIndex token) const -> bool;
  120. // Returns whether the token was created as part of an error recovery effort.
  121. //
  122. // For example, a closing paren inserted to match an unmatched paren.
  123. auto IsRecoveryToken(TokenIndex token) const -> bool;
  124. // Returns the 1-based line number.
  125. auto GetLineNumber(LineIndex line) const -> int;
  126. // Returns the 1-based indentation column number.
  127. auto GetIndentColumnNumber(LineIndex line) const -> int;
  128. // Returns the next line handle.
  129. auto GetNextLine(LineIndex line) const -> LineIndex;
  130. // Returns the previous line handle.
  131. auto GetPrevLine(LineIndex line) const -> LineIndex;
  132. // Returns true if the token comes after the comment.
  133. auto IsAfterComment(TokenIndex token, CommentIndex comment_index) const
  134. -> bool;
  135. // Returns the comment's full text range.
  136. auto GetCommentText(CommentIndex comment_index) const -> llvm::StringRef;
  137. // Returns tokens as YAML. This prints the tracked token information on a
  138. // single line for each token. We use the single-line format so that output is
  139. // compact, and so that tools like `grep` are compatible.
  140. //
  141. // An example token looks like:
  142. //
  143. // - { index: 1, kind: 'Semi', line: 1, column: 1, indent: 1, spelling: ';' }
  144. auto Print(llvm::raw_ostream& out,
  145. bool omit_file_boundary_tokens = false) const -> void;
  146. // Prints a description of a single token. See `Print` for details on the
  147. // format.
  148. auto PrintToken(llvm::raw_ostream& output_stream, TokenIndex token) const
  149. -> void;
  150. // Collects memory usage of members.
  151. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  152. -> void;
  153. // Returns true if the buffer has errors that were detected at lexing time.
  154. auto has_errors() const -> bool { return has_errors_; }
  155. auto tokens() const -> llvm::iterator_range<TokenIterator> {
  156. return llvm::make_range(TokenIterator(TokenIndex(0)),
  157. TokenIterator(TokenIndex(token_infos_.size())));
  158. }
  159. auto size() const -> int { return token_infos_.size(); }
  160. auto comments() const -> llvm::iterator_range<CommentIterator> {
  161. return llvm::make_range(CommentIterator(CommentIndex(0)),
  162. CommentIterator(CommentIndex(comments_.size())));
  163. }
  164. auto comments_size() const -> size_t { return comments_.size(); }
  165. // This is an upper bound on the number of output parse nodes in the absence
  166. // of errors.
  167. auto expected_max_parse_tree_size() const -> int {
  168. return expected_max_parse_tree_size_;
  169. }
  170. auto source() const -> const SourceBuffer& { return *source_; }
  171. private:
  172. friend class Lexer;
  173. friend class TokenDiagnosticConverter;
  174. // A diagnostic location converter that maps token locations into source
  175. // buffer locations.
  176. class SourceBufferDiagnosticConverter
  177. : public DiagnosticConverter<const char*> {
  178. public:
  179. explicit SourceBufferDiagnosticConverter(const TokenizedBuffer* buffer)
  180. : buffer_(buffer) {}
  181. // Map the given position within the source buffer into a diagnostic
  182. // location.
  183. auto ConvertLoc(const char* loc, ContextFnT context_fn) const
  184. -> DiagnosticLoc override;
  185. private:
  186. const TokenizedBuffer* buffer_;
  187. };
  188. // Specifies minimum widths to use when printing a token's fields via
  189. // `printToken`.
  190. struct PrintWidths {
  191. // Widens `this` to the maximum of `this` and `new_width` for each
  192. // dimension.
  193. auto Widen(const PrintWidths& widths) -> void;
  194. int index;
  195. int kind;
  196. int line;
  197. int column;
  198. int indent;
  199. };
  200. // Storage for the information about a specific token in the buffer.
  201. //
  202. // This provides a friendly accessor API to the carefully space-optimized
  203. // storage model of the information we associated with each token.
  204. //
  205. // There are four pieces of information stored here:
  206. // - The kind of the token.
  207. // - Whether that token has leading whitespace before it.
  208. // - A kind-specific payload that can be compressed into a small integer.
  209. // - This class provides dedicated accessors for each different form of
  210. // payload that check the kind and payload correspond correctly.
  211. // - A 32-bit byte offset of the token within the source text.
  212. //
  213. // These are compressed and stored in 8-bytes for each token.
  214. //
  215. // Note that while the class provides some limited setters for payloads and
  216. // mutating methods, setters on this type may be unexpectedly expensive due to
  217. // the bit-packed representation and should be avoided. As such, only the
  218. // minimal necessary setters are provided.
  219. //
  220. // TODO: It might be worth considering a struct-of-arrays data layout in order
  221. // to move the byte offset to a separate array from the rest as it is only hot
  222. // during lexing, and then cold during parsing and semantic analysis. However,
  223. // a trivial approach to that adds more overhead than it saves due to tracking
  224. // two separate vectors and their growth. Making this profitable would likely
  225. // at least require a highly specialized single vector that manages the growth
  226. // once and then provides separate storage areas for the two arrays.
  227. class TokenInfo {
  228. public:
  229. // The kind for this token.
  230. auto kind() const -> TokenKind { return TokenKind::Make(kind_); }
  231. // Whether this token is preceded by whitespace. We only store the preceding
  232. // state, and look at the next token to check for trailing whitespace.
  233. auto has_leading_space() const -> bool { return has_leading_space_; }
  234. // A collection of methods to access the specific payload included with
  235. // particular kinds of tokens. Only the specific payload accessor below may
  236. // be used for an info entry of a token with a particular kind, and these
  237. // check that the kind is valid. Some tokens do not include a payload at all
  238. // and none of these methods may be called.
  239. auto ident_id() const -> IdentifierId {
  240. CARBON_DCHECK(kind() == TokenKind::Identifier);
  241. return IdentifierId(token_payload_);
  242. }
  243. auto set_ident_id(IdentifierId ident_id) -> void {
  244. CARBON_DCHECK(kind() == TokenKind::Identifier);
  245. token_payload_ = ident_id.index;
  246. }
  247. auto string_literal_id() const -> StringLiteralValueId {
  248. CARBON_DCHECK(kind() == TokenKind::StringLiteral);
  249. return StringLiteralValueId(token_payload_);
  250. }
  251. auto int_id() const -> IntId {
  252. CARBON_DCHECK(kind() == TokenKind::IntLiteral ||
  253. kind() == TokenKind::IntTypeLiteral ||
  254. kind() == TokenKind::UnsignedIntTypeLiteral ||
  255. kind() == TokenKind::FloatTypeLiteral);
  256. return IntId(token_payload_);
  257. }
  258. auto real_id() const -> RealId {
  259. CARBON_DCHECK(kind() == TokenKind::RealLiteral);
  260. return RealId(token_payload_);
  261. }
  262. auto closing_token_index() const -> TokenIndex {
  263. CARBON_DCHECK(kind().is_opening_symbol());
  264. return TokenIndex(token_payload_);
  265. }
  266. auto set_closing_token_index(TokenIndex closing_index) -> void {
  267. CARBON_DCHECK(kind().is_opening_symbol());
  268. token_payload_ = closing_index.index;
  269. }
  270. auto opening_token_index() const -> TokenIndex {
  271. CARBON_DCHECK(kind().is_closing_symbol());
  272. return TokenIndex(token_payload_);
  273. }
  274. auto set_opening_token_index(TokenIndex opening_index) -> void {
  275. CARBON_DCHECK(kind().is_closing_symbol());
  276. token_payload_ = opening_index.index;
  277. }
  278. auto error_length() const -> int {
  279. CARBON_DCHECK(kind() == TokenKind::Error);
  280. return token_payload_;
  281. }
  282. // Zero-based byte offset of the token within the file. This can be combined
  283. // with the buffer's line information to locate the line and column of the
  284. // token as well.
  285. auto byte_offset() const -> int32_t { return byte_offset_; }
  286. // Transforms the token into an error token of the given length but at its
  287. // original position and with the same whitespace adjacency.
  288. auto ResetAsError(int error_length) -> void {
  289. // Construct a fresh token to establish any needed invariants and replace
  290. // this token with it.
  291. TokenInfo error(TokenKind::Error, has_leading_space(), error_length,
  292. byte_offset());
  293. *this = error;
  294. }
  295. private:
  296. friend class Lexer;
  297. static constexpr int PayloadBits = 23;
  298. // Constructor for a TokenKind that carries no payload, or where the payload
  299. // will be set later.
  300. //
  301. // Only used by the lexer which enforces only the correct kinds are used.
  302. //
  303. // When the payload is not being set, we leave it uninitialized. At least in
  304. // some cases, this will allow MSan to correctly detect erroneous attempts
  305. // to access the payload, as it works to track uninitialized memory
  306. // bit-for-bit specifically to handle complex cases like bitfields.
  307. TokenInfo(TokenKind kind, bool has_leading_space, int32_t byte_offset)
  308. : kind_(kind),
  309. has_leading_space_(has_leading_space),
  310. byte_offset_(byte_offset) {}
  311. // Constructor for a TokenKind that carries a payload.
  312. //
  313. // Only used by the lexer which enforces the correct kind and payload types.
  314. TokenInfo(TokenKind kind, bool has_leading_space, int payload,
  315. int32_t byte_offset)
  316. : kind_(kind),
  317. has_leading_space_(has_leading_space),
  318. token_payload_(payload),
  319. byte_offset_(byte_offset) {}
  320. // A bitfield that encodes the token's kind, the leading space flag, and the
  321. // remaining bits in a payload. These are encoded together as a bitfield for
  322. // density and because these are the hottest fields of tokens for consumers
  323. // after lexing.
  324. //
  325. // Payload values are typically ID types for which we create at most one per
  326. // token, so we ensure that `token_payload_` is large enough to fit any
  327. // token index. Stores to this field may overflow, but we produce an error
  328. // in `Lexer::Finalize` if the file has more than `MaxTokens` tokens, so
  329. // this value never overflows if lexing succeeds.
  330. TokenKind::RawEnumType kind_ : sizeof(TokenKind) * 8;
  331. bool has_leading_space_ : 1;
  332. unsigned token_payload_ : PayloadBits;
  333. static_assert(MaxTokens <= 1 << PayloadBits,
  334. "Not enough payload bits to store a token index");
  335. // Separate storage for the byte offset, this is hot while lexing but then
  336. // generally cold.
  337. int32_t byte_offset_;
  338. };
  339. static_assert(sizeof(TokenInfo) == 8,
  340. "Expected `TokenInfo` to pack to an 8-byte structure.");
  341. // A comment, which can be a block of lines. These are tracked separately from
  342. // tokens because they don't affect parse; if they were part of tokens, we'd
  343. // need more general special-casing within token logic.
  344. //
  345. // Note that `CommentInfo` is used for an API to expose the comment.
  346. struct CommentData {
  347. // Zero-based byte offset of the start of the comment within the source
  348. // buffer provided.
  349. int32_t start;
  350. // The comment's length.
  351. int32_t length;
  352. };
  353. struct LineInfo {
  354. explicit LineInfo(int32_t start) : start(start), indent(0) {}
  355. // Zero-based byte offset of the start of the line within the source buffer
  356. // provided.
  357. int32_t start;
  358. // The byte offset from the start of the line of the first non-whitespace
  359. // character.
  360. int32_t indent;
  361. };
  362. // The constructor is merely responsible for trivial initialization of
  363. // members. A working object of this type is built with `Lex::Lex` so that its
  364. // return can indicate if an error was encountered while lexing.
  365. explicit TokenizedBuffer(SharedValueStores& value_stores,
  366. SourceBuffer& source)
  367. : value_stores_(&value_stores), source_(&source) {}
  368. auto FindLineIndex(int32_t byte_offset) const -> LineIndex;
  369. auto GetLineInfo(LineIndex line) -> LineInfo&;
  370. auto GetLineInfo(LineIndex line) const -> const LineInfo&;
  371. auto AddLine(LineInfo info) -> LineIndex;
  372. auto GetTokenInfo(TokenIndex token) -> TokenInfo&;
  373. auto GetTokenInfo(TokenIndex token) const -> const TokenInfo&;
  374. auto AddToken(TokenInfo info) -> TokenIndex;
  375. auto GetTokenPrintWidths(TokenIndex token) const -> PrintWidths;
  376. auto PrintToken(llvm::raw_ostream& output_stream, TokenIndex token,
  377. PrintWidths widths) const -> void;
  378. // Adds a comment. This uses the indent to potentially stitch together two
  379. // adjacent comments.
  380. auto AddComment(int32_t indent, int32_t start, int32_t end) -> void;
  381. // Used to allocate computed string literals.
  382. llvm::BumpPtrAllocator allocator_;
  383. SharedValueStores* value_stores_;
  384. SourceBuffer* source_;
  385. llvm::SmallVector<TokenInfo> token_infos_;
  386. llvm::SmallVector<LineInfo> line_infos_;
  387. // Comments in the file.
  388. llvm::SmallVector<CommentData> comments_;
  389. // An upper bound on the number of parse tree nodes that we expect to be
  390. // created for the tokens in this buffer.
  391. int expected_max_parse_tree_size_ = 0;
  392. bool has_errors_ = false;
  393. // A vector of flags for recovery tokens. If empty, there are none. When doing
  394. // token recovery, this will be extended to be indexable by token indices and
  395. // contain true for the tokens that were synthesized for recovery.
  396. llvm::BitVector recovery_tokens_;
  397. };
  398. // A diagnostic emitter that uses positions within a source buffer's text as
  399. // its source of location information.
  400. using LexerDiagnosticEmitter = DiagnosticEmitter<const char*>;
  401. // A diagnostic emitter that uses tokens as its source of location information.
  402. using TokenDiagnosticEmitter = DiagnosticEmitter<TokenIndex>;
  403. inline auto TokenizedBuffer::GetKind(TokenIndex token) const -> TokenKind {
  404. return GetTokenInfo(token).kind();
  405. }
  406. inline auto TokenizedBuffer::HasLeadingWhitespace(TokenIndex token) const
  407. -> bool {
  408. return GetTokenInfo(token).has_leading_space();
  409. }
  410. inline auto TokenizedBuffer::HasTrailingWhitespace(TokenIndex token) const
  411. -> bool {
  412. TokenIterator it(token);
  413. ++it;
  414. return it != tokens().end() && GetTokenInfo(*it).has_leading_space();
  415. }
  416. inline auto TokenizedBuffer::GetTokenInfo(TokenIndex token) -> TokenInfo& {
  417. return token_infos_[token.index];
  418. }
  419. inline auto TokenizedBuffer::GetTokenInfo(TokenIndex token) const
  420. -> const TokenInfo& {
  421. return token_infos_[token.index];
  422. }
  423. inline auto TokenizedBuffer::AddToken(TokenInfo info) -> TokenIndex {
  424. TokenIndex index(token_infos_.size());
  425. token_infos_.push_back(info);
  426. expected_max_parse_tree_size_ += info.kind().expected_max_parse_tree_size();
  427. return index;
  428. }
  429. } // namespace Carbon::Lex
  430. #endif // CARBON_TOOLCHAIN_LEX_TOKENIZED_BUFFER_H_