handle_decl_scope_loop.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 context in which a declaration appears.
  41. enum DeclContextKind : int8_t {
  42. NonClassContext = 0,
  43. ClassContext = 1,
  44. MaxDeclContextKind = ClassContext,
  45. };
  46. // The kind of declaration introduced by an introducer keyword.
  47. enum class DeclIntroducerKind : int8_t {
  48. Unrecognized,
  49. PackagingDecl,
  50. NonPackagingDecl,
  51. };
  52. // Information about a keyword that might be an introducer keyword.
  53. struct DeclIntroducerInfo {
  54. DeclIntroducerKind introducer_kind;
  55. NodeKind node_kind;
  56. StateKind state_kind;
  57. };
  58. } // namespace
  59. static constexpr auto DeclIntroducers = [] {
  60. std::array<DeclIntroducerInfo, MaxDeclContextKind + 1> introducers[] = {
  61. #define CARBON_TOKEN(Name) \
  62. {{{.introducer_kind = DeclIntroducerKind::Unrecognized, \
  63. .node_kind = NodeKind::InvalidParse, \
  64. .state_kind = StateKind::Invalid}, \
  65. {.introducer_kind = DeclIntroducerKind::Unrecognized, \
  66. .node_kind = NodeKind::InvalidParse, \
  67. .state_kind = StateKind::Invalid}}},
  68. #include "toolchain/lex/token_kind.def"
  69. };
  70. auto set = [&](Lex::TokenKind token_kind, NodeKind node_kind,
  71. StateKind state) {
  72. for (int i = 0; i <= MaxDeclContextKind; ++i) {
  73. introducers[token_kind.AsInt()][i] = {
  74. .introducer_kind = DeclIntroducerKind::NonPackagingDecl,
  75. .node_kind = node_kind,
  76. .state_kind = state};
  77. }
  78. };
  79. auto set_contextual = [&](Lex::TokenKind token_kind,
  80. DeclContextKind context_kind, NodeKind node_kind,
  81. StateKind state) {
  82. introducers[token_kind.AsInt()][context_kind] = {
  83. .introducer_kind = DeclIntroducerKind::NonPackagingDecl,
  84. .node_kind = node_kind,
  85. .state_kind = state};
  86. };
  87. auto set_packaging = [&](Lex::TokenKind token_kind, NodeKind node_kind,
  88. StateKind state) {
  89. for (int i = 0; i <= MaxDeclContextKind; ++i) {
  90. introducers[token_kind.AsInt()][i] = {
  91. .introducer_kind = DeclIntroducerKind::PackagingDecl,
  92. .node_kind = node_kind,
  93. .state_kind = state};
  94. }
  95. };
  96. set(Lex::TokenKind::Adapt, NodeKind::AdaptIntroducer,
  97. StateKind::AdaptAfterIntroducer);
  98. set(Lex::TokenKind::Alias, NodeKind::AliasIntroducer, StateKind::Alias);
  99. set(Lex::TokenKind::Base, NodeKind::BaseIntroducer,
  100. StateKind::BaseAfterIntroducer);
  101. set(Lex::TokenKind::Choice, NodeKind::ChoiceIntroducer,
  102. StateKind::ChoiceIntroducer);
  103. set(Lex::TokenKind::Class, NodeKind::ClassIntroducer,
  104. StateKind::TypeAfterIntroducerAsClass);
  105. set(Lex::TokenKind::Constraint, NodeKind::NamedConstraintIntroducer,
  106. StateKind::TypeAfterIntroducerAsNamedConstraint);
  107. set(Lex::TokenKind::Export, NodeKind::ExportIntroducer,
  108. StateKind::ExportName);
  109. // TODO: Treat `extend` as a declaration introducer.
  110. set(Lex::TokenKind::Fn, NodeKind::FunctionIntroducer,
  111. StateKind::FunctionIntroducer);
  112. set(Lex::TokenKind::Impl, NodeKind::ImplIntroducer,
  113. StateKind::ImplAfterIntroducer);
  114. set(Lex::TokenKind::Interface, NodeKind::InterfaceIntroducer,
  115. StateKind::TypeAfterIntroducerAsInterface);
  116. set(Lex::TokenKind::Namespace, NodeKind::NamespaceStart,
  117. StateKind::Namespace);
  118. set(Lex::TokenKind::Let, NodeKind::LetIntroducer, StateKind::Let);
  119. set_contextual(Lex::TokenKind::Var, NonClassContext,
  120. NodeKind::VariableIntroducer, StateKind::VarAsRegular);
  121. set_contextual(Lex::TokenKind::Var, ClassContext, NodeKind::FieldIntroducer,
  122. StateKind::FieldDecl);
  123. set_packaging(Lex::TokenKind::Package, NodeKind::PackageIntroducer,
  124. StateKind::Package);
  125. set_packaging(Lex::TokenKind::Library, NodeKind::LibraryIntroducer,
  126. StateKind::Library);
  127. set_packaging(Lex::TokenKind::Import, NodeKind::ImportIntroducer,
  128. StateKind::Import);
  129. return std::to_array(introducers);
  130. }();
  131. // Attempts to handle the current token as a declaration introducer.
  132. // Returns true if the current position is a declaration. If we see a
  133. // declaration introducer keyword token, replace the placeholder node and switch
  134. // to a state to parse the rest of the declaration.
  135. static auto TryHandleAsDecl(Context& context, Context::State state,
  136. bool saw_modifier,
  137. DeclContextKind decl_context_kind) -> bool {
  138. const auto& info =
  139. DeclIntroducers[context.PositionKind().AsInt()][decl_context_kind];
  140. switch (info.introducer_kind) {
  141. case DeclIntroducerKind::Unrecognized: {
  142. // A `;` with no modifiers is an empty declaration.
  143. if (!saw_modifier) {
  144. if (auto loc = context.ConsumeIf(Lex::TokenKind::Semi)) {
  145. context.ReplacePlaceholderNode(state.subtree_start,
  146. NodeKind::EmptyDecl, *loc);
  147. return true;
  148. }
  149. }
  150. return false;
  151. }
  152. case DeclIntroducerKind::PackagingDecl: {
  153. // Packaging declarations update the packaging state themselves as needed.
  154. break;
  155. }
  156. case DeclIntroducerKind::NonPackagingDecl: {
  157. // Because a non-packaging keyword was encountered, packaging is complete.
  158. // Misplaced packaging keywords may lead to this being re-triggered.
  159. if (context.packaging_state() !=
  160. Context::PackagingState::AfterNonPackagingDecl) {
  161. if (!context.first_non_packaging_token().has_value()) {
  162. context.set_first_non_packaging_token(*context.position());
  163. }
  164. context.set_packaging_state(
  165. Context::PackagingState::AfterNonPackagingDecl);
  166. }
  167. break;
  168. }
  169. }
  170. ApplyIntroducer(context, state, info.node_kind, info.state_kind);
  171. return true;
  172. }
  173. // Returns true if position_kind could be either an introducer or modifier, and
  174. // should be treated as an introducer.
  175. static auto ResolveAmbiguousTokenAsDeclaration(Context& context,
  176. Lex::TokenKind position_kind)
  177. -> bool {
  178. switch (position_kind) {
  179. case Lex::TokenKind::Base:
  180. case Lex::TokenKind::Export:
  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::Adapt:
  189. case Lex::TokenKind::Alias:
  190. case Lex::TokenKind::Class:
  191. case Lex::TokenKind::Constraint:
  192. case Lex::TokenKind::Extern:
  193. case Lex::TokenKind::Fn:
  194. case Lex::TokenKind::Import:
  195. case Lex::TokenKind::Interface:
  196. case Lex::TokenKind::Let:
  197. case Lex::TokenKind::Library:
  198. case Lex::TokenKind::Namespace:
  199. case Lex::TokenKind::Var:
  200. #define CARBON_PARSE_NODE_KIND(Name)
  201. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name) case Lex::TokenKind::Name:
  202. #include "toolchain/parse/node_kind.def"
  203. return false;
  204. case Lex::TokenKind::Package:
  205. // `package.foo` is an expression; any other token after `package` is
  206. // a `package` introducer.
  207. return context.PositionKind(static_cast<Lookahead>(2)) ==
  208. Lex::TokenKind::Period;
  209. default:
  210. return true;
  211. }
  212. break;
  213. default:
  214. return false;
  215. }
  216. }
  217. // Returns true if the current position is a modifier, handling it if so.
  218. static auto TryHandleAsModifier(Context& context) -> bool {
  219. auto position_kind = context.PositionKind();
  220. if (ResolveAmbiguousTokenAsDeclaration(context, position_kind)) {
  221. return false;
  222. }
  223. switch (position_kind) {
  224. #define CARBON_PARSE_NODE_KIND(Name)
  225. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name) \
  226. case Lex::TokenKind::Name: \
  227. context.AddLeafNode(NodeKind::Name##Modifier, context.Consume()); \
  228. return true;
  229. #include "toolchain/parse/node_kind.def"
  230. case Lex::TokenKind::Extern: {
  231. auto extern_token = context.Consume();
  232. if (context.PositionIs(Lex::TokenKind::Library)) {
  233. // `extern library <owning_library>` syntax.
  234. context.ParseLibrarySpecifier(/*accept_default=*/true);
  235. // TODO: Consider error recovery when a non-declaration token is next,
  236. // like a typo of the library name.
  237. context.AddNode(NodeKind::ExternModifierWithLibrary, extern_token,
  238. /*has_error=*/false);
  239. } else {
  240. // `extern` syntax without a library.
  241. context.AddLeafNode(NodeKind::ExternModifier, extern_token);
  242. }
  243. return true;
  244. }
  245. default:
  246. return false;
  247. }
  248. }
  249. static auto HandleDecl(Context& context, DeclContextKind decl_context_kind)
  250. -> void {
  251. auto state = context.PopState();
  252. // Add a placeholder node, to be replaced by the declaration introducer once
  253. // it is found.
  254. context.AddLeafNode(NodeKind::Placeholder, *context.position());
  255. bool saw_modifier = false;
  256. while (TryHandleAsModifier(context)) {
  257. saw_modifier = true;
  258. }
  259. if (!TryHandleAsDecl(context, state, saw_modifier, decl_context_kind)) {
  260. HandleUnrecognizedDecl(context, state.subtree_start);
  261. }
  262. }
  263. auto HandleDeclAsClass(Context& context) -> void {
  264. HandleDecl(context, ClassContext);
  265. }
  266. auto HandleDeclAsNonClass(Context& context) -> void {
  267. HandleDecl(context, NonClassContext);
  268. }
  269. static auto HandleDeclScopeLoop(Context& context, StateKind decl_state_kind)
  270. -> void {
  271. // This maintains the current state unless we're at the end of the scope.
  272. if (context.PositionIs(Lex::TokenKind::CloseCurlyBrace) ||
  273. context.PositionIs(Lex::TokenKind::FileEnd)) {
  274. // This is the end of the scope, so the loop state ends.
  275. context.PopAndDiscardState();
  276. return;
  277. }
  278. context.PushState(decl_state_kind);
  279. }
  280. auto HandleDeclScopeLoopAsClass(Context& context) -> void {
  281. HandleDeclScopeLoop(context, StateKind::DeclAsClass);
  282. }
  283. auto HandleDeclScopeLoopAsNonClass(Context& context) -> void {
  284. HandleDeclScopeLoop(context, StateKind::DeclAsNonClass);
  285. }
  286. } // namespace Carbon::Parse