tokenized_buffer.h 20 KB

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