parser.h 13 KB

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