impl.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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. 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);
  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(context, *facet_type, [&] {
  275. CARBON_DIAGNOSTIC(ImplOfUnidentifiedFacetType, Error,
  276. "facet type {0} cannot be identified in `impl as`",
  277. InstIdAsType);
  278. return context.emitter().Build(impl_decl_id, ImplOfUnidentifiedFacetType,
  279. constraint_id);
  280. });
  281. if (!identified_id.has_value()) {
  282. return SemIR::SpecificInterface::None;
  283. }
  284. const auto& identified = context.identified_facet_types().Get(identified_id);
  285. if (!identified.is_valid_impl_as_target()) {
  286. CARBON_DIAGNOSTIC(ImplOfNotOneInterface, Error,
  287. "impl as {0} interfaces, expected 1", int);
  288. context.emitter().Emit(impl_decl_id, ImplOfNotOneInterface,
  289. identified.num_interfaces_to_impl());
  290. return SemIR::SpecificInterface::None;
  291. }
  292. return identified.impl_as_target_interface();
  293. }
  294. // Returns true if impl redeclaration parameters match.
  295. static auto CheckImplRedeclParamsMatch(Context& context, SemIR::Impl& new_impl,
  296. SemIR::ImplId prev_impl_id) -> bool {
  297. auto& prev_impl = context.impls().Get(prev_impl_id);
  298. // If the parameters aren't the same, then this is not a redeclaration of this
  299. // `impl`. Keep looking for a prior declaration without issuing a diagnostic.
  300. if (!CheckRedeclParamsMatch(context, DeclParams(new_impl),
  301. DeclParams(prev_impl), SemIR::SpecificId::None,
  302. /*diagnose=*/false, /*check_syntax=*/true,
  303. /*check_self=*/true)) {
  304. // NOLINTNEXTLINE(readability-simplify-boolean-expr)
  305. return false;
  306. }
  307. return true;
  308. }
  309. // Returns whether an impl can be redeclared. For example, defined impls
  310. // cannot be redeclared.
  311. static auto IsValidImplRedecl(Context& context, SemIR::Impl& new_impl,
  312. SemIR::ImplId prev_impl_id) -> bool {
  313. auto& prev_impl = context.impls().Get(prev_impl_id);
  314. // TODO: Following #3763, disallow redeclarations in different scopes.
  315. // Following #4672, disallowing defining non-extern declarations in another
  316. // file.
  317. if (auto import_ref =
  318. context.insts().TryGetAs<SemIR::AnyImportRef>(prev_impl.self_id)) {
  319. // TODO: Handle extern.
  320. CARBON_DIAGNOSTIC(RedeclImportedImpl, Error,
  321. "redeclaration of imported impl");
  322. // TODO: Note imported declaration
  323. context.emitter().Emit(new_impl.latest_decl_id(), RedeclImportedImpl);
  324. return false;
  325. }
  326. if (prev_impl.has_definition_started()) {
  327. // Impls aren't merged in order to avoid generic region lookup into a
  328. // mismatching table.
  329. CARBON_DIAGNOSTIC(ImplRedefinition, Error,
  330. "redefinition of `impl {0} as {1}`", InstIdAsRawType,
  331. InstIdAsRawType);
  332. CARBON_DIAGNOSTIC(ImplPreviousDefinition, Note,
  333. "previous definition was here");
  334. context.emitter()
  335. .Build(new_impl.latest_decl_id(), ImplRedefinition, new_impl.self_id,
  336. new_impl.constraint_id)
  337. .Note(prev_impl.definition_id, ImplPreviousDefinition)
  338. .Emit();
  339. return false;
  340. }
  341. // TODO: Only allow redeclaration in a match_first/impl_priority block.
  342. return true;
  343. }
  344. static auto DiagnoseExtendImplOutsideClass(Context& context,
  345. SemIR::LocId loc_id) -> void {
  346. CARBON_DIAGNOSTIC(ExtendImplOutsideClass, Error,
  347. "`extend impl` can only be used in a class");
  348. context.emitter().Emit(loc_id, ExtendImplOutsideClass);
  349. }
  350. // If the specified name scope corresponds to a class, returns the corresponding
  351. // class declaration.
  352. // TODO: Should this be somewhere more central?
  353. static auto TryAsClassScope(Context& context, SemIR::NameScopeId scope_id)
  354. -> std::optional<SemIR::ClassDecl> {
  355. if (!scope_id.has_value()) {
  356. return std::nullopt;
  357. }
  358. auto& scope = context.name_scopes().Get(scope_id);
  359. if (!scope.inst_id().has_value()) {
  360. return std::nullopt;
  361. }
  362. return context.insts().TryGetAs<SemIR::ClassDecl>(scope.inst_id());
  363. }
  364. auto GetImplDefaultSelfType(Context& context) -> SemIR::TypeId {
  365. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  366. if (auto class_decl = TryAsClassScope(context, parent_scope_id)) {
  367. return context.classes().Get(class_decl->class_id).self_type_id;
  368. }
  369. // TODO: This is also valid in a mixin.
  370. return SemIR::TypeId::None;
  371. }
  372. // Process an `extend impl` declaration by extending the impl scope with the
  373. // `impl`'s scope.
  374. static auto ExtendImpl(Context& context, Parse::NodeId extend_node,
  375. SemIR::LocId loc_id, SemIR::ImplId impl_id,
  376. Parse::NodeId self_type_node_id,
  377. SemIR::TypeId self_type_id,
  378. SemIR::LocId implicit_params_loc_id,
  379. SemIR::TypeInstId constraint_type_inst_id,
  380. SemIR::TypeId constraint_type_id) -> bool {
  381. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  382. if (!parent_scope_id.has_value()) {
  383. DiagnoseExtendImplOutsideClass(context, loc_id);
  384. return false;
  385. }
  386. // TODO: This is also valid in a mixin.
  387. if (!TryAsClassScope(context, parent_scope_id)) {
  388. DiagnoseExtendImplOutsideClass(context, loc_id);
  389. return false;
  390. }
  391. auto& parent_scope = context.name_scopes().Get(parent_scope_id);
  392. if (implicit_params_loc_id.has_value()) {
  393. CARBON_DIAGNOSTIC(ExtendImplForall, Error,
  394. "cannot `extend` a parameterized `impl`");
  395. context.emitter().Emit(extend_node, ExtendImplForall);
  396. parent_scope.set_has_error();
  397. return false;
  398. }
  399. const auto& impl = context.impls().Get(impl_id);
  400. if (context.parse_tree().node_kind(self_type_node_id) ==
  401. Parse::NodeKind::ImplTypeAs) {
  402. CARBON_DIAGNOSTIC(ExtendImplSelfAs, Error,
  403. "cannot `extend` an `impl` with an explicit self type");
  404. auto diag = context.emitter().Build(extend_node, ExtendImplSelfAs);
  405. // If the explicit self type is not the default, just bail out.
  406. if (self_type_id != GetImplDefaultSelfType(context)) {
  407. diag.Emit();
  408. parent_scope.set_has_error();
  409. return false;
  410. }
  411. // The explicit self type is the same as the default self type, so suggest
  412. // removing it and recover as if it were not present.
  413. if (auto self_as =
  414. context.parse_tree_and_subtrees().ExtractAs<Parse::ImplTypeAs>(
  415. self_type_node_id)) {
  416. CARBON_DIAGNOSTIC(ExtendImplSelfAsDefault, Note,
  417. "remove the explicit `Self` type here");
  418. diag.Note(self_as->type_expr, ExtendImplSelfAsDefault);
  419. }
  420. diag.Emit();
  421. }
  422. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  423. parent_scope.set_has_error();
  424. } else {
  425. bool is_complete = RequireCompleteType(
  426. context, constraint_type_id, SemIR::LocId(constraint_type_inst_id),
  427. [&] {
  428. CARBON_DIAGNOSTIC(ExtendImplAsIncomplete, Error,
  429. "`extend impl as` incomplete facet type {0}",
  430. InstIdAsType);
  431. return context.emitter().Build(impl.latest_decl_id(),
  432. ExtendImplAsIncomplete,
  433. constraint_type_inst_id);
  434. });
  435. if (!is_complete) {
  436. parent_scope.set_has_error();
  437. return false;
  438. }
  439. }
  440. parent_scope.AddExtendedScope(constraint_type_inst_id);
  441. return true;
  442. }
  443. // Diagnoses when an impl has an unused binding.
  444. static auto DiagnoseUnusedGenericBinding(Context& context, SemIR::LocId loc_id,
  445. SemIR::LocId implicit_params_loc_id,
  446. SemIR::ImplId impl_id) -> void {
  447. auto& impl = context.impls().Get(impl_id);
  448. if (!impl.generic_id.has_value() ||
  449. impl.witness_id == SemIR::ErrorInst::InstId) {
  450. return;
  451. }
  452. auto deduced_specific_id = DeduceImplArguments(
  453. context, loc_id, impl, context.constant_values().Get(impl.self_id),
  454. impl.interface.specific_id);
  455. if (deduced_specific_id.has_value()) {
  456. // Deduction succeeded, all bindings were used.
  457. return;
  458. }
  459. CARBON_DIAGNOSTIC(ImplUnusedBinding, Error,
  460. "`impl` with unused generic binding");
  461. // TODO: This location may be incorrect, the binding may be inherited
  462. // from an outer declaration. It would be nice to get the particular
  463. // binding that was undeducible back from DeduceImplArguments here and
  464. // use that.
  465. auto diag_loc_id =
  466. implicit_params_loc_id.has_value() ? implicit_params_loc_id : loc_id;
  467. context.emitter().Emit(diag_loc_id, ImplUnusedBinding);
  468. // Don't try to match the impl at all, save us work and possible future
  469. // diagnostics.
  470. FillImplWitnessWithErrors(context, context.impls().Get(impl_id));
  471. }
  472. auto StartImplDecl(Context& context, SemIR::LocId loc_id,
  473. SemIR::LocId implicit_params_loc_id, SemIR::Impl impl,
  474. bool is_definition,
  475. std::optional<ExtendImplDecl> extend_impl)
  476. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  477. auto impl_id = SemIR::ImplId::None;
  478. // Add the impl declaration.
  479. auto lookup_bucket_ref = context.impls().GetOrAddLookupBucket(impl);
  480. // TODO: Detect two impl declarations with the same self type and interface,
  481. // and issue an error if they don't match.
  482. for (auto prev_impl_id : lookup_bucket_ref) {
  483. if (CheckImplRedeclParamsMatch(context, impl, prev_impl_id)) {
  484. if (IsValidImplRedecl(context, impl, prev_impl_id)) {
  485. impl_id = prev_impl_id;
  486. } else {
  487. // IsValidImplRedecl() has issued a diagnostic, avoid generating more
  488. // diagnostics for this declaration.
  489. impl.witness_id = SemIR::ErrorInst::InstId;
  490. }
  491. break;
  492. }
  493. }
  494. // Create a new impl if this isn't a valid redeclaration.
  495. if (!impl_id.has_value()) {
  496. impl.generic_id = BuildGeneric(context, impl.latest_decl_id());
  497. if (impl.witness_id != SemIR::ErrorInst::InstId) {
  498. if (impl.interface.interface_id.has_value()) {
  499. impl.witness_id =
  500. ImplWitnessForDeclaration(context, impl, is_definition);
  501. } else {
  502. impl.witness_id = SemIR::ErrorInst::InstId;
  503. // TODO: We might also want to mark that the name scope for the impl has
  504. // an error -- at least once we start making name lookups within the
  505. // impl also look into the facet (eg, so you can name associated
  506. // constants from within the impl).
  507. }
  508. }
  509. FinishGenericDecl(context, SemIR::LocId(impl.latest_decl_id()),
  510. impl.generic_id);
  511. // From here on, use the `Impl` from the `ImplStore` instead of `impl`
  512. // in order to make and see any changes to the `Impl`.
  513. impl_id = context.impls().Add(impl);
  514. lookup_bucket_ref.push_back(impl_id);
  515. AssignImplIdInWitness(context, impl_id, impl.witness_id);
  516. // Looking to see if there are any generic bindings on the `impl`
  517. // declaration that are not deducible. If so, and the `impl` does not
  518. // actually use all its generic bindings, and will never be matched. This
  519. // should be diagnossed to the user.
  520. bool has_error_in_implicit_pattern = false;
  521. if (impl.implicit_param_patterns_id.has_value()) {
  522. for (auto inst_id :
  523. context.inst_blocks().Get(impl.implicit_param_patterns_id)) {
  524. if (inst_id == SemIR::ErrorInst::InstId) {
  525. has_error_in_implicit_pattern = true;
  526. break;
  527. }
  528. }
  529. }
  530. if (!has_error_in_implicit_pattern) {
  531. DiagnoseUnusedGenericBinding(context, loc_id, implicit_params_loc_id,
  532. impl_id);
  533. }
  534. } else {
  535. auto& stored_impl = context.impls().Get(impl_id);
  536. FinishGenericRedecl(context, stored_impl.generic_id);
  537. }
  538. // Write the impl ID into the ImplDecl.
  539. auto impl_decl =
  540. context.insts().GetAs<SemIR::ImplDecl>(impl.first_owning_decl_id);
  541. CARBON_CHECK(!impl_decl.impl_id.has_value());
  542. impl_decl.impl_id = impl_id;
  543. ReplaceInstBeforeConstantUse(context, impl.first_owning_decl_id, impl_decl);
  544. // For an `extend impl` declaration, mark the impl as extending this `impl`.
  545. if (extend_impl) {
  546. auto& stored_impl_info = context.impls().Get(impl_decl.impl_id);
  547. auto self_type_id =
  548. context.types().GetTypeIdForTypeInstId(stored_impl_info.self_id);
  549. if (self_type_id != SemIR::ErrorInst::TypeId) {
  550. auto constraint_id = impl.constraint_id;
  551. if (stored_impl_info.generic_id.has_value()) {
  552. constraint_id = AddTypeInst<SemIR::SpecificConstant>(
  553. context, SemIR::LocId(constraint_id),
  554. {.type_id = SemIR::TypeType::TypeId,
  555. .inst_id = constraint_id,
  556. .specific_id = context.generics().GetSelfSpecific(
  557. stored_impl_info.generic_id)});
  558. }
  559. if (!ExtendImpl(context, extend_impl->extend_node_id, loc_id,
  560. impl_decl.impl_id, extend_impl->self_type_node_id,
  561. self_type_id, implicit_params_loc_id, constraint_id,
  562. extend_impl->constraint_type_id)) {
  563. // Don't allow the invalid impl to be used.
  564. FillImplWitnessWithErrors(context, stored_impl_info);
  565. }
  566. }
  567. }
  568. // Impl definitions are required in the same file as the declaration. We skip
  569. // this requirement if we've already issued an invalid redeclaration error, or
  570. // there is an error that would prevent the impl from being legal to define.
  571. if (!is_definition) {
  572. auto& stored_impl = context.impls().Get(impl_id);
  573. if (stored_impl.witness_id != SemIR::ErrorInst::InstId) {
  574. context.definitions_required_by_decl().push_back(
  575. stored_impl.latest_decl_id());
  576. }
  577. }
  578. return {impl_id, impl.latest_decl_id()};
  579. }
  580. } // namespace Carbon::Check