impl.cpp 26 KB

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