parser.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. // Supported return values for GetDeclarationContext.
  40. enum class DeclarationContext {
  41. File, // Top-level context.
  42. Interface,
  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. 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. // Returns the appropriate ParserState for the input kind.
  223. static auto BraceExpressionKindToParserState(BraceExpressionKind kind,
  224. ParserState type,
  225. ParserState value,
  226. ParserState unknown)
  227. -> ParserState;
  228. // Prints a diagnostic for brace expression syntax errors.
  229. auto HandleBraceExpressionParameterError(StateStackEntry state,
  230. BraceExpressionKind kind) -> void;
  231. // Handles BraceExpressionParameterAs(Type|Value|Unknown).
  232. auto HandleBraceExpressionParameter(BraceExpressionKind kind) -> void;
  233. // Handles BraceExpressionParameterAfterDesignatorAs(Type|Value|Unknown).
  234. auto HandleBraceExpressionParameterAfterDesignator(BraceExpressionKind kind)
  235. -> void;
  236. // Handles BraceExpressionParameterFinishAs(Type|Value|Unknown).
  237. auto HandleBraceExpressionParameterFinish(BraceExpressionKind kind) -> void;
  238. // Handles BraceExpressionFinishAs(Type|Value|Unknown).
  239. auto HandleBraceExpressionFinish(BraceExpressionKind kind) -> void;
  240. // Handles DesignatorAs.
  241. auto HandleDesignator(bool as_struct) -> void;
  242. // When handling errors before the start of the definition, treat it as a
  243. // declaration. Recover to a semicolon when it makes sense as a possible
  244. // function end, otherwise use the fn token for the error.
  245. auto HandleFunctionError(StateStackEntry state, bool skip_past_likely_end)
  246. -> void;
  247. // Handles ParenConditionAs(If|While)
  248. auto HandleParenCondition(ParseNodeKind start_kind, ParserState finish_state)
  249. -> void;
  250. // Handles ParenExpressionParameterFinishAs(Unknown|Tuple).
  251. auto HandleParenExpressionParameterFinish(bool as_tuple) -> void;
  252. // Handles PatternAs(FunctionParameter|Variable).
  253. auto HandlePattern(PatternKind pattern_kind) -> void;
  254. // Handles the `;` after a keyword statement.
  255. auto HandleStatementKeywordFinish(ParseNodeKind node_kind) -> void;
  256. // Handles VarAs(Semicolon|For).
  257. auto HandleVar(ParserState finish_state) -> void;
  258. // `clang-format` has a bug with spacing around `->` returns in macros. See
  259. // https://bugs.llvm.org/show_bug.cgi?id=48320 for details.
  260. #define CARBON_PARSER_STATE(Name) auto Handle##Name##State()->void;
  261. #include "toolchain/parser/parser_state.def"
  262. ParseTree* tree_;
  263. TokenizedBuffer* tokens_;
  264. TokenDiagnosticEmitter* emitter_;
  265. // Whether to print verbose output.
  266. llvm::raw_ostream* vlog_stream_;
  267. // The current position within the token buffer.
  268. TokenizedBuffer::TokenIterator position_;
  269. // The EndOfFile token.
  270. TokenizedBuffer::TokenIterator end_;
  271. llvm::SmallVector<StateStackEntry> state_stack_;
  272. };
  273. } // namespace Carbon
  274. #endif // CARBON_TOOLCHAIN_PARSER_PARSER_H_