parser_impl.h 8.8 KB

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