handle_decl_scope_loop.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. // Output an invalid parse subtree including everything up to the next `;`
  52. // or end of line.
  53. context.ReplacePlaceholderNode(subtree_start, NodeKind::InvalidParseStart,
  54. cursor, /*has_error=*/true);
  55. context.AddNode(NodeKind::InvalidParseSubtree,
  56. context.SkipPastLikelyEnd(cursor), subtree_start,
  57. /*has_error=*/true);
  58. }
  59. // Prints a diagnostic and calls FinishAndSkipInvalidDecl.
  60. static auto HandleUnrecognizedDecl(Context& context, int32_t subtree_start)
  61. -> void {
  62. CARBON_DIAGNOSTIC(UnrecognizedDecl, Error,
  63. "Unrecognized declaration introducer.");
  64. context.emitter().Emit(*context.position(), UnrecognizedDecl);
  65. FinishAndSkipInvalidDecl(context, subtree_start);
  66. }
  67. // Replaces the introducer placeholder node, and pushes the introducer state for
  68. // processing.
  69. static auto ApplyIntroducer(Context& context, Context::StateStackEntry state,
  70. NodeKind introducer_kind, State next_state)
  71. -> void {
  72. context.ReplacePlaceholderNode(state.subtree_start, introducer_kind,
  73. context.Consume());
  74. // Reuse state here to retain its `subtree_start`.
  75. context.PushState(state, next_state);
  76. }
  77. // Handles `base` as a declaration.
  78. static auto HandleBaseAsDecl(Context& context, Context::StateStackEntry state)
  79. -> void {
  80. // At this point, `base` has been ruled out as a modifier (`base class`). If
  81. // it's followed by a colon, it's an introducer (`extend base: BaseType;`).
  82. // Otherwise it's an error.
  83. if (context.PositionIs(Lex::TokenKind::Colon, Lookahead::NextToken)) {
  84. ApplyIntroducer(context, state, NodeKind::BaseIntroducer, State::BaseDecl);
  85. context.PushState(State::Expr);
  86. context.AddLeafNode(NodeKind::BaseColon, context.Consume());
  87. } else {
  88. // TODO: If the next token isn't a colon or `class`, try to recover
  89. // based on whether we're in a class, whether we have an `extend`
  90. // modifier, and the following tokens.
  91. context.AddLeafNode(NodeKind::InvalidParse, context.Consume(),
  92. /*has_error=*/true);
  93. CARBON_DIAGNOSTIC(ExpectedAfterBase, Error,
  94. "`class` or `:` expected after `base`.");
  95. context.emitter().Emit(*context.position(), ExpectedAfterBase);
  96. FinishAndSkipInvalidDecl(context, state.subtree_start);
  97. }
  98. }
  99. // Returns true if the current position is a declaration. If we see a
  100. // declaration introducer keyword token, replace the placeholder node and switch
  101. // to a state to parse the rest of the declaration.
  102. static auto TryHandleAsDecl(Context& context, Context::StateStackEntry state,
  103. bool saw_modifier) -> bool {
  104. switch (context.PositionKind()) {
  105. case Lex::TokenKind::Base: {
  106. HandleBaseAsDecl(context, state);
  107. return true;
  108. }
  109. case Lex::TokenKind::Class: {
  110. ApplyIntroducer(context, state, NodeKind::ClassIntroducer,
  111. State::TypeAfterIntroducerAsClass);
  112. return true;
  113. }
  114. case Lex::TokenKind::Constraint: {
  115. ApplyIntroducer(context, state, NodeKind::NamedConstraintIntroducer,
  116. State::TypeAfterIntroducerAsNamedConstraint);
  117. return true;
  118. }
  119. case Lex::TokenKind::Extend: {
  120. // TODO: Treat this `extend` token as a declaration introducer
  121. HandleUnrecognizedDecl(context, state.subtree_start);
  122. return true;
  123. }
  124. case Lex::TokenKind::Fn: {
  125. ApplyIntroducer(context, state, NodeKind::FunctionIntroducer,
  126. State::FunctionIntroducer);
  127. return true;
  128. }
  129. case Lex::TokenKind::Impl: {
  130. ApplyIntroducer(context, state, NodeKind::ImplIntroducer,
  131. State::ImplAfterIntroducer);
  132. return true;
  133. }
  134. case Lex::TokenKind::Interface: {
  135. ApplyIntroducer(context, state, NodeKind::InterfaceIntroducer,
  136. State::TypeAfterIntroducerAsInterface);
  137. return true;
  138. }
  139. case Lex::TokenKind::Namespace: {
  140. ApplyIntroducer(context, state, NodeKind::NamespaceStart,
  141. State::Namespace);
  142. return true;
  143. }
  144. case Lex::TokenKind::Let: {
  145. ApplyIntroducer(context, state, NodeKind::LetIntroducer, State::Let);
  146. return true;
  147. }
  148. case Lex::TokenKind::Var: {
  149. ApplyIntroducer(context, state, NodeKind::VariableIntroducer,
  150. State::VarAsDecl);
  151. return true;
  152. }
  153. case Lex::TokenKind::Semi: {
  154. if (saw_modifier) {
  155. // Modifiers require an introducer keyword.
  156. HandleUnrecognizedDecl(context, state.subtree_start);
  157. } else {
  158. context.ReplacePlaceholderNode(state.subtree_start, NodeKind::EmptyDecl,
  159. context.Consume());
  160. }
  161. return true;
  162. }
  163. default:
  164. return false;
  165. }
  166. }
  167. // Returns true if position_kind could be either an introducer or modifier, and
  168. // should be treated as an introducer.
  169. static auto ResolveAmbiguousTokenAsDeclaration(Context& context,
  170. Lex::TokenKind position_kind)
  171. -> bool {
  172. switch (position_kind) {
  173. case Lex::TokenKind::Base:
  174. case Lex::TokenKind::Extend:
  175. case Lex::TokenKind::Impl:
  176. // This is an ambiguous token, so now we check what the next token is.
  177. // We use the macro for modifiers, including introducers which are
  178. // also modifiers (such as `base`). Other introducer tokens need to be
  179. // added by hand.
  180. switch (context.PositionKind(Lookahead::NextToken)) {
  181. case Lex::TokenKind::Class:
  182. case Lex::TokenKind::Constraint:
  183. case Lex::TokenKind::Fn:
  184. case Lex::TokenKind::Interface:
  185. case Lex::TokenKind::Let:
  186. case Lex::TokenKind::Namespace:
  187. case Lex::TokenKind::Var:
  188. #define CARBON_PARSE_NODE_KIND(...)
  189. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name, ...) \
  190. case Lex::TokenKind::Name:
  191. #include "toolchain/parse/node_kind.def"
  192. return false;
  193. default:
  194. return true;
  195. }
  196. break;
  197. default:
  198. return false;
  199. }
  200. }
  201. // Returns true if the current position is a modifier, handling it if so.
  202. static auto TryHandleAsModifier(Context& context) -> bool {
  203. auto position_kind = context.PositionKind();
  204. if (ResolveAmbiguousTokenAsDeclaration(context, position_kind)) {
  205. return false;
  206. }
  207. switch (position_kind) {
  208. #define CARBON_PARSE_NODE_KIND(...)
  209. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name, ...) \
  210. case Lex::TokenKind::Name: \
  211. context.AddLeafNode(NodeKind::Name##Modifier, context.Consume()); \
  212. return true;
  213. #include "toolchain/parse/node_kind.def"
  214. default:
  215. return false;
  216. }
  217. }
  218. auto HandleDeclScopeLoop(Context& context) -> void {
  219. // This maintains the current state unless we're at the end of the scope.
  220. if (TryHandleEndOrPackagingDecl(context)) {
  221. return;
  222. }
  223. // Create a state with the correct starting position, with a dummy kind
  224. // until we see the declaration's introducer.
  225. Context::StateStackEntry state{.state = State::Invalid,
  226. .token = *context.position(),
  227. .subtree_start = context.tree().size()};
  228. // Add a placeholder node, to be replaced by the declaration introducer once
  229. // it is found.
  230. context.AddLeafNode(NodeKind::Placeholder, *context.position());
  231. bool saw_modifier = false;
  232. while (TryHandleAsModifier(context)) {
  233. saw_modifier = true;
  234. }
  235. if (!TryHandleAsDecl(context, state, saw_modifier)) {
  236. HandleUnrecognizedDecl(context, state.subtree_start);
  237. }
  238. }
  239. } // namespace Carbon::Parse