parser_impl.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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,
  55. bool has_error = false) -> Node;
  56. // Composes `ConsumeIf` and `AddLeafNode`, propagating the failure case
  57. // through the optional.
  58. auto ConsumeAndAddLeafNodeIf(TokenKind t_kind, ParseNodeKind n_kind)
  59. -> llvm::Optional<Node>;
  60. // Marks the node `n` as having some parse errors and that the tree contains
  61. // a node with a parse error.
  62. auto MarkNodeError(Node n) -> void;
  63. // Tracks the current location as a potential start of a subtree.
  64. //
  65. // This returns a marker representing the current position, which can later
  66. // be used in a call to `AddNode` to mark all nodes created since this
  67. // position as children of the added node.
  68. auto GetSubtreeStartPosition() -> SubtreeStart;
  69. // Add a node to the parse tree that potentially has a subtree larger than
  70. // itself.
  71. //
  72. // Requires a start marker be passed to compute the size of the subtree rooted
  73. // at this node.
  74. auto AddNode(ParseNodeKind n_kind, TokenizedBuffer::Token t,
  75. SubtreeStart start, bool has_error = false) -> Node;
  76. // If the current token is an opening symbol for a matched group, skips
  77. // forward to one past the matched closing symbol and returns true. Otherwise,
  78. // returns false.
  79. auto SkipMatchingGroup() -> bool;
  80. // Skip forward to the given token.
  81. auto SkipTo(TokenizedBuffer::Token t) -> void;
  82. // Find the next token of any of the given kinds at the current bracketing
  83. // level.
  84. auto FindNextOf(std::initializer_list<TokenKind> desired_kinds)
  85. -> llvm::Optional<TokenizedBuffer::Token>;
  86. // Callback used if we find a semicolon when skipping to the end of a
  87. // declaration or statement.
  88. using SemiHandler = llvm::function_ref<
  89. auto(TokenizedBuffer::Token semi)->llvm::Optional<Node>>;
  90. // Skips forward to move past the likely end of a declaration or statement.
  91. //
  92. // Looks forward, skipping over any matched symbol groups, to find the next
  93. // position that is likely past the end of a declaration or statement. This
  94. // is a heuristic and should only be called when skipping past parse errors.
  95. //
  96. // The strategy for recognizing when we have likely passed the end of a
  97. // declaration or statement:
  98. // - If we get to a close curly brace, we likely ended the entire context.
  99. // - If we get to a semicolon, that should have ended the declaration or
  100. // statement.
  101. // - If we get to a new line from the `SkipRoot` token, but with the same or
  102. // less indentation, there is likely a missing semicolon. Continued
  103. // declarations or statements across multiple lines should be indented.
  104. //
  105. // If we find a semicolon based on this skipping, we return that token.
  106. // Otherwise we will return an empty optional.
  107. auto SkipPastLikelyEnd(TokenizedBuffer::Token skip_root)
  108. -> llvm::Optional<TokenizedBuffer::Token>;
  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 contain variable declarations and statements.
  140. auto ParseCodeBlock() -> llvm::Optional<Node>;
  141. // Similar to ParseCodeBlock(), but supports different ParseNodeKinds because
  142. // function definitions are represented differently from other code blocks.
  143. // If subtree_start is before start_kind, earlier nodes will be treated as
  144. // children of the start_kind node.
  145. auto ParseCodeBlock(SubtreeStart subtree_start, ParseNodeKind start_kind,
  146. ParseNodeKind end_kind) -> llvm::Optional<Node>;
  147. // Parses a function declaration with an optional definition. Returns the
  148. // function parse node which is based on the `fn` introducer keyword.
  149. auto ParseFunctionDeclaration() -> Node;
  150. // Parses a variable declaration with an optional initializer.
  151. auto ParseVariableDeclaration() -> Node;
  152. // Parses and returns an empty declaration node from a single semicolon token.
  153. auto ParseEmptyDeclaration() -> Node;
  154. // Parses a package directive.
  155. auto ParsePackageDirective() -> Node;
  156. // Tries to parse a declaration. If a declaration, even an empty one after
  157. // skipping errors, can be parsed, it is returned. There may be parse errors
  158. // even when a node is returned.
  159. auto ParseDeclaration() -> llvm::Optional<Node>;
  160. // Parses a parenthesized expression.
  161. auto ParseParenExpression() -> llvm::Optional<Node>;
  162. // Parses a braced expression.
  163. auto ParseBraceExpression() -> llvm::Optional<Node>;
  164. // Parses a primary expression, which is either a terminal portion of an
  165. // expression tree, such as an identifier or literal, or a parenthesized
  166. // expression.
  167. auto ParsePrimaryExpression() -> llvm::Optional<Node>;
  168. // Parses a designator expression suffix starting with `.`.
  169. auto ParseDesignatorExpression(SubtreeStart start, ParseNodeKind kind,
  170. bool has_errors) -> llvm::Optional<Node>;
  171. // Parses a call expression suffix starting with `(`.
  172. auto ParseCallExpression(SubtreeStart start, bool has_errors)
  173. -> llvm::Optional<Node>;
  174. // Parses a postfix expression, which is a primary expression followed by
  175. // zero or more of the following:
  176. //
  177. // - function applications
  178. // - array indexes (TODO)
  179. // - designators
  180. auto ParsePostfixExpression() -> llvm::Optional<Node>;
  181. enum class OperatorFixity { Prefix, Infix, Postfix };
  182. // Determines whether the current token satisfies the lexical validity rules
  183. // for an infix operator.
  184. auto IsLexicallyValidInfixOperator() -> bool;
  185. // Diagnoses if the current token is not written properly for the given
  186. // fixity, for example because mandatory whitespace is missing.
  187. auto DiagnoseOperatorFixity(OperatorFixity fixity) -> void;
  188. // Determines whether the current trailing operator should be treated as
  189. // infix.
  190. auto IsTrailingOperatorInfix() -> bool;
  191. // Parses an expression involving operators, in a context with the given
  192. // precedence.
  193. auto ParseOperatorExpression(PrecedenceGroup precedence)
  194. -> llvm::Optional<Node>;
  195. // Parses an expression.
  196. auto ParseExpression() -> llvm::Optional<Node>;
  197. // Parses a type expression.
  198. auto ParseType() -> llvm::Optional<Node>;
  199. // Parses an expression statement: an expression followed by a semicolon.
  200. auto ParseExpressionStatement() -> llvm::Optional<Node>;
  201. // Parses the parenthesized condition in an if-statement.
  202. auto ParseParenCondition(TokenKind introducer) -> llvm::Optional<Node>;
  203. // Parses an if-statement.
  204. auto ParseIfStatement() -> llvm::Optional<Node>;
  205. // Parses a while-statement.
  206. auto ParseWhileStatement() -> llvm::Optional<Node>;
  207. // Parses a for-statement.
  208. auto ParseForStatement() -> llvm::Optional<Node>;
  209. enum class KeywordStatementArgument {
  210. None,
  211. Optional,
  212. Mandatory,
  213. };
  214. // Parses a statement of the form `keyword;` such as `break;` or `continue;`.
  215. auto ParseKeywordStatement(ParseNodeKind kind,
  216. KeywordStatementArgument argument)
  217. -> llvm::Optional<Node>;
  218. // Parses a statement.
  219. auto ParseStatement() -> llvm::Optional<Node>;
  220. enum class PatternKind {
  221. Parameter,
  222. Variable,
  223. };
  224. // Parses a pattern.
  225. auto ParsePattern(PatternKind kind) -> llvm::Optional<Node>;
  226. ParseTree& tree_;
  227. TokenizedBuffer& tokens_;
  228. TokenDiagnosticEmitter& emitter_;
  229. // The current position within the token buffer. Never equal to `end`.
  230. TokenizedBuffer::TokenIterator position_;
  231. // The end position of the token buffer. There will always be an `EndOfFile`
  232. // token between `position` (inclusive) and `end` (exclusive).
  233. TokenizedBuffer::TokenIterator end_;
  234. // Managed through RETURN_IF_STACK_LIMITED, which should be invoked by all
  235. // functions.
  236. int stack_depth_ = 0;
  237. };
  238. } // namespace Carbon
  239. #endif // CARBON_TOOLCHAIN_PARSER_PARSER_IMPL_H_