handle_decl_scope_loop.cpp 9.5 KB

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