parser.h 12 KB

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