parser_context.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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_PARSER_PARSER_CONTEXT_H_
  5. #define CARBON_TOOLCHAIN_PARSER_PARSER_CONTEXT_H_
  6. #include <optional>
  7. #include "common/check.h"
  8. #include "common/vlog.h"
  9. #include "toolchain/lexer/token_kind.h"
  10. #include "toolchain/lexer/tokenized_buffer.h"
  11. #include "toolchain/parser/parse_node_kind.h"
  12. #include "toolchain/parser/parse_tree.h"
  13. #include "toolchain/parser/parser_state.h"
  14. #include "toolchain/parser/precedence.h"
  15. namespace Carbon {
  16. // Context and shared functionality for parser handlers. See parser_state.def
  17. // for state documentation.
  18. class ParserContext {
  19. public:
  20. // Possible operator fixities for errors.
  21. enum class OperatorFixity { Prefix, Infix, Postfix };
  22. // Possible return values for FindListToken.
  23. enum class ListTokenKind { Comma, Close, CommaClose };
  24. // Supported kinds for HandlePattern.
  25. enum class PatternKind { DeducedParameter, Parameter, Variable };
  26. // Supported return values for GetDeclarationContext.
  27. enum class DeclarationContext {
  28. File, // Top-level context.
  29. Class,
  30. Interface,
  31. NamedConstraint,
  32. };
  33. // Used to track state on state_stack_.
  34. struct StateStackEntry {
  35. explicit StateStackEntry(ParserState state,
  36. PrecedenceGroup ambient_precedence,
  37. PrecedenceGroup lhs_precedence,
  38. TokenizedBuffer::Token token,
  39. int32_t subtree_start)
  40. : state(state),
  41. ambient_precedence(ambient_precedence),
  42. lhs_precedence(lhs_precedence),
  43. token(token),
  44. subtree_start(subtree_start) {}
  45. // Prints state information for verbose output.
  46. auto Print(llvm::raw_ostream& output) const -> void {
  47. output << state << " @" << token << " subtree_start=" << subtree_start
  48. << " has_error=" << has_error;
  49. };
  50. // The state.
  51. ParserState state;
  52. // Set to true to indicate that an error was found, and that contextual
  53. // error recovery may be needed.
  54. bool has_error = false;
  55. // Precedence information used by expression states in order to determine
  56. // operator precedence. The ambient_precedence deals with how the expression
  57. // should interact with outside context, while the lhs_precedence is
  58. // specific to the lhs of an operator expression.
  59. PrecedenceGroup ambient_precedence;
  60. PrecedenceGroup lhs_precedence;
  61. // A token providing context based on the subtree. This will typically be
  62. // the first token in the subtree, but may sometimes be a token within. It
  63. // will typically be used for the subtree's root node.
  64. TokenizedBuffer::Token token;
  65. // The offset within the ParseTree of the subtree start.
  66. int32_t subtree_start;
  67. };
  68. // We expect StateStackEntry to fit into 12 bytes:
  69. // state = 1 byte
  70. // has_error = 1 byte
  71. // ambient_precedence = 1 byte
  72. // lhs_precedence = 1 byte
  73. // token = 4 bytes
  74. // subtree_start = 4 bytes
  75. // If it becomes bigger, it'd be worth examining better packing; it should be
  76. // feasible to pack the 1-byte entries more tightly.
  77. static_assert(sizeof(StateStackEntry) == 12,
  78. "StateStackEntry has unexpected size!");
  79. explicit ParserContext(ParseTree& tree, TokenizedBuffer& tokens,
  80. TokenDiagnosticEmitter& emitter,
  81. llvm::raw_ostream* vlog_stream);
  82. // Adds a node to the parse tree that has no children (a leaf).
  83. auto AddLeafNode(ParseNodeKind kind, TokenizedBuffer::Token token,
  84. bool has_error = false) -> void;
  85. // Adds a node to the parse tree that has children.
  86. auto AddNode(ParseNodeKind kind, TokenizedBuffer::Token token,
  87. int subtree_start, bool has_error) -> void;
  88. // Returns the current position and moves past it.
  89. auto Consume() -> TokenizedBuffer::Token { return *(position_++); }
  90. // Parses an open paren token, possibly diagnosing if necessary. Creates a
  91. // leaf parse node of the specified start kind. The default_token is used when
  92. // there's no open paren. Returns the open paren token if it was found.
  93. auto ConsumeAndAddOpenParen(TokenizedBuffer::Token default_token,
  94. ParseNodeKind start_kind)
  95. -> std::optional<TokenizedBuffer::Token>;
  96. // Parses a closing symbol corresponding to the opening symbol
  97. // `expected_open`, possibly skipping forward and diagnosing if necessary.
  98. // Creates a parse node of the specified close kind. If `expected_open` is not
  99. // an opening symbol, the parse node will be associated with `state.token`,
  100. // no input will be consumed, and no diagnostic will be emitted.
  101. auto ConsumeAndAddCloseSymbol(TokenizedBuffer::Token expected_open,
  102. StateStackEntry state, ParseNodeKind close_kind)
  103. -> void;
  104. // Composes `ConsumeIf` and `AddLeafNode`, returning false when ConsumeIf
  105. // fails.
  106. auto ConsumeAndAddLeafNodeIf(TokenKind token_kind, ParseNodeKind node_kind)
  107. -> bool;
  108. // Returns the current position and moves past it. Requires the token is the
  109. // expected kind.
  110. auto ConsumeChecked(TokenKind kind) -> TokenizedBuffer::Token;
  111. // If the current position's token matches this `Kind`, returns it and
  112. // advances to the next position. Otherwise returns an empty optional.
  113. auto ConsumeIf(TokenKind kind) -> std::optional<TokenizedBuffer::Token>;
  114. // Find the next token of any of the given kinds at the current bracketing
  115. // level.
  116. auto FindNextOf(std::initializer_list<TokenKind> desired_kinds)
  117. -> std::optional<TokenizedBuffer::Token>;
  118. // If the token is an opening symbol for a matched group, skips to the matched
  119. // closing symbol and returns true. Otherwise, returns false.
  120. auto SkipMatchingGroup() -> bool;
  121. // Skips forward to move past the likely end of a declaration or statement.
  122. //
  123. // Looks forward, skipping over any matched symbol groups, to find the next
  124. // position that is likely past the end of a declaration or statement. This
  125. // is a heuristic and should only be called when skipping past parse errors.
  126. //
  127. // The strategy for recognizing when we have likely passed the end of a
  128. // declaration or statement:
  129. // - If we get to a close curly brace, we likely ended the entire context.
  130. // - If we get to a semicolon, that should have ended the declaration or
  131. // statement.
  132. // - If we get to a new line from the `SkipRoot` token, but with the same or
  133. // less indentation, there is likely a missing semicolon. Continued
  134. // declarations or statements across multiple lines should be indented.
  135. //
  136. // Returns a semicolon token if one is the likely end.
  137. auto SkipPastLikelyEnd(TokenizedBuffer::Token skip_root)
  138. -> std::optional<TokenizedBuffer::Token>;
  139. // Skip forward to the given token. Verifies that it is actually forward.
  140. auto SkipTo(TokenizedBuffer::Token t) -> void;
  141. // Returns true if the current token satisfies the lexical validity rules
  142. // for an infix operator.
  143. auto IsLexicallyValidInfixOperator() -> bool;
  144. // Determines whether the current trailing operator should be treated as
  145. // infix.
  146. auto IsTrailingOperatorInfix() -> bool;
  147. // Diagnoses whether the current token is not written properly for the given
  148. // fixity. For example, because mandatory whitespace is missing. Regardless of
  149. // whether there's an error, it's expected that parsing continues.
  150. auto DiagnoseOperatorFixity(OperatorFixity fixity) -> void;
  151. // If the current position is a `,`, consumes it, adds the provided token, and
  152. // returns `Comma`. Returns `Close` if the current position is close_token
  153. // (for example, `)`). `CommaClose` indicates it found both (for example,
  154. // `,)`). Handles cases where invalid tokens are present by advancing the
  155. // position, and may emit errors. Pass already_has_error in order to suppress
  156. // duplicate errors.
  157. auto ConsumeListToken(ParseNodeKind comma_kind, TokenKind close_kind,
  158. bool already_has_error) -> ListTokenKind;
  159. // Gets the kind of the next token to be consumed.
  160. auto PositionKind() const -> TokenKind {
  161. return tokens_->GetKind(*position_);
  162. }
  163. // Tests whether the next token to be consumed is of the specified kind.
  164. auto PositionIs(TokenKind kind) const -> bool {
  165. return PositionKind() == kind;
  166. }
  167. // Pops the state and keeps the value for inspection.
  168. auto PopState() -> StateStackEntry {
  169. auto back = state_stack_.pop_back_val();
  170. CARBON_VLOG() << "Pop " << state_stack_.size() << ": " << back << "\n";
  171. return back;
  172. }
  173. // Pops the state and discards it.
  174. auto PopAndDiscardState() -> void {
  175. CARBON_VLOG() << "PopAndDiscard " << state_stack_.size() - 1 << ": "
  176. << state_stack_.back() << "\n";
  177. state_stack_.pop_back();
  178. }
  179. // Pushes a new state with the current position for context.
  180. auto PushState(ParserState state) -> void {
  181. PushState(StateStackEntry(state, PrecedenceGroup::ForTopLevelExpression(),
  182. PrecedenceGroup::ForTopLevelExpression(),
  183. *position_, tree_->size()));
  184. }
  185. // Pushes a new state with a specific token for context. Used when forming a
  186. // new subtree with a token that isn't the start of the subtree.
  187. auto PushState(ParserState state, TokenizedBuffer::Token token) -> void {
  188. PushState(StateStackEntry(state, PrecedenceGroup::ForTopLevelExpression(),
  189. PrecedenceGroup::ForTopLevelExpression(), token,
  190. tree_->size()));
  191. }
  192. // Pushes a new expression state with specific precedence.
  193. auto PushStateForExpression(PrecedenceGroup ambient_precedence) -> void {
  194. PushState(StateStackEntry(ParserState::Expression, ambient_precedence,
  195. PrecedenceGroup::ForTopLevelExpression(),
  196. *position_, tree_->size()));
  197. }
  198. // Pushes a new state with detailed precedence for expression resume states.
  199. auto PushStateForExpressionLoop(ParserState state,
  200. PrecedenceGroup ambient_precedence,
  201. PrecedenceGroup lhs_precedence) -> void {
  202. PushState(StateStackEntry(state, ambient_precedence, lhs_precedence,
  203. *position_, tree_->size()));
  204. }
  205. // Pushes a constructed state onto the stack.
  206. auto PushState(StateStackEntry state) -> void {
  207. CARBON_VLOG() << "Push " << state_stack_.size() << ": " << state << "\n";
  208. state_stack_.push_back(state);
  209. CARBON_CHECK(state_stack_.size() < (1 << 20))
  210. << "Excessive stack size: likely infinite loop";
  211. }
  212. // Returns the current declaration context according to state_stack_.
  213. // This is expected to be called in cases which are close to a context.
  214. // Although it looks like it could be O(n) for state_stack_'s depth, valid
  215. // parses should only need to look down a couple steps.
  216. //
  217. // This currently assumes it's being called from within the declaration's
  218. // DeclarationScopeLoop.
  219. auto GetDeclarationContext() -> DeclarationContext;
  220. // Propagates an error up the state stack, to the parent state.
  221. auto ReturnErrorOnState() -> void { state_stack_.back().has_error = true; }
  222. // For ParserHandlePattern, tries to consume a wrapping keyword.
  223. auto ConsumeIfPatternKeyword(TokenKind keyword_token,
  224. ParserState keyword_state, int subtree_start)
  225. -> void;
  226. // Emits a diagnostic for a declaration missing a semi.
  227. auto EmitExpectedDeclarationSemi(TokenKind expected_kind) -> void;
  228. // Emits a diagnostic for a declaration missing a semi or definition.
  229. auto EmitExpectedDeclarationSemiOrDefinition(TokenKind expected_kind) -> void;
  230. // Handles error recovery in a declaration, particularly before any possible
  231. // definition has started (although one could be present). Recover to a
  232. // semicolon when it makes sense as a possible end, otherwise use the
  233. // introducer token for the error.
  234. auto RecoverFromDeclarationError(StateStackEntry state,
  235. ParseNodeKind parse_node_kind,
  236. bool skip_past_likely_end) -> void;
  237. // Prints information for a stack dump.
  238. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  239. auto tree() const -> const ParseTree& { return *tree_; }
  240. auto tokens() const -> const TokenizedBuffer& { return *tokens_; }
  241. auto emitter() -> TokenDiagnosticEmitter& { return *emitter_; }
  242. auto position() -> TokenizedBuffer::TokenIterator& { return position_; }
  243. auto position() const -> TokenizedBuffer::TokenIterator { return position_; }
  244. auto state_stack() -> llvm::SmallVector<StateStackEntry>& {
  245. return state_stack_;
  246. }
  247. auto state_stack() const -> const llvm::SmallVector<StateStackEntry>& {
  248. return state_stack_;
  249. }
  250. private:
  251. // Prints a single token for a stack dump. Used by PrintForStackDump.
  252. auto PrintTokenForStackDump(llvm::raw_ostream& output,
  253. TokenizedBuffer::Token token) const -> void;
  254. ParseTree* tree_;
  255. TokenizedBuffer* tokens_;
  256. TokenDiagnosticEmitter* emitter_;
  257. // Whether to print verbose output.
  258. llvm::raw_ostream* vlog_stream_;
  259. // The current position within the token buffer.
  260. TokenizedBuffer::TokenIterator position_;
  261. // The EndOfFile token.
  262. TokenizedBuffer::TokenIterator end_;
  263. llvm::SmallVector<StateStackEntry> state_stack_;
  264. };
  265. // `clang-format` has a bug with spacing around `->` returns in macros. See
  266. // https://bugs.llvm.org/show_bug.cgi?id=48320 for details.
  267. #define CARBON_PARSER_STATE(Name) \
  268. auto ParserHandle##Name(ParserContext& context)->void;
  269. #include "toolchain/parser/parser_state.def"
  270. } // namespace Carbon
  271. #endif // CARBON_TOOLCHAIN_PARSER_PARSER_CONTEXT_H_