impl.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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. // Checks that `impl_function_id` is a valid implementation of the function
  37. // described in the interface as `interface_function_id`. Returns the value to
  38. // put into the corresponding slot in the witness table, which can be
  39. // `BuiltinErrorInst` if the function is not usable.
  40. static auto CheckAssociatedFunctionImplementation(
  41. Context& context, SemIR::FunctionType interface_function_type,
  42. SemIR::InstId impl_decl_id, SemIR::TypeId self_type_id,
  43. SemIR::InstId witness_inst_id) -> SemIR::InstId {
  44. auto impl_function_decl =
  45. context.insts().TryGetAs<SemIR::FunctionDecl>(impl_decl_id);
  46. if (!impl_function_decl) {
  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. return SemIR::ErrorInst::InstId;
  57. }
  58. auto impl_enclosing_specific_id =
  59. context.types()
  60. .GetAs<SemIR::FunctionType>(impl_function_decl->type_id)
  61. .specific_id;
  62. // Map from the specific for the function type to the specific for the
  63. // function signature. The function signature may have additional generic
  64. // parameters.
  65. auto interface_function_specific_id =
  66. GetSelfSpecificForInterfaceMemberWithSelfType(
  67. context, SemIR::LocId(impl_decl_id),
  68. interface_function_type.specific_id,
  69. context.functions()
  70. .Get(interface_function_type.function_id)
  71. .generic_id,
  72. impl_enclosing_specific_id, self_type_id, witness_inst_id);
  73. return BuildThunk(context, interface_function_type.function_id,
  74. interface_function_specific_id, impl_decl_id);
  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. return;
  112. }
  113. AllocateFacetTypeImplWitness(context, impl.interface.interface_id,
  114. witness_table.elements_id);
  115. witness_block = context.inst_blocks().GetMutable(witness_table.elements_id);
  116. }
  117. const auto& interface = context.interfaces().Get(impl.interface.interface_id);
  118. auto assoc_entities =
  119. context.inst_blocks().Get(interface.associated_entities_id);
  120. CARBON_CHECK(witness_block.size() == assoc_entities.size());
  121. // Check we have a value for all non-function associated constants in the
  122. // witness.
  123. for (auto [assoc_entity, witness_value] :
  124. llvm::zip(assoc_entities, witness_block)) {
  125. auto decl_id = context.constant_values().GetConstantInstId(assoc_entity);
  126. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  127. if (auto decl =
  128. context.insts().TryGetAs<SemIR::AssociatedConstantDecl>(decl_id)) {
  129. if (witness_value == SemIR::InstId::ImplWitnessTablePlaceholder) {
  130. CARBON_DIAGNOSTIC(ImplAssociatedConstantNeedsValue, Error,
  131. "associated constant {0} not given a value in impl "
  132. "of interface {1}",
  133. SemIR::NameId, SemIR::NameId);
  134. CARBON_DIAGNOSTIC(AssociatedConstantHere, Note,
  135. "associated constant declared here");
  136. context.emitter()
  137. .Build(impl.definition_id, ImplAssociatedConstantNeedsValue,
  138. context.associated_constants()
  139. .Get(decl->assoc_const_id)
  140. .name_id,
  141. interface.name_id)
  142. .Note(assoc_entity, AssociatedConstantHere)
  143. .Emit();
  144. witness_value = SemIR::ErrorInst::InstId;
  145. }
  146. }
  147. }
  148. }
  149. // Adds functions to the witness that the specified impl implements the given
  150. // interface.
  151. auto FinishImplWitness(Context& context, SemIR::ImplId impl_id) -> void {
  152. const auto& impl = context.impls().Get(impl_id);
  153. CARBON_CHECK(impl.is_being_defined());
  154. CARBON_CHECK(impl.witness_id.has_value());
  155. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  156. return;
  157. }
  158. auto witness = context.insts().GetAs<SemIR::ImplWitness>(impl.witness_id);
  159. auto witness_table =
  160. context.insts().GetAs<SemIR::ImplWitnessTable>(witness.witness_table_id);
  161. auto witness_block =
  162. context.inst_blocks().GetMutable(witness_table.elements_id);
  163. auto& impl_scope = context.name_scopes().Get(impl.scope_id);
  164. auto self_type_id = context.types().GetTypeIdForTypeInstId(impl.self_id);
  165. const auto& interface = context.interfaces().Get(impl.interface.interface_id);
  166. auto assoc_entities =
  167. context.inst_blocks().Get(interface.associated_entities_id);
  168. llvm::SmallVector<SemIR::InstId> used_decl_ids;
  169. for (auto [assoc_entity, witness_value] :
  170. llvm::zip(assoc_entities, witness_block)) {
  171. auto decl_id =
  172. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  173. context.sem_ir(), impl.interface.specific_id, assoc_entity));
  174. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  175. auto decl = context.insts().Get(decl_id);
  176. CARBON_KIND_SWITCH(decl) {
  177. case CARBON_KIND(SemIR::StructValue struct_value): {
  178. if (struct_value.type_id == SemIR::ErrorInst::TypeId) {
  179. witness_value = SemIR::ErrorInst::InstId;
  180. break;
  181. }
  182. auto type_inst = context.types().GetAsInst(struct_value.type_id);
  183. auto fn_type = type_inst.TryAs<SemIR::FunctionType>();
  184. if (!fn_type) {
  185. CARBON_FATAL("Unexpected type: {0}", type_inst);
  186. }
  187. auto& fn = context.functions().Get(fn_type->function_id);
  188. auto lookup_result =
  189. LookupNameInExactScope(context, SemIR::LocId(decl_id), fn.name_id,
  190. impl.scope_id, impl_scope);
  191. if (lookup_result.is_found()) {
  192. used_decl_ids.push_back(lookup_result.target_inst_id());
  193. witness_value = CheckAssociatedFunctionImplementation(
  194. context, *fn_type, lookup_result.target_inst_id(), self_type_id,
  195. impl.witness_id);
  196. } else {
  197. CARBON_DIAGNOSTIC(
  198. ImplMissingFunction, Error,
  199. "missing implementation of {0} in impl of interface {1}",
  200. SemIR::NameId, SemIR::NameId);
  201. auto builder =
  202. context.emitter().Build(impl.definition_id, ImplMissingFunction,
  203. fn.name_id, interface.name_id);
  204. NoteAssociatedFunction(context, builder, fn_type->function_id);
  205. builder.Emit();
  206. witness_value = SemIR::ErrorInst::InstId;
  207. }
  208. break;
  209. }
  210. case SemIR::AssociatedConstantDecl::Kind: {
  211. // These are set to their final values already.
  212. break;
  213. }
  214. default:
  215. CARBON_CHECK(decl_id == SemIR::ErrorInst::InstId,
  216. "Unexpected kind of associated entity {0}", decl);
  217. witness_value = SemIR::ErrorInst::InstId;
  218. break;
  219. }
  220. }
  221. // TODO: Diagnose if any declarations in the impl are not in used_decl_ids.
  222. }
  223. auto FillImplWitnessWithErrors(Context& context, SemIR::Impl& impl) -> void {
  224. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  225. return;
  226. }
  227. auto witness = context.insts().GetAs<SemIR::ImplWitness>(impl.witness_id);
  228. auto witness_table =
  229. context.insts().GetAs<SemIR::ImplWitnessTable>(witness.witness_table_id);
  230. auto witness_block =
  231. context.inst_blocks().GetMutable(witness_table.elements_id);
  232. for (auto& elem : witness_block) {
  233. if (elem == SemIR::InstId::ImplWitnessTablePlaceholder) {
  234. elem = SemIR::ErrorInst::InstId;
  235. }
  236. }
  237. impl.witness_id = SemIR::ErrorInst::InstId;
  238. }
  239. auto AssignImplIdInWitness(Context& context, SemIR::ImplId impl_id,
  240. SemIR::InstId witness_id) -> void {
  241. if (witness_id == SemIR::ErrorInst::InstId) {
  242. return;
  243. }
  244. auto witness = context.insts().GetAs<SemIR::ImplWitness>(witness_id);
  245. auto witness_table =
  246. context.insts().GetAs<SemIR::ImplWitnessTable>(witness.witness_table_id);
  247. witness_table.impl_id = impl_id;
  248. // Note: The `ImplWitnessTable` instruction is `Unique`, so while this marks
  249. // the instruction as being a dependent instruction of a generic impl, it will
  250. // not be substituted into the eval block.
  251. ReplaceInstBeforeConstantUse(context, witness.witness_table_id,
  252. witness_table);
  253. }
  254. auto IsImplEffectivelyFinal(Context& context, const SemIR::Impl& impl) -> bool {
  255. return impl.is_final ||
  256. (context.constant_values().Get(impl.self_id).is_concrete() &&
  257. context.constant_values().Get(impl.constraint_id).is_concrete());
  258. }
  259. auto CheckConstraintIsInterface(Context& context, SemIR::InstId impl_decl_id,
  260. SemIR::TypeInstId constraint_id)
  261. -> SemIR::SpecificInterface {
  262. auto facet_type_id = context.types().GetTypeIdForTypeInstId(constraint_id);
  263. if (facet_type_id == SemIR::ErrorInst::TypeId) {
  264. return SemIR::SpecificInterface::None;
  265. }
  266. auto facet_type = context.types().TryGetAs<SemIR::FacetType>(facet_type_id);
  267. if (!facet_type) {
  268. CARBON_DIAGNOSTIC(ImplAsNonFacetType, Error, "impl as non-facet type {0}",
  269. InstIdAsType);
  270. context.emitter().Emit(impl_decl_id, ImplAsNonFacetType, constraint_id);
  271. return SemIR::SpecificInterface::None;
  272. }
  273. auto identified_id = RequireIdentifiedFacetType(context, *facet_type, [&] {
  274. CARBON_DIAGNOSTIC(ImplOfUnidentifiedFacetType, Error,
  275. "facet type {0} cannot be identified in `impl as`",
  276. InstIdAsType);
  277. return context.emitter().Build(impl_decl_id, ImplOfUnidentifiedFacetType,
  278. constraint_id);
  279. });
  280. if (!identified_id.has_value()) {
  281. return SemIR::SpecificInterface::None;
  282. }
  283. const auto& identified = context.identified_facet_types().Get(identified_id);
  284. if (!identified.is_valid_impl_as_target()) {
  285. CARBON_DIAGNOSTIC(ImplOfNotOneInterface, Error,
  286. "impl as {0} interfaces, expected 1", int);
  287. context.emitter().Emit(impl_decl_id, ImplOfNotOneInterface,
  288. identified.num_interfaces_to_impl());
  289. return SemIR::SpecificInterface::None;
  290. }
  291. return identified.impl_as_target_interface();
  292. }
  293. // Returns true if impl redeclaration parameters match.
  294. static auto CheckImplRedeclParamsMatch(Context& context, SemIR::Impl& new_impl,
  295. SemIR::ImplId prev_impl_id) -> bool {
  296. auto& prev_impl = context.impls().Get(prev_impl_id);
  297. // If the parameters aren't the same, then this is not a redeclaration of this
  298. // `impl`. Keep looking for a prior declaration without issuing a diagnostic.
  299. if (!CheckRedeclParamsMatch(context, DeclParams(new_impl),
  300. DeclParams(prev_impl), SemIR::SpecificId::None,
  301. /*diagnose=*/false, /*check_syntax=*/true,
  302. /*check_self=*/true)) {
  303. // NOLINTNEXTLINE(readability-simplify-boolean-expr)
  304. return false;
  305. }
  306. return true;
  307. }
  308. // Returns whether an impl can be redeclared. For example, defined impls
  309. // cannot be redeclared.
  310. static auto IsValidImplRedecl(Context& context, SemIR::Impl& new_impl,
  311. SemIR::ImplId prev_impl_id) -> bool {
  312. auto& prev_impl = context.impls().Get(prev_impl_id);
  313. // TODO: Following #3763, disallow redeclarations in different scopes.
  314. // Following #4672, disallowing defining non-extern declarations in another
  315. // file.
  316. if (auto import_ref =
  317. context.insts().TryGetAs<SemIR::AnyImportRef>(prev_impl.self_id)) {
  318. // TODO: Handle extern.
  319. CARBON_DIAGNOSTIC(RedeclImportedImpl, Error,
  320. "redeclaration of imported impl");
  321. // TODO: Note imported declaration
  322. context.emitter().Emit(new_impl.latest_decl_id(), RedeclImportedImpl);
  323. return false;
  324. }
  325. if (prev_impl.has_definition_started()) {
  326. // Impls aren't merged in order to avoid generic region lookup into a
  327. // mismatching table.
  328. CARBON_DIAGNOSTIC(ImplRedefinition, Error,
  329. "redefinition of `impl {0} as {1}`", InstIdAsRawType,
  330. InstIdAsRawType);
  331. CARBON_DIAGNOSTIC(ImplPreviousDefinition, Note,
  332. "previous definition was here");
  333. context.emitter()
  334. .Build(new_impl.latest_decl_id(), ImplRedefinition, new_impl.self_id,
  335. new_impl.constraint_id)
  336. .Note(prev_impl.definition_id, ImplPreviousDefinition)
  337. .Emit();
  338. return false;
  339. }
  340. // TODO: Only allow redeclaration in a match_first/impl_priority block.
  341. return true;
  342. }
  343. static auto DiagnoseExtendImplOutsideClass(Context& context,
  344. SemIR::LocId loc_id) -> void {
  345. CARBON_DIAGNOSTIC(ExtendImplOutsideClass, Error,
  346. "`extend impl` can only be used in a class");
  347. context.emitter().Emit(loc_id, ExtendImplOutsideClass);
  348. }
  349. // If the specified name scope corresponds to a class, returns the corresponding
  350. // class declaration.
  351. // TODO: Should this be somewhere more central?
  352. static auto TryAsClassScope(Context& context, SemIR::NameScopeId scope_id)
  353. -> std::optional<SemIR::ClassDecl> {
  354. if (!scope_id.has_value()) {
  355. return std::nullopt;
  356. }
  357. auto& scope = context.name_scopes().Get(scope_id);
  358. if (!scope.inst_id().has_value()) {
  359. return std::nullopt;
  360. }
  361. return context.insts().TryGetAs<SemIR::ClassDecl>(scope.inst_id());
  362. }
  363. auto GetImplDefaultSelfType(Context& context) -> SemIR::TypeId {
  364. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  365. if (auto class_decl = TryAsClassScope(context, parent_scope_id)) {
  366. return context.classes().Get(class_decl->class_id).self_type_id;
  367. }
  368. // TODO: This is also valid in a mixin.
  369. return SemIR::TypeId::None;
  370. }
  371. // Process an `extend impl` declaration by extending the impl scope with the
  372. // `impl`'s scope.
  373. static auto ExtendImpl(Context& context, Parse::NodeId extend_node,
  374. SemIR::LocId loc_id, SemIR::ImplId impl_id,
  375. Parse::NodeId self_type_node_id,
  376. SemIR::TypeId self_type_id,
  377. SemIR::LocId implicit_params_loc_id,
  378. SemIR::TypeInstId constraint_type_inst_id,
  379. SemIR::TypeId constraint_type_id) -> bool {
  380. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  381. if (!parent_scope_id.has_value()) {
  382. DiagnoseExtendImplOutsideClass(context, loc_id);
  383. return false;
  384. }
  385. // TODO: This is also valid in a mixin.
  386. if (!TryAsClassScope(context, parent_scope_id)) {
  387. DiagnoseExtendImplOutsideClass(context, loc_id);
  388. return false;
  389. }
  390. auto& parent_scope = context.name_scopes().Get(parent_scope_id);
  391. if (implicit_params_loc_id.has_value()) {
  392. CARBON_DIAGNOSTIC(ExtendImplForall, Error,
  393. "cannot `extend` a parameterized `impl`");
  394. context.emitter().Emit(extend_node, ExtendImplForall);
  395. parent_scope.set_has_error();
  396. return false;
  397. }
  398. const auto& impl = context.impls().Get(impl_id);
  399. if (context.parse_tree().node_kind(self_type_node_id) ==
  400. Parse::NodeKind::ImplTypeAs) {
  401. CARBON_DIAGNOSTIC(ExtendImplSelfAs, Error,
  402. "cannot `extend` an `impl` with an explicit self type");
  403. auto diag = context.emitter().Build(extend_node, ExtendImplSelfAs);
  404. // If the explicit self type is not the default, just bail out.
  405. if (self_type_id != GetImplDefaultSelfType(context)) {
  406. diag.Emit();
  407. parent_scope.set_has_error();
  408. return false;
  409. }
  410. // The explicit self type is the same as the default self type, so suggest
  411. // removing it and recover as if it were not present.
  412. if (auto self_as =
  413. context.parse_tree_and_subtrees().ExtractAs<Parse::ImplTypeAs>(
  414. self_type_node_id)) {
  415. CARBON_DIAGNOSTIC(ExtendImplSelfAsDefault, Note,
  416. "remove the explicit `Self` type here");
  417. diag.Note(self_as->type_expr, ExtendImplSelfAsDefault);
  418. }
  419. diag.Emit();
  420. }
  421. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  422. parent_scope.set_has_error();
  423. } else {
  424. bool is_complete = RequireCompleteType(
  425. context, constraint_type_id, SemIR::LocId(constraint_type_inst_id),
  426. [&] {
  427. CARBON_DIAGNOSTIC(ExtendImplAsIncomplete, Error,
  428. "`extend impl as` incomplete facet type {0}",
  429. InstIdAsType);
  430. return context.emitter().Build(impl.latest_decl_id(),
  431. ExtendImplAsIncomplete,
  432. constraint_type_inst_id);
  433. });
  434. if (!is_complete) {
  435. parent_scope.set_has_error();
  436. return false;
  437. }
  438. }
  439. parent_scope.AddExtendedScope(constraint_type_inst_id);
  440. return true;
  441. }
  442. // Diagnoses when an impl has an unused binding.
  443. static auto DiagnoseUnusedGenericBinding(Context& context, SemIR::LocId loc_id,
  444. SemIR::LocId implicit_params_loc_id,
  445. SemIR::ImplId impl_id) -> void {
  446. auto& impl = context.impls().Get(impl_id);
  447. if (!impl.generic_id.has_value() ||
  448. impl.witness_id == SemIR::ErrorInst::InstId) {
  449. return;
  450. }
  451. auto deduced_specific_id = DeduceImplArguments(
  452. context, loc_id, impl, context.constant_values().Get(impl.self_id),
  453. impl.interface.specific_id);
  454. if (deduced_specific_id.has_value()) {
  455. // Deduction succeeded, all bindings were used.
  456. return;
  457. }
  458. CARBON_DIAGNOSTIC(ImplUnusedBinding, Error,
  459. "`impl` with unused generic binding");
  460. // TODO: This location may be incorrect, the binding may be inherited
  461. // from an outer declaration. It would be nice to get the particular
  462. // binding that was undeducible back from DeduceImplArguments here and
  463. // use that.
  464. auto diag_loc_id =
  465. implicit_params_loc_id.has_value() ? implicit_params_loc_id : loc_id;
  466. context.emitter().Emit(diag_loc_id, ImplUnusedBinding);
  467. // Don't try to match the impl at all, save us work and possible future
  468. // diagnostics.
  469. FillImplWitnessWithErrors(context, context.impls().Get(impl_id));
  470. }
  471. auto StartImplDecl(Context& context, SemIR::LocId loc_id,
  472. SemIR::LocId implicit_params_loc_id, SemIR::Impl impl,
  473. bool is_definition,
  474. std::optional<ExtendImplDecl> extend_impl)
  475. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  476. auto impl_id = SemIR::ImplId::None;
  477. // Add the impl declaration.
  478. auto lookup_bucket_ref = context.impls().GetOrAddLookupBucket(impl);
  479. // TODO: Detect two impl declarations with the same self type and interface,
  480. // and issue an error if they don't match.
  481. for (auto prev_impl_id : lookup_bucket_ref) {
  482. if (CheckImplRedeclParamsMatch(context, impl, prev_impl_id)) {
  483. if (IsValidImplRedecl(context, impl, prev_impl_id)) {
  484. impl_id = prev_impl_id;
  485. } else {
  486. // IsValidImplRedecl() has issued a diagnostic, avoid generating more
  487. // diagnostics for this declaration.
  488. impl.witness_id = SemIR::ErrorInst::InstId;
  489. }
  490. break;
  491. }
  492. }
  493. // Create a new impl if this isn't a valid redeclaration.
  494. if (!impl_id.has_value()) {
  495. impl.generic_id = BuildGeneric(context, impl.latest_decl_id());
  496. if (impl.witness_id != SemIR::ErrorInst::InstId) {
  497. if (impl.interface.interface_id.has_value()) {
  498. impl.witness_id =
  499. ImplWitnessForDeclaration(context, impl, is_definition);
  500. } else {
  501. impl.witness_id = SemIR::ErrorInst::InstId;
  502. // TODO: We might also want to mark that the name scope for the impl has
  503. // an error -- at least once we start making name lookups within the
  504. // impl also look into the facet (eg, so you can name associated
  505. // constants from within the impl).
  506. }
  507. }
  508. FinishGenericDecl(context, SemIR::LocId(impl.latest_decl_id()),
  509. impl.generic_id);
  510. // From here on, use the `Impl` from the `ImplStore` instead of `impl`
  511. // in order to make and see any changes to the `Impl`.
  512. impl_id = context.impls().Add(impl);
  513. lookup_bucket_ref.push_back(impl_id);
  514. AssignImplIdInWitness(context, impl_id, impl.witness_id);
  515. // Looking to see if there are any generic bindings on the `impl`
  516. // declaration that are not deducible. If so, and the `impl` does not
  517. // actually use all its generic bindings, and will never be matched. This
  518. // should be diagnossed to the user.
  519. bool has_error_in_implicit_pattern = false;
  520. if (impl.implicit_param_patterns_id.has_value()) {
  521. for (auto inst_id :
  522. context.inst_blocks().Get(impl.implicit_param_patterns_id)) {
  523. if (inst_id == SemIR::ErrorInst::InstId) {
  524. has_error_in_implicit_pattern = true;
  525. break;
  526. }
  527. }
  528. }
  529. if (!has_error_in_implicit_pattern) {
  530. DiagnoseUnusedGenericBinding(context, loc_id, implicit_params_loc_id,
  531. impl_id);
  532. }
  533. } else {
  534. auto& stored_impl = context.impls().Get(impl_id);
  535. FinishGenericRedecl(context, stored_impl.generic_id);
  536. }
  537. // Write the impl ID into the ImplDecl.
  538. auto impl_decl =
  539. context.insts().GetAs<SemIR::ImplDecl>(impl.first_owning_decl_id);
  540. CARBON_CHECK(!impl_decl.impl_id.has_value());
  541. impl_decl.impl_id = impl_id;
  542. ReplaceInstBeforeConstantUse(context, impl.first_owning_decl_id, impl_decl);
  543. // For an `extend impl` declaration, mark the impl as extending this `impl`.
  544. if (extend_impl) {
  545. auto& stored_impl_info = context.impls().Get(impl_decl.impl_id);
  546. auto self_type_id =
  547. context.types().GetTypeIdForTypeInstId(stored_impl_info.self_id);
  548. if (self_type_id != SemIR::ErrorInst::TypeId) {
  549. auto constraint_id = impl.constraint_id;
  550. if (stored_impl_info.generic_id.has_value()) {
  551. constraint_id = AddTypeInst<SemIR::SpecificConstant>(
  552. context, SemIR::LocId(constraint_id),
  553. {.type_id = SemIR::TypeType::TypeId,
  554. .inst_id = constraint_id,
  555. .specific_id = context.generics().GetSelfSpecific(
  556. stored_impl_info.generic_id)});
  557. }
  558. if (!ExtendImpl(context, extend_impl->extend_node_id, loc_id,
  559. impl_decl.impl_id, extend_impl->self_type_node_id,
  560. self_type_id, implicit_params_loc_id, constraint_id,
  561. extend_impl->constraint_type_id)) {
  562. // Don't allow the invalid impl to be used.
  563. FillImplWitnessWithErrors(context, stored_impl_info);
  564. }
  565. }
  566. }
  567. // Impl definitions are required in the same file as the declaration. We skip
  568. // this requirement if we've already issued an invalid redeclaration error, or
  569. // there is an error that would prevent the impl from being legal to define.
  570. if (!is_definition) {
  571. auto& stored_impl = context.impls().Get(impl_id);
  572. if (stored_impl.witness_id != SemIR::ErrorInst::InstId) {
  573. context.definitions_required_by_decl().push_back(
  574. stored_impl.latest_decl_id());
  575. }
  576. }
  577. return {impl_id, impl.latest_decl_id()};
  578. }
  579. } // namespace Carbon::Check