parser.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 "common/check.h"
  7. #include "llvm/ADT/Optional.h"
  8. #include "toolchain/lexer/token_kind.h"
  9. #include "toolchain/lexer/tokenized_buffer.h"
  10. #include "toolchain/parser/parse_node_kind.h"
  11. #include "toolchain/parser/parse_tree.h"
  12. #include "toolchain/parser/parser_state.h"
  13. #include "toolchain/parser/precedence.h"
  14. namespace Carbon {
  15. // This parser uses a stack for state transitions. See parser_state.def for
  16. // state documentation.
  17. class Parser {
  18. public:
  19. // Parses the tokens into a parse tree, emitting any errors encountered.
  20. //
  21. // This is the entry point to the parser implementation.
  22. static auto Parse(TokenizedBuffer& tokens, TokenDiagnosticEmitter& emitter)
  23. -> ParseTree {
  24. ParseTree tree(tokens);
  25. Parser parser(tree, tokens, emitter);
  26. parser.Parse();
  27. return tree;
  28. }
  29. private:
  30. // Possible operator fixities for errors.
  31. enum class OperatorFixity { Prefix, Infix, Postfix };
  32. // Supported kinds of patterns for HandlePattern.
  33. enum class PatternKind { Parameter, Variable };
  34. // Helper class for tracing state_stack_ on crashes.
  35. class PrettyStackTraceParseState;
  36. // Used to track state on state_stack_.
  37. struct StateStackEntry {
  38. StateStackEntry(ParserState state, PrecedenceGroup ambient_precedence,
  39. PrecedenceGroup lhs_precedence,
  40. TokenizedBuffer::Token token, int32_t subtree_start)
  41. : state(state),
  42. ambient_precedence(ambient_precedence),
  43. lhs_precedence(lhs_precedence),
  44. token(token),
  45. subtree_start(subtree_start) {}
  46. // The state.
  47. ParserState state;
  48. // Set to true to indicate that an error was found, and that contextual
  49. // error recovery may be needed.
  50. bool has_error = false;
  51. // Precedence information used by expression states in order to determine
  52. // operator precedence. The ambient_precedence deals with how the expression
  53. // should interact with outside context, while the lhs_precedence is
  54. // specific to the lhs of an operator expression.
  55. PrecedenceGroup ambient_precedence;
  56. PrecedenceGroup lhs_precedence;
  57. // A token providing context based on the subtree. This will typically be
  58. // the first token in the subtree, but may sometimes be a token within. It
  59. // will typically be used for the subtree's root node.
  60. TokenizedBuffer::Token token;
  61. // The offset within the ParseTree of the subtree start.
  62. int32_t subtree_start;
  63. };
  64. // We expect StateStackEntry to fit into 12 bytes:
  65. // state = 1 byte
  66. // has_error = 1 byte
  67. // ambient_precedence = 1 byte
  68. // lhs_precedence = 1 byte
  69. // token = 4 bytes
  70. // subtree_start = 4 bytes
  71. // If it becomes bigger, it'd be worth examining better packing; it should be
  72. // feasible to pack the 1-byte entries more tightly.
  73. static_assert(sizeof(StateStackEntry) == 12,
  74. "StateStackEntry has unexpected size!");
  75. // Possible return values for FindListToken.
  76. enum class ListTokenKind {
  77. Comma,
  78. Close,
  79. CommaClose,
  80. };
  81. // The kind of brace expression being evaluated.
  82. enum class BraceExpressionKind { Unknown, Value, Type };
  83. Parser(ParseTree& tree, TokenizedBuffer& tokens,
  84. TokenDiagnosticEmitter& emitter);
  85. auto Parse() -> void;
  86. // Adds a node to the parse tree that has no children (a leaf).
  87. auto AddLeafNode(ParseNodeKind kind, TokenizedBuffer::Token token,
  88. bool has_error = false) -> void;
  89. // Adds a node to the parse tree that has children.
  90. auto AddNode(ParseNodeKind kind, TokenizedBuffer::Token token,
  91. int subtree_start, bool has_error) -> void;
  92. // Returns the current position and moves past it.
  93. auto Consume() -> TokenizedBuffer::Token { return *(position_++); }
  94. // Parses a close paren token corresponding to the given open paren token,
  95. // possibly skipping forward and diagnosing if necessary. Creates a parse node
  96. // of the specified kind if successful.
  97. auto ConsumeAndAddCloseParen(TokenizedBuffer::Token open_paren,
  98. ParseNodeKind close_kind) -> bool;
  99. // Composes `ConsumeIf` and `AddLeafNode`, returning false when ConsumeIf
  100. // fails.
  101. auto ConsumeAndAddLeafNodeIf(TokenKind token_kind, ParseNodeKind node_kind)
  102. -> bool;
  103. // If the current position's token matches this `Kind`, returns it and
  104. // advances to the next position. Otherwise returns an empty optional.
  105. auto ConsumeIf(TokenKind kind) -> llvm::Optional<TokenizedBuffer::Token>;
  106. // Find the next token of any of the given kinds at the current bracketing
  107. // level.
  108. auto FindNextOf(std::initializer_list<TokenKind> desired_kinds)
  109. -> llvm::Optional<TokenizedBuffer::Token>;
  110. // If the token is an opening symbol for a matched group, skips to the matched
  111. // closing symbol and returns true. Otherwise, returns false.
  112. auto SkipMatchingGroup() -> bool;
  113. // Skips forward to move past the likely end of a declaration or statement.
  114. //
  115. // Looks forward, skipping over any matched symbol groups, to find the next
  116. // position that is likely past the end of a declaration or statement. This
  117. // is a heuristic and should only be called when skipping past parse errors.
  118. //
  119. // The strategy for recognizing when we have likely passed the end of a
  120. // declaration or statement:
  121. // - If we get to a close curly brace, we likely ended the entire context.
  122. // - If we get to a semicolon, that should have ended the declaration or
  123. // statement.
  124. // - If we get to a new line from the `SkipRoot` token, but with the same or
  125. // less indentation, there is likely a missing semicolon. Continued
  126. // declarations or statements across multiple lines should be indented.
  127. //
  128. // Returns a semicolon token if one is the likely end.
  129. auto SkipPastLikelyEnd(TokenizedBuffer::Token skip_root)
  130. -> llvm::Optional<TokenizedBuffer::Token>;
  131. // Skip forward to the given token. Verifies that it is actually forward.
  132. auto SkipTo(TokenizedBuffer::Token t) -> void;
  133. // Returns true if the current token satisfies the lexical validity rules
  134. // for an infix operator.
  135. auto IsLexicallyValidInfixOperator() -> bool;
  136. // Determines whether the current trailing operator should be treated as
  137. // infix.
  138. auto IsTrailingOperatorInfix() -> bool;
  139. // Diagnoses whether the current token is not written properly for the given
  140. // fixity. For example, because mandatory whitespace is missing. Regardless of
  141. // whether there's an error, it's expected that parsing continues.
  142. auto DiagnoseOperatorFixity(OperatorFixity fixity) -> void;
  143. // If the current position is a `,`, consumes it, adds the provided token, and
  144. // returns `Comma`. Returns `Close` if the current position is close_token
  145. // (for example, `)`). `CommaClose` indicates it found both (for example,
  146. // `,)`). Handles cases where invalid tokens are present by advancing the
  147. // position, and may emit errors. Pass already_has_error in order to suppress
  148. // duplicate errors.
  149. auto ConsumeListToken(ParseNodeKind comma_kind, TokenKind close_kind,
  150. bool already_has_error) -> ListTokenKind;
  151. // Gets the kind of the next token to be consumed.
  152. auto PositionKind() const -> TokenKind {
  153. return tokens_->GetKind(*position_);
  154. }
  155. // Tests whether the next token to be consumed is of the specified kind.
  156. auto PositionIs(TokenKind kind) const -> bool {
  157. return PositionKind() == kind;
  158. }
  159. // Pops the state and keeps the value for inspection.
  160. auto PopState() -> StateStackEntry { return state_stack_.pop_back_val(); }
  161. // Pops the state and discards it.
  162. auto PopAndDiscardState() -> void { state_stack_.pop_back(); }
  163. // Pushes a new state with the current position for context.
  164. auto PushState(ParserState state) -> void {
  165. PushState(StateStackEntry(state, PrecedenceGroup::ForTopLevelExpression(),
  166. PrecedenceGroup::ForTopLevelExpression(),
  167. *position_, tree_->size()));
  168. }
  169. // Pushes a new expression state with specific precedence.
  170. auto PushStateForExpression(PrecedenceGroup ambient_precedence) -> void {
  171. PushState(StateStackEntry(ParserState::Expression(), ambient_precedence,
  172. PrecedenceGroup::ForTopLevelExpression(),
  173. *position_, tree_->size()));
  174. }
  175. // Pushes a new state with detailed precedence for expression resume states.
  176. auto PushStateForExpressionLoop(ParserState state,
  177. PrecedenceGroup ambient_precedence,
  178. PrecedenceGroup lhs_precedence) -> void {
  179. PushState(StateStackEntry(state, ambient_precedence, lhs_precedence,
  180. *position_, tree_->size()));
  181. }
  182. // Pushes a constructed state onto the stack.
  183. auto PushState(StateStackEntry state) -> void {
  184. state_stack_.push_back(state);
  185. CARBON_CHECK(state_stack_.size() < (1 << 20))
  186. << "Excessive stack size: likely infinite loop";
  187. }
  188. // Propagates an error up the state stack, to the parent state.
  189. auto ReturnErrorOnState() -> void { state_stack_.back().has_error = true; }
  190. // Returns the appropriate ParserState for the input kind.
  191. static auto BraceExpressionKindToParserState(BraceExpressionKind kind,
  192. ParserState type,
  193. ParserState value,
  194. ParserState unknown)
  195. -> ParserState;
  196. // Prints a diagnostic for brace expression syntax errors.
  197. auto HandleBraceExpressionParameterError(StateStackEntry state,
  198. BraceExpressionKind kind) -> void;
  199. // Handles BraceExpressionParameterAs(Type|Value|Unknown).
  200. auto HandleBraceExpressionParameter(BraceExpressionKind kind) -> void;
  201. // Handles BraceExpressionParameterAfterDesignatorAs(Type|Value|Unknown).
  202. auto HandleBraceExpressionParameterAfterDesignator(BraceExpressionKind kind)
  203. -> void;
  204. // Handles BraceExpressionParameterFinishAs(Type|Value|Unknown).
  205. auto HandleBraceExpressionParameterFinish(BraceExpressionKind kind) -> void;
  206. // Handles BraceExpressionFinishAs(Type|Value|Unknown).
  207. auto HandleBraceExpressionFinish(BraceExpressionKind kind) -> void;
  208. // Handles DesignatorAs.
  209. auto HandleDesignator(bool as_struct) -> void;
  210. // When handling errors before the start of the definition, treat it as a
  211. // declaration. Recover to a semicolon when it makes sense as a possible
  212. // function end, otherwise use the fn token for the error.
  213. auto HandleFunctionError(StateStackEntry state, bool skip_past_likely_end)
  214. -> void;
  215. // Handles ParenExpressionParameterFinish(AsUnknown|AsTuple).
  216. auto HandleParenExpressionParameterFinish(bool as_tuple) -> void;
  217. // Handles PatternAs(FunctionParameter|Variable).
  218. auto HandlePattern(PatternKind pattern_kind) -> void;
  219. // Handles the `;` after a keyword statement.
  220. auto HandleStatementKeywordFinish(ParseNodeKind node_kind) -> void;
  221. // Handles VarAs(RequireSemicolon|NoSemicolon).
  222. auto HandleVar(bool require_semicolon) -> void;
  223. // Handles VarFinishAs(RequireSemicolon|NoSemicolon).
  224. auto HandleVarFinish(bool require_semicolon) -> void;
  225. // `clang-format` has a bug with spacing around `->` returns in macros. See
  226. // https://bugs.llvm.org/show_bug.cgi?id=48320 for details.
  227. #define CARBON_PARSER_STATE(Name) auto Handle##Name##State()->void;
  228. #include "toolchain/parser/parser_state.def"
  229. ParseTree* tree_;
  230. TokenizedBuffer* tokens_;
  231. TokenDiagnosticEmitter* emitter_;
  232. // The current position within the token buffer.
  233. TokenizedBuffer::TokenIterator position_;
  234. // The EndOfFile token.
  235. TokenizedBuffer::TokenIterator end_;
  236. llvm::SmallVector<StateStackEntry> state_stack_;
  237. };
  238. } // namespace Carbon
  239. #endif // CARBON_TOOLCHAIN_PARSER_PARSER_H_