handle_decl_scope_loop.cpp 10 KB

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