impl.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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/impl.h"
  5. #include "toolchain/base/kind_switch.h"
  6. #include "toolchain/check/context.h"
  7. #include "toolchain/check/deduce.h"
  8. #include "toolchain/check/eval.h"
  9. #include "toolchain/check/facet_type.h"
  10. #include "toolchain/check/function.h"
  11. #include "toolchain/check/generic.h"
  12. #include "toolchain/check/import_ref.h"
  13. #include "toolchain/check/inst.h"
  14. #include "toolchain/check/interface.h"
  15. #include "toolchain/check/merge.h"
  16. #include "toolchain/check/name_lookup.h"
  17. #include "toolchain/check/name_scope.h"
  18. #include "toolchain/check/thunk.h"
  19. #include "toolchain/check/type.h"
  20. #include "toolchain/check/type_completion.h"
  21. #include "toolchain/check/type_structure.h"
  22. #include "toolchain/diagnostics/diagnostic_emitter.h"
  23. #include "toolchain/sem_ir/generic.h"
  24. #include "toolchain/sem_ir/ids.h"
  25. #include "toolchain/sem_ir/impl.h"
  26. #include "toolchain/sem_ir/inst.h"
  27. #include "toolchain/sem_ir/typed_insts.h"
  28. namespace Carbon::Check {
  29. // Adds the location of the associated function to a diagnostic.
  30. static auto NoteAssociatedFunction(Context& context, DiagnosticBuilder& builder,
  31. SemIR::FunctionId function_id) -> void {
  32. CARBON_DIAGNOSTIC(AssociatedFunctionHere, Note,
  33. "associated function {0} declared here", SemIR::NameId);
  34. const auto& function = context.functions().Get(function_id);
  35. builder.Note(function.latest_decl_id(), AssociatedFunctionHere,
  36. function.name_id);
  37. }
  38. auto CheckAssociatedFunctionImplementation(
  39. Context& context, SemIR::FunctionType interface_function_type,
  40. SemIR::InstId impl_decl_id, SemIR::TypeId self_type_id,
  41. SemIR::InstId witness_inst_id, bool defer_thunk_definition)
  42. -> SemIR::InstId {
  43. auto impl_function_decl =
  44. context.insts().TryGetAs<SemIR::FunctionDecl>(impl_decl_id);
  45. if (!impl_function_decl) {
  46. if (impl_decl_id != SemIR::ErrorInst::InstId) {
  47. CARBON_DIAGNOSTIC(ImplFunctionWithNonFunction, Error,
  48. "associated function {0} implemented by non-function",
  49. SemIR::NameId);
  50. auto builder = context.emitter().Build(
  51. impl_decl_id, ImplFunctionWithNonFunction,
  52. context.functions().Get(interface_function_type.function_id).name_id);
  53. NoteAssociatedFunction(context, builder,
  54. interface_function_type.function_id);
  55. builder.Emit();
  56. }
  57. return SemIR::ErrorInst::InstId;
  58. }
  59. auto impl_enclosing_specific_id =
  60. context.types()
  61. .GetAs<SemIR::FunctionType>(impl_function_decl->type_id)
  62. .specific_id;
  63. // Map from the specific for the function type to the specific for the
  64. // function signature. The function signature may have additional generic
  65. // parameters.
  66. auto interface_function_specific_id =
  67. GetSelfSpecificForInterfaceMemberWithSelfType(
  68. context, SemIR::LocId(impl_decl_id),
  69. interface_function_type.specific_id,
  70. context.functions()
  71. .Get(interface_function_type.function_id)
  72. .generic_id,
  73. impl_enclosing_specific_id, self_type_id, witness_inst_id);
  74. return BuildThunk(context, interface_function_type.function_id,
  75. interface_function_specific_id, impl_decl_id,
  76. defer_thunk_definition);
  77. }
  78. // Builds an initial witness from the rewrites in the facet type, if any.
  79. auto ImplWitnessForDeclaration(Context& context, const SemIR::Impl& impl,
  80. bool has_definition) -> SemIR::InstId {
  81. CARBON_CHECK(!impl.has_definition_started());
  82. auto self_type_id = context.types().GetTypeIdForTypeInstId(impl.self_id);
  83. if (self_type_id == SemIR::ErrorInst::TypeId) {
  84. // When 'impl as' is invalid, the self type is an error.
  85. return SemIR::ErrorInst::InstId;
  86. }
  87. return InitialFacetTypeImplWitness(
  88. context, SemIR::LocId(impl.latest_decl_id()), impl.constraint_id,
  89. impl.self_id, impl.interface,
  90. context.generics().GetSelfSpecific(impl.generic_id), has_definition);
  91. }
  92. auto ImplWitnessStartDefinition(Context& context, SemIR::Impl& impl) -> void {
  93. CARBON_CHECK(impl.is_being_defined());
  94. CARBON_CHECK(impl.witness_id.has_value());
  95. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  96. return;
  97. }
  98. auto witness = context.insts().GetAs<SemIR::ImplWitness>(impl.witness_id);
  99. auto witness_table =
  100. context.insts().GetAs<SemIR::ImplWitnessTable>(witness.witness_table_id);
  101. auto witness_block =
  102. context.inst_blocks().GetMutable(witness_table.elements_id);
  103. // `witness_table.elements_id` will be `SemIR::InstBlockId::Empty` when the
  104. // definition is the first declaration and the interface has no members. The
  105. // other case where `witness_block` will be empty is when we are using a
  106. // placeholder witness. This happens when there is a forward declaration of
  107. // the impl and the facet type has no rewrite constraints and so it wasn't
  108. // required to be complete.
  109. if (witness_table.elements_id != SemIR::InstBlockId::Empty &&
  110. witness_block.empty()) {
  111. if (!RequireCompleteFacetTypeForImplDefinition(
  112. context, SemIR::LocId(impl.latest_decl_id()), impl.constraint_id)) {
  113. FillImplWitnessWithErrors(context, impl);
  114. return;
  115. }
  116. AllocateFacetTypeImplWitness(context, impl.interface.interface_id,
  117. witness_table.elements_id);
  118. witness_block = context.inst_blocks().GetMutable(witness_table.elements_id);
  119. }
  120. const auto& interface = context.interfaces().Get(impl.interface.interface_id);
  121. auto assoc_entities =
  122. context.inst_blocks().Get(interface.associated_entities_id);
  123. CARBON_CHECK(witness_block.size() == assoc_entities.size());
  124. // Check we have a value for all non-function associated constants in the
  125. // witness.
  126. for (auto [assoc_entity, witness_value] :
  127. llvm::zip_equal(assoc_entities, witness_block)) {
  128. auto decl_id = context.constant_values().GetConstantInstId(assoc_entity);
  129. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  130. if (auto decl =
  131. context.insts().TryGetAs<SemIR::AssociatedConstantDecl>(decl_id)) {
  132. if (witness_value == SemIR::InstId::ImplWitnessTablePlaceholder) {
  133. CARBON_DIAGNOSTIC(ImplAssociatedConstantNeedsValue, Error,
  134. "associated constant {0} not given a value in impl "
  135. "of interface {1}",
  136. SemIR::NameId, SemIR::NameId);
  137. CARBON_DIAGNOSTIC(AssociatedConstantHere, Note,
  138. "associated constant declared here");
  139. context.emitter()
  140. .Build(impl.definition_id, ImplAssociatedConstantNeedsValue,
  141. context.associated_constants()
  142. .Get(decl->assoc_const_id)
  143. .name_id,
  144. interface.name_id)
  145. .Note(assoc_entity, AssociatedConstantHere)
  146. .Emit();
  147. witness_value = SemIR::ErrorInst::InstId;
  148. }
  149. }
  150. }
  151. }
  152. // Adds functions to the witness that the specified impl implements the given
  153. // interface.
  154. auto FinishImplWitness(Context& context, SemIR::ImplId impl_id) -> void {
  155. const auto& impl = context.impls().Get(impl_id);
  156. CARBON_CHECK(impl.is_being_defined());
  157. CARBON_CHECK(impl.witness_id.has_value());
  158. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  159. return;
  160. }
  161. auto witness = context.insts().GetAs<SemIR::ImplWitness>(impl.witness_id);
  162. auto witness_table =
  163. context.insts().GetAs<SemIR::ImplWitnessTable>(witness.witness_table_id);
  164. auto witness_block =
  165. context.inst_blocks().GetMutable(witness_table.elements_id);
  166. auto& impl_scope = context.name_scopes().Get(impl.scope_id);
  167. auto self_type_id = context.types().GetTypeIdForTypeInstId(impl.self_id);
  168. const auto& interface = context.interfaces().Get(impl.interface.interface_id);
  169. auto assoc_entities =
  170. context.inst_blocks().Get(interface.associated_entities_id);
  171. llvm::SmallVector<SemIR::InstId> used_decl_ids;
  172. for (auto [assoc_entity, witness_value] :
  173. llvm::zip_equal(assoc_entities, witness_block)) {
  174. auto decl_id =
  175. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  176. context.sem_ir(), impl.interface.specific_id, assoc_entity));
  177. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  178. auto decl = context.insts().Get(decl_id);
  179. CARBON_KIND_SWITCH(decl) {
  180. case CARBON_KIND(SemIR::StructValue struct_value): {
  181. if (struct_value.type_id == SemIR::ErrorInst::TypeId) {
  182. witness_value = SemIR::ErrorInst::InstId;
  183. break;
  184. }
  185. auto type_inst = context.types().GetAsInst(struct_value.type_id);
  186. auto fn_type = type_inst.TryAs<SemIR::FunctionType>();
  187. if (!fn_type) {
  188. CARBON_FATAL("Unexpected type: {0}", type_inst);
  189. }
  190. auto& fn = context.functions().Get(fn_type->function_id);
  191. auto lookup_result =
  192. LookupNameInExactScope(context, SemIR::LocId(decl_id), fn.name_id,
  193. impl.scope_id, impl_scope);
  194. if (lookup_result.is_found()) {
  195. used_decl_ids.push_back(lookup_result.target_inst_id());
  196. witness_value = CheckAssociatedFunctionImplementation(
  197. context, *fn_type, lookup_result.target_inst_id(), self_type_id,
  198. impl.witness_id, /*defer_thunk_definition=*/true);
  199. } else {
  200. CARBON_DIAGNOSTIC(
  201. ImplMissingFunction, Error,
  202. "missing implementation of {0} in impl of interface {1}",
  203. SemIR::NameId, SemIR::NameId);
  204. auto builder =
  205. context.emitter().Build(impl.definition_id, ImplMissingFunction,
  206. fn.name_id, interface.name_id);
  207. NoteAssociatedFunction(context, builder, fn_type->function_id);
  208. builder.Emit();
  209. witness_value = SemIR::ErrorInst::InstId;
  210. }
  211. break;
  212. }
  213. case SemIR::AssociatedConstantDecl::Kind: {
  214. // These are set to their final values already.
  215. break;
  216. }
  217. default:
  218. CARBON_CHECK(decl_id == SemIR::ErrorInst::InstId,
  219. "Unexpected kind of associated entity {0}", decl);
  220. witness_value = SemIR::ErrorInst::InstId;
  221. break;
  222. }
  223. }
  224. // TODO: Diagnose if any declarations in the impl are not in used_decl_ids.
  225. }
  226. auto FillImplWitnessWithErrors(Context& context, SemIR::Impl& impl) -> void {
  227. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  228. return;
  229. }
  230. auto witness = context.insts().GetAs<SemIR::ImplWitness>(impl.witness_id);
  231. auto witness_table =
  232. context.insts().GetAs<SemIR::ImplWitnessTable>(witness.witness_table_id);
  233. auto witness_block =
  234. context.inst_blocks().GetMutable(witness_table.elements_id);
  235. for (auto& elem : witness_block) {
  236. if (elem == SemIR::InstId::ImplWitnessTablePlaceholder) {
  237. elem = SemIR::ErrorInst::InstId;
  238. }
  239. }
  240. impl.witness_id = SemIR::ErrorInst::InstId;
  241. }
  242. auto AssignImplIdInWitness(Context& context, SemIR::ImplId impl_id,
  243. SemIR::InstId witness_id) -> void {
  244. if (witness_id == SemIR::ErrorInst::InstId) {
  245. return;
  246. }
  247. auto witness = context.insts().GetAs<SemIR::ImplWitness>(witness_id);
  248. auto witness_table =
  249. context.insts().GetAs<SemIR::ImplWitnessTable>(witness.witness_table_id);
  250. witness_table.impl_id = impl_id;
  251. // Note: The `ImplWitnessTable` instruction is `Unique`, so while this marks
  252. // the instruction as being a dependent instruction of a generic impl, it will
  253. // not be substituted into the eval block.
  254. ReplaceInstBeforeConstantUse(context, witness.witness_table_id,
  255. witness_table);
  256. }
  257. auto IsImplEffectivelyFinal(Context& context, const SemIR::Impl& impl) -> bool {
  258. return impl.is_final ||
  259. (context.constant_values().Get(impl.self_id).is_concrete() &&
  260. context.constant_values().Get(impl.constraint_id).is_concrete());
  261. }
  262. auto CheckConstraintIsInterface(Context& context, SemIR::InstId impl_decl_id,
  263. SemIR::TypeInstId constraint_id)
  264. -> SemIR::SpecificInterface {
  265. auto facet_type_id = context.types().GetTypeIdForTypeInstId(constraint_id);
  266. if (facet_type_id == SemIR::ErrorInst::TypeId) {
  267. return SemIR::SpecificInterface::None;
  268. }
  269. auto facet_type = context.types().TryGetAs<SemIR::FacetType>(facet_type_id);
  270. if (!facet_type) {
  271. CARBON_DIAGNOSTIC(ImplAsNonFacetType, Error, "impl as non-facet type {0}",
  272. InstIdAsType);
  273. context.emitter().Emit(impl_decl_id, ImplAsNonFacetType, constraint_id);
  274. return SemIR::SpecificInterface::None;
  275. }
  276. auto identified_id = RequireIdentifiedFacetType(
  277. context, SemIR::LocId(constraint_id), *facet_type, [&] {
  278. CARBON_DIAGNOSTIC(ImplOfUnidentifiedFacetType, Error,
  279. "facet type {0} cannot be identified in `impl as`",
  280. InstIdAsType);
  281. return context.emitter().Build(
  282. impl_decl_id, ImplOfUnidentifiedFacetType, constraint_id);
  283. });
  284. if (!identified_id.has_value()) {
  285. return SemIR::SpecificInterface::None;
  286. }
  287. const auto& identified = context.identified_facet_types().Get(identified_id);
  288. if (!identified.is_valid_impl_as_target()) {
  289. CARBON_DIAGNOSTIC(ImplOfNotOneInterface, Error,
  290. "impl as {0} interfaces, expected 1", int);
  291. context.emitter().Emit(impl_decl_id, ImplOfNotOneInterface,
  292. identified.num_interfaces_to_impl());
  293. return SemIR::SpecificInterface::None;
  294. }
  295. return identified.impl_as_target_interface();
  296. }
  297. // Returns true if impl redeclaration parameters match.
  298. static auto CheckImplRedeclParamsMatch(Context& context, SemIR::Impl& new_impl,
  299. SemIR::ImplId prev_impl_id) -> bool {
  300. auto& prev_impl = context.impls().Get(prev_impl_id);
  301. // If the parameters aren't the same, then this is not a redeclaration of this
  302. // `impl`. Keep looking for a prior declaration without issuing a diagnostic.
  303. if (!CheckRedeclParamsMatch(context, DeclParams(new_impl),
  304. DeclParams(prev_impl), SemIR::SpecificId::None,
  305. /*diagnose=*/false, /*check_syntax=*/true,
  306. /*check_self=*/true)) {
  307. // NOLINTNEXTLINE(readability-simplify-boolean-expr)
  308. return false;
  309. }
  310. return true;
  311. }
  312. // Returns whether an impl can be redeclared. For example, defined impls
  313. // cannot be redeclared.
  314. static auto IsValidImplRedecl(Context& context, SemIR::Impl& new_impl,
  315. SemIR::ImplId prev_impl_id) -> bool {
  316. auto& prev_impl = context.impls().Get(prev_impl_id);
  317. // TODO: Following #3763, disallow redeclarations in different scopes.
  318. // Following #4672, disallowing defining non-extern declarations in another
  319. // file.
  320. if (auto import_ref =
  321. context.insts().TryGetAs<SemIR::AnyImportRef>(prev_impl.self_id)) {
  322. // TODO: Handle extern.
  323. CARBON_DIAGNOSTIC(RedeclImportedImpl, Error,
  324. "redeclaration of imported impl");
  325. // TODO: Note imported declaration
  326. context.emitter().Emit(new_impl.latest_decl_id(), RedeclImportedImpl);
  327. return false;
  328. }
  329. if (prev_impl.has_definition_started()) {
  330. // Impls aren't merged in order to avoid generic region lookup into a
  331. // mismatching table.
  332. CARBON_DIAGNOSTIC(ImplRedefinition, Error,
  333. "redefinition of `impl {0} as {1}`", InstIdAsRawType,
  334. InstIdAsRawType);
  335. CARBON_DIAGNOSTIC(ImplPreviousDefinition, Note,
  336. "previous definition was here");
  337. context.emitter()
  338. .Build(new_impl.latest_decl_id(), ImplRedefinition, new_impl.self_id,
  339. new_impl.constraint_id)
  340. .Note(prev_impl.definition_id, ImplPreviousDefinition)
  341. .Emit();
  342. return false;
  343. }
  344. // TODO: Only allow redeclaration in a match_first/impl_priority block.
  345. return true;
  346. }
  347. // Apply an `extend impl` declaration by extending the parent scope with the
  348. // `impl`. If there's an error it is diagnosed and false is returned.
  349. static auto ApplyExtendImplAs(Context& context, SemIR::LocId loc_id,
  350. const SemIR::Impl& impl,
  351. Parse::NodeId extend_node,
  352. SemIR::LocId implicit_params_loc_id) -> bool {
  353. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  354. // TODO: Also handle the parent scope being a mixin or an interface.
  355. auto class_scope = TryAsClassScope(context, parent_scope_id);
  356. if (!class_scope) {
  357. if (impl.witness_id != SemIR::ErrorInst::InstId) {
  358. CARBON_DIAGNOSTIC(
  359. ExtendImplOutsideClass, Error,
  360. "`extend impl` can only be used in an interface or class");
  361. context.emitter().Emit(loc_id, ExtendImplOutsideClass);
  362. }
  363. return false;
  364. }
  365. auto& parent_scope = *class_scope->name_scope;
  366. // An error was already diagnosed, but this is `extend impl as` inside a
  367. // class, so propagate the error into the enclosing class scope.
  368. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  369. parent_scope.set_has_error();
  370. return false;
  371. }
  372. if (implicit_params_loc_id.has_value()) {
  373. CARBON_DIAGNOSTIC(ExtendImplForall, Error,
  374. "cannot `extend` a parameterized `impl`");
  375. context.emitter().Emit(extend_node, ExtendImplForall);
  376. parent_scope.set_has_error();
  377. return false;
  378. }
  379. if (!RequireCompleteType(
  380. context, context.types().GetTypeIdForTypeInstId(impl.constraint_id),
  381. SemIR::LocId(impl.constraint_id), [&] {
  382. CARBON_DIAGNOSTIC(ExtendImplAsIncomplete, Error,
  383. "`extend impl as` incomplete facet type {0}",
  384. InstIdAsType);
  385. return context.emitter().Build(impl.latest_decl_id(),
  386. ExtendImplAsIncomplete,
  387. impl.constraint_id);
  388. })) {
  389. parent_scope.set_has_error();
  390. return false;
  391. }
  392. if (!impl.generic_id.has_value()) {
  393. parent_scope.AddExtendedScope(impl.constraint_id);
  394. } else {
  395. auto constraint_id_in_self_specific = AddTypeInst<SemIR::SpecificConstant>(
  396. context, SemIR::LocId(impl.constraint_id),
  397. {.type_id = SemIR::TypeType::TypeId,
  398. .inst_id = impl.constraint_id,
  399. .specific_id = context.generics().GetSelfSpecific(impl.generic_id)});
  400. parent_scope.AddExtendedScope(constraint_id_in_self_specific);
  401. }
  402. return true;
  403. }
  404. // Diagnoses when an impl has an unused binding.
  405. static auto DiagnoseUnusedGenericBinding(Context& context, SemIR::LocId loc_id,
  406. SemIR::LocId implicit_params_loc_id,
  407. SemIR::ImplId impl_id) -> void {
  408. auto& impl = context.impls().Get(impl_id);
  409. if (!impl.generic_id.has_value() ||
  410. impl.witness_id == SemIR::ErrorInst::InstId) {
  411. return;
  412. }
  413. auto deduced_specific_id = DeduceImplArguments(
  414. context, loc_id, impl, context.constant_values().Get(impl.self_id),
  415. impl.interface.specific_id);
  416. if (deduced_specific_id.has_value()) {
  417. // Deduction succeeded, all bindings were used.
  418. return;
  419. }
  420. CARBON_DIAGNOSTIC(ImplUnusedBinding, Error,
  421. "`impl` with unused generic binding");
  422. // TODO: This location may be incorrect, the binding may be inherited
  423. // from an outer declaration. It would be nice to get the particular
  424. // binding that was undeducible back from DeduceImplArguments here and
  425. // use that.
  426. auto diag_loc_id =
  427. implicit_params_loc_id.has_value() ? implicit_params_loc_id : loc_id;
  428. context.emitter().Emit(diag_loc_id, ImplUnusedBinding);
  429. // Don't try to match the impl at all, save us work and possible future
  430. // diagnostics.
  431. FillImplWitnessWithErrors(context, context.impls().Get(impl_id));
  432. }
  433. auto GetOrAddImpl(Context& context, SemIR::LocId loc_id,
  434. SemIR::LocId implicit_params_loc_id, SemIR::Impl impl,
  435. bool is_definition, Parse::NodeId extend_node)
  436. -> SemIR::ImplId {
  437. auto impl_id = SemIR::ImplId::None;
  438. // Add the impl declaration.
  439. auto lookup_bucket_ref = context.impls().GetOrAddLookupBucket(impl);
  440. // TODO: Detect two impl declarations with the same self type and interface,
  441. // and issue an error if they don't match.
  442. for (auto prev_impl_id : lookup_bucket_ref) {
  443. if (CheckImplRedeclParamsMatch(context, impl, prev_impl_id)) {
  444. if (IsValidImplRedecl(context, impl, prev_impl_id)) {
  445. impl_id = prev_impl_id;
  446. } else {
  447. // IsValidImplRedecl() has issued a diagnostic, take care to avoid
  448. // generating more diagnostics for this declaration.
  449. impl.witness_id = SemIR::ErrorInst::InstId;
  450. }
  451. break;
  452. }
  453. }
  454. if (impl_id.has_value()) {
  455. // This is a redeclaration of another impl, now held in `impl_id`.
  456. auto& prev_impl = context.impls().Get(impl_id);
  457. FinishGenericRedecl(context, prev_impl.generic_id);
  458. return impl_id;
  459. }
  460. // This is a new declaration (possibly with an attached definition). Create a
  461. // new `impl_id`, filling the missing generic and witness in the provided
  462. // `Impl`.
  463. impl.generic_id = BuildGeneric(context, impl.latest_decl_id());
  464. // Due to lack of an instruction to set to `ErrorInst`, an `InterfaceId::None`
  465. // indicates that the interface could not be identified and an error was
  466. // diagnosed. If there's any error in the construction of the impl, then the
  467. // witness can't be constructed. We set it to `ErrorInst` to make the impl
  468. // unusable for impl lookup.
  469. if (!impl.interface.interface_id.has_value() ||
  470. impl.self_id == SemIR::ErrorInst::TypeInstId ||
  471. impl.constraint_id == SemIR::ErrorInst::TypeInstId) {
  472. impl.witness_id = SemIR::ErrorInst::InstId;
  473. // TODO: We might also want to mark that the name scope for the impl has an
  474. // error -- at least once we start making name lookups within the impl also
  475. // look into the facet (eg, so you can name associated constants from within
  476. // the impl).
  477. }
  478. if (impl.witness_id != SemIR::ErrorInst::InstId) {
  479. impl.witness_id = ImplWitnessForDeclaration(context, impl, is_definition);
  480. }
  481. FinishGenericDecl(context, SemIR::LocId(impl.latest_decl_id()),
  482. impl.generic_id);
  483. // From here on, use the `Impl` from the `ImplStore` instead of `impl`
  484. // in order to make and see any changes to the `Impl`.
  485. impl_id = context.impls().Add(impl);
  486. lookup_bucket_ref.push_back(impl_id);
  487. AssignImplIdInWitness(context, impl_id, impl.witness_id);
  488. auto& stored_impl_info = context.impls().Get(impl_id);
  489. // Looking to see if there are any generic bindings on the `impl`
  490. // declaration that are not deducible. If so, and the `impl` does not
  491. // actually use all its generic bindings, and will never be matched. This
  492. // should be diagnossed to the user.
  493. bool has_error_in_implicit_pattern = false;
  494. if (impl.implicit_param_patterns_id.has_value()) {
  495. for (auto inst_id :
  496. context.inst_blocks().Get(impl.implicit_param_patterns_id)) {
  497. if (inst_id == SemIR::ErrorInst::InstId) {
  498. has_error_in_implicit_pattern = true;
  499. break;
  500. }
  501. }
  502. }
  503. if (!has_error_in_implicit_pattern) {
  504. DiagnoseUnusedGenericBinding(context, loc_id, implicit_params_loc_id,
  505. impl_id);
  506. }
  507. // For an `extend impl` declaration, mark the impl as extending this `impl`.
  508. if (extend_node.has_value()) {
  509. if (!ApplyExtendImplAs(context, loc_id, stored_impl_info, extend_node,
  510. implicit_params_loc_id)) {
  511. // Don't allow the invalid impl to be used.
  512. FillImplWitnessWithErrors(context, stored_impl_info);
  513. }
  514. }
  515. return impl_id;
  516. }
  517. } // namespace Carbon::Check