handle_decl_scope_loop.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. #include "toolchain/parse/state.h"
  10. namespace Carbon::Parse {
  11. // Finishes an invalid declaration, skipping past its end.
  12. static auto FinishAndSkipInvalidDecl(Context& context, int32_t subtree_start)
  13. -> void {
  14. auto cursor = *context.position();
  15. // Output an invalid parse subtree including everything up to the next `;`
  16. // or end of line.
  17. context.ReplacePlaceholderNode(subtree_start, NodeKind::InvalidParseStart,
  18. cursor, /*has_error=*/true);
  19. context.AddNode(NodeKind::InvalidParseSubtree,
  20. context.SkipPastLikelyEnd(cursor), /*has_error=*/true);
  21. }
  22. // Prints a diagnostic and calls FinishAndSkipInvalidDecl.
  23. static auto HandleUnrecognizedDecl(Context& context, int32_t subtree_start)
  24. -> void {
  25. CARBON_DIAGNOSTIC(UnrecognizedDecl, Error,
  26. "unrecognized declaration introducer");
  27. context.emitter().Emit(*context.position(), UnrecognizedDecl);
  28. FinishAndSkipInvalidDecl(context, subtree_start);
  29. }
  30. // Replaces the introducer placeholder node, and pushes the introducer state for
  31. // processing.
  32. static auto ApplyIntroducer(Context& context, Context::State state,
  33. NodeKind introducer_kind, StateKind next_state_kind)
  34. -> void {
  35. context.ReplacePlaceholderNode(state.subtree_start, introducer_kind,
  36. context.Consume());
  37. // Reuse state here to retain its `subtree_start`.
  38. context.PushState(state, next_state_kind);
  39. }
  40. namespace {
  41. // The kind of context in which a declaration appears.
  42. enum DeclContextKind : int8_t {
  43. RegularContext = 0,
  44. ClassContext = 1,
  45. InterfaceContext = 2,
  46. MaxDeclContextKind = InterfaceContext,
  47. };
  48. // The kind of declaration introduced by an introducer keyword.
  49. enum class DeclIntroducerKind : int8_t {
  50. Unrecognized,
  51. PackagingDecl,
  52. NonPackagingDecl,
  53. };
  54. // Information about a keyword that might be an introducer keyword.
  55. struct DeclIntroducerInfo {
  56. DeclIntroducerKind introducer_kind;
  57. NodeKind node_kind;
  58. StateKind state_kind;
  59. };
  60. } // namespace
  61. static constexpr auto DeclIntroducers = [] {
  62. std::array<DeclIntroducerInfo, MaxDeclContextKind + 1> introducers[] = {
  63. #define CARBON_TOKEN(Name) \
  64. {{{.introducer_kind = DeclIntroducerKind::Unrecognized, \
  65. .node_kind = NodeKind::InvalidParse, \
  66. .state_kind = StateKind::Invalid}, \
  67. {.introducer_kind = DeclIntroducerKind::Unrecognized, \
  68. .node_kind = NodeKind::InvalidParse, \
  69. .state_kind = StateKind::Invalid}, \
  70. {.introducer_kind = DeclIntroducerKind::Unrecognized, \
  71. .node_kind = NodeKind::InvalidParse, \
  72. .state_kind = StateKind::Invalid}}},
  73. #include "toolchain/lex/token_kind.def"
  74. };
  75. auto set = [&](Lex::TokenKind token_kind, NodeKind node_kind,
  76. StateKind state) {
  77. for (int i = 0; i <= MaxDeclContextKind; ++i) {
  78. introducers[token_kind.AsInt()][i] = {
  79. .introducer_kind = DeclIntroducerKind::NonPackagingDecl,
  80. .node_kind = node_kind,
  81. .state_kind = state};
  82. }
  83. };
  84. auto set_contextual = [&](Lex::TokenKind token_kind,
  85. DeclContextKind context_kind, NodeKind node_kind,
  86. StateKind state) {
  87. introducers[token_kind.AsInt()][context_kind] = {
  88. .introducer_kind = DeclIntroducerKind::NonPackagingDecl,
  89. .node_kind = node_kind,
  90. .state_kind = state};
  91. };
  92. auto set_packaging = [&](Lex::TokenKind token_kind, NodeKind node_kind,
  93. StateKind state) {
  94. for (int i = 0; i <= MaxDeclContextKind; ++i) {
  95. introducers[token_kind.AsInt()][i] = {
  96. .introducer_kind = DeclIntroducerKind::PackagingDecl,
  97. .node_kind = node_kind,
  98. .state_kind = state};
  99. }
  100. };
  101. set(Lex::TokenKind::Adapt, NodeKind::AdaptIntroducer,
  102. StateKind::AdaptAfterIntroducer);
  103. set(Lex::TokenKind::Alias, NodeKind::AliasIntroducer, StateKind::Alias);
  104. set(Lex::TokenKind::Base, NodeKind::BaseIntroducer,
  105. StateKind::BaseAfterIntroducer);
  106. set(Lex::TokenKind::Choice, NodeKind::ChoiceIntroducer,
  107. StateKind::ChoiceIntroducer);
  108. set(Lex::TokenKind::Class, NodeKind::ClassIntroducer,
  109. StateKind::TypeAfterIntroducerAsClass);
  110. set(Lex::TokenKind::Constraint, NodeKind::NamedConstraintIntroducer,
  111. StateKind::TypeAfterIntroducerAsNamedConstraint);
  112. set(Lex::TokenKind::Export, NodeKind::ExportIntroducer,
  113. StateKind::ExportName);
  114. // TODO: Treat `extend` as a declaration introducer.
  115. set(Lex::TokenKind::Fn, NodeKind::FunctionIntroducer,
  116. StateKind::FunctionIntroducer);
  117. set(Lex::TokenKind::Impl, NodeKind::ImplIntroducer,
  118. StateKind::ImplAfterIntroducer);
  119. set(Lex::TokenKind::Interface, NodeKind::InterfaceIntroducer,
  120. StateKind::TypeAfterIntroducerAsInterface);
  121. set(Lex::TokenKind::Namespace, NodeKind::NamespaceStart,
  122. StateKind::Namespace);
  123. set(Lex::TokenKind::Observe, NodeKind::ObserveIntroducer,
  124. StateKind::ObserveAfterIntroducer);
  125. set(Lex::TokenKind::Require, NodeKind::RequireIntroducer,
  126. StateKind::RequireAfterIntroducer);
  127. set_contextual(Lex::TokenKind::Let, RegularContext, NodeKind::LetIntroducer,
  128. StateKind::Let);
  129. set_contextual(Lex::TokenKind::Let, ClassContext, NodeKind::LetIntroducer,
  130. StateKind::Let);
  131. set_contextual(Lex::TokenKind::Let, InterfaceContext,
  132. NodeKind::AssociatedConstantIntroducer,
  133. StateKind::AssociatedConstant);
  134. set_contextual(Lex::TokenKind::Var, RegularContext,
  135. NodeKind::VariableIntroducer, StateKind::VarAsRegular);
  136. set_contextual(Lex::TokenKind::Var, ClassContext, NodeKind::FieldIntroducer,
  137. StateKind::FieldDecl);
  138. set_packaging(Lex::TokenKind::Package, NodeKind::PackageIntroducer,
  139. StateKind::Package);
  140. set_packaging(Lex::TokenKind::Library, NodeKind::LibraryIntroducer,
  141. StateKind::Library);
  142. set_packaging(Lex::TokenKind::Import, NodeKind::ImportIntroducer,
  143. StateKind::Import);
  144. return std::to_array(introducers);
  145. }();
  146. // Attempts to handle the current token as a declaration introducer.
  147. // Returns true if the current position is a declaration. If we see a
  148. // declaration introducer keyword token, replace the placeholder node and switch
  149. // to a state to parse the rest of the declaration.
  150. static auto TryHandleAsDecl(Context& context, Context::State state,
  151. bool saw_modifier,
  152. DeclContextKind decl_context_kind) -> bool {
  153. const auto& info =
  154. DeclIntroducers[context.PositionKind().AsInt()][decl_context_kind];
  155. switch (info.introducer_kind) {
  156. case DeclIntroducerKind::Unrecognized: {
  157. // A `;` with no modifiers is an empty declaration.
  158. if (!saw_modifier) {
  159. if (auto loc = context.ConsumeIf(Lex::TokenKind::Semi)) {
  160. context.ReplacePlaceholderNode(state.subtree_start,
  161. NodeKind::EmptyDecl, *loc);
  162. return true;
  163. }
  164. }
  165. return false;
  166. }
  167. case DeclIntroducerKind::PackagingDecl: {
  168. // Packaging declarations update the packaging state themselves as needed.
  169. break;
  170. }
  171. case DeclIntroducerKind::NonPackagingDecl: {
  172. // Because a non-packaging keyword was encountered, packaging is complete.
  173. // Misplaced packaging keywords may lead to this being re-triggered.
  174. if (context.packaging_state() !=
  175. Context::PackagingState::AfterNonPackagingDecl) {
  176. if (!context.first_non_packaging_token().has_value()) {
  177. context.set_first_non_packaging_token(*context.position());
  178. }
  179. context.set_packaging_state(
  180. Context::PackagingState::AfterNonPackagingDecl);
  181. }
  182. break;
  183. }
  184. }
  185. ApplyIntroducer(context, state, info.node_kind, info.state_kind);
  186. return true;
  187. }
  188. // Returns true if position_kind could be either an introducer or modifier, and
  189. // should be treated as an introducer.
  190. static auto ResolveAmbiguousTokenAsDeclaration(Context& context,
  191. Lex::TokenKind position_kind)
  192. -> bool {
  193. switch (position_kind) {
  194. case Lex::TokenKind::Base:
  195. case Lex::TokenKind::Export:
  196. case Lex::TokenKind::Extend:
  197. case Lex::TokenKind::Impl:
  198. // This is an ambiguous token, so now we check what the next token is.
  199. // We use the macro for modifiers, including introducers which are
  200. // also modifiers (such as `base`). Other introducer tokens need to be
  201. // added by hand.
  202. switch (context.PositionKind(Lookahead::NextToken)) {
  203. case Lex::TokenKind::Adapt:
  204. case Lex::TokenKind::Alias:
  205. case Lex::TokenKind::Class:
  206. case Lex::TokenKind::Constraint:
  207. case Lex::TokenKind::Extern:
  208. case Lex::TokenKind::Fn:
  209. case Lex::TokenKind::Import:
  210. case Lex::TokenKind::Interface:
  211. case Lex::TokenKind::Let:
  212. case Lex::TokenKind::Library:
  213. case Lex::TokenKind::Namespace:
  214. case Lex::TokenKind::Require:
  215. case Lex::TokenKind::Var:
  216. #define CARBON_PARSE_NODE_KIND(Name)
  217. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name) case Lex::TokenKind::Name:
  218. #include "toolchain/parse/node_kind.def"
  219. return false;
  220. case Lex::TokenKind::Package:
  221. // `package.foo` is an expression; any other token after `package` is
  222. // a `package` introducer.
  223. return context.PositionKind(static_cast<Lookahead>(2)) ==
  224. Lex::TokenKind::Period;
  225. default:
  226. return true;
  227. }
  228. break;
  229. default:
  230. return false;
  231. }
  232. }
  233. // Returns true if the current position is a modifier, handling it if so.
  234. static auto TryHandleAsModifier(Context& context) -> bool {
  235. auto position_kind = context.PositionKind();
  236. if (ResolveAmbiguousTokenAsDeclaration(context, position_kind)) {
  237. return false;
  238. }
  239. switch (position_kind) {
  240. #define CARBON_PARSE_NODE_KIND(Name)
  241. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name) \
  242. case Lex::TokenKind::Name: \
  243. context.AddLeafNode(NodeKind::Name##Modifier, context.Consume()); \
  244. return true;
  245. #include "toolchain/parse/node_kind.def"
  246. case Lex::TokenKind::Extern: {
  247. auto extern_token = context.Consume();
  248. if (context.PositionIs(Lex::TokenKind::Library)) {
  249. // `extern library <owning_library>` syntax.
  250. context.ParseLibrarySpecifier(/*accept_default=*/true);
  251. // TODO: Consider error recovery when a non-declaration token is next,
  252. // like a typo of the library name.
  253. context.AddNode(NodeKind::ExternModifierWithLibrary, extern_token,
  254. /*has_error=*/false);
  255. } else {
  256. // `extern` syntax without a library.
  257. context.AddLeafNode(NodeKind::ExternModifier, extern_token);
  258. }
  259. return true;
  260. }
  261. default:
  262. return false;
  263. }
  264. }
  265. static auto HandleDecl(Context& context, DeclContextKind decl_context_kind)
  266. -> void {
  267. auto state = context.PopState();
  268. // Add a placeholder node, to be replaced by the declaration introducer once
  269. // it is found.
  270. context.AddLeafNode(NodeKind::Placeholder, *context.position());
  271. bool saw_modifier = false;
  272. while (TryHandleAsModifier(context)) {
  273. saw_modifier = true;
  274. }
  275. if (!TryHandleAsDecl(context, state, saw_modifier, decl_context_kind)) {
  276. HandleUnrecognizedDecl(context, state.subtree_start);
  277. }
  278. }
  279. auto HandleDeclAsClass(Context& context) -> void {
  280. HandleDecl(context, ClassContext);
  281. }
  282. auto HandleDeclAsInterface(Context& context) -> void {
  283. HandleDecl(context, InterfaceContext);
  284. }
  285. auto HandleDeclAsRegular(Context& context) -> void {
  286. HandleDecl(context, RegularContext);
  287. }
  288. static auto HandleDeclScopeLoop(Context& context, StateKind decl_state_kind)
  289. -> void {
  290. // This maintains the current state unless we're at the end of the scope.
  291. if (context.PositionIs(Lex::TokenKind::CloseCurlyBrace) ||
  292. context.PositionIs(Lex::TokenKind::FileEnd)) {
  293. // This is the end of the scope, so the loop state ends.
  294. context.PopAndDiscardState();
  295. return;
  296. }
  297. context.PushState(decl_state_kind);
  298. }
  299. auto HandleDeclScopeLoopAsClass(Context& context) -> void {
  300. HandleDeclScopeLoop(context, StateKind::DeclAsClass);
  301. }
  302. auto HandleDeclScopeLoopAsInterface(Context& context) -> void {
  303. HandleDeclScopeLoop(context, StateKind::DeclAsInterface);
  304. }
  305. auto HandleDeclScopeLoopAsRegular(Context& context) -> void {
  306. HandleDeclScopeLoop(context, StateKind::DeclAsRegular);
  307. }
  308. } // namespace Carbon::Parse