handle_decl_scope_loop.cpp 9.4 KB

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