context.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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/lex/token_kind.h"
  10. #include "toolchain/lex/tokenized_buffer.h"
  11. #include "toolchain/parse/node_kind.h"
  12. #include "toolchain/parse/precedence.h"
  13. #include "toolchain/parse/state.h"
  14. #include "toolchain/parse/tree.h"
  15. namespace Carbon::Parse {
  16. // An amount by which to look ahead of the current token. Lookahead should be
  17. // used sparingly, and unbounded lookahead should be avoided.
  18. //
  19. // TODO: Decide whether we want to avoid lookahead altogether.
  20. //
  21. // NOLINTNEXTLINE(performance-enum-size): Deliberately matches index size.
  22. enum class Lookahead : int32_t {
  23. CurrentToken = 0,
  24. NextToken = 1,
  25. };
  26. // Context and shared functionality for parser handlers. See state.def for state
  27. // documentation.
  28. class Context {
  29. public:
  30. // Possible operator fixities for errors.
  31. enum class OperatorFixity : int8_t { Prefix, Infix, Postfix };
  32. // Possible return values for FindListToken.
  33. enum class ListTokenKind : int8_t { Comma, Close, CommaClose };
  34. // Supported kinds for HandleBindingPattern.
  35. enum class BindingPatternKind : int8_t {
  36. ImplicitParam,
  37. Param,
  38. Variable,
  39. Let
  40. };
  41. // Supported return values for GetDeclContext.
  42. enum class DeclContext : int8_t {
  43. File, // Top-level context.
  44. Class,
  45. Interface,
  46. NamedConstraint,
  47. };
  48. // Used for restricting ordering of `package` and `import` directives.
  49. enum class PackagingState : int8_t {
  50. FileStart,
  51. InImports,
  52. AfterNonPackagingDecl,
  53. // A warning about `import` placement has been issued so we don't keep
  54. // issuing more (when `import` is repeated) until more non-`import`
  55. // declarations come up.
  56. InImportsAfterNonPackagingDecl,
  57. };
  58. // Used to track state on state_stack_.
  59. struct StateStackEntry : public Printable<StateStackEntry> {
  60. explicit StateStackEntry(State state, PrecedenceGroup ambient_precedence,
  61. PrecedenceGroup lhs_precedence,
  62. Lex::TokenIndex token, int32_t subtree_start)
  63. : state(state),
  64. ambient_precedence(ambient_precedence),
  65. lhs_precedence(lhs_precedence),
  66. token(token),
  67. subtree_start(subtree_start) {}
  68. // Prints state information for verbose output.
  69. auto Print(llvm::raw_ostream& output) const -> void {
  70. output << state << " @" << token << " subtree_start=" << subtree_start
  71. << " has_error=" << has_error;
  72. };
  73. // The state.
  74. State state;
  75. // Set to true to indicate that an error was found, and that contextual
  76. // error recovery may be needed.
  77. bool has_error = false;
  78. // Precedence information used by expression states in order to determine
  79. // operator precedence. The ambient_precedence deals with how the expression
  80. // should interact with outside context, while the lhs_precedence is
  81. // specific to the lhs of an operator expression.
  82. PrecedenceGroup ambient_precedence;
  83. PrecedenceGroup lhs_precedence;
  84. // A token providing context based on the subtree. This will typically be
  85. // the first token in the subtree, but may sometimes be a token within. It
  86. // will typically be used for the subtree's root node.
  87. Lex::TokenIndex token;
  88. // The offset within the Tree of the subtree start.
  89. int32_t subtree_start;
  90. };
  91. // We expect StateStackEntry to fit into 12 bytes:
  92. // state = 1 byte
  93. // has_error = 1 byte
  94. // ambient_precedence = 1 byte
  95. // lhs_precedence = 1 byte
  96. // token = 4 bytes
  97. // subtree_start = 4 bytes
  98. // If it becomes bigger, it'd be worth examining better packing; it should be
  99. // feasible to pack the 1-byte entries more tightly.
  100. static_assert(sizeof(StateStackEntry) == 12,
  101. "StateStackEntry has unexpected size!");
  102. explicit Context(Tree& tree, Lex::TokenizedBuffer& tokens,
  103. Lex::TokenDiagnosticEmitter& emitter,
  104. llvm::raw_ostream* vlog_stream);
  105. // Adds a node to the parse tree that has no children (a leaf).
  106. auto AddLeafNode(NodeKind kind, Lex::TokenIndex token, bool has_error = false)
  107. -> void;
  108. // Adds a node to the parse tree that has children.
  109. auto AddNode(NodeKind kind, Lex::TokenIndex token, int subtree_start,
  110. bool has_error) -> void;
  111. // Replaces the placeholder node at the indicated position with a leaf node.
  112. //
  113. // To reserve a position in the parse tree, you may add a placeholder parse
  114. // node using code like:
  115. // ```
  116. // context.PushState(State::WillFillInPlaceholder);
  117. // context.AddLeafNode(NodeKind::Placeholder, *context.position());
  118. // ```
  119. // It may be replaced with the intended leaf parse node with code like:
  120. // ```
  121. // auto HandleWillFillInPlaceholder(Context& context) -> void {
  122. // auto state = context.PopState();
  123. // context.ReplacePlaceholderNode(state.subtree_start, /* replacement */);
  124. // }
  125. // ```
  126. auto ReplacePlaceholderNode(int32_t position, NodeKind kind,
  127. Lex::TokenIndex token, bool has_error = false)
  128. -> void;
  129. // Returns the current position and moves past it.
  130. auto Consume() -> Lex::TokenIndex { return *(position_++); }
  131. // Consumes the current token. Does not return it.
  132. auto ConsumeAndDiscard() -> void { ++position_; }
  133. // Parses an open paren token, possibly diagnosing if necessary. Creates a
  134. // leaf parse node of the specified start kind. The default_token is used when
  135. // there's no open paren. Returns the open paren token if it was found.
  136. auto ConsumeAndAddOpenParen(Lex::TokenIndex default_token,
  137. NodeKind start_kind)
  138. -> std::optional<Lex::TokenIndex>;
  139. // Parses a closing symbol corresponding to the opening symbol
  140. // `expected_open`, possibly skipping forward and diagnosing if necessary.
  141. // Creates a parse node of the specified close kind. If `expected_open` is not
  142. // an opening symbol, the parse node will be associated with `state.token`,
  143. // no input will be consumed, and no diagnostic will be emitted.
  144. auto ConsumeAndAddCloseSymbol(Lex::TokenIndex expected_open,
  145. StateStackEntry state, NodeKind close_kind)
  146. -> void;
  147. // Composes `ConsumeIf` and `AddLeafNode`, returning false when ConsumeIf
  148. // fails.
  149. auto ConsumeAndAddLeafNodeIf(Lex::TokenKind token_kind, NodeKind node_kind)
  150. -> bool;
  151. // Returns the current position and moves past it. Requires the token is the
  152. // expected kind.
  153. auto ConsumeChecked(Lex::TokenKind kind) -> Lex::TokenIndex;
  154. // If the current position's token matches this `Kind`, returns it and
  155. // advances to the next position. Otherwise returns an empty optional.
  156. auto ConsumeIf(Lex::TokenKind kind) -> std::optional<Lex::TokenIndex>;
  157. // Find the next token of any of the given kinds at the current bracketing
  158. // level.
  159. auto FindNextOf(std::initializer_list<Lex::TokenKind> desired_kinds)
  160. -> std::optional<Lex::TokenIndex>;
  161. // If the token is an opening symbol for a matched group, skips to the matched
  162. // closing symbol and returns true. Otherwise, returns false.
  163. auto SkipMatchingGroup() -> bool;
  164. // Skips forward to move past the likely end of a declaration or statement.
  165. //
  166. // Looks forward, skipping over any matched symbol groups, to find the next
  167. // position that is likely past the end of a declaration or statement. This
  168. // is a heuristic and should only be called when skipping past parse errors.
  169. //
  170. // The strategy for recognizing when we have likely passed the end of a
  171. // declaration or statement:
  172. // - If we get to a close curly brace, we likely ended the entire context.
  173. // - If we get to a semicolon, that should have ended the declaration or
  174. // statement.
  175. // - If we get to a new line from the `SkipRoot` token, but with the same or
  176. // less indentation, there is likely a missing semicolon. Continued
  177. // declarations or statements across multiple lines should be indented.
  178. //
  179. // Returns a semicolon token if one is the likely end.
  180. auto SkipPastLikelyEnd(Lex::TokenIndex skip_root)
  181. -> std::optional<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 " << state_stack_.size() << ": " << back << "\n";
  218. return back;
  219. }
  220. // Pops the state and discards it.
  221. auto PopAndDiscardState() -> void {
  222. CARBON_VLOG() << "PopAndDiscard " << state_stack_.size() - 1 << ": "
  223. << state_stack_.back() << "\n";
  224. state_stack_.pop_back();
  225. }
  226. // Pushes a new state with the current position for context.
  227. auto PushState(State state) -> void {
  228. PushState(StateStackEntry(state, PrecedenceGroup::ForTopLevelExpr(),
  229. PrecedenceGroup::ForTopLevelExpr(), *position_,
  230. tree_->size()));
  231. }
  232. // Pushes a new state with a specific token for context. Used when forming a
  233. // new subtree with a token that isn't the start of the subtree.
  234. auto PushState(State state, Lex::TokenIndex token) -> void {
  235. PushState(StateStackEntry(state, PrecedenceGroup::ForTopLevelExpr(),
  236. PrecedenceGroup::ForTopLevelExpr(), token,
  237. tree_->size()));
  238. }
  239. // Pushes a new expression state with specific precedence.
  240. auto PushStateForExpr(PrecedenceGroup ambient_precedence) -> void {
  241. PushState(StateStackEntry(State::Expr, ambient_precedence,
  242. PrecedenceGroup::ForTopLevelExpr(), *position_,
  243. tree_->size()));
  244. }
  245. // Pushes a new state with detailed precedence for expression resume states.
  246. auto PushStateForExprLoop(State state, PrecedenceGroup ambient_precedence,
  247. PrecedenceGroup lhs_precedence) -> void {
  248. PushState(StateStackEntry(state, ambient_precedence, lhs_precedence,
  249. *position_, tree_->size()));
  250. }
  251. // Pushes a constructed state onto the stack.
  252. auto PushState(StateStackEntry state) -> void {
  253. CARBON_VLOG() << "Push " << state_stack_.size() << ": " << state << "\n";
  254. state_stack_.push_back(state);
  255. CARBON_CHECK(state_stack_.size() < (1 << 20))
  256. << "Excessive stack size: likely infinite loop";
  257. }
  258. // Returns the current declaration context according to state_stack_.
  259. // This is expected to be called in cases which are close to a context.
  260. // Although it looks like it could be O(n) for state_stack_'s depth, valid
  261. // parses should only need to look down a couple steps.
  262. //
  263. // This currently assumes it's being called from within the declaration's
  264. // DeclScopeLoop.
  265. auto GetDeclContext() -> DeclContext;
  266. // Propagates an error up the state stack, to the parent state.
  267. auto ReturnErrorOnState() -> void { state_stack_.back().has_error = true; }
  268. // For HandleBindingPattern, tries to consume a wrapping keyword.
  269. auto ConsumeIfBindingPatternKeyword(Lex::TokenKind keyword_token,
  270. State keyword_state, int subtree_start)
  271. -> void;
  272. // Emits a diagnostic for a declaration missing a semi.
  273. auto EmitExpectedDeclSemi(Lex::TokenKind expected_kind) -> void;
  274. // Emits a diagnostic for a declaration missing a semi or definition.
  275. auto EmitExpectedDeclSemiOrDefinition(Lex::TokenKind expected_kind) -> void;
  276. // Handles error recovery in a declaration, particularly before any possible
  277. // definition has started (although one could be present). Recover to a
  278. // semicolon when it makes sense as a possible end, otherwise use the
  279. // introducer token for the error.
  280. auto RecoverFromDeclError(StateStackEntry state, NodeKind parse_node_kind,
  281. bool skip_past_likely_end) -> void;
  282. // Sets the package directive information. Called at most once.
  283. auto set_packaging_directive(Tree::PackagingNames packaging_names,
  284. Tree::ApiOrImpl api_or_impl) -> void {
  285. CARBON_CHECK(!tree_->packaging_directive_);
  286. tree_->packaging_directive_ = {.names = packaging_names,
  287. .api_or_impl = api_or_impl};
  288. }
  289. // Adds an import.
  290. auto AddImport(Tree::PackagingNames package) -> void {
  291. tree_->imports_.push_back(package);
  292. }
  293. // Prints information for a stack dump.
  294. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  295. auto tree() const -> const Tree& { return *tree_; }
  296. auto tokens() const -> const Lex::TokenizedBuffer& { return *tokens_; }
  297. auto emitter() -> Lex::TokenDiagnosticEmitter& { return *emitter_; }
  298. auto position() -> Lex::TokenIterator& { return position_; }
  299. auto position() const -> Lex::TokenIterator { return position_; }
  300. auto state_stack() -> llvm::SmallVector<StateStackEntry>& {
  301. return state_stack_;
  302. }
  303. auto state_stack() const -> const llvm::SmallVector<StateStackEntry>& {
  304. return state_stack_;
  305. }
  306. auto packaging_state() const -> PackagingState { return packaging_state_; }
  307. auto set_packaging_state(PackagingState packaging_state) -> void {
  308. packaging_state_ = packaging_state;
  309. }
  310. auto first_non_packaging_token() const -> Lex::TokenIndex {
  311. return first_non_packaging_token_;
  312. }
  313. auto set_first_non_packaging_token(Lex::TokenIndex token) -> void {
  314. CARBON_CHECK(!first_non_packaging_token_.is_valid());
  315. first_non_packaging_token_ = token;
  316. }
  317. private:
  318. // Prints a single token for a stack dump. Used by PrintForStackDump.
  319. auto PrintTokenForStackDump(llvm::raw_ostream& output,
  320. Lex::TokenIndex token) const -> void;
  321. Tree* tree_;
  322. Lex::TokenizedBuffer* tokens_;
  323. Lex::TokenDiagnosticEmitter* emitter_;
  324. // Whether to print verbose output.
  325. llvm::raw_ostream* vlog_stream_;
  326. // The current position within the token buffer.
  327. Lex::TokenIterator position_;
  328. // The FileEnd token.
  329. Lex::TokenIterator end_;
  330. llvm::SmallVector<StateStackEntry> state_stack_;
  331. // The current packaging state, whether `import`/`package` are allowed.
  332. PackagingState packaging_state_ = PackagingState::FileStart;
  333. // The first non-packaging token, starting as invalid. Used for packaging
  334. // state warnings.
  335. Lex::TokenIndex first_non_packaging_token_ = Lex::TokenIndex::Invalid;
  336. };
  337. // `clang-format` has a bug with spacing around `->` returns in macros. See
  338. // https://bugs.llvm.org/show_bug.cgi?id=48320 for details.
  339. #define CARBON_PARSE_STATE(Name) auto Handle##Name(Context& context)->void;
  340. #include "toolchain/parse/state.def"
  341. } // namespace Carbon::Parse
  342. #endif // CARBON_TOOLCHAIN_PARSE_CONTEXT_H_