handle_decl_scope_loop.cpp 9.8 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. #include "toolchain/lex/token_kind.h"
  5. #include "toolchain/parse/context.h"
  6. #include "toolchain/parse/node_kind.h"
  7. namespace Carbon::Parse {
  8. // Handles positions which are end of scope and packaging declarations. Returns
  9. // true when either applies. When the position is neither, returns false, and
  10. // may still update packaging state.
  11. static auto TryHandleEndOrPackagingDecl(Context& context) -> bool {
  12. switch (context.PositionKind()) {
  13. case Lex::TokenKind::CloseCurlyBrace:
  14. case Lex::TokenKind::FileEnd: {
  15. // This is the end of the scope, so the loop state ends.
  16. context.PopAndDiscardState();
  17. return true;
  18. }
  19. // `import`, `library`, and `package` manage their packaging state.
  20. case Lex::TokenKind::Import: {
  21. context.PushState(State::Import);
  22. return true;
  23. }
  24. case Lex::TokenKind::Library: {
  25. context.PushState(State::Library);
  26. return true;
  27. }
  28. case Lex::TokenKind::Package: {
  29. context.PushState(State::Package);
  30. return true;
  31. }
  32. default: {
  33. // Because a non-packaging keyword was encountered, packaging is complete.
  34. // Misplaced packaging keywords may lead to this being re-triggered.
  35. if (context.packaging_state() !=
  36. Context::PackagingState::AfterNonPackagingDecl) {
  37. if (!context.first_non_packaging_token().is_valid()) {
  38. context.set_first_non_packaging_token(*context.position());
  39. }
  40. context.set_packaging_state(
  41. Context::PackagingState::AfterNonPackagingDecl);
  42. }
  43. return false;
  44. }
  45. }
  46. }
  47. // Finishes an invalid declaration, skipping past its end.
  48. static auto FinishAndSkipInvalidDecl(Context& context, int32_t subtree_start)
  49. -> void {
  50. auto cursor = *context.position();
  51. // Consume to the next `;` or end of line. We ignore the return value since
  52. // we only care how much was consumed, not whether it ended with a `;`.
  53. // TODO: adjust the return of SkipPastLikelyEnd or create a new function
  54. // to avoid going through these hoops.
  55. context.SkipPastLikelyEnd(cursor);
  56. // Set `iter` to the last token consumed, one before the current position.
  57. auto iter = context.position();
  58. --iter;
  59. // Output an invalid parse subtree including everything up to the last token
  60. // consumed.
  61. context.ReplacePlaceholderNode(subtree_start, NodeKind::InvalidParseStart,
  62. cursor, /*has_error=*/true);
  63. context.AddNode(NodeKind::InvalidParseSubtree, *iter, subtree_start,
  64. /*has_error=*/true);
  65. }
  66. // Prints a diagnostic and calls FinishAndSkipInvalidDecl.
  67. static auto HandleUnrecognizedDecl(Context& context, int32_t subtree_start)
  68. -> void {
  69. CARBON_DIAGNOSTIC(UnrecognizedDecl, Error,
  70. "Unrecognized declaration introducer.");
  71. context.emitter().Emit(*context.position(), UnrecognizedDecl);
  72. FinishAndSkipInvalidDecl(context, subtree_start);
  73. }
  74. // Replaces the introducer placeholder node, and pushes the introducer state for
  75. // processing.
  76. static auto ApplyIntroducer(Context& context, Context::StateStackEntry state,
  77. NodeKind introducer_kind, State next_state)
  78. -> void {
  79. context.ReplacePlaceholderNode(state.subtree_start, introducer_kind,
  80. context.Consume());
  81. // Reuse state here to retain its `subtree_start`.
  82. state.state = next_state;
  83. context.PushState(state);
  84. }
  85. // Handles `base` as a declaration.
  86. static auto HandleBaseAsDecl(Context& context, Context::StateStackEntry state)
  87. -> void {
  88. // At this point, `base` has been ruled out as a modifier (`base class`). If
  89. // it's followed by a colon, it's an introducer (`extend base: BaseType;`).
  90. // Otherwise it's an error.
  91. if (context.PositionIs(Lex::TokenKind::Colon, Lookahead::NextToken)) {
  92. ApplyIntroducer(context, state, NodeKind::BaseIntroducer, State::BaseDecl);
  93. context.PushState(State::Expr);
  94. context.AddLeafNode(NodeKind::BaseColon, context.Consume());
  95. } else {
  96. // TODO: If the next token isn't a colon or `class`, try to recover
  97. // based on whether we're in a class, whether we have an `extend`
  98. // modifier, and the following tokens.
  99. context.AddLeafNode(NodeKind::InvalidParse, context.Consume(),
  100. /*has_error=*/true);
  101. CARBON_DIAGNOSTIC(ExpectedAfterBase, Error,
  102. "`class` or `:` expected after `base`.");
  103. context.emitter().Emit(*context.position(), ExpectedAfterBase);
  104. FinishAndSkipInvalidDecl(context, state.subtree_start);
  105. }
  106. }
  107. // Returns true if the current position is a declaration. If we see a
  108. // declaration introducer keyword token, replace the placeholder node and switch
  109. // to a state to parse the rest of the declaration.
  110. static auto TryHandleAsDecl(Context& context, Context::StateStackEntry state,
  111. bool saw_modifier) -> bool {
  112. switch (context.PositionKind()) {
  113. case Lex::TokenKind::Base: {
  114. HandleBaseAsDecl(context, state);
  115. return true;
  116. }
  117. case Lex::TokenKind::Class: {
  118. ApplyIntroducer(context, state, NodeKind::ClassIntroducer,
  119. State::TypeAfterIntroducerAsClass);
  120. return true;
  121. }
  122. case Lex::TokenKind::Constraint: {
  123. ApplyIntroducer(context, state, NodeKind::NamedConstraintIntroducer,
  124. State::TypeAfterIntroducerAsNamedConstraint);
  125. return true;
  126. }
  127. case Lex::TokenKind::Extend: {
  128. // TODO: Treat this `extend` token as a declaration introducer
  129. HandleUnrecognizedDecl(context, state.subtree_start);
  130. return true;
  131. }
  132. case Lex::TokenKind::Fn: {
  133. ApplyIntroducer(context, state, NodeKind::FunctionIntroducer,
  134. State::FunctionIntroducer);
  135. return true;
  136. }
  137. case Lex::TokenKind::Impl: {
  138. // TODO: Treat this `impl` token as a declaration introducer
  139. HandleUnrecognizedDecl(context, state.subtree_start);
  140. return true;
  141. }
  142. case Lex::TokenKind::Interface: {
  143. ApplyIntroducer(context, state, NodeKind::InterfaceIntroducer,
  144. State::TypeAfterIntroducerAsInterface);
  145. return true;
  146. }
  147. case Lex::TokenKind::Namespace: {
  148. ApplyIntroducer(context, state, NodeKind::NamespaceStart,
  149. State::Namespace);
  150. return true;
  151. }
  152. case Lex::TokenKind::Let: {
  153. ApplyIntroducer(context, state, NodeKind::LetIntroducer, State::Let);
  154. return true;
  155. }
  156. case Lex::TokenKind::Var: {
  157. ApplyIntroducer(context, state, NodeKind::VariableIntroducer,
  158. State::VarAsDecl);
  159. return true;
  160. }
  161. case Lex::TokenKind::Semi: {
  162. if (saw_modifier) {
  163. // Modifiers require an introducer keyword.
  164. HandleUnrecognizedDecl(context, state.subtree_start);
  165. } else {
  166. context.ReplacePlaceholderNode(state.subtree_start, NodeKind::EmptyDecl,
  167. context.Consume());
  168. }
  169. return true;
  170. }
  171. default:
  172. return false;
  173. }
  174. }
  175. // Returns true if position_kind could be either an introducer or modifier, and
  176. // should be treated as an introducer.
  177. static auto ResolveAmbiguousTokenAsDeclaration(Context& context,
  178. Lex::TokenKind position_kind)
  179. -> bool {
  180. switch (position_kind) {
  181. case Lex::TokenKind::Base:
  182. case Lex::TokenKind::Extend:
  183. case Lex::TokenKind::Impl:
  184. // This is an ambiguous token, so now we check what the next token is.
  185. // We use the macro for modifiers, including introducers which are
  186. // also modifiers (such as `base`). Other introducer tokens need to be
  187. // added by hand.
  188. switch (context.PositionKind(Lookahead::NextToken)) {
  189. case Lex::TokenKind::Class:
  190. case Lex::TokenKind::Constraint:
  191. case Lex::TokenKind::Fn:
  192. case Lex::TokenKind::Interface:
  193. case Lex::TokenKind::Let:
  194. case Lex::TokenKind::Namespace:
  195. case Lex::TokenKind::Var:
  196. #define CARBON_PARSE_NODE_KIND(...)
  197. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name, ...) \
  198. case Lex::TokenKind::Name:
  199. #include "toolchain/parse/node_kind.def"
  200. return false;
  201. default:
  202. return true;
  203. }
  204. break;
  205. default:
  206. return false;
  207. }
  208. }
  209. // Returns true if the current position is a modifier, handling it if so.
  210. static auto TryHandleAsModifier(Context& context) -> bool {
  211. auto position_kind = context.PositionKind();
  212. if (ResolveAmbiguousTokenAsDeclaration(context, position_kind)) {
  213. return false;
  214. }
  215. switch (position_kind) {
  216. #define CARBON_PARSE_NODE_KIND(...)
  217. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name, ...) \
  218. case Lex::TokenKind::Name: \
  219. context.AddLeafNode(NodeKind::Name##Modifier, context.Consume()); \
  220. return true;
  221. #include "toolchain/parse/node_kind.def"
  222. default:
  223. return false;
  224. }
  225. }
  226. auto HandleDeclScopeLoop(Context& context) -> void {
  227. // This maintains the current state unless we're at the end of the scope.
  228. if (TryHandleEndOrPackagingDecl(context)) {
  229. return;
  230. }
  231. // Create a state with the correct starting position, with a dummy kind
  232. // until we see the declaration's introducer.
  233. Context::StateStackEntry state{.state = State::Invalid,
  234. .token = *context.position(),
  235. .subtree_start = context.tree().size()};
  236. // Add a placeholder node, to be replaced by the declaration introducer once
  237. // it is found.
  238. context.AddLeafNode(NodeKind::Placeholder, *context.position());
  239. bool saw_modifier = false;
  240. while (TryHandleAsModifier(context)) {
  241. saw_modifier = true;
  242. }
  243. if (!TryHandleAsDecl(context, state, saw_modifier)) {
  244. HandleUnrecognizedDecl(context, state.subtree_start);
  245. }
  246. }
  247. } // namespace Carbon::Parse