handle_decl_scope_loop.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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::Alias: {
  106. ApplyIntroducer(context, state, NodeKind::AliasIntroducer, State::Alias);
  107. return true;
  108. }
  109. case Lex::TokenKind::Base: {
  110. HandleBaseAsDecl(context, state);
  111. return true;
  112. }
  113. case Lex::TokenKind::Class: {
  114. ApplyIntroducer(context, state, NodeKind::ClassIntroducer,
  115. State::TypeAfterIntroducerAsClass);
  116. return true;
  117. }
  118. case Lex::TokenKind::Constraint: {
  119. ApplyIntroducer(context, state, NodeKind::NamedConstraintIntroducer,
  120. State::TypeAfterIntroducerAsNamedConstraint);
  121. return true;
  122. }
  123. case Lex::TokenKind::Extend: {
  124. // TODO: Treat this `extend` token as a declaration introducer
  125. HandleUnrecognizedDecl(context, state.subtree_start);
  126. return true;
  127. }
  128. case Lex::TokenKind::Fn: {
  129. ApplyIntroducer(context, state, NodeKind::FunctionIntroducer,
  130. State::FunctionIntroducer);
  131. return true;
  132. }
  133. case Lex::TokenKind::Impl: {
  134. ApplyIntroducer(context, state, NodeKind::ImplIntroducer,
  135. State::ImplAfterIntroducer);
  136. return true;
  137. }
  138. case Lex::TokenKind::Interface: {
  139. ApplyIntroducer(context, state, NodeKind::InterfaceIntroducer,
  140. State::TypeAfterIntroducerAsInterface);
  141. return true;
  142. }
  143. case Lex::TokenKind::Namespace: {
  144. ApplyIntroducer(context, state, NodeKind::NamespaceStart,
  145. State::Namespace);
  146. return true;
  147. }
  148. case Lex::TokenKind::Let: {
  149. ApplyIntroducer(context, state, NodeKind::LetIntroducer, State::Let);
  150. return true;
  151. }
  152. case Lex::TokenKind::Var: {
  153. ApplyIntroducer(context, state, NodeKind::VariableIntroducer,
  154. State::VarAsDecl);
  155. return true;
  156. }
  157. case Lex::TokenKind::Choice: {
  158. ApplyIntroducer(context, state, NodeKind::ChoiceIntroducer,
  159. State::ChoiceIntroducer);
  160. return true;
  161. }
  162. case Lex::TokenKind::Semi: {
  163. if (saw_modifier) {
  164. // Modifiers require an introducer keyword.
  165. HandleUnrecognizedDecl(context, state.subtree_start);
  166. } else {
  167. context.ReplacePlaceholderNode(state.subtree_start, NodeKind::EmptyDecl,
  168. context.Consume());
  169. }
  170. return true;
  171. }
  172. default:
  173. return false;
  174. }
  175. }
  176. // Returns true if position_kind could be either an introducer or modifier, and
  177. // should be treated as an introducer.
  178. static auto ResolveAmbiguousTokenAsDeclaration(Context& context,
  179. Lex::TokenKind position_kind)
  180. -> bool {
  181. switch (position_kind) {
  182. case Lex::TokenKind::Base:
  183. case Lex::TokenKind::Extend:
  184. case Lex::TokenKind::Impl:
  185. // This is an ambiguous token, so now we check what the next token is.
  186. // We use the macro for modifiers, including introducers which are
  187. // also modifiers (such as `base`). Other introducer tokens need to be
  188. // added by hand.
  189. switch (context.PositionKind(Lookahead::NextToken)) {
  190. case Lex::TokenKind::Alias:
  191. case Lex::TokenKind::Class:
  192. case Lex::TokenKind::Constraint:
  193. case Lex::TokenKind::Fn:
  194. case Lex::TokenKind::Interface:
  195. case Lex::TokenKind::Let:
  196. case Lex::TokenKind::Namespace:
  197. case Lex::TokenKind::Var:
  198. #define CARBON_PARSE_NODE_KIND(...)
  199. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name, ...) \
  200. case Lex::TokenKind::Name:
  201. #include "toolchain/parse/node_kind.def"
  202. return false;
  203. default:
  204. return true;
  205. }
  206. break;
  207. default:
  208. return false;
  209. }
  210. }
  211. // Returns true if the current position is a modifier, handling it if so.
  212. static auto TryHandleAsModifier(Context& context) -> bool {
  213. auto position_kind = context.PositionKind();
  214. if (ResolveAmbiguousTokenAsDeclaration(context, position_kind)) {
  215. return false;
  216. }
  217. switch (position_kind) {
  218. #define CARBON_PARSE_NODE_KIND(...)
  219. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name, ...) \
  220. case Lex::TokenKind::Name: \
  221. context.AddLeafNode(NodeKind::Name##Modifier, context.Consume()); \
  222. return true;
  223. #include "toolchain/parse/node_kind.def"
  224. default:
  225. return false;
  226. }
  227. }
  228. auto HandleDeclScopeLoop(Context& context) -> void {
  229. // This maintains the current state unless we're at the end of the scope.
  230. if (TryHandleEndOrPackagingDecl(context)) {
  231. return;
  232. }
  233. // Create a state with the correct starting position, with a dummy kind
  234. // until we see the declaration's introducer.
  235. Context::StateStackEntry state{.state = State::Invalid,
  236. .token = *context.position(),
  237. .subtree_start = context.tree().size()};
  238. // Add a placeholder node, to be replaced by the declaration introducer once
  239. // it is found.
  240. context.AddLeafNode(NodeKind::Placeholder, *context.position());
  241. bool saw_modifier = false;
  242. while (TryHandleAsModifier(context)) {
  243. saw_modifier = true;
  244. }
  245. if (!TryHandleAsDecl(context, state, saw_modifier)) {
  246. HandleUnrecognizedDecl(context, state.subtree_start);
  247. }
  248. }
  249. } // namespace Carbon::Parse