impl.cpp 24 KB

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