handle_decl_scope_loop.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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 <array>
  5. #include "toolchain/lex/token_kind.h"
  6. #include "toolchain/parse/context.h"
  7. #include "toolchain/parse/handle.h"
  8. #include "toolchain/parse/node_kind.h"
  9. namespace Carbon::Parse {
  10. // Finishes an invalid declaration, skipping past its end.
  11. static auto FinishAndSkipInvalidDecl(Context& context, int32_t subtree_start)
  12. -> void {
  13. auto cursor = *context.position();
  14. // Output an invalid parse subtree including everything up to the next `;`
  15. // or end of line.
  16. context.ReplacePlaceholderNode(subtree_start, NodeKind::InvalidParseStart,
  17. cursor, /*has_error=*/true);
  18. context.AddNode(NodeKind::InvalidParseSubtree,
  19. context.SkipPastLikelyEnd(cursor), /*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::State state,
  32. NodeKind introducer_kind, StateKind next_state_kind)
  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_kind);
  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. StateKind state_kind;
  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_kind = StateKind::Invalid},
  59. #include "toolchain/lex/token_kind.def"
  60. };
  61. auto set = [&](Lex::TokenKind token_kind, NodeKind node_kind,
  62. StateKind state) {
  63. introducers[token_kind.AsInt()] = {
  64. .introducer_kind = DeclIntroducerKind::NonPackagingDecl,
  65. .node_kind = node_kind,
  66. .state_kind = state};
  67. };
  68. auto set_packaging = [&](Lex::TokenKind token_kind, NodeKind node_kind,
  69. StateKind state) {
  70. introducers[token_kind.AsInt()] = {
  71. .introducer_kind = DeclIntroducerKind::PackagingDecl,
  72. .node_kind = node_kind,
  73. .state_kind = state};
  74. };
  75. set(Lex::TokenKind::Adapt, NodeKind::AdaptIntroducer,
  76. StateKind::AdaptAfterIntroducer);
  77. set(Lex::TokenKind::Alias, NodeKind::AliasIntroducer, StateKind::Alias);
  78. set(Lex::TokenKind::Base, NodeKind::BaseIntroducer,
  79. StateKind::BaseAfterIntroducer);
  80. set(Lex::TokenKind::Choice, NodeKind::ChoiceIntroducer,
  81. StateKind::ChoiceIntroducer);
  82. set(Lex::TokenKind::Class, NodeKind::ClassIntroducer,
  83. StateKind::TypeAfterIntroducerAsClass);
  84. set(Lex::TokenKind::Constraint, NodeKind::NamedConstraintIntroducer,
  85. StateKind::TypeAfterIntroducerAsNamedConstraint);
  86. set(Lex::TokenKind::Export, NodeKind::ExportIntroducer,
  87. StateKind::ExportName);
  88. // TODO: Treat `extend` as a declaration introducer.
  89. set(Lex::TokenKind::Fn, NodeKind::FunctionIntroducer,
  90. StateKind::FunctionIntroducer);
  91. set(Lex::TokenKind::Impl, NodeKind::ImplIntroducer,
  92. StateKind::ImplAfterIntroducer);
  93. set(Lex::TokenKind::Interface, NodeKind::InterfaceIntroducer,
  94. StateKind::TypeAfterIntroducerAsInterface);
  95. set(Lex::TokenKind::Namespace, NodeKind::NamespaceStart,
  96. StateKind::Namespace);
  97. set(Lex::TokenKind::Let, NodeKind::LetIntroducer, StateKind::Let);
  98. set(Lex::TokenKind::Var, NodeKind::VariableIntroducer, StateKind::VarAsDecl);
  99. set_packaging(Lex::TokenKind::Package, NodeKind::PackageIntroducer,
  100. StateKind::Package);
  101. set_packaging(Lex::TokenKind::Library, NodeKind::LibraryIntroducer,
  102. StateKind::Library);
  103. set_packaging(Lex::TokenKind::Import, NodeKind::ImportIntroducer,
  104. StateKind::Import);
  105. return std::to_array(introducers);
  106. }();
  107. // Attempts to handle the current token as a declaration introducer.
  108. // Returns true if the current position is a declaration. If we see a
  109. // declaration introducer keyword token, replace the placeholder node and switch
  110. // to a state to parse the rest of the declaration.
  111. static auto TryHandleAsDecl(Context& context, Context::State state,
  112. bool saw_modifier) -> bool {
  113. const auto& info = DeclIntroducers[context.PositionKind().AsInt()];
  114. switch (info.introducer_kind) {
  115. case DeclIntroducerKind::Unrecognized: {
  116. // A `;` with no modifiers is an empty declaration.
  117. if (!saw_modifier) {
  118. if (auto loc = context.ConsumeIf(Lex::TokenKind::Semi)) {
  119. context.ReplacePlaceholderNode(state.subtree_start,
  120. NodeKind::EmptyDecl, *loc);
  121. return true;
  122. }
  123. }
  124. return false;
  125. }
  126. case DeclIntroducerKind::PackagingDecl: {
  127. // Packaging declarations update the packaging state themselves as needed.
  128. break;
  129. }
  130. case DeclIntroducerKind::NonPackagingDecl: {
  131. // Because a non-packaging keyword was encountered, packaging is complete.
  132. // Misplaced packaging keywords may lead to this being re-triggered.
  133. if (context.packaging_state() !=
  134. Context::PackagingState::AfterNonPackagingDecl) {
  135. if (!context.first_non_packaging_token().has_value()) {
  136. context.set_first_non_packaging_token(*context.position());
  137. }
  138. context.set_packaging_state(
  139. Context::PackagingState::AfterNonPackagingDecl);
  140. }
  141. break;
  142. }
  143. }
  144. ApplyIntroducer(context, state, info.node_kind, info.state_kind);
  145. return true;
  146. }
  147. // Returns true if position_kind could be either an introducer or modifier, and
  148. // should be treated as an introducer.
  149. static auto ResolveAmbiguousTokenAsDeclaration(Context& context,
  150. Lex::TokenKind position_kind)
  151. -> bool {
  152. switch (position_kind) {
  153. case Lex::TokenKind::Base:
  154. case Lex::TokenKind::Export:
  155. case Lex::TokenKind::Extend:
  156. case Lex::TokenKind::Impl:
  157. // This is an ambiguous token, so now we check what the next token is.
  158. // We use the macro for modifiers, including introducers which are
  159. // also modifiers (such as `base`). Other introducer tokens need to be
  160. // added by hand.
  161. switch (context.PositionKind(Lookahead::NextToken)) {
  162. case Lex::TokenKind::Adapt:
  163. case Lex::TokenKind::Alias:
  164. case Lex::TokenKind::Class:
  165. case Lex::TokenKind::Constraint:
  166. case Lex::TokenKind::Extern:
  167. case Lex::TokenKind::Fn:
  168. case Lex::TokenKind::Import:
  169. case Lex::TokenKind::Interface:
  170. case Lex::TokenKind::Let:
  171. case Lex::TokenKind::Library:
  172. case Lex::TokenKind::Namespace:
  173. case Lex::TokenKind::Var:
  174. #define CARBON_PARSE_NODE_KIND(Name)
  175. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name) case Lex::TokenKind::Name:
  176. #include "toolchain/parse/node_kind.def"
  177. return false;
  178. case Lex::TokenKind::Package:
  179. // `package.foo` is an expression; any other token after `package` is
  180. // a `package` introducer.
  181. return context.PositionKind(static_cast<Lookahead>(2)) ==
  182. Lex::TokenKind::Period;
  183. default:
  184. return true;
  185. }
  186. break;
  187. default:
  188. return false;
  189. }
  190. }
  191. // Returns true if the current position is a modifier, handling it if so.
  192. static auto TryHandleAsModifier(Context& context) -> bool {
  193. auto position_kind = context.PositionKind();
  194. if (ResolveAmbiguousTokenAsDeclaration(context, position_kind)) {
  195. return false;
  196. }
  197. switch (position_kind) {
  198. #define CARBON_PARSE_NODE_KIND(Name)
  199. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name) \
  200. case Lex::TokenKind::Name: \
  201. context.AddLeafNode(NodeKind::Name##Modifier, context.Consume()); \
  202. return true;
  203. #include "toolchain/parse/node_kind.def"
  204. case Lex::TokenKind::Extern: {
  205. auto extern_token = context.Consume();
  206. if (context.PositionIs(Lex::TokenKind::Library)) {
  207. // `extern library <owning_library>` syntax.
  208. context.ParseLibrarySpecifier(/*accept_default=*/true);
  209. // TODO: Consider error recovery when a non-declaration token is next,
  210. // like a typo of the library name.
  211. context.AddNode(NodeKind::ExternModifierWithLibrary, extern_token,
  212. /*has_error=*/false);
  213. } else {
  214. // `extern` syntax without a library.
  215. context.AddLeafNode(NodeKind::ExternModifier, extern_token);
  216. }
  217. return true;
  218. }
  219. default:
  220. return false;
  221. }
  222. }
  223. auto HandleDecl(Context& context) -> void {
  224. auto state = context.PopState();
  225. // Add a placeholder node, to be replaced by the declaration introducer once
  226. // it is found.
  227. context.AddLeafNode(NodeKind::Placeholder, *context.position());
  228. bool saw_modifier = false;
  229. while (TryHandleAsModifier(context)) {
  230. saw_modifier = true;
  231. }
  232. if (!TryHandleAsDecl(context, state, saw_modifier)) {
  233. HandleUnrecognizedDecl(context, state.subtree_start);
  234. }
  235. }
  236. auto HandleDeclScopeLoop(Context& context) -> void {
  237. // This maintains the current state unless we're at the end of the scope.
  238. if (context.PositionIs(Lex::TokenKind::CloseCurlyBrace) ||
  239. context.PositionIs(Lex::TokenKind::FileEnd)) {
  240. // This is the end of the scope, so the loop state ends.
  241. context.PopAndDiscardState();
  242. return;
  243. }
  244. context.PushState(StateKind::Decl);
  245. }
  246. } // namespace Carbon::Parse