parser_impl.h 10 KB

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