handle_decl_scope_loop.cpp 9.8 KB

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