context.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. // Context and shared functionality for parser handlers. See state.def for state
  17. // documentation.
  18. class Context {
  19. public:
  20. // Possible operator fixities for errors.
  21. enum class OperatorFixity : int8_t { Prefix, Infix, Postfix };
  22. // Possible return values for FindListToken.
  23. enum class ListTokenKind : int8_t { Comma, Close, CommaClose };
  24. // Supported kinds for HandlePattern.
  25. enum class PatternKind : int8_t { ImplicitParam, Param, Variable, Let };
  26. // Supported return values for GetDeclContext.
  27. enum class DeclContext : int8_t {
  28. File, // Top-level context.
  29. Class,
  30. Interface,
  31. NamedConstraint,
  32. };
  33. // Used for restricting ordering of `package` and `import` directives.
  34. enum class PackagingState : int8_t {
  35. StartOfFile,
  36. InImports,
  37. AfterNonPackagingDecl,
  38. // A warning about `import` placement has been issued so we don't keep
  39. // issuing more (when `import` is repeated) until more non-`import`
  40. // declarations come up.
  41. InImportsAfterNonPackagingDecl,
  42. };
  43. // Used to track state on state_stack_.
  44. struct StateStackEntry : public Printable<StateStackEntry> {
  45. explicit StateStackEntry(State state, PrecedenceGroup ambient_precedence,
  46. PrecedenceGroup lhs_precedence, Lex::Token token,
  47. int32_t subtree_start)
  48. : state(state),
  49. ambient_precedence(ambient_precedence),
  50. lhs_precedence(lhs_precedence),
  51. token(token),
  52. subtree_start(subtree_start) {}
  53. // Prints state information for verbose output.
  54. auto Print(llvm::raw_ostream& output) const -> void {
  55. output << state << " @" << token << " subtree_start=" << subtree_start
  56. << " has_error=" << has_error;
  57. };
  58. // The state.
  59. State state;
  60. // Set to true to indicate that an error was found, and that contextual
  61. // error recovery may be needed.
  62. bool has_error = 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;
  68. PrecedenceGroup lhs_precedence;
  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::Token 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 = 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. Lex::TokenDiagnosticEmitter& emitter,
  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::Token token, bool has_error = false)
  92. -> void;
  93. // Adds a node to the parse tree that has children.
  94. auto AddNode(NodeKind kind, Lex::Token token, int subtree_start,
  95. bool has_error) -> void;
  96. // Returns the current position and moves past it.
  97. auto Consume() -> Lex::Token { return *(position_++); }
  98. // Consumes the current token. Does not return it.
  99. auto ConsumeAndDiscard() -> void { ++position_; }
  100. // Parses an open paren token, possibly diagnosing if necessary. Creates a
  101. // leaf parse node of the specified start kind. The default_token is used when
  102. // there's no open paren. Returns the open paren token if it was found.
  103. auto ConsumeAndAddOpenParen(Lex::Token default_token, NodeKind start_kind)
  104. -> std::optional<Lex::Token>;
  105. // Parses a closing symbol corresponding to the opening symbol
  106. // `expected_open`, possibly skipping forward and diagnosing if necessary.
  107. // Creates a parse node of the specified close kind. If `expected_open` is not
  108. // an opening symbol, the parse node will be associated with `state.token`,
  109. // no input will be consumed, and no diagnostic will be emitted.
  110. auto ConsumeAndAddCloseSymbol(Lex::Token expected_open, StateStackEntry state,
  111. NodeKind close_kind) -> void;
  112. // Composes `ConsumeIf` and `AddLeafNode`, returning false when ConsumeIf
  113. // fails.
  114. auto ConsumeAndAddLeafNodeIf(Lex::TokenKind token_kind, NodeKind node_kind)
  115. -> bool;
  116. // Returns the current position and moves past it. Requires the token is the
  117. // expected kind.
  118. auto ConsumeChecked(Lex::TokenKind kind) -> Lex::Token;
  119. // If the current position's token matches this `Kind`, returns it and
  120. // advances to the next position. Otherwise returns an empty optional.
  121. auto ConsumeIf(Lex::TokenKind kind) -> std::optional<Lex::Token>;
  122. // Find the next token of any of the given kinds at the current bracketing
  123. // level.
  124. auto FindNextOf(std::initializer_list<Lex::TokenKind> desired_kinds)
  125. -> std::optional<Lex::Token>;
  126. // If the token is an opening symbol for a matched group, skips to the matched
  127. // closing symbol and returns true. Otherwise, returns false.
  128. auto SkipMatchingGroup() -> bool;
  129. // Skips forward to move past the likely end of a declaration or statement.
  130. //
  131. // Looks forward, skipping over any matched symbol groups, to find the next
  132. // position that is likely past the end of a declaration or statement. This
  133. // is a heuristic and should only be called when skipping past parse errors.
  134. //
  135. // The strategy for recognizing when we have likely passed the end of a
  136. // declaration or statement:
  137. // - If we get to a close curly brace, we likely ended the entire context.
  138. // - If we get to a semicolon, that should have ended the declaration or
  139. // statement.
  140. // - If we get to a new line from the `SkipRoot` token, but with the same or
  141. // less indentation, there is likely a missing semicolon. Continued
  142. // declarations or statements across multiple lines should be indented.
  143. //
  144. // Returns a semicolon token if one is the likely end.
  145. auto SkipPastLikelyEnd(Lex::Token skip_root) -> std::optional<Lex::Token>;
  146. // Skip forward to the given token. Verifies that it is actually forward.
  147. auto SkipTo(Lex::Token t) -> void;
  148. // Returns true if the current token satisfies the lexical validity rules
  149. // for an infix operator.
  150. auto IsLexicallyValidInfixOperator() -> bool;
  151. // Determines whether the current trailing operator should be treated as
  152. // infix.
  153. auto IsTrailingOperatorInfix() -> bool;
  154. // Diagnoses whether the current token is not written properly for the given
  155. // fixity. For example, because mandatory whitespace is missing. Regardless of
  156. // whether there's an error, it's expected that parsing continues.
  157. auto DiagnoseOperatorFixity(OperatorFixity fixity) -> void;
  158. // If the current position is a `,`, consumes it, adds the provided token, and
  159. // returns `Comma`. Returns `Close` if the current position is close_token
  160. // (for example, `)`). `CommaClose` indicates it found both (for example,
  161. // `,)`). Handles cases where invalid tokens are present by advancing the
  162. // position, and may emit errors. Pass already_has_error in order to suppress
  163. // duplicate errors.
  164. auto ConsumeListToken(NodeKind comma_kind, Lex::TokenKind close_kind,
  165. bool already_has_error) -> ListTokenKind;
  166. // Gets the kind of the next token to be consumed.
  167. auto PositionKind() const -> Lex::TokenKind {
  168. return tokens_->GetKind(*position_);
  169. }
  170. // Tests whether the next token to be consumed is of the specified kind.
  171. auto PositionIs(Lex::TokenKind kind) const -> bool {
  172. return PositionKind() == kind;
  173. }
  174. // Pops the state and keeps the value for inspection.
  175. auto PopState() -> StateStackEntry {
  176. auto back = state_stack_.pop_back_val();
  177. CARBON_VLOG() << "Pop " << state_stack_.size() << ": " << back << "\n";
  178. return back;
  179. }
  180. // Pops the state and discards it.
  181. auto PopAndDiscardState() -> void {
  182. CARBON_VLOG() << "PopAndDiscard " << state_stack_.size() - 1 << ": "
  183. << state_stack_.back() << "\n";
  184. state_stack_.pop_back();
  185. }
  186. // Pushes a new state with the current position for context.
  187. auto PushState(State state) -> void {
  188. PushState(StateStackEntry(state, PrecedenceGroup::ForTopLevelExpr(),
  189. PrecedenceGroup::ForTopLevelExpr(), *position_,
  190. tree_->size()));
  191. }
  192. // Pushes a new state with a specific token for context. Used when forming a
  193. // new subtree with a token that isn't the start of the subtree.
  194. auto PushState(State state, Lex::Token token) -> void {
  195. PushState(StateStackEntry(state, PrecedenceGroup::ForTopLevelExpr(),
  196. PrecedenceGroup::ForTopLevelExpr(), token,
  197. tree_->size()));
  198. }
  199. // Pushes a new expression state with specific precedence.
  200. auto PushStateForExpr(PrecedenceGroup ambient_precedence) -> void {
  201. PushState(StateStackEntry(State::Expr, ambient_precedence,
  202. PrecedenceGroup::ForTopLevelExpr(), *position_,
  203. tree_->size()));
  204. }
  205. // Pushes a new state with detailed precedence for expression resume states.
  206. auto PushStateForExprLoop(State state, PrecedenceGroup ambient_precedence,
  207. PrecedenceGroup lhs_precedence) -> void {
  208. PushState(StateStackEntry(state, ambient_precedence, lhs_precedence,
  209. *position_, tree_->size()));
  210. }
  211. // Pushes a constructed state onto the stack.
  212. auto PushState(StateStackEntry state) -> void {
  213. CARBON_VLOG() << "Push " << state_stack_.size() << ": " << state << "\n";
  214. state_stack_.push_back(state);
  215. CARBON_CHECK(state_stack_.size() < (1 << 20))
  216. << "Excessive stack size: likely infinite loop";
  217. }
  218. // Returns the current declaration context according to state_stack_.
  219. // This is expected to be called in cases which are close to a context.
  220. // Although it looks like it could be O(n) for state_stack_'s depth, valid
  221. // parses should only need to look down a couple steps.
  222. //
  223. // This currently assumes it's being called from within the declaration's
  224. // DeclScopeLoop.
  225. auto GetDeclContext() -> DeclContext;
  226. // Propagates an error up the state stack, to the parent state.
  227. auto ReturnErrorOnState() -> void { state_stack_.back().has_error = true; }
  228. // For HandlePattern, tries to consume a wrapping keyword.
  229. auto ConsumeIfPatternKeyword(Lex::TokenKind keyword_token,
  230. State keyword_state, int subtree_start) -> void;
  231. // Emits a diagnostic for a declaration missing a semi.
  232. auto EmitExpectedDeclSemi(Lex::TokenKind expected_kind) -> void;
  233. // Emits a diagnostic for a declaration missing a semi or definition.
  234. auto EmitExpectedDeclSemiOrDefinition(Lex::TokenKind expected_kind) -> void;
  235. // Handles error recovery in a declaration, particularly before any possible
  236. // definition has started (although one could be present). Recover to a
  237. // semicolon when it makes sense as a possible end, otherwise use the
  238. // introducer token for the error.
  239. auto RecoverFromDeclError(StateStackEntry state, NodeKind parse_node_kind,
  240. bool skip_past_likely_end) -> void;
  241. // Prints information for a stack dump.
  242. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  243. auto tree() const -> const Tree& { return *tree_; }
  244. auto tokens() const -> const Lex::TokenizedBuffer& { return *tokens_; }
  245. auto emitter() -> Lex::TokenDiagnosticEmitter& { return *emitter_; }
  246. auto position() -> Lex::TokenIterator& { return position_; }
  247. auto position() const -> Lex::TokenIterator { return position_; }
  248. auto state_stack() -> llvm::SmallVector<StateStackEntry>& {
  249. return state_stack_;
  250. }
  251. auto state_stack() const -> const llvm::SmallVector<StateStackEntry>& {
  252. return state_stack_;
  253. }
  254. auto packaging_state() const -> PackagingState { return packaging_state_; }
  255. auto set_packaging_state(PackagingState packaging_state) -> void {
  256. packaging_state_ = packaging_state;
  257. }
  258. auto first_non_packaging_token() const -> Lex::Token {
  259. return first_non_packaging_token_;
  260. }
  261. auto set_first_non_packaging_token(Lex::Token token) -> void {
  262. CARBON_CHECK(!first_non_packaging_token_.is_valid());
  263. first_non_packaging_token_ = token;
  264. }
  265. private:
  266. // Prints a single token for a stack dump. Used by PrintForStackDump.
  267. auto PrintTokenForStackDump(llvm::raw_ostream& output, Lex::Token token) const
  268. -> void;
  269. Tree* tree_;
  270. Lex::TokenizedBuffer* tokens_;
  271. Lex::TokenDiagnosticEmitter* emitter_;
  272. // Whether to print verbose output.
  273. llvm::raw_ostream* vlog_stream_;
  274. // The current position within the token buffer.
  275. Lex::TokenIterator position_;
  276. // The EndOfFile token.
  277. Lex::TokenIterator end_;
  278. llvm::SmallVector<StateStackEntry> state_stack_;
  279. // The current packaging state, whether `import`/`package` are allowed.
  280. PackagingState packaging_state_ = PackagingState::StartOfFile;
  281. // The first non-packaging token, starting as invalid. Used for packaging
  282. // state warnings.
  283. Lex::Token first_non_packaging_token_ = Lex::Token::Invalid;
  284. };
  285. // `clang-format` has a bug with spacing around `->` returns in macros. See
  286. // https://bugs.llvm.org/show_bug.cgi?id=48320 for details.
  287. #define CARBON_PARSE_STATE(Name) auto Handle##Name(Context& context)->void;
  288. #include "toolchain/parse/state.def"
  289. } // namespace Carbon::Parse
  290. #endif // CARBON_TOOLCHAIN_PARSE_CONTEXT_H_