parser.h 13 KB

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