parser_impl.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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_IMPL_H_
  5. #define CARBON_TOOLCHAIN_PARSER_PARSER_IMPL_H_
  6. #include "llvm/ADT/Optional.h"
  7. #include "toolchain/diagnostics/diagnostic_emitter.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/precedence.h"
  13. namespace Carbon {
  14. class ParseTree::Parser {
  15. public:
  16. // Parses the tokens into a parse tree, emitting any errors encountered.
  17. //
  18. // This is the entry point to the parser implementation.
  19. static auto Parse(TokenizedBuffer& tokens, TokenDiagnosticEmitter& emitter)
  20. -> ParseTree;
  21. private:
  22. class ScopedStackStep;
  23. struct SubtreeStart;
  24. explicit Parser(ParseTree& tree_arg, TokenizedBuffer& tokens_arg,
  25. TokenDiagnosticEmitter& emitter);
  26. auto AtEndOfFile() -> bool {
  27. return tokens_.GetKind(*position_) == TokenKind::EndOfFile();
  28. }
  29. // Gets the kind of the next token to be consumed.
  30. [[nodiscard]] auto NextTokenKind() const -> TokenKind {
  31. return tokens_.GetKind(*position_);
  32. }
  33. // Tests whether the next token to be consumed is of the specified kind.
  34. [[nodiscard]] auto NextTokenIs(TokenKind kind) const -> bool {
  35. return NextTokenKind() == kind;
  36. }
  37. // Tests whether the next token to be consumed is of any of the specified
  38. // kinds.
  39. [[nodiscard]] auto NextTokenIsOneOf(
  40. std::initializer_list<TokenKind> kinds) const -> bool {
  41. return NextTokenKind().IsOneOf(kinds);
  42. }
  43. // Requires (and asserts) that the current position matches the provided
  44. // `Kind`. Returns the current token and advances to the next position.
  45. auto Consume(TokenKind kind) -> TokenizedBuffer::Token;
  46. // If the current position's token matches this `Kind`, returns it and
  47. // advances to the next position. Otherwise returns an empty optional.
  48. auto ConsumeIf(TokenKind kind) -> llvm::Optional<TokenizedBuffer::Token>;
  49. // Adds a node to the parse tree that is fully parsed, has no children
  50. // ("leaf"), and has a subsequent sibling.
  51. //
  52. // This sets up the next sibling of the node to be the next node in the parse
  53. // tree's preorder sequence.
  54. auto AddLeafNode(ParseNodeKind kind, TokenizedBuffer::Token token) -> Node;
  55. // Composes `consumeIf` and `addLeafNode`, propagating the failure case
  56. // through the optional.
  57. auto ConsumeAndAddLeafNodeIf(TokenKind t_kind, ParseNodeKind n_kind)
  58. -> llvm::Optional<Node>;
  59. // Marks the node `N` as having some parse errors and that the tree contains
  60. // a node with a parse error.
  61. auto MarkNodeError(Node n) -> void;
  62. // Tracks the current location as a potential start of a subtree.
  63. //
  64. // This returns a marker representing the current position, which can later
  65. // be used in a call to `AddNode` to mark all nodes created since this
  66. // position as children of the added node.
  67. auto GetSubtreeStartPosition() -> SubtreeStart;
  68. // Add a node to the parse tree that potentially has a subtree larger than
  69. // itself.
  70. //
  71. // Requires a start marker be passed to compute the size of the subtree rooted
  72. // at this node.
  73. auto AddNode(ParseNodeKind n_kind, TokenizedBuffer::Token t,
  74. SubtreeStart start, bool has_error = false) -> Node;
  75. // If the current token is an opening symbol for a matched group, skips
  76. // forward to one past the matched closing symbol and returns true. Otherwise,
  77. // returns false.
  78. auto SkipMatchingGroup() -> bool;
  79. // Skip forward to the given token.
  80. auto SkipTo(TokenizedBuffer::Token t) -> void;
  81. // Find the next token of any of the given kinds at the current bracketing
  82. // level.
  83. auto FindNextOf(std::initializer_list<TokenKind> desired_kinds)
  84. -> llvm::Optional<TokenizedBuffer::Token>;
  85. // Callback used if we find a semicolon when skipping to the end of a
  86. // declaration or statement.
  87. using SemiHandler = llvm::function_ref<
  88. auto(TokenizedBuffer::Token semi)->llvm::Optional<Node>>;
  89. // Skips forward to move past the likely end of a declaration or statement.
  90. //
  91. // Looks forward, skipping over any matched symbol groups, to find the next
  92. // position that is likely past the end of a declaration or statement. This
  93. // is a heuristic and should only be called when skipping past parse errors.
  94. //
  95. // The strategy for recognizing when we have likely passed the end of a
  96. // declaration or statement:
  97. // - If we get to a close curly brace, we likely ended the entire context.
  98. // - If we get to a semicolon, that should have ended the declaration or
  99. // statement.
  100. // - If we get to a new line from the `SkipRoot` token, but with the same or
  101. // less indentation, there is likely a missing semicolon. Continued
  102. // declarations or statements across multiple lines should be indented.
  103. //
  104. // If we find a semicolon based on this skipping, we call `on_semi_` to try
  105. // to build a parse node to represent it, and will return that node.
  106. // Otherwise we will return an empty optional.
  107. auto SkipPastLikelyEnd(TokenizedBuffer::Token skip_root, SemiHandler on_semi)
  108. -> llvm::Optional<Node>;
  109. // Parses a close paren token corresponding to the given open paren token,
  110. // possibly skipping forward and diagnosing if necessary. Creates and returns
  111. // a parse node of the specified kind if successful.
  112. auto ParseCloseParen(TokenizedBuffer::Token open_paren, ParseNodeKind kind)
  113. -> llvm::Optional<Node>;
  114. // Parses a comma-separated list with the given delimiters.
  115. template <typename ListElementParser, typename ListCompletionHandler>
  116. auto ParseList(TokenKind open, TokenKind close,
  117. ListElementParser list_element_parser,
  118. ParseNodeKind comma_kind, ListCompletionHandler list_handler,
  119. bool allow_trailing_comma = false) -> llvm::Optional<Node>;
  120. // Parses a parenthesized, comma-separated list.
  121. template <typename ListElementParser, typename ListCompletionHandler>
  122. auto ParseParenList(ListElementParser list_element_parser,
  123. ParseNodeKind comma_kind,
  124. ListCompletionHandler list_handler,
  125. bool allow_trailing_comma = false)
  126. -> llvm::Optional<Node> {
  127. return ParseList(TokenKind::OpenParen(), TokenKind::CloseParen(),
  128. list_element_parser, comma_kind, list_handler,
  129. allow_trailing_comma);
  130. }
  131. // Parses a single function parameter declaration.
  132. auto ParseFunctionParameter() -> llvm::Optional<Node>;
  133. // Parses the signature of the function, consisting of a parameter list and an
  134. // optional return type. Returns the root node of the signature which must be
  135. // based on the open parenthesis of the parameter list.
  136. auto ParseFunctionSignature() -> bool;
  137. // Parses a block of code: `{ ... }`.
  138. //
  139. // These can form the definition for a function or be nested within a function
  140. // definition. These contain variable declarations and statements.
  141. auto ParseCodeBlock() -> llvm::Optional<Node>;
  142. // Parses a function declaration with an optional definition. Returns the
  143. // function parse node which is based on the `fn` introducer keyword.
  144. auto ParseFunctionDeclaration() -> Node;
  145. // Parses a variable declaration with an optional initializer.
  146. auto ParseVariableDeclaration() -> Node;
  147. // Parses and returns an empty declaration node from a single semicolon token.
  148. auto ParseEmptyDeclaration() -> Node;
  149. // Tries to parse a declaration. If a declaration, even an empty one after
  150. // skipping errors, can be parsed, it is returned. There may be parse errors
  151. // even when a node is returned.
  152. auto ParseDeclaration() -> llvm::Optional<Node>;
  153. // Parses a parenthesized expression.
  154. auto ParseParenExpression() -> llvm::Optional<Node>;
  155. // Parses a braced expression.
  156. auto ParseBraceExpression() -> llvm::Optional<Node>;
  157. // Parses a primary expression, which is either a terminal portion of an
  158. // expression tree, such as an identifier or literal, or a parenthesized
  159. // expression.
  160. auto ParsePrimaryExpression() -> llvm::Optional<Node>;
  161. // Parses a designator expression suffix starting with `.`.
  162. auto ParseDesignatorExpression(SubtreeStart start, ParseNodeKind kind,
  163. bool has_errors) -> llvm::Optional<Node>;
  164. // Parses a call expression suffix starting with `(`.
  165. auto ParseCallExpression(SubtreeStart start, bool has_errors)
  166. -> llvm::Optional<Node>;
  167. // Parses a postfix expression, which is a primary expression followed by
  168. // zero or more of the following:
  169. //
  170. // - function applications
  171. // - array indexes (TODO)
  172. // - designators
  173. auto ParsePostfixExpression() -> llvm::Optional<Node>;
  174. enum class OperatorFixity { Prefix, Infix, Postfix };
  175. // Determines whether the current token satisfies the lexical validity rules
  176. // for an infix operator.
  177. auto IsLexicallyValidInfixOperator() -> bool;
  178. // Diagnoses if the current token is not written properly for the given
  179. // fixity, for example because mandatory whitespace is missing.
  180. auto DiagnoseOperatorFixity(OperatorFixity fixity) -> void;
  181. // Determines whether the current trailing operator should be treated as
  182. // infix.
  183. auto IsTrailingOperatorInfix() -> bool;
  184. // Parses an expression involving operators, in a context with the given
  185. // precedence.
  186. auto ParseOperatorExpression(PrecedenceGroup precedence)
  187. -> llvm::Optional<Node>;
  188. // Parses an expression.
  189. auto ParseExpression() -> llvm::Optional<Node>;
  190. // Parses a type expression.
  191. auto ParseType() -> llvm::Optional<Node>;
  192. // Parses an expression statement: an expression followed by a semicolon.
  193. auto ParseExpressionStatement() -> llvm::Optional<Node>;
  194. // Parses the parenthesized condition in an if-statement.
  195. auto ParseParenCondition(TokenKind introducer) -> llvm::Optional<Node>;
  196. // Parses an if-statement.
  197. auto ParseIfStatement() -> llvm::Optional<Node>;
  198. // Parses a while-statement.
  199. auto ParseWhileStatement() -> llvm::Optional<Node>;
  200. enum class KeywordStatementArgument {
  201. None,
  202. Optional,
  203. Mandatory,
  204. };
  205. // Parses a statement of the form `keyword;` such as `break;` or `continue;`.
  206. auto ParseKeywordStatement(ParseNodeKind kind,
  207. KeywordStatementArgument argument)
  208. -> llvm::Optional<Node>;
  209. // Parses a statement.
  210. auto ParseStatement() -> llvm::Optional<Node>;
  211. enum class PatternKind {
  212. Parameter,
  213. Variable,
  214. };
  215. // Parses a pattern.
  216. auto ParsePattern(PatternKind kind) -> llvm::Optional<Node>;
  217. ParseTree& tree_;
  218. TokenizedBuffer& tokens_;
  219. TokenDiagnosticEmitter& emitter_;
  220. // The current position within the token buffer. Never equal to `end`.
  221. TokenizedBuffer::TokenIterator position_;
  222. // The end position of the token buffer. There will always be an `EndOfFile`
  223. // token between `position` (inclusive) and `end` (exclusive).
  224. TokenizedBuffer::TokenIterator end_;
  225. // Managed through RETURN_IF_STACK_LIMITED, which should be invoked by all
  226. // functions.
  227. int stack_depth_ = 0;
  228. };
  229. } // namespace Carbon
  230. #endif // CARBON_TOOLCHAIN_PARSER_PARSER_IMPL_H_