context.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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_PARSE_CONTEXT_H_
  5. #define CARBON_TOOLCHAIN_PARSE_CONTEXT_H_
  6. #include <optional>
  7. #include "common/check.h"
  8. #include "common/vlog.h"
  9. #include "toolchain/diagnostics/diagnostic_converter.h"
  10. #include "toolchain/lex/token_kind.h"
  11. #include "toolchain/lex/tokenized_buffer.h"
  12. #include "toolchain/parse/node_kind.h"
  13. #include "toolchain/parse/precedence.h"
  14. #include "toolchain/parse/state.h"
  15. #include "toolchain/parse/tree.h"
  16. namespace Carbon::Parse {
  17. // An amount by which to look ahead of the current token. Lookahead should be
  18. // used sparingly, and unbounded lookahead should be avoided.
  19. //
  20. // TODO: Decide whether we want to avoid lookahead altogether.
  21. //
  22. // NOLINTNEXTLINE(performance-enum-size): Deliberately matches index size.
  23. enum class Lookahead : int32_t {
  24. CurrentToken = 0,
  25. NextToken = 1,
  26. };
  27. // Context and shared functionality for parser handlers. See state.def for state
  28. // documentation.
  29. class Context {
  30. public:
  31. // Possible operator fixities for errors.
  32. enum class OperatorFixity : int8_t { Prefix, Infix, Postfix };
  33. // Possible return values for FindListToken.
  34. enum class ListTokenKind : int8_t { Comma, Close, CommaClose };
  35. // Used for restricting ordering of `package` and `import` declarations.
  36. enum class PackagingState : int8_t {
  37. FileStart,
  38. InImports,
  39. AfterNonPackagingDecl,
  40. // A warning about `import` placement has been issued so we don't keep
  41. // issuing more (when `import` is repeated) until more non-`import`
  42. // declarations come up.
  43. InImportsAfterNonPackagingDecl,
  44. };
  45. // Used to track state on state_stack_.
  46. struct StateStackEntry : public Printable<StateStackEntry> {
  47. // Prints state information for verbose output.
  48. auto Print(llvm::raw_ostream& output) const -> void {
  49. output << state << " @" << token << " subtree_start=" << subtree_start
  50. << " has_error=" << has_error;
  51. }
  52. // The state.
  53. State state;
  54. // Set to true to indicate that an error was found, and that contextual
  55. // error recovery may be needed.
  56. bool has_error : 1 = false;
  57. // Set to true to indicate that this state is handling a pattern nested
  58. // inside a `var` pattern.
  59. // TODO: This is meaningful only for patterns, and the precedence fields
  60. // are meaningful only for expressions, so expressing them as a union
  61. // could help catch errors.
  62. bool in_var_pattern : 1 = false;
  63. // Precedence information used by expression states in order to determine
  64. // operator precedence. The ambient_precedence deals with how the expression
  65. // should interact with outside context, while the lhs_precedence is
  66. // specific to the lhs of an operator expression.
  67. PrecedenceGroup ambient_precedence = PrecedenceGroup::ForTopLevelExpr();
  68. PrecedenceGroup lhs_precedence = PrecedenceGroup::ForTopLevelExpr();
  69. // A token providing context based on the subtree. This will typically be
  70. // the first token in the subtree, but may sometimes be a token within. It
  71. // will typically be used for the subtree's root node.
  72. Lex::TokenIndex token;
  73. // The offset within the Tree of the subtree start.
  74. int32_t subtree_start;
  75. };
  76. // We expect StateStackEntry to fit into 12 bytes:
  77. // state = 1 byte
  78. // has_error and in_var_pattern = 1 byte
  79. // ambient_precedence = 1 byte
  80. // lhs_precedence = 1 byte
  81. // token = 4 bytes
  82. // subtree_start = 4 bytes
  83. // If it becomes bigger, it'd be worth examining better packing; it should be
  84. // feasible to pack the 1-byte entries more tightly.
  85. static_assert(sizeof(StateStackEntry) == 12,
  86. "StateStackEntry has unexpected size!");
  87. explicit Context(Tree* tree, Lex::TokenizedBuffer* tokens,
  88. DiagnosticConsumer* consumer,
  89. llvm::raw_ostream* vlog_stream);
  90. // Adds a node to the parse tree that has no children (a leaf).
  91. auto AddLeafNode(NodeKind kind, Lex::TokenIndex token, bool has_error = false)
  92. -> void {
  93. AddNode(kind, token, has_error);
  94. }
  95. // Adds a node to the parse tree that has children.
  96. auto AddNode(NodeKind kind, Lex::TokenIndex token, bool has_error) -> void {
  97. CARBON_CHECK(has_error || (kind != NodeKind::InvalidParse &&
  98. kind != NodeKind::InvalidParseStart &&
  99. kind != NodeKind::InvalidParseSubtree),
  100. "{0} nodes must always have an error", kind);
  101. tree_->node_impls_.push_back(Tree::NodeImpl(kind, has_error, token));
  102. }
  103. // Adds an invalid parse node.
  104. auto AddInvalidParse(Lex::TokenIndex token) -> void {
  105. AddNode(NodeKind::InvalidParse, token, /*has_error=*/true);
  106. }
  107. // Replaces the placeholder node at the indicated position with a leaf node.
  108. //
  109. // To reserve a position in the parse tree, you may add a placeholder parse
  110. // node using code like:
  111. // ```
  112. // context.PushState(State::WillFillInPlaceholder);
  113. // context.AddLeafNode(NodeKind::Placeholder, *context.position());
  114. // ```
  115. // It may be replaced with the intended leaf parse node with code like:
  116. // ```
  117. // auto HandleWillFillInPlaceholder(Context& context) -> void {
  118. // auto state = context.PopState();
  119. // context.ReplacePlaceholderNode(state.subtree_start, /* replacement */);
  120. // }
  121. // ```
  122. auto ReplacePlaceholderNode(int32_t position, NodeKind kind,
  123. Lex::TokenIndex token, bool has_error = false)
  124. -> void;
  125. // Returns the current position and moves past it.
  126. auto Consume() -> Lex::TokenIndex { return *(position_++); }
  127. // Consumes the current token. Does not return it.
  128. auto ConsumeAndDiscard() -> void { ++position_; }
  129. // Parses an open paren token, possibly diagnosing if necessary. Creates a
  130. // leaf parse node of the specified start kind. The default_token is used when
  131. // there's no open paren. Returns the open paren token if it was found.
  132. auto ConsumeAndAddOpenParen(Lex::TokenIndex default_token,
  133. NodeKind start_kind)
  134. -> std::optional<Lex::TokenIndex>;
  135. // Parses a closing symbol corresponding to the opening symbol
  136. // `expected_open`, possibly skipping forward and diagnosing if necessary.
  137. // Creates a parse node of the specified close kind. If `expected_open` is not
  138. // an opening symbol, the parse node will be associated with `state.token`,
  139. // no input will be consumed, and no diagnostic will be emitted.
  140. auto ConsumeAndAddCloseSymbol(Lex::TokenIndex expected_open,
  141. StateStackEntry state, NodeKind close_kind)
  142. -> void;
  143. // Composes `ConsumeIf` and `AddLeafNode`, returning false when ConsumeIf
  144. // fails.
  145. auto ConsumeAndAddLeafNodeIf(Lex::TokenKind token_kind, NodeKind node_kind)
  146. -> bool;
  147. // Returns the current position and moves past it. Requires the token is the
  148. // expected kind.
  149. auto ConsumeChecked(Lex::TokenKind kind) -> Lex::TokenIndex;
  150. // If the current position's token matches this `Kind`, returns it and
  151. // advances to the next position. Otherwise returns an empty optional.
  152. auto ConsumeIf(Lex::TokenKind kind) -> std::optional<Lex::TokenIndex> {
  153. if (!PositionIs(kind)) {
  154. return std::nullopt;
  155. }
  156. return Consume();
  157. }
  158. // Find the next token of any of the given kinds at the current bracketing
  159. // level.
  160. auto FindNextOf(std::initializer_list<Lex::TokenKind> desired_kinds)
  161. -> std::optional<Lex::TokenIndex>;
  162. // If the token is an opening symbol for a matched group, skips to the matched
  163. // closing symbol and returns true. Otherwise, returns false.
  164. auto SkipMatchingGroup() -> bool;
  165. // Skips forward to move past the likely end of a declaration or statement.
  166. //
  167. // Looks forward, skipping over any matched symbol groups, to find the next
  168. // position that is likely past the end of a declaration or statement. This
  169. // is a heuristic and should only be called when skipping past parse errors.
  170. //
  171. // The strategy for recognizing when we have likely passed the end of a
  172. // declaration or statement:
  173. // - If we get to a close curly brace, we likely ended the entire context.
  174. // - If we get to a semicolon, that should have ended the declaration or
  175. // statement.
  176. // - If we get to a new line from the `SkipRoot` token, but with the same or
  177. // less indentation, there is likely a missing semicolon. Continued
  178. // declarations or statements across multiple lines should be indented.
  179. //
  180. // Returns the last token consumed.
  181. auto SkipPastLikelyEnd(Lex::TokenIndex skip_root) -> Lex::TokenIndex;
  182. // Skip forward to the given token. Verifies that it is actually forward.
  183. auto SkipTo(Lex::TokenIndex t) -> void;
  184. // Returns true if the current token satisfies the lexical validity rules
  185. // for an infix operator.
  186. auto IsLexicallyValidInfixOperator() -> bool;
  187. // Determines whether the current trailing operator should be treated as
  188. // infix.
  189. auto IsTrailingOperatorInfix() -> bool;
  190. // Diagnoses whether the current token is not written properly for the given
  191. // fixity. For example, because mandatory whitespace is missing. Regardless of
  192. // whether there's an error, it's expected that parsing continues.
  193. auto DiagnoseOperatorFixity(OperatorFixity fixity) -> void;
  194. // If the current position is a `,`, consumes it, adds the provided token, and
  195. // returns `Comma`. Returns `Close` if the current position is close_token
  196. // (for example, `)`). `CommaClose` indicates it found both (for example,
  197. // `,)`). Handles cases where invalid tokens are present by advancing the
  198. // position, and may emit errors. Pass already_has_error in order to suppress
  199. // duplicate errors.
  200. auto ConsumeListToken(NodeKind comma_kind, Lex::TokenKind close_kind,
  201. bool already_has_error) -> ListTokenKind;
  202. // Gets the kind of the next token to be consumed. If `lookahead` is
  203. // provided, it specifies which token to inspect.
  204. auto PositionKind(Lookahead lookahead = Lookahead::CurrentToken) const
  205. -> Lex::TokenKind {
  206. return tokens_->GetKind(position_[static_cast<int32_t>(lookahead)]);
  207. }
  208. // Tests whether the next token to be consumed is of the specified kind. If
  209. // `lookahead` is provided, it specifies which token to inspect.
  210. auto PositionIs(Lex::TokenKind kind,
  211. Lookahead lookahead = Lookahead::CurrentToken) const -> bool {
  212. return PositionKind(lookahead) == kind;
  213. }
  214. // Pops the state and keeps the value for inspection.
  215. auto PopState() -> StateStackEntry {
  216. auto back = state_stack_.pop_back_val();
  217. CARBON_VLOG("Pop {0}: {1}\n", state_stack_.size(), back);
  218. return back;
  219. }
  220. // Pops the state and discards it.
  221. auto PopAndDiscardState() -> void {
  222. CARBON_VLOG("PopAndDiscard {0}: {1}\n", state_stack_.size() - 1,
  223. state_stack_.back());
  224. state_stack_.pop_back();
  225. }
  226. // Pushes a new state with the current position for context.
  227. auto PushState(State state) -> void { PushState(state, *position_); }
  228. // Pushes a new state with a specific token for context. Used when forming a
  229. // new subtree when the current position isn't the start of the subtree.
  230. auto PushState(State state, Lex::TokenIndex token) -> void {
  231. PushState({.state = state, .token = token, .subtree_start = tree_->size()});
  232. }
  233. // Pushes a new expression state with specific precedence.
  234. auto PushStateForExpr(PrecedenceGroup ambient_precedence) -> void {
  235. PushState({.state = State::Expr,
  236. .ambient_precedence = ambient_precedence,
  237. .token = *position_,
  238. .subtree_start = tree_->size()});
  239. }
  240. // Pushes a new state with detailed precedence for expression resume states.
  241. auto PushStateForExprLoop(State state, PrecedenceGroup ambient_precedence,
  242. PrecedenceGroup lhs_precedence) -> void {
  243. PushState({.state = state,
  244. .ambient_precedence = ambient_precedence,
  245. .lhs_precedence = lhs_precedence,
  246. .token = *position_,
  247. .subtree_start = tree_->size()});
  248. }
  249. // Pushes a new state for handling a pattern. `in_var_pattern` indicates
  250. // whether that pattern is nested inside a `var` pattern.
  251. auto PushStateForPattern(State state, bool in_var_pattern) -> void {
  252. PushState({.state = state,
  253. .in_var_pattern = in_var_pattern,
  254. .token = *position_,
  255. .subtree_start = tree_->size()});
  256. }
  257. // Pushes a constructed state onto the stack.
  258. auto PushState(StateStackEntry state) -> void {
  259. CARBON_VLOG("Push {0}: {1}\n", state_stack_.size(), state);
  260. state_stack_.push_back(state);
  261. CARBON_CHECK(state_stack_.size() < (1 << 20),
  262. "Excessive stack size: likely infinite loop");
  263. }
  264. // Pushes a constructed state onto the stack, with a different parse state.
  265. auto PushState(StateStackEntry state_entry, State parse_state) -> void {
  266. state_entry.state = parse_state;
  267. PushState(state_entry);
  268. }
  269. // Propagates an error up the state stack, to the parent state.
  270. auto ReturnErrorOnState() -> void { state_stack_.back().has_error = true; }
  271. // Adds a node for a declaration's semicolon. Includes error recovery when the
  272. // token is not a semicolon, using `decl_kind` and `is_def_allowed` to inform
  273. // diagnostics.
  274. auto AddNodeExpectingDeclSemi(StateStackEntry state, NodeKind node_kind,
  275. Lex::TokenKind decl_kind, bool is_def_allowed)
  276. -> void;
  277. // Emits a diagnostic for a declaration missing a semi.
  278. auto DiagnoseExpectedDeclSemi(Lex::TokenKind expected_kind) -> void;
  279. // Emits a diagnostic for a declaration missing a semi or definition.
  280. auto DiagnoseExpectedDeclSemiOrDefinition(Lex::TokenKind expected_kind)
  281. -> void;
  282. // Handles error recovery in a declaration, particularly before any possible
  283. // definition has started (although one could be present). Recover to a
  284. // semicolon when it makes sense as a possible end, otherwise use the
  285. // introducer token for the error.
  286. auto RecoverFromDeclError(StateStackEntry state, NodeKind node_kind,
  287. bool skip_past_likely_end) -> void;
  288. // Handles parsing of the library name. Returns the name's ID on success,
  289. // which may be invalid for `default`.
  290. // TODO: Add an invalid node on error, fix callers to adapt.
  291. auto ParseLibraryName(bool accept_default)
  292. -> std::optional<StringLiteralValueId>;
  293. // Handles parsing `library <name>`. Requires that the position is a `library`
  294. // token. Returns the name's ID on success, which may be invalid for
  295. // `default`.
  296. auto ParseLibrarySpecifier(bool accept_default)
  297. -> std::optional<StringLiteralValueId>;
  298. // Sets the package declaration information. Called at most once.
  299. auto set_packaging_decl(Tree::PackagingNames packaging_names, bool is_impl)
  300. -> void {
  301. CARBON_CHECK(!tree_->packaging_decl_);
  302. tree_->packaging_decl_ = {.names = packaging_names, .is_impl = is_impl};
  303. }
  304. // Adds an import.
  305. auto AddImport(Tree::PackagingNames package) -> void {
  306. tree_->imports_.push_back(package);
  307. }
  308. // Adds a function definition start node, and begins tracking a deferred
  309. // definition if necessary.
  310. auto AddFunctionDefinitionStart(Lex::TokenIndex token, bool has_error)
  311. -> void;
  312. // Adds a function definition node, and ends tracking a deferred definition if
  313. // necessary.
  314. auto AddFunctionDefinition(Lex::TokenIndex token, bool has_error) -> void;
  315. // Prints information for a stack dump.
  316. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  317. auto tree() const -> const Tree& { return *tree_; }
  318. auto tokens() const -> const Lex::TokenizedBuffer& { return *tokens_; }
  319. auto has_errors() const -> bool { return err_tracker_.seen_error(); }
  320. auto emitter() -> Lex::TokenDiagnosticEmitter& { return emitter_; }
  321. auto position() -> Lex::TokenIterator& { return position_; }
  322. auto position() const -> Lex::TokenIterator { return position_; }
  323. auto state_stack() -> llvm::SmallVector<StateStackEntry>& {
  324. return state_stack_;
  325. }
  326. auto state_stack() const -> const llvm::SmallVector<StateStackEntry>& {
  327. return state_stack_;
  328. }
  329. auto packaging_state() const -> PackagingState { return packaging_state_; }
  330. auto set_packaging_state(PackagingState packaging_state) -> void {
  331. packaging_state_ = packaging_state;
  332. }
  333. auto first_non_packaging_token() const -> Lex::TokenIndex {
  334. return first_non_packaging_token_;
  335. }
  336. auto set_first_non_packaging_token(Lex::TokenIndex token) -> void {
  337. CARBON_CHECK(!first_non_packaging_token_.has_value());
  338. first_non_packaging_token_ = token;
  339. }
  340. private:
  341. // Applies the `position_` to the `last_byte_offset` returned by `ConvertLoc`.
  342. class TokenDiagnosticConverterForParse
  343. : public Lex::TokenDiagnosticConverter {
  344. public:
  345. explicit TokenDiagnosticConverterForParse(Lex::TokenizedBuffer* tokens,
  346. Lex::TokenIterator* position)
  347. : Lex::TokenDiagnosticConverter(tokens), position_(position) {}
  348. auto ConvertLoc(Lex::TokenIndex token, ContextFnT context_fn) const
  349. -> ConvertedDiagnosticLoc override {
  350. auto converted =
  351. Lex::TokenDiagnosticConverter::ConvertLoc(token, context_fn);
  352. converted.last_byte_offset = std::max(
  353. converted.last_byte_offset, tokens().GetByteOffset(**position_));
  354. return converted;
  355. }
  356. private:
  357. // The position in `Parse()`.
  358. Lex::TokenIterator* position_;
  359. };
  360. // Prints a single token for a stack dump. Used by PrintForStackDump.
  361. auto PrintTokenForStackDump(llvm::raw_ostream& output,
  362. Lex::TokenIndex token) const -> void;
  363. Tree* tree_;
  364. Lex::TokenizedBuffer* tokens_;
  365. TokenDiagnosticConverterForParse converter_;
  366. ErrorTrackingDiagnosticConsumer err_tracker_;
  367. Lex::TokenDiagnosticEmitter emitter_;
  368. // Whether to print verbose output.
  369. llvm::raw_ostream* vlog_stream_;
  370. // The current position within the token buffer.
  371. Lex::TokenIterator position_;
  372. // The FileEnd token.
  373. Lex::TokenIterator end_;
  374. llvm::SmallVector<StateStackEntry> state_stack_;
  375. // The deferred definition indexes of functions whose definitions have begun
  376. // but not yet finished.
  377. llvm::SmallVector<DeferredDefinitionIndex> deferred_definition_stack_;
  378. // The current packaging state, whether `import`/`package` are allowed.
  379. PackagingState packaging_state_ = PackagingState::FileStart;
  380. // The first non-packaging token, starting as invalid. Used for packaging
  381. // state warnings.
  382. Lex::TokenIndex first_non_packaging_token_ = Lex::TokenIndex::None;
  383. };
  384. } // namespace Carbon::Parse
  385. #endif // CARBON_TOOLCHAIN_PARSE_CONTEXT_H_