handle_decl_scope_loop.cpp 10 KB

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