handle_decl_scope_loop.cpp 10.0 KB

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