impl.cpp 33 KB

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