impl.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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/convert.h"
  8. #include "toolchain/check/deduce.h"
  9. #include "toolchain/check/eval.h"
  10. #include "toolchain/check/facet_type.h"
  11. #include "toolchain/check/function.h"
  12. #include "toolchain/check/generic.h"
  13. #include "toolchain/check/import_ref.h"
  14. #include "toolchain/check/inst.h"
  15. #include "toolchain/check/interface.h"
  16. #include "toolchain/check/merge.h"
  17. #include "toolchain/check/name_lookup.h"
  18. #include "toolchain/check/name_scope.h"
  19. #include "toolchain/check/thunk.h"
  20. #include "toolchain/check/type.h"
  21. #include "toolchain/check/type_completion.h"
  22. #include "toolchain/check/type_structure.h"
  23. #include "toolchain/diagnostics/diagnostic_emitter.h"
  24. #include "toolchain/sem_ir/generic.h"
  25. #include "toolchain/sem_ir/ids.h"
  26. #include "toolchain/sem_ir/impl.h"
  27. #include "toolchain/sem_ir/inst.h"
  28. #include "toolchain/sem_ir/typed_insts.h"
  29. namespace Carbon::Check {
  30. // Adds the location of the associated function to a diagnostic.
  31. static auto NoteAssociatedFunction(Context& context, DiagnosticBuilder& builder,
  32. SemIR::FunctionId function_id) -> void {
  33. CARBON_DIAGNOSTIC(AssociatedFunctionHere, Note,
  34. "associated function {0} declared here", SemIR::NameId);
  35. const auto& function = context.functions().Get(function_id);
  36. builder.Note(function.latest_decl_id(), AssociatedFunctionHere,
  37. function.name_id);
  38. }
  39. auto CheckAssociatedFunctionImplementation(
  40. Context& context, SemIR::FunctionType interface_function_type,
  41. SemIR::InstId impl_decl_id, SemIR::TypeId self_type_id,
  42. SemIR::InstId witness_inst_id, bool defer_thunk_definition)
  43. -> SemIR::InstId {
  44. auto impl_function_decl =
  45. context.insts().TryGetAs<SemIR::FunctionDecl>(impl_decl_id);
  46. if (!impl_function_decl) {
  47. if (impl_decl_id != SemIR::ErrorInst::InstId) {
  48. CARBON_DIAGNOSTIC(ImplFunctionWithNonFunction, Error,
  49. "associated function {0} implemented by non-function",
  50. SemIR::NameId);
  51. auto builder = context.emitter().Build(
  52. impl_decl_id, ImplFunctionWithNonFunction,
  53. context.functions().Get(interface_function_type.function_id).name_id);
  54. NoteAssociatedFunction(context, builder,
  55. interface_function_type.function_id);
  56. builder.Emit();
  57. }
  58. return SemIR::ErrorInst::InstId;
  59. }
  60. auto impl_enclosing_specific_id =
  61. context.types()
  62. .GetAs<SemIR::FunctionType>(impl_function_decl->type_id)
  63. .specific_id;
  64. // Map from the specific for the function type to the specific for the
  65. // function signature. The function signature may have additional generic
  66. // parameters.
  67. auto interface_function_specific_id =
  68. GetSelfSpecificForInterfaceMemberWithSelfType(
  69. context, SemIR::LocId(impl_decl_id),
  70. interface_function_type.specific_id,
  71. context.functions()
  72. .Get(interface_function_type.function_id)
  73. .generic_id,
  74. impl_enclosing_specific_id, self_type_id, witness_inst_id);
  75. return BuildThunk(context, interface_function_type.function_id,
  76. interface_function_specific_id, impl_decl_id,
  77. defer_thunk_definition);
  78. }
  79. // Returns true if impl redeclaration parameters match.
  80. static auto CheckImplRedeclParamsMatch(Context& context,
  81. const SemIR::Impl& new_impl,
  82. SemIR::ImplId prev_impl_id) -> bool {
  83. auto& prev_impl = context.impls().Get(prev_impl_id);
  84. // If the parameters aren't the same, then this is not a redeclaration of this
  85. // `impl`. Keep looking for a prior declaration without issuing a diagnostic.
  86. if (!CheckRedeclParamsMatch(context, DeclParams(new_impl),
  87. DeclParams(prev_impl), SemIR::SpecificId::None,
  88. /*diagnose=*/false, /*check_syntax=*/true,
  89. /*check_self=*/true)) {
  90. // NOLINTNEXTLINE(readability-simplify-boolean-expr)
  91. return false;
  92. }
  93. return true;
  94. }
  95. // Returns whether an impl can be redeclared. For example, defined impls
  96. // cannot be redeclared.
  97. static auto IsValidImplRedecl(Context& context, const SemIR::Impl& new_impl,
  98. SemIR::ImplId prev_impl_id) -> bool {
  99. auto& prev_impl = context.impls().Get(prev_impl_id);
  100. // TODO: Following #3763, disallow redeclarations in different scopes.
  101. // Following #4672, disallowing defining non-extern declarations in another
  102. // file.
  103. if (auto import_ref =
  104. context.insts().TryGetAs<SemIR::AnyImportRef>(prev_impl.self_id)) {
  105. // TODO: Handle extern.
  106. CARBON_DIAGNOSTIC(RedeclImportedImpl, Error,
  107. "redeclaration of imported impl");
  108. // TODO: Note imported declaration
  109. context.emitter().Emit(new_impl.latest_decl_id(), RedeclImportedImpl);
  110. return false;
  111. }
  112. if (prev_impl.has_definition_started()) {
  113. // Impls aren't merged in order to avoid generic region lookup into a
  114. // mismatching table.
  115. CARBON_DIAGNOSTIC(ImplRedefinition, Error,
  116. "redefinition of `impl {0} as {1}`", InstIdAsRawType,
  117. InstIdAsRawType);
  118. CARBON_DIAGNOSTIC(ImplPreviousDefinition, Note,
  119. "previous definition was here");
  120. context.emitter()
  121. .Build(new_impl.latest_decl_id(), ImplRedefinition, new_impl.self_id,
  122. new_impl.constraint_id)
  123. .Note(prev_impl.definition_id, ImplPreviousDefinition)
  124. .Emit();
  125. return false;
  126. }
  127. // TODO: Only allow redeclaration in a match_first/impl_priority block.
  128. return true;
  129. }
  130. // Looks for any unused generic bindings. If one is found, it is diagnosed and
  131. // false is returned.
  132. static auto VerifyAllGenericBindingsUsed(Context& context, SemIR::LocId loc_id,
  133. SemIR::LocId implicit_params_loc_id,
  134. SemIR::Impl& impl) -> bool {
  135. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  136. return true;
  137. }
  138. if (!impl.generic_id.has_value()) {
  139. return true;
  140. }
  141. if (impl.implicit_param_patterns_id.has_value()) {
  142. for (auto inst_id :
  143. context.inst_blocks().Get(impl.implicit_param_patterns_id)) {
  144. if (inst_id == SemIR::ErrorInst::InstId) {
  145. // An error was already diagnosed for a generic binding.
  146. return true;
  147. }
  148. }
  149. }
  150. auto deduced_specific_id = DeduceImplArguments(
  151. context, loc_id, impl, context.constant_values().Get(impl.self_id),
  152. impl.interface.specific_id);
  153. if (deduced_specific_id.has_value()) {
  154. // Deduction succeeded, all bindings were used.
  155. return true;
  156. }
  157. CARBON_DIAGNOSTIC(ImplUnusedBinding, Error,
  158. "`impl` with unused generic binding");
  159. // TODO: This location may be incorrect, the binding may be inherited
  160. // from an outer declaration. It would be nice to get the particular
  161. // binding that was undeducible back from DeduceImplArguments here and
  162. // use that.
  163. auto diag_loc_id =
  164. implicit_params_loc_id.has_value() ? implicit_params_loc_id : loc_id;
  165. context.emitter().Emit(diag_loc_id, ImplUnusedBinding);
  166. return false;
  167. }
  168. // Apply an `extend impl` declaration by extending the parent scope with the
  169. // `impl`. If there's an error it is diagnosed and false is returned.
  170. static auto ApplyExtendImplAs(Context& context, SemIR::LocId loc_id,
  171. const SemIR::Impl& impl,
  172. Parse::NodeId extend_node,
  173. SemIR::LocId implicit_params_loc_id) -> bool {
  174. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  175. // TODO: Also handle the parent scope being a mixin.
  176. auto class_scope = TryAsClassScope(context, parent_scope_id);
  177. if (!class_scope) {
  178. if (impl.witness_id != SemIR::ErrorInst::InstId) {
  179. CARBON_DIAGNOSTIC(
  180. ExtendImplOutsideClass, Error,
  181. "`extend impl` can only be used in an interface or class");
  182. context.emitter().Emit(loc_id, ExtendImplOutsideClass);
  183. }
  184. return false;
  185. }
  186. auto& parent_scope = *class_scope->name_scope;
  187. // An error was already diagnosed, but this is `extend impl as` inside a
  188. // class, so propagate the error into the enclosing class scope.
  189. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  190. parent_scope.set_has_error();
  191. return false;
  192. }
  193. if (implicit_params_loc_id.has_value()) {
  194. CARBON_DIAGNOSTIC(ExtendImplForall, Error,
  195. "cannot `extend` a parameterized `impl`");
  196. context.emitter().Emit(extend_node, ExtendImplForall);
  197. parent_scope.set_has_error();
  198. return false;
  199. }
  200. if (!RequireCompleteType(
  201. context, context.types().GetTypeIdForTypeInstId(impl.constraint_id),
  202. SemIR::LocId(impl.constraint_id), [&] {
  203. CARBON_DIAGNOSTIC(ExtendImplAsIncomplete, Error,
  204. "`extend impl as` incomplete facet type {0}",
  205. InstIdAsType);
  206. return context.emitter().Build(impl.latest_decl_id(),
  207. ExtendImplAsIncomplete,
  208. impl.constraint_id);
  209. })) {
  210. parent_scope.set_has_error();
  211. return false;
  212. }
  213. if (!impl.generic_id.has_value()) {
  214. parent_scope.AddExtendedScope(impl.constraint_id);
  215. } else {
  216. auto constraint_id_in_self_specific = AddTypeInst<SemIR::SpecificConstant>(
  217. context, SemIR::LocId(impl.constraint_id),
  218. {.type_id = SemIR::TypeType::TypeId,
  219. .inst_id = impl.constraint_id,
  220. .specific_id = context.generics().GetSelfSpecific(impl.generic_id)});
  221. parent_scope.AddExtendedScope(constraint_id_in_self_specific);
  222. }
  223. return true;
  224. }
  225. auto FindImplId(Context& context, const SemIR::Impl& query_impl)
  226. -> std::variant<RedeclaredImpl, NewImpl> {
  227. // Look for an existing matching declaration.
  228. auto lookup_bucket_ref = context.impls().GetOrAddLookupBucket(query_impl);
  229. // TODO: Detect two impl declarations with the same self type and interface,
  230. // and issue an error if they don't match.
  231. for (auto prev_impl_id : lookup_bucket_ref) {
  232. if (CheckImplRedeclParamsMatch(context, query_impl, prev_impl_id)) {
  233. if (IsValidImplRedecl(context, query_impl, prev_impl_id)) {
  234. return RedeclaredImpl{.prev_impl_id = prev_impl_id};
  235. } else {
  236. // IsValidImplRedecl() has issued a diagnostic, take care to avoid
  237. // generating more diagnostics for this declaration.
  238. return NewImpl{.lookup_bucket = lookup_bucket_ref,
  239. .find_had_error = true};
  240. }
  241. break;
  242. }
  243. }
  244. return NewImpl{.lookup_bucket = lookup_bucket_ref, .find_had_error = false};
  245. }
  246. // Sets the `ImplId` in the `ImplWitnessTable`.
  247. static auto AssignImplIdInWitness(Context& context, SemIR::ImplId impl_id,
  248. SemIR::InstId witness_id) -> void {
  249. if (witness_id == SemIR::ErrorInst::InstId) {
  250. return;
  251. }
  252. auto witness = context.insts().GetAs<SemIR::ImplWitness>(witness_id);
  253. auto witness_table =
  254. context.insts().GetAs<SemIR::ImplWitnessTable>(witness.witness_table_id);
  255. witness_table.impl_id = impl_id;
  256. // Note: The `ImplWitnessTable` instruction is `Unique`, so while this marks
  257. // the instruction as being a dependent instruction of a generic impl, it will
  258. // not be substituted into the eval block.
  259. ReplaceInstBeforeConstantUse(context, witness.witness_table_id,
  260. witness_table);
  261. }
  262. auto AddImpl(Context& context, const SemIR::Impl& impl,
  263. SemIR::ImplStore::LookupBucketRef lookup_bucket,
  264. Parse::NodeId extend_node, SemIR::LocId implicit_params_loc_id)
  265. -> SemIR::ImplId {
  266. auto impl_decl_id = impl.latest_decl_id();
  267. // From here on, use the `Impl` from the `ImplStore` instead of `impl` in
  268. // order to make and see any changes to the `Impl`.
  269. auto impl_id = context.impls().Add(impl);
  270. lookup_bucket.push_back(impl_id);
  271. AssignImplIdInWitness(context, impl_id, impl.witness_id);
  272. auto& stored_impl = context.impls().Get(impl_id);
  273. // Look to see if there are any generic bindings on the `impl` declaration
  274. // that are not deducible. If so, and the `impl` does not actually use all
  275. // its generic bindings, and will never be matched. This should be
  276. // diagnossed to the user.
  277. if (!VerifyAllGenericBindingsUsed(context, SemIR::LocId(impl_decl_id),
  278. implicit_params_loc_id, stored_impl)) {
  279. FillImplWitnessWithErrors(context, stored_impl);
  280. }
  281. if (extend_node.has_value()) {
  282. if (!ApplyExtendImplAs(context, SemIR::LocId(impl_decl_id), stored_impl,
  283. extend_node, implicit_params_loc_id)) {
  284. FillImplWitnessWithErrors(context, stored_impl);
  285. }
  286. }
  287. return impl_id;
  288. }
  289. // Returns whether the `LookupImplWitness` of `witness_id` matches `interface`.
  290. static auto WitnessQueryMatchesInterface(
  291. Context& context, SemIR::InstId witness_id,
  292. const SemIR::SpecificInterface& interface) -> bool {
  293. auto lookup = context.insts().GetAs<SemIR::LookupImplWitness>(witness_id);
  294. return interface ==
  295. context.specific_interfaces().Get(lookup.query_specific_interface_id);
  296. }
  297. auto AddImplWitnessForDeclaration(Context& context, SemIR::LocId loc_id,
  298. const SemIR::Impl& impl,
  299. SemIR::SpecificId self_specific_id)
  300. -> SemIR::InstId {
  301. auto facet_type_id =
  302. context.types().GetTypeIdForTypeInstId(impl.constraint_id);
  303. CARBON_CHECK(facet_type_id != SemIR::ErrorInst::TypeId);
  304. auto facet_type = context.types().GetAs<SemIR::FacetType>(facet_type_id);
  305. const auto& facet_type_info =
  306. context.facet_types().Get(facet_type.facet_type_id);
  307. // An iterator over the rewrite_constraints where the LHS of the rewrite names
  308. // a member of the `impl.interface`. This filters out rewrites of names
  309. // from other interfaces, as they do not set values in the witness table.
  310. auto rewrites_into_interface_to_witness = llvm::make_filter_range(
  311. facet_type_info.rewrite_constraints,
  312. [&](const SemIR::FacetTypeInfo::RewriteConstraint& rewrite) {
  313. auto access = context.insts().GetAs<SemIR::ImplWitnessAccess>(
  314. GetImplWitnessAccessWithoutSubstitution(context, rewrite.lhs_id));
  315. return WitnessQueryMatchesInterface(context, access.witness_id,
  316. impl.interface);
  317. });
  318. if (rewrites_into_interface_to_witness.empty()) {
  319. // The witness table is not needed until the definition. Make a placeholder
  320. // for the declaration.
  321. auto witness_table_inst_id = AddInst<SemIR::ImplWitnessTable>(
  322. context, loc_id,
  323. {.elements_id = context.inst_blocks().AddPlaceholder(),
  324. .impl_id = SemIR::ImplId::None});
  325. return AddInst<SemIR::ImplWitness>(
  326. context, loc_id,
  327. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  328. .witness_table_id = witness_table_inst_id,
  329. .specific_id = self_specific_id});
  330. }
  331. const auto& interface = context.interfaces().Get(impl.interface.interface_id);
  332. if (!interface.is_complete()) {
  333. // This is a declaration with rewrite constraints into `.Self`, but the
  334. // interface is not complete. Those rewrites have already been diagnosed as
  335. // an error in their member access.
  336. return SemIR::ErrorInst::InstId;
  337. }
  338. auto assoc_entities =
  339. context.inst_blocks().Get(interface.associated_entities_id);
  340. // TODO: When this function is used for things other than just impls, may want
  341. // to only load the specific associated entities that are mentioned in rewrite
  342. // rules.
  343. for (auto decl_id : assoc_entities) {
  344. LoadImportRef(context, decl_id);
  345. }
  346. SemIR::InstId witness_inst_id = SemIR::InstId::None;
  347. llvm::MutableArrayRef<SemIR::InstId> table;
  348. {
  349. auto elements_id =
  350. context.inst_blocks().AddUninitialized(assoc_entities.size());
  351. table = context.inst_blocks().GetMutable(elements_id);
  352. for (auto& uninit : table) {
  353. uninit = SemIR::InstId::ImplWitnessTablePlaceholder;
  354. }
  355. auto witness_table_inst_id = AddInst<SemIR::ImplWitnessTable>(
  356. context, loc_id,
  357. {.elements_id = elements_id, .impl_id = SemIR::ImplId::None});
  358. witness_inst_id = AddInst<SemIR::ImplWitness>(
  359. context, loc_id,
  360. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  361. .witness_table_id = witness_table_inst_id,
  362. .specific_id = self_specific_id});
  363. }
  364. for (auto rewrite : rewrites_into_interface_to_witness) {
  365. auto access = context.insts().GetAs<SemIR::ImplWitnessAccess>(
  366. GetImplWitnessAccessWithoutSubstitution(context, rewrite.lhs_id));
  367. auto& table_entry = table[access.index.index];
  368. if (table_entry == SemIR::ErrorInst::InstId) {
  369. // Don't overwrite an error value. This prioritizes not generating
  370. // multiple errors for one associated constant over picking a value
  371. // for it to use to attempt recovery.
  372. continue;
  373. }
  374. auto rewrite_inst_id = rewrite.rhs_id;
  375. if (rewrite_inst_id == SemIR::ErrorInst::InstId) {
  376. table_entry = SemIR::ErrorInst::InstId;
  377. continue;
  378. }
  379. auto decl_id = context.constant_values().GetConstantInstId(
  380. assoc_entities[access.index.index]);
  381. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  382. if (decl_id == SemIR::ErrorInst::InstId) {
  383. table_entry = SemIR::ErrorInst::InstId;
  384. continue;
  385. }
  386. auto assoc_constant_decl =
  387. context.insts().TryGetAs<SemIR::AssociatedConstantDecl>(decl_id);
  388. if (!assoc_constant_decl) {
  389. auto type_id = context.insts().Get(decl_id).type_id();
  390. auto type_inst = context.types().GetAsInst(type_id);
  391. auto fn_type = type_inst.As<SemIR::FunctionType>();
  392. const auto& fn = context.functions().Get(fn_type.function_id);
  393. CARBON_DIAGNOSTIC(RewriteForAssociatedFunction, Error,
  394. "rewrite specified for associated function {0}",
  395. SemIR::NameId);
  396. context.emitter().Emit(impl.constraint_id, RewriteForAssociatedFunction,
  397. fn.name_id);
  398. table_entry = SemIR::ErrorInst::InstId;
  399. continue;
  400. }
  401. // FacetTypes resolution disallows two rewrites to the same associated
  402. // constant, so we won't ever have a facet write twice to the same position
  403. // in the witness table.
  404. CARBON_CHECK(table_entry == SemIR::InstId::ImplWitnessTablePlaceholder);
  405. // If the associated constant has a symbolic type, convert the rewrite
  406. // value to that type now we know the value of `Self`.
  407. SemIR::TypeId assoc_const_type_id = assoc_constant_decl->type_id;
  408. if (assoc_const_type_id.is_symbolic()) {
  409. // Get the type of the associated constant in this interface with this
  410. // value for `Self`.
  411. assoc_const_type_id = GetTypeForSpecificAssociatedEntity(
  412. context, SemIR::LocId(impl.constraint_id), impl.interface.specific_id,
  413. decl_id, context.types().GetTypeIdForTypeInstId(impl.self_id),
  414. witness_inst_id);
  415. // Perform the conversion of the value to the type. We skipped this when
  416. // forming the facet type because the type of the associated constant
  417. // was symbolic.
  418. auto converted_inst_id =
  419. ConvertToValueOfType(context, SemIR::LocId(impl.constraint_id),
  420. rewrite_inst_id, assoc_const_type_id);
  421. // Canonicalize the converted constant value.
  422. converted_inst_id =
  423. context.constant_values().GetConstantInstId(converted_inst_id);
  424. // The result of conversion can be non-constant even if the original
  425. // value was constant.
  426. if (converted_inst_id.has_value()) {
  427. rewrite_inst_id = converted_inst_id;
  428. } else {
  429. const auto& assoc_const = context.associated_constants().Get(
  430. assoc_constant_decl->assoc_const_id);
  431. CARBON_DIAGNOSTIC(
  432. AssociatedConstantNotConstantAfterConversion, Error,
  433. "associated constant {0} given value {1} that is not constant "
  434. "after conversion to {2}",
  435. SemIR::NameId, InstIdAsConstant, SemIR::TypeId);
  436. context.emitter().Emit(
  437. impl.constraint_id, AssociatedConstantNotConstantAfterConversion,
  438. assoc_const.name_id, rewrite_inst_id, assoc_const_type_id);
  439. rewrite_inst_id = SemIR::ErrorInst::InstId;
  440. }
  441. }
  442. CARBON_CHECK(rewrite_inst_id == context.constant_values().GetConstantInstId(
  443. rewrite_inst_id),
  444. "Rewritten value for associated constant is not canonical.");
  445. table_entry = AddInst<SemIR::ImplWitnessAssociatedConstant>(
  446. context, loc_id,
  447. {.type_id = context.insts().Get(rewrite_inst_id).type_id(),
  448. .inst_id = rewrite_inst_id});
  449. }
  450. return witness_inst_id;
  451. }
  452. auto ImplWitnessStartDefinition(Context& context, SemIR::Impl& impl) -> void {
  453. CARBON_CHECK(impl.is_being_defined());
  454. CARBON_CHECK(impl.witness_id.has_value());
  455. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  456. return;
  457. }
  458. if (!RequireCompleteType(
  459. context, context.types().GetTypeIdForTypeInstId(impl.constraint_id),
  460. SemIR::LocId(impl.constraint_id), [&] {
  461. CARBON_DIAGNOSTIC(ImplAsIncompleteFacetTypeDefinition, Error,
  462. "definition of impl as incomplete facet type {0}",
  463. InstIdAsType);
  464. return context.emitter().Build(SemIR::LocId(impl.latest_decl_id()),
  465. ImplAsIncompleteFacetTypeDefinition,
  466. impl.constraint_id);
  467. })) {
  468. FillImplWitnessWithErrors(context, impl);
  469. return;
  470. }
  471. const auto& interface = context.interfaces().Get(impl.interface.interface_id);
  472. auto assoc_entities =
  473. context.inst_blocks().Get(interface.associated_entities_id);
  474. for (auto decl_id : assoc_entities) {
  475. LoadImportRef(context, decl_id);
  476. }
  477. auto witness = context.insts().GetAs<SemIR::ImplWitness>(impl.witness_id);
  478. auto witness_table =
  479. context.insts().GetAs<SemIR::ImplWitnessTable>(witness.witness_table_id);
  480. auto witness_block =
  481. context.inst_blocks().GetMutable(witness_table.elements_id);
  482. // The impl declaration may have created a placeholder witness table, or a
  483. // full witness table. We can detect that the witness table is a placeholder
  484. // table if it's not the `Empty` id, but it is empty still. If it was a
  485. // placeholder, we can replace the placeholder here with a table of the proper
  486. // size, since the interface must be complete for the impl definition.
  487. bool witness_table_is_placeholder =
  488. witness_table.elements_id != SemIR::InstBlockId::Empty &&
  489. witness_block.empty();
  490. if (witness_table_is_placeholder) {
  491. // TODO: Since our `empty_table` repeats the same value throughout, we could
  492. // skip an allocation here if there was a `ReplacePlaceholder` function that
  493. // took a size and value instead of an array of values.
  494. llvm::SmallVector<SemIR::InstId> empty_table(
  495. assoc_entities.size(), SemIR::InstId::ImplWitnessTablePlaceholder);
  496. context.inst_blocks().ReplacePlaceholder(witness_table.elements_id,
  497. empty_table);
  498. witness_block = context.inst_blocks().GetMutable(witness_table.elements_id);
  499. }
  500. // Check we have a value for all non-function associated constants in the
  501. // witness.
  502. for (auto [assoc_entity, witness_value] :
  503. llvm::zip_equal(assoc_entities, witness_block)) {
  504. auto decl_id = context.constant_values().GetConstantInstId(assoc_entity);
  505. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  506. if (auto decl =
  507. context.insts().TryGetAs<SemIR::AssociatedConstantDecl>(decl_id)) {
  508. if (witness_value == SemIR::InstId::ImplWitnessTablePlaceholder) {
  509. CARBON_DIAGNOSTIC(ImplAssociatedConstantNeedsValue, Error,
  510. "associated constant {0} not given a value in impl "
  511. "of interface {1}",
  512. SemIR::NameId, SemIR::NameId);
  513. CARBON_DIAGNOSTIC(AssociatedConstantHere, Note,
  514. "associated constant declared here");
  515. context.emitter()
  516. .Build(impl.definition_id, ImplAssociatedConstantNeedsValue,
  517. context.associated_constants()
  518. .Get(decl->assoc_const_id)
  519. .name_id,
  520. interface.name_id)
  521. .Note(assoc_entity, AssociatedConstantHere)
  522. .Emit();
  523. witness_value = SemIR::ErrorInst::InstId;
  524. }
  525. }
  526. }
  527. }
  528. // Adds functions to the witness that the specified impl implements the given
  529. // interface.
  530. auto FinishImplWitness(Context& context, const SemIR::Impl& impl) -> void {
  531. CARBON_CHECK(impl.is_being_defined());
  532. CARBON_CHECK(impl.witness_id.has_value());
  533. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  534. return;
  535. }
  536. auto witness = context.insts().GetAs<SemIR::ImplWitness>(impl.witness_id);
  537. auto witness_table =
  538. context.insts().GetAs<SemIR::ImplWitnessTable>(witness.witness_table_id);
  539. auto witness_block =
  540. context.inst_blocks().GetMutable(witness_table.elements_id);
  541. auto& impl_scope = context.name_scopes().Get(impl.scope_id);
  542. auto self_type_id = context.types().GetTypeIdForTypeInstId(impl.self_id);
  543. const auto& interface = context.interfaces().Get(impl.interface.interface_id);
  544. auto assoc_entities =
  545. context.inst_blocks().Get(interface.associated_entities_id);
  546. llvm::SmallVector<SemIR::InstId> used_decl_ids;
  547. for (auto [assoc_entity, witness_value] :
  548. llvm::zip_equal(assoc_entities, witness_block)) {
  549. auto decl_id =
  550. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  551. context.sem_ir(), impl.interface.specific_id, assoc_entity));
  552. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  553. auto decl = context.insts().Get(decl_id);
  554. CARBON_KIND_SWITCH(decl) {
  555. case CARBON_KIND(SemIR::StructValue struct_value): {
  556. if (struct_value.type_id == SemIR::ErrorInst::TypeId) {
  557. witness_value = SemIR::ErrorInst::InstId;
  558. break;
  559. }
  560. auto type_inst = context.types().GetAsInst(struct_value.type_id);
  561. auto fn_type = type_inst.TryAs<SemIR::FunctionType>();
  562. if (!fn_type) {
  563. CARBON_FATAL("Unexpected type: {0}", type_inst);
  564. }
  565. auto& fn = context.functions().Get(fn_type->function_id);
  566. auto lookup_result =
  567. LookupNameInExactScope(context, SemIR::LocId(decl_id), fn.name_id,
  568. impl.scope_id, impl_scope);
  569. if (lookup_result.is_found()) {
  570. used_decl_ids.push_back(lookup_result.target_inst_id());
  571. witness_value = CheckAssociatedFunctionImplementation(
  572. context, *fn_type, lookup_result.target_inst_id(), self_type_id,
  573. impl.witness_id, /*defer_thunk_definition=*/true);
  574. } else {
  575. CARBON_DIAGNOSTIC(
  576. ImplMissingFunction, Error,
  577. "missing implementation of {0} in impl of interface {1}",
  578. SemIR::NameId, SemIR::NameId);
  579. auto builder =
  580. context.emitter().Build(impl.definition_id, ImplMissingFunction,
  581. fn.name_id, interface.name_id);
  582. NoteAssociatedFunction(context, builder, fn_type->function_id);
  583. builder.Emit();
  584. witness_value = SemIR::ErrorInst::InstId;
  585. }
  586. break;
  587. }
  588. case SemIR::AssociatedConstantDecl::Kind: {
  589. // These are set to their final values already.
  590. break;
  591. }
  592. default:
  593. CARBON_CHECK(decl_id == SemIR::ErrorInst::InstId,
  594. "Unexpected kind of associated entity {0}", decl);
  595. witness_value = SemIR::ErrorInst::InstId;
  596. break;
  597. }
  598. }
  599. // TODO: Diagnose if any declarations in the impl are not in used_decl_ids.
  600. }
  601. auto FillImplWitnessWithErrors(Context& context, SemIR::Impl& impl) -> void {
  602. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  603. return;
  604. }
  605. auto witness = context.insts().GetAs<SemIR::ImplWitness>(impl.witness_id);
  606. auto witness_table =
  607. context.insts().GetAs<SemIR::ImplWitnessTable>(witness.witness_table_id);
  608. auto witness_block =
  609. context.inst_blocks().GetMutable(witness_table.elements_id);
  610. for (auto& elem : witness_block) {
  611. if (elem == SemIR::InstId::ImplWitnessTablePlaceholder) {
  612. elem = SemIR::ErrorInst::InstId;
  613. }
  614. }
  615. impl.witness_id = SemIR::ErrorInst::InstId;
  616. }
  617. auto IsImplEffectivelyFinal(Context& context, const SemIR::Impl& impl) -> bool {
  618. return impl.is_final ||
  619. (context.constant_values().Get(impl.self_id).is_concrete() &&
  620. context.constant_values().Get(impl.constraint_id).is_concrete());
  621. }
  622. auto CheckConstraintIsInterface(Context& context, SemIR::InstId impl_decl_id,
  623. SemIR::TypeInstId constraint_id)
  624. -> SemIR::SpecificInterface {
  625. auto facet_type_id = context.types().GetTypeIdForTypeInstId(constraint_id);
  626. if (facet_type_id == SemIR::ErrorInst::TypeId) {
  627. return SemIR::SpecificInterface::None;
  628. }
  629. auto facet_type = context.types().TryGetAs<SemIR::FacetType>(facet_type_id);
  630. if (!facet_type) {
  631. CARBON_DIAGNOSTIC(ImplAsNonFacetType, Error, "impl as non-facet type {0}",
  632. InstIdAsType);
  633. context.emitter().Emit(impl_decl_id, ImplAsNonFacetType, constraint_id);
  634. return SemIR::SpecificInterface::None;
  635. }
  636. auto identified_id = RequireIdentifiedFacetType(
  637. context, SemIR::LocId(constraint_id), *facet_type, [&] {
  638. CARBON_DIAGNOSTIC(ImplOfUnidentifiedFacetType, Error,
  639. "facet type {0} cannot be identified in `impl as`",
  640. InstIdAsType);
  641. return context.emitter().Build(
  642. impl_decl_id, ImplOfUnidentifiedFacetType, constraint_id);
  643. });
  644. if (!identified_id.has_value()) {
  645. return SemIR::SpecificInterface::None;
  646. }
  647. const auto& identified = context.identified_facet_types().Get(identified_id);
  648. if (!identified.is_valid_impl_as_target()) {
  649. CARBON_DIAGNOSTIC(ImplOfNotOneInterface, Error,
  650. "impl as {0} interfaces, expected 1", int);
  651. context.emitter().Emit(impl_decl_id, ImplOfNotOneInterface,
  652. identified.num_interfaces_to_impl());
  653. return SemIR::SpecificInterface::None;
  654. }
  655. return identified.impl_as_target_interface();
  656. }
  657. } // namespace Carbon::Check