tokenized_buffer.h 20 KB

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