tokenized_buffer.h 20 KB

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