impl.cpp 35 KB

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