parser_impl.h 9.4 KB

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