impl.cpp 35 KB

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