handle_impl.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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/check/context.h"
  5. #include "toolchain/check/convert.h"
  6. #include "toolchain/check/decl_name_stack.h"
  7. #include "toolchain/check/generic.h"
  8. #include "toolchain/check/handle.h"
  9. #include "toolchain/check/impl.h"
  10. #include "toolchain/check/merge.h"
  11. #include "toolchain/check/modifiers.h"
  12. #include "toolchain/parse/typed_nodes.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::Check {
  16. auto HandleParseNode(Context& context, Parse::ImplIntroducerId node_id)
  17. -> bool {
  18. // Create an instruction block to hold the instructions created for the type
  19. // and interface.
  20. context.inst_block_stack().Push();
  21. // Push the bracketing node.
  22. context.node_stack().Push(node_id);
  23. // Optional modifiers follow.
  24. context.decl_introducer_state_stack().Push<Lex::TokenKind::Impl>();
  25. // An impl doesn't have a name per se, but it makes the processing more
  26. // consistent to imagine that it does. This also gives us a scope for implicit
  27. // parameters.
  28. context.decl_name_stack().PushScopeAndStartName();
  29. // This might be a generic impl.
  30. StartGenericDecl(context);
  31. // Push a pattern block for the signature of the `forall` (if any).
  32. // TODO: Instead use a separate parse node kinds for `impl` and `impl forall`,
  33. // and only push a pattern block in `forall` case.
  34. context.pattern_block_stack().Push();
  35. return true;
  36. }
  37. auto HandleParseNode(Context& context, Parse::ImplForallId node_id) -> bool {
  38. auto params_id =
  39. context.node_stack().Pop<Parse::NodeKind::ImplicitParamList>();
  40. context.node_stack()
  41. .PopAndDiscardSoloNodeId<Parse::NodeKind::ImplicitParamListStart>();
  42. RequireGenericParams(context, params_id);
  43. context.node_stack().Push(node_id, params_id);
  44. return true;
  45. }
  46. auto HandleParseNode(Context& context, Parse::TypeImplAsId node_id) -> bool {
  47. auto [self_node, self_id] = context.node_stack().PopExprWithNodeId();
  48. auto self_type_id = ExprAsType(context, self_node, self_id);
  49. context.node_stack().Push(node_id, self_type_id);
  50. // Introduce `Self`. Note that we add this name lexically rather than adding
  51. // to the `NameScopeId` of the `impl`, because this happens before we enter
  52. // the `impl` scope or even identify which `impl` we're declaring.
  53. // TODO: Revisit this once #3714 is resolved.
  54. context.AddNameToLookup(SemIR::NameId::SelfType,
  55. context.types().GetInstId(self_type_id));
  56. return true;
  57. }
  58. // If the specified name scope corresponds to a class, returns the corresponding
  59. // class declaration.
  60. // TODO: Should this be somewhere more central?
  61. static auto TryAsClassScope(Context& context, SemIR::NameScopeId scope_id)
  62. -> std::optional<SemIR::ClassDecl> {
  63. if (!scope_id.is_valid()) {
  64. return std::nullopt;
  65. }
  66. auto& scope = context.name_scopes().Get(scope_id);
  67. if (!scope.inst_id.is_valid()) {
  68. return std::nullopt;
  69. }
  70. return context.insts().TryGetAs<SemIR::ClassDecl>(scope.inst_id);
  71. }
  72. static auto GetDefaultSelfType(Context& context) -> SemIR::TypeId {
  73. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  74. if (auto class_decl = TryAsClassScope(context, parent_scope_id)) {
  75. return context.classes().Get(class_decl->class_id).self_type_id;
  76. }
  77. // TODO: This is also valid in a mixin.
  78. return SemIR::TypeId::Invalid;
  79. }
  80. auto HandleParseNode(Context& context, Parse::DefaultSelfImplAsId node_id)
  81. -> bool {
  82. auto self_type_id = GetDefaultSelfType(context);
  83. if (!self_type_id.is_valid()) {
  84. CARBON_DIAGNOSTIC(ImplAsOutsideClass, Error,
  85. "`impl as` can only be used in a class");
  86. context.emitter().Emit(node_id, ImplAsOutsideClass);
  87. self_type_id = SemIR::TypeId::Error;
  88. }
  89. // There's no need to push `Self` into scope here, because we can find it in
  90. // the parent class scope.
  91. context.node_stack().Push(node_id, self_type_id);
  92. return true;
  93. }
  94. // Process an `extend impl` declaration by extending the impl scope with the
  95. // `impl`'s scope.
  96. static auto ExtendImpl(Context& context, Parse::NodeId extend_node,
  97. Parse::AnyImplDeclId node_id,
  98. Parse::NodeId self_type_node, SemIR::TypeId self_type_id,
  99. Parse::NodeId params_node, SemIR::TypeId constraint_id)
  100. -> void {
  101. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  102. auto& parent_scope = context.name_scopes().Get(parent_scope_id);
  103. // TODO: This is also valid in a mixin.
  104. if (!TryAsClassScope(context, parent_scope_id)) {
  105. CARBON_DIAGNOSTIC(ExtendImplOutsideClass, Error,
  106. "`extend impl` can only be used in a class");
  107. context.emitter().Emit(node_id, ExtendImplOutsideClass);
  108. return;
  109. }
  110. if (params_node.is_valid()) {
  111. CARBON_DIAGNOSTIC(ExtendImplForall, Error,
  112. "cannot `extend` a parameterized `impl`");
  113. context.emitter().Emit(extend_node, ExtendImplForall);
  114. parent_scope.has_error = true;
  115. return;
  116. }
  117. if (context.parse_tree().node_kind(self_type_node) ==
  118. Parse::NodeKind::TypeImplAs) {
  119. CARBON_DIAGNOSTIC(ExtendImplSelfAs, Error,
  120. "cannot `extend` an `impl` with an explicit self type");
  121. auto diag = context.emitter().Build(extend_node, ExtendImplSelfAs);
  122. // If the explicit self type is not the default, just bail out.
  123. if (self_type_id != GetDefaultSelfType(context)) {
  124. diag.Emit();
  125. parent_scope.has_error = true;
  126. return;
  127. }
  128. // The explicit self type is the same as the default self type, so suggest
  129. // removing it and recover as if it were not present.
  130. if (auto self_as =
  131. context.parse_tree_and_subtrees().ExtractAs<Parse::TypeImplAs>(
  132. self_type_node)) {
  133. CARBON_DIAGNOSTIC(ExtendImplSelfAsDefault, Note,
  134. "remove the explicit `Self` type here");
  135. diag.Note(self_as->type_expr, ExtendImplSelfAsDefault);
  136. }
  137. diag.Emit();
  138. }
  139. auto interface_type =
  140. context.types().TryGetAs<SemIR::InterfaceType>(constraint_id);
  141. if (!interface_type) {
  142. context.TODO(node_id, "extending non-interface constraint");
  143. parent_scope.has_error = true;
  144. return;
  145. }
  146. auto& interface = context.interfaces().Get(interface_type->interface_id);
  147. if (!interface.is_defined()) {
  148. CARBON_DIAGNOSTIC(ExtendUndefinedInterface, Error,
  149. "`extend impl` requires a definition for interface `{0}`",
  150. SemIR::TypeId);
  151. auto diag = context.emitter().Build(node_id, ExtendUndefinedInterface,
  152. constraint_id);
  153. context.NoteUndefinedInterface(interface_type->interface_id, diag);
  154. diag.Emit();
  155. parent_scope.has_error = true;
  156. return;
  157. }
  158. parent_scope.extended_scopes.push_back(interface.scope_id);
  159. }
  160. // Pops the parameters of an `impl`, forming a `NameComponent` with no
  161. // associated name that describes them.
  162. static auto PopImplIntroducerAndParamsAsNameComponent(
  163. Context& context, Parse::AnyImplDeclId end_of_decl_node_id)
  164. -> NameComponent {
  165. auto [implicit_params_loc_id, implicit_params_id] =
  166. context.node_stack().PopWithNodeIdIf<Parse::NodeKind::ImplForall>();
  167. Parse::NodeId first_param_node_id =
  168. context.node_stack().PopForSoloNodeId<Parse::NodeKind::ImplIntroducer>();
  169. Parse::NodeId last_param_node_id = end_of_decl_node_id;
  170. return {
  171. .name_loc_id = Parse::NodeId::Invalid,
  172. .name_id = SemIR::NameId::Invalid,
  173. .first_param_node_id = first_param_node_id,
  174. .last_param_node_id = last_param_node_id,
  175. .implicit_params_loc_id = implicit_params_loc_id,
  176. .implicit_params_id =
  177. implicit_params_id.value_or(SemIR::InstBlockId::Invalid),
  178. .params_loc_id = Parse::NodeId::Invalid,
  179. .params_id = SemIR::InstBlockId::Invalid,
  180. .pattern_block_id = context.pattern_block_stack().Pop(),
  181. };
  182. }
  183. static auto MergeImplRedecl(Context& context, SemIR::Impl& new_impl,
  184. SemIR::ImplId prev_impl_id) -> bool {
  185. auto& prev_impl = context.impls().Get(prev_impl_id);
  186. // TODO: Following #3763, disallow redeclarations in different scopes.
  187. // If the parameters aren't the same, then this is not a redeclaration of this
  188. // `impl`. Keep looking for a prior declaration without issuing a diagnostic.
  189. if (!CheckRedeclParamsMatch(context, DeclParams(new_impl),
  190. DeclParams(prev_impl), SemIR::SpecificId::Invalid,
  191. /*check_syntax=*/true, /*diagnose=*/false)) {
  192. // NOLINTNEXTLINE(readability-simplify-boolean-expr)
  193. return false;
  194. }
  195. // TODO: CheckIsAllowedRedecl. We don't have a suitable NameId; decide if we
  196. // need to treat the `T as I` as a kind of name.
  197. // TODO: Merge information from the new declaration into the old one as
  198. // needed.
  199. return true;
  200. }
  201. // Build an ImplDecl describing the signature of an impl. This handles the
  202. // common logic shared by impl forward declarations and impl definitions.
  203. static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId node_id,
  204. bool is_definition)
  205. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  206. auto [constraint_node, constraint_id] =
  207. context.node_stack().PopExprWithNodeId();
  208. auto [self_type_node, self_type_id] =
  209. context.node_stack().PopWithNodeId<Parse::NodeCategory::ImplAs>();
  210. // Pop the `impl` introducer and any `forall` parameters as a "name".
  211. auto name = PopImplIntroducerAndParamsAsNameComponent(context, node_id);
  212. auto decl_block_id = context.inst_block_stack().Pop();
  213. // Convert the constraint expression to a type.
  214. // TODO: Check that its constant value is a constraint.
  215. auto constraint_type_id = ExprAsType(context, constraint_node, constraint_id);
  216. // Process modifiers.
  217. // TODO: Should we somehow permit access specifiers on `impl`s?
  218. // TODO: Handle `final` modifier.
  219. auto introducer =
  220. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Impl>();
  221. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::ImplDecl);
  222. // Finish processing the name, which should be empty, but might have
  223. // parameters.
  224. auto name_context = context.decl_name_stack().FinishImplName();
  225. CARBON_CHECK(name_context.state == DeclNameStack::NameContext::State::Empty);
  226. // TODO: Check for an orphan `impl`.
  227. // Add the impl declaration.
  228. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::Invalid,
  229. .decl_block_id = decl_block_id};
  230. auto impl_decl_id =
  231. context.AddPlaceholderInst(SemIR::LocIdAndInst(node_id, impl_decl));
  232. SemIR::Impl impl_info = {
  233. name_context.MakeEntityWithParamsBase(name, impl_decl_id,
  234. /*is_extern=*/false,
  235. SemIR::LibraryNameId::Invalid),
  236. {.self_id = self_type_id, .constraint_id = constraint_type_id}};
  237. // Add the impl declaration.
  238. auto& lookup_bucket = context.impls().GetOrAddLookupBucket(
  239. impl_info.self_id, impl_info.constraint_id);
  240. for (auto prev_impl_id : lookup_bucket) {
  241. if (MergeImplRedecl(context, impl_info, prev_impl_id)) {
  242. impl_decl.impl_id = prev_impl_id;
  243. break;
  244. }
  245. }
  246. // Create a new impl if this isn't a valid redeclaration.
  247. if (!impl_decl.impl_id.is_valid()) {
  248. impl_info.generic_id = FinishGenericDecl(context, impl_decl_id);
  249. impl_decl.impl_id = context.impls().Add(impl_info);
  250. lookup_bucket.push_back(impl_decl.impl_id);
  251. } else {
  252. FinishGenericRedecl(context, impl_decl_id,
  253. context.impls().Get(impl_decl.impl_id).generic_id);
  254. }
  255. // Write the impl ID into the ImplDecl.
  256. context.ReplaceInstBeforeConstantUse(impl_decl_id, impl_decl);
  257. // For an `extend impl` declaration, mark the impl as extending this `impl`.
  258. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  259. auto extend_node = introducer.modifier_node_id(ModifierOrder::Decl);
  260. ExtendImpl(context, extend_node, node_id, self_type_node, self_type_id,
  261. name.implicit_params_loc_id, constraint_type_id);
  262. }
  263. if (!is_definition && context.IsImplFile()) {
  264. context.definitions_required().push_back(impl_decl_id);
  265. }
  266. return {impl_decl.impl_id, impl_decl_id};
  267. }
  268. auto HandleParseNode(Context& context, Parse::ImplDeclId node_id) -> bool {
  269. BuildImplDecl(context, node_id, /*is_definition=*/false);
  270. context.decl_name_stack().PopScope();
  271. return true;
  272. }
  273. auto HandleParseNode(Context& context, Parse::ImplDefinitionStartId node_id)
  274. -> bool {
  275. auto [impl_id, impl_decl_id] =
  276. BuildImplDecl(context, node_id, /*is_definition=*/true);
  277. auto& impl_info = context.impls().Get(impl_id);
  278. if (impl_info.is_defined()) {
  279. CARBON_DIAGNOSTIC(ImplRedefinition, Error,
  280. "redefinition of `impl {0} as {1}`", SemIR::TypeId,
  281. SemIR::TypeId);
  282. CARBON_DIAGNOSTIC(ImplPreviousDefinition, Note,
  283. "previous definition was here");
  284. context.emitter()
  285. .Build(node_id, ImplRedefinition, impl_info.self_id,
  286. impl_info.constraint_id)
  287. .Note(impl_info.definition_id, ImplPreviousDefinition)
  288. .Emit();
  289. } else {
  290. impl_info.definition_id = impl_decl_id;
  291. impl_info.scope_id = context.name_scopes().Add(
  292. impl_decl_id, SemIR::NameId::Invalid,
  293. context.decl_name_stack().PeekParentScopeId());
  294. }
  295. context.scope_stack().Push(impl_decl_id, impl_info.scope_id);
  296. context.inst_block_stack().Push();
  297. context.node_stack().Push(node_id, impl_id);
  298. // TODO: Handle the case where there's control flow in the impl body. For
  299. // example:
  300. //
  301. // impl C as I {
  302. // fn F() -> if true then i32 else f64;
  303. // }
  304. //
  305. // We may need to track a list of instruction blocks here, as we do for a
  306. // function.
  307. impl_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  308. return true;
  309. }
  310. auto HandleParseNode(Context& context, Parse::ImplDefinitionId /*node_id*/)
  311. -> bool {
  312. auto impl_id =
  313. context.node_stack().Pop<Parse::NodeKind::ImplDefinitionStart>();
  314. if (!context.impls().Get(impl_id).is_defined()) {
  315. context.impls().Get(impl_id).witness_id =
  316. BuildImplWitness(context, impl_id);
  317. }
  318. context.inst_block_stack().Pop();
  319. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  320. return true;
  321. }
  322. } // namespace Carbon::Check