impl.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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 IsImplEffectivelyFinal(Context& context, const SemIR::Impl& impl) -> bool {
  243. return impl.is_final ||
  244. (context.constant_values().Get(impl.self_id).is_concrete() &&
  245. context.constant_values().Get(impl.constraint_id).is_concrete());
  246. }
  247. auto CheckConstraintIsInterface(Context& context, SemIR::InstId impl_decl_id,
  248. SemIR::TypeInstId constraint_id)
  249. -> SemIR::SpecificInterface {
  250. auto facet_type_id = context.types().GetTypeIdForTypeInstId(constraint_id);
  251. if (facet_type_id == SemIR::ErrorInst::TypeId) {
  252. return SemIR::SpecificInterface::None;
  253. }
  254. auto facet_type = context.types().TryGetAs<SemIR::FacetType>(facet_type_id);
  255. if (!facet_type) {
  256. CARBON_DIAGNOSTIC(ImplAsNonFacetType, Error, "impl as non-facet type {0}",
  257. InstIdAsType);
  258. context.emitter().Emit(impl_decl_id, ImplAsNonFacetType, constraint_id);
  259. return SemIR::SpecificInterface::None;
  260. }
  261. auto identified_id = RequireIdentifiedFacetType(
  262. context, SemIR::LocId(constraint_id), *facet_type, [&] {
  263. CARBON_DIAGNOSTIC(ImplOfUnidentifiedFacetType, Error,
  264. "facet type {0} cannot be identified in `impl as`",
  265. InstIdAsType);
  266. return context.emitter().Build(
  267. impl_decl_id, ImplOfUnidentifiedFacetType, constraint_id);
  268. });
  269. if (!identified_id.has_value()) {
  270. return SemIR::SpecificInterface::None;
  271. }
  272. const auto& identified = context.identified_facet_types().Get(identified_id);
  273. if (!identified.is_valid_impl_as_target()) {
  274. CARBON_DIAGNOSTIC(ImplOfNotOneInterface, Error,
  275. "impl as {0} interfaces, expected 1", int);
  276. context.emitter().Emit(impl_decl_id, ImplOfNotOneInterface,
  277. identified.num_interfaces_to_impl());
  278. return SemIR::SpecificInterface::None;
  279. }
  280. return identified.impl_as_target_interface();
  281. }
  282. // Returns true if impl redeclaration parameters match.
  283. static auto CheckImplRedeclParamsMatch(Context& context, SemIR::Impl& new_impl,
  284. SemIR::ImplId prev_impl_id) -> bool {
  285. auto& prev_impl = context.impls().Get(prev_impl_id);
  286. // If the parameters aren't the same, then this is not a redeclaration of this
  287. // `impl`. Keep looking for a prior declaration without issuing a diagnostic.
  288. if (!CheckRedeclParamsMatch(context, DeclParams(new_impl),
  289. DeclParams(prev_impl), SemIR::SpecificId::None,
  290. /*diagnose=*/false, /*check_syntax=*/true,
  291. /*check_self=*/true)) {
  292. // NOLINTNEXTLINE(readability-simplify-boolean-expr)
  293. return false;
  294. }
  295. return true;
  296. }
  297. // Returns whether an impl can be redeclared. For example, defined impls
  298. // cannot be redeclared.
  299. static auto IsValidImplRedecl(Context& context, SemIR::Impl& new_impl,
  300. SemIR::ImplId prev_impl_id) -> bool {
  301. auto& prev_impl = context.impls().Get(prev_impl_id);
  302. // TODO: Following #3763, disallow redeclarations in different scopes.
  303. // Following #4672, disallowing defining non-extern declarations in another
  304. // file.
  305. if (auto import_ref =
  306. context.insts().TryGetAs<SemIR::AnyImportRef>(prev_impl.self_id)) {
  307. // TODO: Handle extern.
  308. CARBON_DIAGNOSTIC(RedeclImportedImpl, Error,
  309. "redeclaration of imported impl");
  310. // TODO: Note imported declaration
  311. context.emitter().Emit(new_impl.latest_decl_id(), RedeclImportedImpl);
  312. return false;
  313. }
  314. if (prev_impl.has_definition_started()) {
  315. // Impls aren't merged in order to avoid generic region lookup into a
  316. // mismatching table.
  317. CARBON_DIAGNOSTIC(ImplRedefinition, Error,
  318. "redefinition of `impl {0} as {1}`", InstIdAsRawType,
  319. InstIdAsRawType);
  320. CARBON_DIAGNOSTIC(ImplPreviousDefinition, Note,
  321. "previous definition was here");
  322. context.emitter()
  323. .Build(new_impl.latest_decl_id(), ImplRedefinition, new_impl.self_id,
  324. new_impl.constraint_id)
  325. .Note(prev_impl.definition_id, ImplPreviousDefinition)
  326. .Emit();
  327. return false;
  328. }
  329. // TODO: Only allow redeclaration in a match_first/impl_priority block.
  330. return true;
  331. }
  332. // Sets the `ImplId` in the `ImplWitnessTable`.
  333. static auto AssignImplIdInWitness(Context& context, SemIR::ImplId impl_id,
  334. SemIR::InstId witness_id) -> void {
  335. if (witness_id == SemIR::ErrorInst::InstId) {
  336. return;
  337. }
  338. auto witness = context.insts().GetAs<SemIR::ImplWitness>(witness_id);
  339. auto witness_table =
  340. context.insts().GetAs<SemIR::ImplWitnessTable>(witness.witness_table_id);
  341. witness_table.impl_id = impl_id;
  342. // Note: The `ImplWitnessTable` instruction is `Unique`, so while this marks
  343. // the instruction as being a dependent instruction of a generic impl, it will
  344. // not be substituted into the eval block.
  345. ReplaceInstBeforeConstantUse(context, witness.witness_table_id,
  346. witness_table);
  347. }
  348. // Looks for any unused generic bindings. If one is found, it is diagnosed and
  349. // false is returned.
  350. static auto VerifyAllGenericBindingsUsed(Context& context, SemIR::LocId loc_id,
  351. SemIR::LocId implicit_params_loc_id,
  352. SemIR::Impl& impl) -> bool {
  353. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  354. return true;
  355. }
  356. if (!impl.generic_id.has_value()) {
  357. return true;
  358. }
  359. if (impl.implicit_param_patterns_id.has_value()) {
  360. for (auto inst_id :
  361. context.inst_blocks().Get(impl.implicit_param_patterns_id)) {
  362. if (inst_id == SemIR::ErrorInst::InstId) {
  363. // An error was already diagnosed for a generic binding.
  364. return true;
  365. }
  366. }
  367. }
  368. auto deduced_specific_id = DeduceImplArguments(
  369. context, loc_id, impl, context.constant_values().Get(impl.self_id),
  370. impl.interface.specific_id);
  371. if (deduced_specific_id.has_value()) {
  372. // Deduction succeeded, all bindings were used.
  373. return true;
  374. }
  375. CARBON_DIAGNOSTIC(ImplUnusedBinding, Error,
  376. "`impl` with unused generic binding");
  377. // TODO: This location may be incorrect, the binding may be inherited
  378. // from an outer declaration. It would be nice to get the particular
  379. // binding that was undeducible back from DeduceImplArguments here and
  380. // use that.
  381. auto diag_loc_id =
  382. implicit_params_loc_id.has_value() ? implicit_params_loc_id : loc_id;
  383. context.emitter().Emit(diag_loc_id, ImplUnusedBinding);
  384. return false;
  385. }
  386. // Apply an `extend impl` declaration by extending the parent scope with the
  387. // `impl`. If there's an error it is diagnosed and false is returned.
  388. static auto ApplyExtendImplAs(Context& context, SemIR::LocId loc_id,
  389. const SemIR::Impl& impl,
  390. Parse::NodeId extend_node,
  391. SemIR::LocId implicit_params_loc_id) -> bool {
  392. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  393. // TODO: Also handle the parent scope being a mixin or an interface.
  394. auto class_scope = TryAsClassScope(context, parent_scope_id);
  395. if (!class_scope) {
  396. if (impl.witness_id != SemIR::ErrorInst::InstId) {
  397. CARBON_DIAGNOSTIC(
  398. ExtendImplOutsideClass, Error,
  399. "`extend impl` can only be used in an interface or class");
  400. context.emitter().Emit(loc_id, ExtendImplOutsideClass);
  401. }
  402. return false;
  403. }
  404. auto& parent_scope = *class_scope->name_scope;
  405. // An error was already diagnosed, but this is `extend impl as` inside a
  406. // class, so propagate the error into the enclosing class scope.
  407. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  408. parent_scope.set_has_error();
  409. return false;
  410. }
  411. if (implicit_params_loc_id.has_value()) {
  412. CARBON_DIAGNOSTIC(ExtendImplForall, Error,
  413. "cannot `extend` a parameterized `impl`");
  414. context.emitter().Emit(extend_node, ExtendImplForall);
  415. parent_scope.set_has_error();
  416. return false;
  417. }
  418. if (!RequireCompleteType(
  419. context, context.types().GetTypeIdForTypeInstId(impl.constraint_id),
  420. SemIR::LocId(impl.constraint_id), [&] {
  421. CARBON_DIAGNOSTIC(ExtendImplAsIncomplete, Error,
  422. "`extend impl as` incomplete facet type {0}",
  423. InstIdAsType);
  424. return context.emitter().Build(impl.latest_decl_id(),
  425. ExtendImplAsIncomplete,
  426. impl.constraint_id);
  427. })) {
  428. parent_scope.set_has_error();
  429. return false;
  430. }
  431. if (!impl.generic_id.has_value()) {
  432. parent_scope.AddExtendedScope(impl.constraint_id);
  433. } else {
  434. auto constraint_id_in_self_specific = AddTypeInst<SemIR::SpecificConstant>(
  435. context, SemIR::LocId(impl.constraint_id),
  436. {.type_id = SemIR::TypeType::TypeId,
  437. .inst_id = impl.constraint_id,
  438. .specific_id = context.generics().GetSelfSpecific(impl.generic_id)});
  439. parent_scope.AddExtendedScope(constraint_id_in_self_specific);
  440. }
  441. return true;
  442. }
  443. auto GetOrAddImpl(Context& context, SemIR::LocId loc_id,
  444. SemIR::LocId implicit_params_loc_id, SemIR::Impl impl,
  445. bool is_definition, Parse::NodeId extend_node)
  446. -> SemIR::ImplId {
  447. auto impl_id = SemIR::ImplId::None;
  448. // Add the impl declaration.
  449. auto lookup_bucket_ref = context.impls().GetOrAddLookupBucket(impl);
  450. // TODO: Detect two impl declarations with the same self type and interface,
  451. // and issue an error if they don't match.
  452. for (auto prev_impl_id : lookup_bucket_ref) {
  453. if (CheckImplRedeclParamsMatch(context, impl, prev_impl_id)) {
  454. if (IsValidImplRedecl(context, impl, prev_impl_id)) {
  455. impl_id = prev_impl_id;
  456. } else {
  457. // IsValidImplRedecl() has issued a diagnostic, take care to avoid
  458. // generating more diagnostics for this declaration.
  459. impl.witness_id = SemIR::ErrorInst::InstId;
  460. }
  461. break;
  462. }
  463. }
  464. if (impl_id.has_value()) {
  465. // This is a redeclaration of another impl, now held in `impl_id`.
  466. auto& prev_impl = context.impls().Get(impl_id);
  467. FinishGenericRedecl(context, prev_impl.generic_id);
  468. return impl_id;
  469. }
  470. // This is a new declaration (possibly with an attached definition). Create a
  471. // new `impl_id`, filling the missing generic and witness in the provided
  472. // `Impl`.
  473. impl.generic_id = BuildGeneric(context, impl.latest_decl_id());
  474. // Due to lack of an instruction to set to `ErrorInst`, an `InterfaceId::None`
  475. // indicates that the interface could not be identified and an error was
  476. // diagnosed. If there's any error in the construction of the impl, then the
  477. // witness can't be constructed. We set it to `ErrorInst` to make the impl
  478. // unusable for impl lookup.
  479. if (!impl.interface.interface_id.has_value() ||
  480. impl.self_id == SemIR::ErrorInst::TypeInstId ||
  481. impl.constraint_id == SemIR::ErrorInst::TypeInstId) {
  482. impl.witness_id = SemIR::ErrorInst::InstId;
  483. // TODO: We might also want to mark that the name scope for the impl has an
  484. // error -- at least once we start making name lookups within the impl also
  485. // look into the facet (eg, so you can name associated constants from within
  486. // the impl).
  487. }
  488. if (impl.witness_id != SemIR::ErrorInst::InstId) {
  489. impl.witness_id = ImplWitnessForDeclaration(context, impl, is_definition);
  490. }
  491. FinishGenericDecl(context, SemIR::LocId(impl.latest_decl_id()),
  492. impl.generic_id);
  493. // From here on, use the `Impl` from the `ImplStore` instead of `impl`
  494. // in order to make and see any changes to the `Impl`.
  495. impl_id = context.impls().Add(impl);
  496. lookup_bucket_ref.push_back(impl_id);
  497. AssignImplIdInWitness(context, impl_id, impl.witness_id);
  498. auto& stored_impl = context.impls().Get(impl_id);
  499. // Look to see if there are any generic bindings on the `impl` declaration
  500. // that are not deducible. If so, and the `impl` does not actually use all its
  501. // generic bindings, and will never be matched. This should be diagnosed to
  502. // the user.
  503. if (!VerifyAllGenericBindingsUsed(context, loc_id, implicit_params_loc_id,
  504. stored_impl)) {
  505. FillImplWitnessWithErrors(context, stored_impl);
  506. }
  507. if (extend_node.has_value()) {
  508. if (!ApplyExtendImplAs(context, loc_id, stored_impl, extend_node,
  509. implicit_params_loc_id)) {
  510. FillImplWitnessWithErrors(context, stored_impl);
  511. }
  512. }
  513. return impl_id;
  514. }
  515. } // namespace Carbon::Check