parser.h 15 KB

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