tokenized_buffer.h 19 KB

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