context.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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_PARSE_CONTEXT_H_
  5. #define CARBON_TOOLCHAIN_PARSE_CONTEXT_H_
  6. #include <optional>
  7. #include "common/check.h"
  8. #include "common/vlog.h"
  9. #include "toolchain/lex/token_kind.h"
  10. #include "toolchain/lex/tokenized_buffer.h"
  11. #include "toolchain/parse/node_kind.h"
  12. #include "toolchain/parse/precedence.h"
  13. #include "toolchain/parse/state.h"
  14. #include "toolchain/parse/tree.h"
  15. namespace Carbon::Parse {
  16. // An amount by which to look ahead of the current token. Lookahead should be
  17. // used sparingly, and unbounded lookahead should be avoided.
  18. //
  19. // TODO: Decide whether we want to avoid lookahead altogether.
  20. //
  21. // NOLINTNEXTLINE(performance-enum-size): Deliberately matches index size.
  22. enum class Lookahead : int32_t {
  23. CurrentToken = 0,
  24. NextToken = 1,
  25. };
  26. // Context and shared functionality for parser handlers. See state.def for state
  27. // documentation.
  28. class Context {
  29. public:
  30. // Possible operator fixities for errors.
  31. enum class OperatorFixity : int8_t { Prefix, Infix, Postfix };
  32. // Possible return values for FindListToken.
  33. enum class ListTokenKind : int8_t { Comma, Close, CommaClose };
  34. // Used for restricting ordering of `package` and `import` declarations.
  35. enum class PackagingState : int8_t {
  36. FileStart,
  37. InImports,
  38. AfterNonPackagingDecl,
  39. // A warning about `import` placement has been issued so we don't keep
  40. // issuing more (when `import` is repeated) until more non-`import`
  41. // declarations come up.
  42. InImportsAfterNonPackagingDecl,
  43. };
  44. // Used to track state on state_stack_.
  45. struct StateStackEntry : public Printable<StateStackEntry> {
  46. // Prints state information for verbose output.
  47. auto Print(llvm::raw_ostream& output) const -> void {
  48. output << state << " @" << token << " subtree_start=" << subtree_start
  49. << " has_error=" << has_error;
  50. }
  51. // The state.
  52. State state;
  53. // Set to true to indicate that an error was found, and that contextual
  54. // error recovery may be needed.
  55. bool has_error = false;
  56. // Precedence information used by expression states in order to determine
  57. // operator precedence. The ambient_precedence deals with how the expression
  58. // should interact with outside context, while the lhs_precedence is
  59. // specific to the lhs of an operator expression.
  60. PrecedenceGroup ambient_precedence = PrecedenceGroup::ForTopLevelExpr();
  61. PrecedenceGroup lhs_precedence = PrecedenceGroup::ForTopLevelExpr();
  62. // A token providing context based on the subtree. This will typically be
  63. // the first token in the subtree, but may sometimes be a token within. It
  64. // will typically be used for the subtree's root node.
  65. Lex::TokenIndex token;
  66. // The offset within the Tree of the subtree start.
  67. int32_t subtree_start;
  68. };
  69. // We expect StateStackEntry to fit into 12 bytes:
  70. // state = 1 byte
  71. // has_error = 1 byte
  72. // ambient_precedence = 1 byte
  73. // lhs_precedence = 1 byte
  74. // token = 4 bytes
  75. // subtree_start = 4 bytes
  76. // If it becomes bigger, it'd be worth examining better packing; it should be
  77. // feasible to pack the 1-byte entries more tightly.
  78. static_assert(sizeof(StateStackEntry) == 12,
  79. "StateStackEntry has unexpected size!");
  80. explicit Context(Tree& tree, Lex::TokenizedBuffer& tokens,
  81. Lex::TokenDiagnosticEmitter& emitter,
  82. llvm::raw_ostream* vlog_stream);
  83. // Adds a node to the parse tree that has no children (a leaf).
  84. auto AddLeafNode(NodeKind kind, Lex::TokenIndex token, bool has_error = false)
  85. -> void {
  86. AddNode(kind, token, has_error);
  87. }
  88. // Adds a node to the parse tree that has children.
  89. auto AddNode(NodeKind kind, Lex::TokenIndex token, bool has_error) -> void {
  90. CARBON_CHECK(has_error || (kind != NodeKind::InvalidParse &&
  91. kind != NodeKind::InvalidParseStart &&
  92. kind != NodeKind::InvalidParseSubtree),
  93. "{0} nodes must always have an error", kind);
  94. tree_->node_impls_.push_back(
  95. {.kind = kind, .has_error = has_error, .token = token});
  96. }
  97. // Adds an invalid parse node.
  98. auto AddInvalidParse(Lex::TokenIndex token) -> void {
  99. AddNode(NodeKind::InvalidParse, token, /*has_error=*/true);
  100. }
  101. // Replaces the placeholder node at the indicated position with a leaf node.
  102. //
  103. // To reserve a position in the parse tree, you may add a placeholder parse
  104. // node using code like:
  105. // ```
  106. // context.PushState(State::WillFillInPlaceholder);
  107. // context.AddLeafNode(NodeKind::Placeholder, *context.position());
  108. // ```
  109. // It may be replaced with the intended leaf parse node with code like:
  110. // ```
  111. // auto HandleWillFillInPlaceholder(Context& context) -> void {
  112. // auto state = context.PopState();
  113. // context.ReplacePlaceholderNode(state.subtree_start, /* replacement */);
  114. // }
  115. // ```
  116. auto ReplacePlaceholderNode(int32_t position, NodeKind kind,
  117. Lex::TokenIndex token, bool has_error = false)
  118. -> void;
  119. // Returns the current position and moves past it.
  120. auto Consume() -> Lex::TokenIndex { return *(position_++); }
  121. // Consumes the current token. Does not return it.
  122. auto ConsumeAndDiscard() -> void { ++position_; }
  123. // Parses an open paren token, possibly diagnosing if necessary. Creates a
  124. // leaf parse node of the specified start kind. The default_token is used when
  125. // there's no open paren. Returns the open paren token if it was found.
  126. auto ConsumeAndAddOpenParen(Lex::TokenIndex default_token,
  127. NodeKind start_kind)
  128. -> std::optional<Lex::TokenIndex>;
  129. // Parses a closing symbol corresponding to the opening symbol
  130. // `expected_open`, possibly skipping forward and diagnosing if necessary.
  131. // Creates a parse node of the specified close kind. If `expected_open` is not
  132. // an opening symbol, the parse node will be associated with `state.token`,
  133. // no input will be consumed, and no diagnostic will be emitted.
  134. auto ConsumeAndAddCloseSymbol(Lex::TokenIndex expected_open,
  135. StateStackEntry state, NodeKind close_kind)
  136. -> void;
  137. // Composes `ConsumeIf` and `AddLeafNode`, returning false when ConsumeIf
  138. // fails.
  139. auto ConsumeAndAddLeafNodeIf(Lex::TokenKind token_kind, NodeKind node_kind)
  140. -> bool;
  141. // Returns the current position and moves past it. Requires the token is the
  142. // expected kind.
  143. auto ConsumeChecked(Lex::TokenKind kind) -> Lex::TokenIndex;
  144. // If the current position's token matches this `Kind`, returns it and
  145. // advances to the next position. Otherwise returns an empty optional.
  146. auto ConsumeIf(Lex::TokenKind kind) -> std::optional<Lex::TokenIndex> {
  147. if (!PositionIs(kind)) {
  148. return std::nullopt;
  149. }
  150. return Consume();
  151. }
  152. // Find the next token of any of the given kinds at the current bracketing
  153. // level.
  154. auto FindNextOf(std::initializer_list<Lex::TokenKind> desired_kinds)
  155. -> std::optional<Lex::TokenIndex>;
  156. // If the token is an opening symbol for a matched group, skips to the matched
  157. // closing symbol and returns true. Otherwise, returns false.
  158. auto SkipMatchingGroup() -> bool;
  159. // Skips forward to move past the likely end of a declaration or statement.
  160. //
  161. // Looks forward, skipping over any matched symbol groups, to find the next
  162. // position that is likely past the end of a declaration or statement. This
  163. // is a heuristic and should only be called when skipping past parse errors.
  164. //
  165. // The strategy for recognizing when we have likely passed the end of a
  166. // declaration or statement:
  167. // - If we get to a close curly brace, we likely ended the entire context.
  168. // - If we get to a semicolon, that should have ended the declaration or
  169. // statement.
  170. // - If we get to a new line from the `SkipRoot` token, but with the same or
  171. // less indentation, there is likely a missing semicolon. Continued
  172. // declarations or statements across multiple lines should be indented.
  173. //
  174. // Returns the last token consumed.
  175. auto SkipPastLikelyEnd(Lex::TokenIndex skip_root) -> Lex::TokenIndex;
  176. // Skip forward to the given token. Verifies that it is actually forward.
  177. auto SkipTo(Lex::TokenIndex t) -> void;
  178. // Returns true if the current token satisfies the lexical validity rules
  179. // for an infix operator.
  180. auto IsLexicallyValidInfixOperator() -> bool;
  181. // Determines whether the current trailing operator should be treated as
  182. // infix.
  183. auto IsTrailingOperatorInfix() -> bool;
  184. // Diagnoses whether the current token is not written properly for the given
  185. // fixity. For example, because mandatory whitespace is missing. Regardless of
  186. // whether there's an error, it's expected that parsing continues.
  187. auto DiagnoseOperatorFixity(OperatorFixity fixity) -> void;
  188. // If the current position is a `,`, consumes it, adds the provided token, and
  189. // returns `Comma`. Returns `Close` if the current position is close_token
  190. // (for example, `)`). `CommaClose` indicates it found both (for example,
  191. // `,)`). Handles cases where invalid tokens are present by advancing the
  192. // position, and may emit errors. Pass already_has_error in order to suppress
  193. // duplicate errors.
  194. auto ConsumeListToken(NodeKind comma_kind, Lex::TokenKind close_kind,
  195. bool already_has_error) -> ListTokenKind;
  196. // Gets the kind of the next token to be consumed. If `lookahead` is
  197. // provided, it specifies which token to inspect.
  198. auto PositionKind(Lookahead lookahead = Lookahead::CurrentToken) const
  199. -> Lex::TokenKind {
  200. return tokens_->GetKind(position_[static_cast<int32_t>(lookahead)]);
  201. }
  202. // Tests whether the next token to be consumed is of the specified kind. If
  203. // `lookahead` is provided, it specifies which token to inspect.
  204. auto PositionIs(Lex::TokenKind kind,
  205. Lookahead lookahead = Lookahead::CurrentToken) const -> bool {
  206. return PositionKind(lookahead) == kind;
  207. }
  208. // Pops the state and keeps the value for inspection.
  209. auto PopState() -> StateStackEntry {
  210. auto back = state_stack_.pop_back_val();
  211. CARBON_VLOG("Pop {0}: {1}\n", state_stack_.size(), back);
  212. return back;
  213. }
  214. // Pops the state and discards it.
  215. auto PopAndDiscardState() -> void {
  216. CARBON_VLOG("PopAndDiscard {0}: {1}\n", state_stack_.size() - 1,
  217. state_stack_.back());
  218. state_stack_.pop_back();
  219. }
  220. // Pushes a new state with the current position for context.
  221. auto PushState(State state) -> void { PushState(state, *position_); }
  222. // Pushes a new state with a specific token for context. Used when forming a
  223. // new subtree when the current position isn't the start of the subtree.
  224. auto PushState(State state, Lex::TokenIndex token) -> void {
  225. PushState({.state = state, .token = token, .subtree_start = tree_->size()});
  226. }
  227. // Pushes a new expression state with specific precedence.
  228. auto PushStateForExpr(PrecedenceGroup ambient_precedence) -> void {
  229. PushState({.state = State::Expr,
  230. .ambient_precedence = ambient_precedence,
  231. .token = *position_,
  232. .subtree_start = tree_->size()});
  233. }
  234. // Pushes a new state with detailed precedence for expression resume states.
  235. auto PushStateForExprLoop(State state, PrecedenceGroup ambient_precedence,
  236. PrecedenceGroup lhs_precedence) -> void {
  237. PushState({.state = state,
  238. .ambient_precedence = ambient_precedence,
  239. .lhs_precedence = lhs_precedence,
  240. .token = *position_,
  241. .subtree_start = tree_->size()});
  242. }
  243. // Pushes a constructed state onto the stack.
  244. auto PushState(StateStackEntry state) -> void {
  245. CARBON_VLOG("Push {0}: {1}\n", state_stack_.size(), state);
  246. state_stack_.push_back(state);
  247. CARBON_CHECK(state_stack_.size() < (1 << 20),
  248. "Excessive stack size: likely infinite loop");
  249. }
  250. // Pushes a constructed state onto the stack, with a different parse state.
  251. auto PushState(StateStackEntry state_entry, State parse_state) -> void {
  252. state_entry.state = parse_state;
  253. PushState(state_entry);
  254. }
  255. // Propagates an error up the state stack, to the parent state.
  256. auto ReturnErrorOnState() -> void { state_stack_.back().has_error = true; }
  257. // Adds a node for a declaration's semicolon. Includes error recovery when the
  258. // token is not a semicolon, using `decl_kind` and `is_def_allowed` to inform
  259. // diagnostics.
  260. auto AddNodeExpectingDeclSemi(StateStackEntry state, NodeKind node_kind,
  261. Lex::TokenKind decl_kind, bool is_def_allowed)
  262. -> void;
  263. // Emits a diagnostic for a declaration missing a semi.
  264. auto DiagnoseExpectedDeclSemi(Lex::TokenKind expected_kind) -> void;
  265. // Emits a diagnostic for a declaration missing a semi or definition.
  266. auto DiagnoseExpectedDeclSemiOrDefinition(Lex::TokenKind expected_kind)
  267. -> void;
  268. // Handles error recovery in a declaration, particularly before any possible
  269. // definition has started (although one could be present). Recover to a
  270. // semicolon when it makes sense as a possible end, otherwise use the
  271. // introducer token for the error.
  272. auto RecoverFromDeclError(StateStackEntry state, NodeKind node_kind,
  273. bool skip_past_likely_end) -> void;
  274. // Handles parsing of the library name. Returns the name's ID on success,
  275. // which may be invalid for `default`.
  276. // TODO: Add an invalid node on error, fix callers to adapt.
  277. auto ParseLibraryName(bool accept_default)
  278. -> std::optional<StringLiteralValueId>;
  279. // Handles parsing `library <name>`. Requires that the position is a `library`
  280. // token. Returns the name's ID on success, which may be invalid for
  281. // `default`.
  282. auto ParseLibrarySpecifier(bool accept_default)
  283. -> std::optional<StringLiteralValueId>;
  284. // Sets the package declaration information. Called at most once.
  285. auto set_packaging_decl(Tree::PackagingNames packaging_names, bool is_impl)
  286. -> void {
  287. CARBON_CHECK(!tree_->packaging_decl_);
  288. tree_->packaging_decl_ = {.names = packaging_names, .is_impl = is_impl};
  289. }
  290. // Adds an import.
  291. auto AddImport(Tree::PackagingNames package) -> void {
  292. tree_->imports_.push_back(package);
  293. }
  294. // Adds a function definition start node, and begins tracking a deferred
  295. // definition if necessary.
  296. auto AddFunctionDefinitionStart(Lex::TokenIndex token, bool has_error)
  297. -> void;
  298. // Adds a function definition node, and ends tracking a deferred definition if
  299. // necessary.
  300. auto AddFunctionDefinition(Lex::TokenIndex token, bool has_error) -> void;
  301. // Prints information for a stack dump.
  302. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  303. auto tree() const -> const Tree& { return *tree_; }
  304. auto tokens() const -> const Lex::TokenizedBuffer& { return *tokens_; }
  305. auto emitter() -> Lex::TokenDiagnosticEmitter& { return *emitter_; }
  306. auto position() -> Lex::TokenIterator& { return position_; }
  307. auto position() const -> Lex::TokenIterator { return position_; }
  308. auto state_stack() -> llvm::SmallVector<StateStackEntry>& {
  309. return state_stack_;
  310. }
  311. auto state_stack() const -> const llvm::SmallVector<StateStackEntry>& {
  312. return state_stack_;
  313. }
  314. auto packaging_state() const -> PackagingState { return packaging_state_; }
  315. auto set_packaging_state(PackagingState packaging_state) -> void {
  316. packaging_state_ = packaging_state;
  317. }
  318. auto first_non_packaging_token() const -> Lex::TokenIndex {
  319. return first_non_packaging_token_;
  320. }
  321. auto set_first_non_packaging_token(Lex::TokenIndex token) -> void {
  322. CARBON_CHECK(!first_non_packaging_token_.is_valid());
  323. first_non_packaging_token_ = token;
  324. }
  325. private:
  326. // Prints a single token for a stack dump. Used by PrintForStackDump.
  327. auto PrintTokenForStackDump(llvm::raw_ostream& output,
  328. Lex::TokenIndex token) const -> void;
  329. Tree* tree_;
  330. Lex::TokenizedBuffer* tokens_;
  331. Lex::TokenDiagnosticEmitter* emitter_;
  332. // Whether to print verbose output.
  333. llvm::raw_ostream* vlog_stream_;
  334. // The current position within the token buffer.
  335. Lex::TokenIterator position_;
  336. // The FileEnd token.
  337. Lex::TokenIterator end_;
  338. llvm::SmallVector<StateStackEntry> state_stack_;
  339. // The deferred definition indexes of functions whose definitions have begun
  340. // but not yet finished.
  341. llvm::SmallVector<DeferredDefinitionIndex> deferred_definition_stack_;
  342. // The current packaging state, whether `import`/`package` are allowed.
  343. PackagingState packaging_state_ = PackagingState::FileStart;
  344. // The first non-packaging token, starting as invalid. Used for packaging
  345. // state warnings.
  346. Lex::TokenIndex first_non_packaging_token_ = Lex::TokenIndex::Invalid;
  347. };
  348. } // namespace Carbon::Parse
  349. #endif // CARBON_TOOLCHAIN_PARSE_CONTEXT_H_