impl.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. auto GetImplDefaultSelfType(Context& context) -> SemIR::TypeId {
  366. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  367. if (auto class_decl = TryAsClassScope(context, parent_scope_id)) {
  368. return context.classes().Get(class_decl->class_id).self_type_id;
  369. }
  370. // TODO: This is also valid in a mixin.
  371. return SemIR::TypeId::None;
  372. }
  373. // Process an `extend impl` declaration by extending the impl scope with the
  374. // `impl`'s scope.
  375. static auto ExtendImpl(Context& context, Parse::NodeId extend_node,
  376. SemIR::LocId loc_id, SemIR::ImplId impl_id,
  377. Parse::NodeId self_type_node_id,
  378. SemIR::TypeId self_type_id,
  379. SemIR::LocId implicit_params_loc_id,
  380. SemIR::TypeInstId constraint_type_inst_id,
  381. SemIR::TypeId constraint_type_id) -> bool {
  382. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  383. if (!parent_scope_id.has_value()) {
  384. DiagnoseExtendImplOutsideClass(context, loc_id);
  385. return false;
  386. }
  387. // TODO: This is also valid in a mixin.
  388. if (!TryAsClassScope(context, parent_scope_id)) {
  389. DiagnoseExtendImplOutsideClass(context, loc_id);
  390. return false;
  391. }
  392. auto& parent_scope = context.name_scopes().Get(parent_scope_id);
  393. if (implicit_params_loc_id.has_value()) {
  394. CARBON_DIAGNOSTIC(ExtendImplForall, Error,
  395. "cannot `extend` a parameterized `impl`");
  396. context.emitter().Emit(extend_node, ExtendImplForall);
  397. parent_scope.set_has_error();
  398. return false;
  399. }
  400. const auto& impl = context.impls().Get(impl_id);
  401. if (context.parse_tree().node_kind(self_type_node_id) ==
  402. Parse::NodeKind::ImplTypeAs) {
  403. CARBON_DIAGNOSTIC(ExtendImplSelfAs, Error,
  404. "cannot `extend` an `impl` with an explicit self type");
  405. auto diag = context.emitter().Build(extend_node, ExtendImplSelfAs);
  406. // If the explicit self type is not the default, just bail out.
  407. if (self_type_id != GetImplDefaultSelfType(context)) {
  408. diag.Emit();
  409. parent_scope.set_has_error();
  410. return false;
  411. }
  412. // The explicit self type is the same as the default self type, so suggest
  413. // removing it and recover as if it were not present.
  414. if (auto self_as =
  415. context.parse_tree_and_subtrees().ExtractAs<Parse::ImplTypeAs>(
  416. self_type_node_id)) {
  417. CARBON_DIAGNOSTIC(ExtendImplSelfAsDefault, Note,
  418. "remove the explicit `Self` type here");
  419. diag.Note(self_as->type_expr, ExtendImplSelfAsDefault);
  420. }
  421. diag.Emit();
  422. }
  423. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  424. parent_scope.set_has_error();
  425. } else {
  426. bool is_complete = RequireCompleteType(
  427. context, constraint_type_id, SemIR::LocId(constraint_type_inst_id),
  428. [&] {
  429. CARBON_DIAGNOSTIC(ExtendImplAsIncomplete, Error,
  430. "`extend impl as` incomplete facet type {0}",
  431. InstIdAsType);
  432. return context.emitter().Build(impl.latest_decl_id(),
  433. ExtendImplAsIncomplete,
  434. constraint_type_inst_id);
  435. });
  436. if (!is_complete) {
  437. parent_scope.set_has_error();
  438. return false;
  439. }
  440. }
  441. parent_scope.AddExtendedScope(constraint_type_inst_id);
  442. return true;
  443. }
  444. // Diagnoses when an impl has an unused binding.
  445. static auto DiagnoseUnusedGenericBinding(Context& context, SemIR::LocId loc_id,
  446. SemIR::LocId implicit_params_loc_id,
  447. SemIR::ImplId impl_id) -> void {
  448. auto& impl = context.impls().Get(impl_id);
  449. if (!impl.generic_id.has_value() ||
  450. impl.witness_id == SemIR::ErrorInst::InstId) {
  451. return;
  452. }
  453. auto deduced_specific_id = DeduceImplArguments(
  454. context, loc_id, impl, context.constant_values().Get(impl.self_id),
  455. impl.interface.specific_id);
  456. if (deduced_specific_id.has_value()) {
  457. // Deduction succeeded, all bindings were used.
  458. return;
  459. }
  460. CARBON_DIAGNOSTIC(ImplUnusedBinding, Error,
  461. "`impl` with unused generic binding");
  462. // TODO: This location may be incorrect, the binding may be inherited
  463. // from an outer declaration. It would be nice to get the particular
  464. // binding that was undeducible back from DeduceImplArguments here and
  465. // use that.
  466. auto diag_loc_id =
  467. implicit_params_loc_id.has_value() ? implicit_params_loc_id : loc_id;
  468. context.emitter().Emit(diag_loc_id, ImplUnusedBinding);
  469. // Don't try to match the impl at all, save us work and possible future
  470. // diagnostics.
  471. FillImplWitnessWithErrors(context, context.impls().Get(impl_id));
  472. }
  473. auto StartImplDecl(Context& context, SemIR::LocId loc_id,
  474. SemIR::LocId implicit_params_loc_id, SemIR::Impl impl,
  475. bool is_definition,
  476. std::optional<ExtendImplDecl> extend_impl)
  477. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  478. auto impl_id = SemIR::ImplId::None;
  479. // Add the impl declaration.
  480. auto lookup_bucket_ref = context.impls().GetOrAddLookupBucket(impl);
  481. // TODO: Detect two impl declarations with the same self type and interface,
  482. // and issue an error if they don't match.
  483. for (auto prev_impl_id : lookup_bucket_ref) {
  484. if (CheckImplRedeclParamsMatch(context, impl, prev_impl_id)) {
  485. if (IsValidImplRedecl(context, impl, prev_impl_id)) {
  486. impl_id = prev_impl_id;
  487. } else {
  488. // IsValidImplRedecl() has issued a diagnostic, avoid generating more
  489. // diagnostics for this declaration.
  490. impl.witness_id = SemIR::ErrorInst::InstId;
  491. }
  492. break;
  493. }
  494. }
  495. // Create a new impl if this isn't a valid redeclaration.
  496. if (!impl_id.has_value()) {
  497. impl.generic_id = BuildGeneric(context, impl.latest_decl_id());
  498. if (impl.witness_id != SemIR::ErrorInst::InstId) {
  499. if (impl.interface.interface_id.has_value()) {
  500. impl.witness_id =
  501. ImplWitnessForDeclaration(context, impl, is_definition);
  502. } else {
  503. impl.witness_id = SemIR::ErrorInst::InstId;
  504. // TODO: We might also want to mark that the name scope for the impl has
  505. // an error -- at least once we start making name lookups within the
  506. // impl also look into the facet (eg, so you can name associated
  507. // constants from within the impl).
  508. }
  509. }
  510. FinishGenericDecl(context, SemIR::LocId(impl.latest_decl_id()),
  511. impl.generic_id);
  512. // From here on, use the `Impl` from the `ImplStore` instead of `impl`
  513. // in order to make and see any changes to the `Impl`.
  514. impl_id = context.impls().Add(impl);
  515. lookup_bucket_ref.push_back(impl_id);
  516. AssignImplIdInWitness(context, impl_id, impl.witness_id);
  517. // Looking to see if there are any generic bindings on the `impl`
  518. // declaration that are not deducible. If so, and the `impl` does not
  519. // actually use all its generic bindings, and will never be matched. This
  520. // should be diagnossed to the user.
  521. bool has_error_in_implicit_pattern = false;
  522. if (impl.implicit_param_patterns_id.has_value()) {
  523. for (auto inst_id :
  524. context.inst_blocks().Get(impl.implicit_param_patterns_id)) {
  525. if (inst_id == SemIR::ErrorInst::InstId) {
  526. has_error_in_implicit_pattern = true;
  527. break;
  528. }
  529. }
  530. }
  531. if (!has_error_in_implicit_pattern) {
  532. DiagnoseUnusedGenericBinding(context, loc_id, implicit_params_loc_id,
  533. impl_id);
  534. }
  535. } else {
  536. auto& stored_impl = context.impls().Get(impl_id);
  537. FinishGenericRedecl(context, stored_impl.generic_id);
  538. }
  539. // Write the impl ID into the ImplDecl.
  540. auto impl_decl =
  541. context.insts().GetAs<SemIR::ImplDecl>(impl.first_owning_decl_id);
  542. CARBON_CHECK(!impl_decl.impl_id.has_value());
  543. impl_decl.impl_id = impl_id;
  544. ReplaceInstBeforeConstantUse(context, impl.first_owning_decl_id, impl_decl);
  545. // For an `extend impl` declaration, mark the impl as extending this `impl`.
  546. if (extend_impl) {
  547. auto& stored_impl_info = context.impls().Get(impl_decl.impl_id);
  548. auto self_type_id =
  549. context.types().GetTypeIdForTypeInstId(stored_impl_info.self_id);
  550. if (self_type_id != SemIR::ErrorInst::TypeId) {
  551. auto constraint_id = impl.constraint_id;
  552. if (stored_impl_info.generic_id.has_value()) {
  553. constraint_id = AddTypeInst<SemIR::SpecificConstant>(
  554. context, SemIR::LocId(constraint_id),
  555. {.type_id = SemIR::TypeType::TypeId,
  556. .inst_id = constraint_id,
  557. .specific_id = context.generics().GetSelfSpecific(
  558. stored_impl_info.generic_id)});
  559. }
  560. if (!ExtendImpl(context, extend_impl->extend_node_id, loc_id,
  561. impl_decl.impl_id, extend_impl->self_type_node_id,
  562. self_type_id, implicit_params_loc_id, constraint_id,
  563. extend_impl->constraint_type_id)) {
  564. // Don't allow the invalid impl to be used.
  565. FillImplWitnessWithErrors(context, stored_impl_info);
  566. }
  567. }
  568. }
  569. // Impl definitions are required in the same file as the declaration. We skip
  570. // this requirement if we've already issued an invalid redeclaration error, or
  571. // there is an error that would prevent the impl from being legal to define.
  572. if (!is_definition) {
  573. auto& stored_impl = context.impls().Get(impl_id);
  574. if (stored_impl.witness_id != SemIR::ErrorInst::InstId) {
  575. context.definitions_required_by_decl().push_back(
  576. stored_impl.latest_decl_id());
  577. }
  578. }
  579. return {impl_id, impl.latest_decl_id()};
  580. }
  581. } // namespace Carbon::Check