handle_decl_scope_loop.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. // Finishes an invalid declaration, skipping past its end.
  9. static auto FinishAndSkipInvalidDecl(Context& context, int32_t subtree_start)
  10. -> void {
  11. auto cursor = *context.position();
  12. // Output an invalid parse subtree including everything up to the next `;`
  13. // or end of line.
  14. context.ReplacePlaceholderNode(subtree_start, NodeKind::InvalidParseStart,
  15. cursor, /*has_error=*/true);
  16. context.AddNode(NodeKind::InvalidParseSubtree,
  17. context.SkipPastLikelyEnd(cursor), subtree_start,
  18. /*has_error=*/true);
  19. }
  20. // Prints a diagnostic and calls FinishAndSkipInvalidDecl.
  21. static auto HandleUnrecognizedDecl(Context& context, int32_t subtree_start)
  22. -> void {
  23. CARBON_DIAGNOSTIC(UnrecognizedDecl, Error,
  24. "Unrecognized declaration introducer.");
  25. context.emitter().Emit(*context.position(), UnrecognizedDecl);
  26. FinishAndSkipInvalidDecl(context, subtree_start);
  27. }
  28. // Replaces the introducer placeholder node, and pushes the introducer state for
  29. // processing.
  30. static auto ApplyIntroducer(Context& context, Context::StateStackEntry state,
  31. NodeKind introducer_kind, State next_state)
  32. -> void {
  33. context.ReplacePlaceholderNode(state.subtree_start, introducer_kind,
  34. context.Consume());
  35. // Reuse state here to retain its `subtree_start`.
  36. context.PushState(state, next_state);
  37. }
  38. namespace {
  39. // The kind of declaration introduced by an introducer keyword.
  40. enum class DeclIntroducerKind : int8_t {
  41. Unrecognized,
  42. PackagingDecl,
  43. NonPackagingDecl,
  44. };
  45. // Information about a keyword that might be an introducer keyword.
  46. struct DeclIntroducerInfo {
  47. DeclIntroducerKind introducer_kind;
  48. NodeKind node_kind;
  49. State state;
  50. };
  51. } // namespace
  52. static constexpr auto DeclIntroducers = [] {
  53. DeclIntroducerInfo introducers[] = {
  54. #define CARBON_TOKEN(Name) \
  55. {DeclIntroducerKind::Unrecognized, NodeKind::InvalidParse, State::Invalid},
  56. #include "toolchain/lex/token_kind.def"
  57. };
  58. auto set = [&](Lex::TokenKind token_kind, NodeKind node_kind, State state) {
  59. introducers[token_kind.AsInt()] = {DeclIntroducerKind::NonPackagingDecl,
  60. node_kind, state};
  61. };
  62. auto set_packaging = [&](Lex::TokenKind token_kind, NodeKind node_kind,
  63. State state) {
  64. introducers[token_kind.AsInt()] = {DeclIntroducerKind::PackagingDecl,
  65. node_kind, state};
  66. };
  67. set(Lex::TokenKind::Adapt, NodeKind::AdaptIntroducer,
  68. State::AdaptAfterIntroducer);
  69. set(Lex::TokenKind::Alias, NodeKind::AliasIntroducer, State::Alias);
  70. set(Lex::TokenKind::Base, NodeKind::BaseIntroducer,
  71. State::BaseAfterIntroducer);
  72. set(Lex::TokenKind::Choice, NodeKind::ChoiceIntroducer,
  73. State::ChoiceIntroducer);
  74. set(Lex::TokenKind::Class, NodeKind::ClassIntroducer,
  75. State::TypeAfterIntroducerAsClass);
  76. set(Lex::TokenKind::Constraint, NodeKind::NamedConstraintIntroducer,
  77. State::TypeAfterIntroducerAsNamedConstraint);
  78. set(Lex::TokenKind::Export, NodeKind::ExportIntroducer, State::ExportName);
  79. // TODO: Treat `extend` as a declaration introducer.
  80. set(Lex::TokenKind::Fn, NodeKind::FunctionIntroducer,
  81. State::FunctionIntroducer);
  82. set(Lex::TokenKind::Impl, NodeKind::ImplIntroducer,
  83. State::ImplAfterIntroducer);
  84. set(Lex::TokenKind::Interface, NodeKind::InterfaceIntroducer,
  85. State::TypeAfterIntroducerAsInterface);
  86. set(Lex::TokenKind::Namespace, NodeKind::NamespaceStart, State::Namespace);
  87. set(Lex::TokenKind::Let, NodeKind::LetIntroducer, State::Let);
  88. set(Lex::TokenKind::Var, NodeKind::VariableIntroducer, State::VarAsDecl);
  89. set_packaging(Lex::TokenKind::Package, NodeKind::PackageIntroducer,
  90. State::Package);
  91. set_packaging(Lex::TokenKind::Library, NodeKind::LibraryIntroducer,
  92. State::Library);
  93. set_packaging(Lex::TokenKind::Import, NodeKind::ImportIntroducer,
  94. State::Import);
  95. return std::to_array(introducers);
  96. }();
  97. // Attempts to handle the current token as a declaration introducer.
  98. // Returns true if the current position is a declaration. If we see a
  99. // declaration introducer keyword token, replace the placeholder node and switch
  100. // to a state to parse the rest of the declaration.
  101. static auto TryHandleAsDecl(Context& context, Context::StateStackEntry state,
  102. bool saw_modifier) -> bool {
  103. const auto& info = DeclIntroducers[context.PositionKind().AsInt()];
  104. switch (info.introducer_kind) {
  105. case DeclIntroducerKind::Unrecognized: {
  106. // A `;` with no modifiers is an empty declaration.
  107. if (!saw_modifier) {
  108. if (auto loc = context.ConsumeIf(Lex::TokenKind::Semi)) {
  109. context.ReplacePlaceholderNode(state.subtree_start,
  110. NodeKind::EmptyDecl, *loc);
  111. return true;
  112. }
  113. }
  114. return false;
  115. }
  116. case DeclIntroducerKind::PackagingDecl: {
  117. // Packaging declarations update the packaging state themselves as needed.
  118. break;
  119. }
  120. case DeclIntroducerKind::NonPackagingDecl: {
  121. // Because a non-packaging keyword was encountered, packaging is complete.
  122. // Misplaced packaging keywords may lead to this being re-triggered.
  123. if (context.packaging_state() !=
  124. Context::PackagingState::AfterNonPackagingDecl) {
  125. if (!context.first_non_packaging_token().is_valid()) {
  126. context.set_first_non_packaging_token(*context.position());
  127. }
  128. context.set_packaging_state(
  129. Context::PackagingState::AfterNonPackagingDecl);
  130. }
  131. break;
  132. }
  133. }
  134. ApplyIntroducer(context, state, info.node_kind, info.state);
  135. return true;
  136. }
  137. // Returns true if position_kind could be either an introducer or modifier, and
  138. // should be treated as an introducer.
  139. static auto ResolveAmbiguousTokenAsDeclaration(Context& context,
  140. Lex::TokenKind position_kind)
  141. -> bool {
  142. switch (position_kind) {
  143. case Lex::TokenKind::Base:
  144. case Lex::TokenKind::Export:
  145. case Lex::TokenKind::Extend:
  146. case Lex::TokenKind::Impl:
  147. // This is an ambiguous token, so now we check what the next token is.
  148. // We use the macro for modifiers, including introducers which are
  149. // also modifiers (such as `base`). Other introducer tokens need to be
  150. // added by hand.
  151. switch (context.PositionKind(Lookahead::NextToken)) {
  152. case Lex::TokenKind::Adapt:
  153. case Lex::TokenKind::Alias:
  154. case Lex::TokenKind::Class:
  155. case Lex::TokenKind::Constraint:
  156. case Lex::TokenKind::Fn:
  157. case Lex::TokenKind::Import:
  158. case Lex::TokenKind::Interface:
  159. case Lex::TokenKind::Let:
  160. case Lex::TokenKind::Library:
  161. case Lex::TokenKind::Namespace:
  162. case Lex::TokenKind::Var:
  163. #define CARBON_PARSE_NODE_KIND(...)
  164. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name, ...) \
  165. case Lex::TokenKind::Name:
  166. #include "toolchain/parse/node_kind.def"
  167. return false;
  168. case Lex::TokenKind::Package:
  169. // `package.foo` is an expression; any other token after `package` is
  170. // a `package` introducer.
  171. return context.PositionKind(static_cast<Lookahead>(2)) ==
  172. Lex::TokenKind::Period;
  173. default:
  174. return true;
  175. }
  176. break;
  177. default:
  178. return false;
  179. }
  180. }
  181. // Returns true if the current position is a modifier, handling it if so.
  182. static auto TryHandleAsModifier(Context& context) -> bool {
  183. auto position_kind = context.PositionKind();
  184. if (ResolveAmbiguousTokenAsDeclaration(context, position_kind)) {
  185. return false;
  186. }
  187. switch (position_kind) {
  188. #define CARBON_PARSE_NODE_KIND(...)
  189. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name, ...) \
  190. case Lex::TokenKind::Name: \
  191. context.AddLeafNode(NodeKind::Name##Modifier, context.Consume()); \
  192. return true;
  193. #include "toolchain/parse/node_kind.def"
  194. default:
  195. return false;
  196. }
  197. }
  198. auto HandleDeclScopeLoop(Context& context) -> void {
  199. // This maintains the current state unless we're at the end of the scope.
  200. if (context.PositionIs(Lex::TokenKind::CloseCurlyBrace) ||
  201. context.PositionIs(Lex::TokenKind::FileEnd)) {
  202. // This is the end of the scope, so the loop state ends.
  203. context.PopAndDiscardState();
  204. return;
  205. }
  206. // Create a state with the correct starting position, with a dummy kind
  207. // until we see the declaration's introducer.
  208. Context::StateStackEntry state{.state = State::Invalid,
  209. .token = *context.position(),
  210. .subtree_start = context.tree().size()};
  211. // Add a placeholder node, to be replaced by the declaration introducer once
  212. // it is found.
  213. context.AddLeafNode(NodeKind::Placeholder, *context.position());
  214. bool saw_modifier = false;
  215. while (TryHandleAsModifier(context)) {
  216. saw_modifier = true;
  217. }
  218. if (!TryHandleAsDecl(context, state, saw_modifier)) {
  219. HandleUnrecognizedDecl(context, state.subtree_start);
  220. }
  221. }
  222. } // namespace Carbon::Parse