parser.h 13 KB

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