impl_lookup.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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_lookup.h"
  5. #include <algorithm>
  6. #include <functional>
  7. #include <utility>
  8. #include <variant>
  9. #include "toolchain/base/kind_switch.h"
  10. #include "toolchain/check/cpp/impl_lookup.h"
  11. #include "toolchain/check/custom_witness.h"
  12. #include "toolchain/check/deduce.h"
  13. #include "toolchain/check/diagnostic_helpers.h"
  14. #include "toolchain/check/eval.h"
  15. #include "toolchain/check/facet_type.h"
  16. #include "toolchain/check/generic.h"
  17. #include "toolchain/check/impl.h"
  18. #include "toolchain/check/import_ref.h"
  19. #include "toolchain/check/inst.h"
  20. #include "toolchain/check/subst.h"
  21. #include "toolchain/check/type.h"
  22. #include "toolchain/check/type_completion.h"
  23. #include "toolchain/check/type_structure.h"
  24. #include "toolchain/sem_ir/facet_type_info.h"
  25. #include "toolchain/sem_ir/ids.h"
  26. #include "toolchain/sem_ir/impl.h"
  27. #include "toolchain/sem_ir/inst.h"
  28. #include "toolchain/sem_ir/typed_insts.h"
  29. namespace Carbon::Check {
  30. // Returns IRs which are allowed to define an `impl` involving the arguments.
  31. // This is limited by the orphan rule.
  32. static auto FindAssociatedImportIRs(
  33. Context& context, SemIR::ConstantId query_self_const_id,
  34. SemIR::SpecificInterface query_specific_interface)
  35. -> llvm::SmallVector<SemIR::ImportIRId> {
  36. llvm::SmallVector<SemIR::ImportIRId> result;
  37. // Add an entity to our result.
  38. auto add_entity = [&](const SemIR::EntityWithParamsBase& entity) {
  39. // We will look for impls in the import IR associated with the first owning
  40. // declaration.
  41. auto decl_id = entity.first_owning_decl_id;
  42. if (!decl_id.has_value()) {
  43. return;
  44. }
  45. auto import_ir_inst = GetCanonicalImportIRInst(context, decl_id);
  46. const auto* sem_ir = &context.sem_ir();
  47. if (import_ir_inst.ir_id().has_value()) {
  48. sem_ir = context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  49. }
  50. // For an instruction imported from C++, `GetCanonicalImportIRInst` returns
  51. // the final Carbon import instruction, so go one extra step to check for a
  52. // C++ import.
  53. if (auto import_ir_inst_id =
  54. sem_ir->insts().GetImportSource(import_ir_inst.inst_id());
  55. import_ir_inst_id.has_value()) {
  56. result.push_back(
  57. sem_ir->import_ir_insts().Get(import_ir_inst_id).ir_id());
  58. } else if (import_ir_inst.ir_id().has_value()) {
  59. result.push_back(import_ir_inst.ir_id());
  60. }
  61. };
  62. llvm::SmallVector<SemIR::InstId> worklist;
  63. // Push the contents of an instruction block onto our worklist.
  64. auto push_block = [&](SemIR::InstBlockId block_id) {
  65. if (block_id.has_value()) {
  66. llvm::append_range(worklist, context.inst_blocks().Get(block_id));
  67. }
  68. };
  69. // Add the arguments of a specific to the worklist.
  70. auto push_args = [&](SemIR::SpecificId specific_id) {
  71. if (specific_id.has_value()) {
  72. push_block(context.specifics().Get(specific_id).args_id);
  73. }
  74. };
  75. worklist.push_back(context.constant_values().GetInstId(query_self_const_id));
  76. add_entity(context.interfaces().Get(query_specific_interface.interface_id));
  77. push_args(query_specific_interface.specific_id);
  78. while (!worklist.empty()) {
  79. auto inst_id = worklist.pop_back_val();
  80. // Visit the operands of the constant.
  81. auto inst = context.insts().Get(inst_id);
  82. for (auto arg : {inst.arg0_and_kind(), inst.arg1_and_kind()}) {
  83. CARBON_KIND_SWITCH(arg) {
  84. case CARBON_KIND(SemIR::InstId inst_id): {
  85. if (inst_id.has_value()) {
  86. worklist.push_back(inst_id);
  87. }
  88. break;
  89. }
  90. case CARBON_KIND(SemIR::TypeInstId inst_id): {
  91. if (inst_id.has_value()) {
  92. worklist.push_back(inst_id);
  93. }
  94. break;
  95. }
  96. case CARBON_KIND(SemIR::InstBlockId inst_block_id): {
  97. push_block(inst_block_id);
  98. break;
  99. }
  100. case CARBON_KIND(SemIR::ClassId class_id): {
  101. add_entity(context.classes().Get(class_id));
  102. break;
  103. }
  104. case CARBON_KIND(SemIR::InterfaceId interface_id): {
  105. add_entity(context.interfaces().Get(interface_id));
  106. break;
  107. }
  108. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  109. const auto& facet_type_info =
  110. context.facet_types().Get(facet_type_id);
  111. for (const auto& impl : facet_type_info.extend_constraints) {
  112. add_entity(context.interfaces().Get(impl.interface_id));
  113. push_args(impl.specific_id);
  114. }
  115. for (const auto& impl : facet_type_info.self_impls_constraints) {
  116. add_entity(context.interfaces().Get(impl.interface_id));
  117. push_args(impl.specific_id);
  118. }
  119. break;
  120. }
  121. case CARBON_KIND(SemIR::FunctionId function_id): {
  122. add_entity(context.functions().Get(function_id));
  123. break;
  124. }
  125. case CARBON_KIND(SemIR::SpecificId specific_id): {
  126. push_args(specific_id);
  127. break;
  128. }
  129. default: {
  130. break;
  131. }
  132. }
  133. }
  134. }
  135. // Deduplicate.
  136. llvm::sort(result, [](SemIR::ImportIRId a, SemIR::ImportIRId b) {
  137. return a.index < b.index;
  138. });
  139. result.erase(llvm::unique(result), result.end());
  140. return result;
  141. }
  142. // Returns true if a cycle was found and diagnosed.
  143. static auto FindAndDiagnoseImplLookupCycle(
  144. Context& context,
  145. const llvm::SmallVector<Context::ImplLookupStackEntry>& stack,
  146. SemIR::LocId loc_id, SemIR::ConstantId query_self_const_id,
  147. SemIR::ConstantId query_facet_type_const_id) -> bool {
  148. // Deduction of the interface parameters can do further impl lookups, and we
  149. // need to ensure we terminate.
  150. //
  151. // https://docs.carbon-lang.dev/docs/design/generics/details.html#acyclic-rule
  152. // - We look for violations of the acyclic rule by seeing if a previous lookup
  153. // had all the same type inputs.
  154. // - The `query_facet_type_const_id` encodes the entire facet type being
  155. // looked up, including any specific parameters for a generic interface.
  156. //
  157. // TODO: Implement the termination rule, which requires looking at the
  158. // complexity of the types on the top of (or throughout?) the stack:
  159. // https://docs.carbon-lang.dev/docs/design/generics/details.html#termination-rule
  160. for (auto [i, entry] : llvm::enumerate(stack)) {
  161. if (entry.query_self_const_id == query_self_const_id &&
  162. entry.query_facet_type_const_id == query_facet_type_const_id) {
  163. auto facet_type_type_id =
  164. context.types().GetTypeIdForTypeConstantId(query_facet_type_const_id);
  165. CARBON_DIAGNOSTIC(ImplLookupCycle, Error,
  166. "cycle found in search for impl of {0} for type {1}",
  167. SemIR::TypeId, SemIR::TypeId);
  168. auto builder = context.emitter().Build(
  169. loc_id, ImplLookupCycle, facet_type_type_id,
  170. context.types().GetTypeIdForTypeConstantId(query_self_const_id));
  171. for (const auto& active_entry : llvm::drop_begin(stack, i)) {
  172. if (active_entry.impl_loc.has_value()) {
  173. CARBON_DIAGNOSTIC(ImplLookupCycleNote, Note,
  174. "determining if this impl clause matches", );
  175. builder.Note(active_entry.impl_loc, ImplLookupCycleNote);
  176. }
  177. }
  178. builder.Emit();
  179. return true;
  180. }
  181. }
  182. return false;
  183. }
  184. struct InterfacesFromConstantId {
  185. llvm::ArrayRef<SemIR::SpecificInterface> interfaces;
  186. bool other_requirements;
  187. };
  188. // Gets the set of `SpecificInterface`s that are required by a facet type
  189. // (as a constant value), and any special requirements.
  190. static auto GetInterfacesFromConstantId(
  191. Context& context, SemIR::LocId loc_id,
  192. SemIR::ConstantId query_facet_type_const_id)
  193. -> std::optional<InterfacesFromConstantId> {
  194. auto facet_type_inst_id =
  195. context.constant_values().GetInstId(query_facet_type_const_id);
  196. auto facet_type_inst =
  197. context.insts().GetAs<SemIR::FacetType>(facet_type_inst_id);
  198. const auto& facet_type_info =
  199. context.facet_types().Get(facet_type_inst.facet_type_id);
  200. auto identified_id =
  201. RequireIdentifiedFacetType(context, loc_id, facet_type_inst, [&] {
  202. CARBON_DIAGNOSTIC(ImplLookupInUnidentifiedFacetType, Error,
  203. "facet type {0} can not be identified", InstIdAsType);
  204. return context.emitter().Build(
  205. loc_id, ImplLookupInUnidentifiedFacetType, facet_type_inst_id);
  206. });
  207. if (!identified_id.has_value()) {
  208. return std::nullopt;
  209. }
  210. return {{.interfaces = context.identified_facet_types()
  211. .Get(identified_id)
  212. .required_interfaces(),
  213. .other_requirements = facet_type_info.other_requirements}};
  214. }
  215. static auto GetWitnessIdForImpl(Context& context, SemIR::LocId loc_id,
  216. bool query_is_concrete,
  217. SemIR::ConstantId query_self_const_id,
  218. const SemIR::SpecificInterface& interface,
  219. const SemIR::Impl& impl)
  220. -> EvalImplLookupResult {
  221. // The impl may have generic arguments, in which case we need to deduce them
  222. // to find what they are given the specific type and interface query. We use
  223. // that specific to map values in the impl to the deduced values.
  224. auto specific_id = SemIR::SpecificId::None;
  225. if (impl.generic_id.has_value()) {
  226. specific_id = DeduceImplArguments(
  227. context, loc_id, impl, query_self_const_id, interface.specific_id);
  228. if (!specific_id.has_value()) {
  229. return EvalImplLookupResult::MakeNone();
  230. }
  231. }
  232. // The self type of the impl must match the type in the query, or this is an
  233. // `impl T as ...` for some other type `T` and should not be considered.
  234. auto noncanonical_deduced_self_const_id = SemIR::GetConstantValueInSpecific(
  235. context.sem_ir(), specific_id, impl.self_id);
  236. // In a generic `impl forall` the self type can be a FacetAccessType, which
  237. // will not be the same constant value as a query facet value. We move through
  238. // to the facet value here, and if the query was a FacetAccessType we did the
  239. // same there so they still match.
  240. auto deduced_self_const_id =
  241. GetCanonicalFacetOrTypeValue(context, noncanonical_deduced_self_const_id);
  242. if (query_self_const_id != deduced_self_const_id) {
  243. return EvalImplLookupResult::MakeNone();
  244. }
  245. // The impl's constraint is a facet type which it is implementing for the self
  246. // type: the `I` in `impl ... as I`. The deduction step may be unable to be
  247. // fully applied to the types in the constraint and result in an error here,
  248. // in which case it does not match the query.
  249. auto deduced_constraint_id =
  250. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  251. context.sem_ir(), specific_id, impl.constraint_id));
  252. if (deduced_constraint_id == SemIR::ErrorInst::InstId) {
  253. return EvalImplLookupResult::MakeNone();
  254. }
  255. auto deduced_constraint_facet_type_id =
  256. context.insts()
  257. .GetAs<SemIR::FacetType>(deduced_constraint_id)
  258. .facet_type_id;
  259. const auto& deduced_constraint_facet_type_info =
  260. context.facet_types().Get(deduced_constraint_facet_type_id);
  261. CARBON_CHECK(deduced_constraint_facet_type_info.extend_constraints.size() ==
  262. 1);
  263. if (deduced_constraint_facet_type_info.other_requirements) {
  264. return EvalImplLookupResult::MakeNone();
  265. }
  266. // The specifics in the queried interface must match the deduced specifics in
  267. // the impl's constraint facet type.
  268. auto impl_interface_specific_id =
  269. deduced_constraint_facet_type_info.extend_constraints[0].specific_id;
  270. auto query_interface_specific_id = interface.specific_id;
  271. if (impl_interface_specific_id != query_interface_specific_id) {
  272. return EvalImplLookupResult::MakeNone();
  273. }
  274. LoadImportRef(context, impl.witness_id);
  275. if (specific_id.has_value()) {
  276. // Add an instruction to support requiring an impl definition which may not
  277. // otherwise be generated. This is used to resolve dependency chains when
  278. // `MakeFinal` is returned without a concrete definition; particularly final
  279. // impls with symbolic constants.
  280. AddInstInNoBlock(
  281. context, loc_id,
  282. SemIR::RequireSpecificDefinition{
  283. .type_id = GetSingletonType(
  284. context, SemIR::RequireSpecificDefinitionType::TypeInstId),
  285. .specific_id = specific_id});
  286. // We need a definition of the specific `impl` so we can access its
  287. // witness.
  288. ResolveSpecificDefinition(context, loc_id, specific_id);
  289. }
  290. if (query_is_concrete || impl.is_final) {
  291. // TODO: These final results should be cached somehow. Positive (non-None)
  292. // results could be cached globally, as they can not change. But
  293. // negative results can change after a final impl is written, so
  294. // they can only be cached in a limited way, or the cache needs to
  295. // be invalidated by writing a final impl that would match.
  296. return EvalImplLookupResult::MakeFinal(
  297. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  298. context.sem_ir(), specific_id, impl.witness_id)));
  299. } else {
  300. return EvalImplLookupResult::MakeNonFinal();
  301. }
  302. }
  303. // Finds a lookup result from `query_self_inst_id` if it is a facet value that
  304. // names the query interface in its facet type. Note that `query_self_inst_id`
  305. // is allowed to be a non-canonical facet value in order to find a concrete
  306. // witness, so it's not referenced as a constant value.
  307. static auto LookupImplWitnessInSelfFacetValue(
  308. Context& context, SemIR::LocId loc_id,
  309. SemIR::InstId self_facet_value_inst_id,
  310. SemIR::SpecificInterface query_specific_interface) -> EvalImplLookupResult {
  311. auto facet_type = context.types().TryGetAs<SemIR::FacetType>(
  312. context.insts().Get(self_facet_value_inst_id).type_id());
  313. if (!facet_type) {
  314. return EvalImplLookupResult::MakeNone();
  315. }
  316. // The position of the interface in `required_interfaces()` is also the
  317. // position of the witness for that interface in `FacetValue`. The
  318. // `FacetValue` witnesses are the output of an impl lookup, which finds and
  319. // returns witnesses in the same order.
  320. auto identified_id =
  321. RequireIdentifiedFacetType(context, loc_id, *facet_type, nullptr);
  322. // This should not be possible as FacetValue is constructed by a conversion
  323. // to a facet type, which performs impl lookup for that facet type, and
  324. // lookup only succeeds for complete facet types.
  325. CARBON_CHECK(identified_id.has_value(),
  326. "FacetValue was constructed with an incomplete facet type");
  327. auto facet_type_required_interfaces =
  328. llvm::enumerate(context.identified_facet_types()
  329. .Get(identified_id)
  330. .required_interfaces());
  331. auto it = llvm::find_if(facet_type_required_interfaces, [=](auto e) {
  332. return e.value() == query_specific_interface;
  333. });
  334. if (it == facet_type_required_interfaces.end()) {
  335. return EvalImplLookupResult::MakeNone();
  336. }
  337. auto index = (*it).index();
  338. if (auto facet_value = context.insts().TryGetAs<SemIR::FacetValue>(
  339. self_facet_value_inst_id)) {
  340. auto witness_id =
  341. context.inst_blocks().Get(facet_value->witnesses_block_id)[index];
  342. if (context.insts().Is<SemIR::ImplWitness>(witness_id)) {
  343. return EvalImplLookupResult::MakeFinal(witness_id);
  344. }
  345. }
  346. return EvalImplLookupResult::MakeNonFinal();
  347. }
  348. // Substitutes witnesess in place of `LookupImplWitness` queries into `.Self`,
  349. // when the witness is for the same interface as the one `.Self` is referring
  350. // to.
  351. //
  352. // This allows access to the `FacetType` and its constraints from the witness,
  353. // and allows `ImplWitnessAccess` instructions to be immediately resolved to a
  354. // more specific value when possible.
  355. class SubstWitnessesCallbacks : public SubstInstCallbacks {
  356. public:
  357. // `context` must not be null.
  358. explicit SubstWitnessesCallbacks(
  359. Context* context, SemIR::LocId loc_id,
  360. llvm::ArrayRef<SemIR::SpecificInterface> interfaces,
  361. llvm::ArrayRef<SemIR::InstId> witness_inst_ids)
  362. : SubstInstCallbacks(context),
  363. loc_id_(loc_id),
  364. interfaces_(interfaces),
  365. witness_inst_ids_(witness_inst_ids) {}
  366. auto Subst(SemIR::InstId& inst_id) -> SubstResult override {
  367. // `FacetType` can be concrete even when it has rewrite constraints that
  368. // have a symbolic dependency on `.Self`. See use of
  369. // `GetConstantValueIgnoringPeriodSelf` in eval. So in order to recurse into
  370. // `FacetType` we must check for it before the `is_concrete` early return.
  371. if (context().insts().Is<SemIR::FacetType>(inst_id)) {
  372. ++facet_type_depth_;
  373. return SubstOperands;
  374. }
  375. if (context().constant_values().Get(inst_id).is_concrete()) {
  376. return FullySubstituted;
  377. }
  378. auto access = context().insts().TryGetAs<SemIR::ImplWitnessAccess>(inst_id);
  379. if (!access) {
  380. return SubstOperands;
  381. }
  382. auto lookup =
  383. context().insts().GetAs<SemIR::LookupImplWitness>(access->witness_id);
  384. auto bind_name = context().insts().TryGetAs<SemIR::SymbolicBinding>(
  385. lookup.query_self_inst_id);
  386. if (!bind_name) {
  387. return SubstOperands;
  388. }
  389. const auto& self_entity_name =
  390. context().entity_names().Get(bind_name->entity_name_id);
  391. if (self_entity_name.name_id != SemIR::NameId::PeriodSelf) {
  392. return SubstOperands;
  393. }
  394. // TODO: Once we are numbering `EntityName`, (see the third model in
  395. // https://docs.google.com/document/d/1Yt-i5AmF76LSvD4TrWRIAE_92kii6j5yFiW-S7ahzlg/edit?tab=t.0#heading=h.7urbxcq23olv)
  396. // then verify that the index here is equal to the `facet_type_depth_`,
  397. // which would mean that it is a reference to the top-level `Self`, which is
  398. // being replaced with the impl lookup query self facet value (and then we
  399. // use the witness derived from it).
  400. //
  401. // For now, we only substitute if depth == 0, which is incorrect inside
  402. // nested facet types, as it can miss references in specifics up to the top
  403. // level facet value.
  404. if (facet_type_depth_ > 0) {
  405. return SubstOperands;
  406. }
  407. auto witness_id =
  408. FindWitnessForInterface(lookup.query_specific_interface_id);
  409. if (!witness_id.has_value()) {
  410. return SubstOperands;
  411. }
  412. inst_id = RebuildNewInst(
  413. context().insts().GetLocIdForDesugaring(loc_id_),
  414. SemIR::ImplWitnessAccess{.type_id = GetSingletonType(
  415. context(), SemIR::WitnessType::TypeInstId),
  416. .witness_id = witness_id,
  417. .index = access->index});
  418. // Once we replace a witness, we either have a concrete value or some
  419. // reference to an associated constant that came from the witness's facet
  420. // type. We don't want to substitute into the witness's facet type, so we
  421. // don't recurse on whatever came from the witness.
  422. return FullySubstituted;
  423. }
  424. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst)
  425. -> SemIR::InstId override {
  426. if (context().insts().Is<SemIR::FacetType>(orig_inst_id)) {
  427. --facet_type_depth_;
  428. }
  429. return RebuildNewInst(loc_id_, new_inst);
  430. }
  431. auto ReuseUnchanged(SemIR::InstId orig_inst_id) -> SemIR::InstId override {
  432. if (context().insts().Is<SemIR::FacetType>(orig_inst_id)) {
  433. --facet_type_depth_;
  434. }
  435. return orig_inst_id;
  436. }
  437. private:
  438. auto FindWitnessForInterface(SemIR::SpecificInterfaceId specific_interface_id)
  439. -> SemIR::InstId {
  440. auto lookup_query_interface =
  441. context().specific_interfaces().Get(specific_interface_id);
  442. for (auto [interface, witness_inst_id] :
  443. llvm::zip_equal(interfaces_, witness_inst_ids_)) {
  444. // If the `LookupImplWitness` for `.Self` is not looking for the same
  445. // interface as we have a witness for, this is not the right witness to
  446. // use to replace the lookup for `.Self`.
  447. if (interface.interface_id == lookup_query_interface.interface_id) {
  448. return witness_inst_id;
  449. }
  450. }
  451. return SemIR::InstId::None;
  452. }
  453. SemIR::LocId loc_id_;
  454. llvm::ArrayRef<SemIR::SpecificInterface> interfaces_;
  455. llvm::ArrayRef<SemIR::InstId> witness_inst_ids_;
  456. int facet_type_depth_ = 0;
  457. };
  458. static auto VerifyQueryFacetTypeConstraints(
  459. Context& context, SemIR::LocId loc_id,
  460. SemIR::InstId query_facet_type_inst_id,
  461. llvm::ArrayRef<SemIR::SpecificInterface> interfaces,
  462. llvm::ArrayRef<SemIR::InstId> witness_inst_ids) -> bool {
  463. CARBON_CHECK(context.insts().Is<SemIR::FacetType>(query_facet_type_inst_id));
  464. const auto& facet_type_info = context.facet_types().Get(
  465. context.insts()
  466. .GetAs<SemIR::FacetType>(query_facet_type_inst_id)
  467. .facet_type_id);
  468. if (!facet_type_info.rewrite_constraints.empty()) {
  469. auto callbacks =
  470. SubstWitnessesCallbacks(&context, loc_id, interfaces, witness_inst_ids);
  471. for (const auto& rewrite : facet_type_info.rewrite_constraints) {
  472. auto lhs_id = SubstInst(context, rewrite.lhs_id, callbacks);
  473. auto rhs_id = SubstInst(context, rewrite.rhs_id, callbacks);
  474. if (lhs_id != rhs_id) {
  475. // TODO: Provide a diagnostic note and location for which rewrite
  476. // constraint was not satisfied, if a diagnostic is going to be
  477. // displayed for the LookupImplWitessFailure. This will require plumbing
  478. // through a callback that lets us add a Note to another diagnostic.
  479. return false;
  480. }
  481. }
  482. }
  483. // TODO: Validate that the witnesses satisfy the other requirements in the
  484. // `facet_type_info`.
  485. return true;
  486. }
  487. // Begin a search for an impl declaration matching the query. We do this by
  488. // creating an LookupImplWitness instruction and evaluating. If it's able to
  489. // find a final concrete impl, then it will evaluate to that `ImplWitness` but
  490. // if not, it will evaluate to itself as a symbolic witness to be further
  491. // evaluated with a more specific query when building a specific for the generic
  492. // context the query came from.
  493. static auto GetOrAddLookupImplWitness(Context& context, SemIR::LocId loc_id,
  494. SemIR::ConstantId query_self_const_id,
  495. SemIR::SpecificInterface interface)
  496. -> SemIR::InstId {
  497. auto witness_const_id = EvalOrAddInst(
  498. context, context.insts().GetLocIdForDesugaring(loc_id),
  499. SemIR::LookupImplWitness{
  500. .type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  501. .query_self_inst_id =
  502. context.constant_values().GetInstId(query_self_const_id),
  503. .query_specific_interface_id =
  504. context.specific_interfaces().Add(interface),
  505. });
  506. // We use a NotConstant result from eval to communicate back an impl
  507. // lookup failure. See `EvalConstantInst()` for `LookupImplWitness`.
  508. if (!witness_const_id.is_constant()) {
  509. return SemIR::InstId::None;
  510. }
  511. return context.constant_values().GetInstId(witness_const_id);
  512. }
  513. auto LookupImplWitness(Context& context, SemIR::LocId loc_id,
  514. SemIR::ConstantId query_self_const_id,
  515. SemIR::ConstantId query_facet_type_const_id)
  516. -> SemIR::InstBlockIdOrError {
  517. if (query_self_const_id == SemIR::ErrorInst::ConstantId ||
  518. query_facet_type_const_id == SemIR::ErrorInst::ConstantId) {
  519. return SemIR::InstBlockIdOrError::MakeError();
  520. }
  521. {
  522. // The query self value is a type value or a facet value.
  523. auto query_self_type_id =
  524. context.insts()
  525. .Get(context.constant_values().GetInstId(query_self_const_id))
  526. .type_id();
  527. CARBON_CHECK(context.types().Is<SemIR::TypeType>(query_self_type_id) ||
  528. context.types().Is<SemIR::FacetType>(query_self_type_id));
  529. // The query facet type value is indeed a facet type.
  530. CARBON_CHECK(context.insts().Is<SemIR::FacetType>(
  531. context.constant_values().GetInstId(query_facet_type_const_id)));
  532. }
  533. auto interfaces_from_constant_id =
  534. GetInterfacesFromConstantId(context, loc_id, query_facet_type_const_id);
  535. if (!interfaces_from_constant_id) {
  536. return SemIR::InstBlockIdOrError::MakeError();
  537. }
  538. auto [interfaces, other_requirements] = *interfaces_from_constant_id;
  539. if (other_requirements) {
  540. // TODO: Remove this when other requirements go away.
  541. return SemIR::InstBlockId::None;
  542. }
  543. if (interfaces.empty()) {
  544. return SemIR::InstBlockId::Empty;
  545. }
  546. if (FindAndDiagnoseImplLookupCycle(context, context.impl_lookup_stack(),
  547. loc_id, query_self_const_id,
  548. query_facet_type_const_id)) {
  549. return SemIR::InstBlockIdOrError::MakeError();
  550. }
  551. auto& stack = context.impl_lookup_stack();
  552. stack.push_back({
  553. .query_self_const_id = query_self_const_id,
  554. .query_facet_type_const_id = query_facet_type_const_id,
  555. });
  556. // We need to find a witness for each interface in `interfaces`. Every
  557. // consumer of a facet type needs to agree on the order of interfaces used for
  558. // its witnesses.
  559. llvm::SmallVector<SemIR::InstId> result_witness_ids;
  560. for (const auto& interface : interfaces) {
  561. // TODO: Since both `interfaces` and `query_self_const_id` are sorted lists,
  562. // do an O(N+M) merge instead of O(N*M) nested loops.
  563. auto result_witness_id = GetOrAddLookupImplWitness(
  564. context, loc_id, query_self_const_id, interface);
  565. if (result_witness_id.has_value()) {
  566. result_witness_ids.push_back(result_witness_id);
  567. } else {
  568. // At least one queried interface in the facet type has no witness for the
  569. // given type, we can stop looking for more.
  570. break;
  571. }
  572. }
  573. stack.pop_back();
  574. // All interfaces in the query facet type must have been found to be available
  575. // through some impl, or directly on the value's facet type if
  576. // `query_self_const_id` is a facet value.
  577. if (result_witness_ids.size() != interfaces.size()) {
  578. return SemIR::InstBlockId::None;
  579. }
  580. // Verify rewrite constraints in the query constraint are satisfied after
  581. // applying the rewrites from the found witnesses.
  582. if (!VerifyQueryFacetTypeConstraints(
  583. context, loc_id,
  584. context.constant_values().GetInstId(query_facet_type_const_id),
  585. interfaces, result_witness_ids)) {
  586. return SemIR::InstBlockId::None;
  587. }
  588. return context.inst_blocks().AddCanonical(result_witness_ids);
  589. }
  590. // Returns whether the query is concrete, it is false if the self type or
  591. // interface specifics have a symbolic dependency.
  592. static auto QueryIsConcrete(Context& context, SemIR::ConstantId self_const_id,
  593. const SemIR::SpecificInterface& specific_interface)
  594. -> bool {
  595. if (!self_const_id.is_concrete()) {
  596. return false;
  597. }
  598. if (!specific_interface.specific_id.has_value()) {
  599. return true;
  600. }
  601. auto args_id =
  602. context.specifics().Get(specific_interface.specific_id).args_id;
  603. for (auto inst_id : context.inst_blocks().Get(args_id)) {
  604. if (!context.constant_values().Get(inst_id).is_concrete()) {
  605. return false;
  606. }
  607. }
  608. return true;
  609. }
  610. namespace {
  611. // A class to filter imported impls based on whether they could possibly match a
  612. // query, prior to importing them. For now we only consider impls that are for
  613. // an interface that's being queried.
  614. //
  615. // TODO: There's a lot more we could do to filter out impls that can't possibly
  616. // match.
  617. class ImportImplFilter {
  618. public:
  619. explicit ImportImplFilter(Context& context, SemIR::ImportIRId import_ir_id,
  620. SemIR::SpecificInterface interface)
  621. : context_(&context),
  622. interface_id_(interface.interface_id),
  623. import_ir_id_(import_ir_id),
  624. import_ir_(context_->import_irs().Get(import_ir_id).sem_ir),
  625. cached_import_interface_id_(SemIR::InterfaceId::None) {}
  626. // Returns whether the given impl is potentially relevant for the current
  627. // query.
  628. auto IsRelevantImpl(SemIR::ImplId import_impl_id) -> bool {
  629. auto impl_interface_id =
  630. import_ir_->impls().Get(import_impl_id).interface.interface_id;
  631. if (!impl_interface_id.has_value()) {
  632. // This indicates that an error occurred when type-checking the impl.
  633. // TODO: Use an explicit error value for this rather than None.
  634. return false;
  635. }
  636. return IsRelevantInterface(impl_interface_id);
  637. }
  638. private:
  639. // Returns whether an impl for the given interface might be relevant to the
  640. // current query.
  641. auto IsRelevantInterface(SemIR::InterfaceId import_interface_id) -> bool {
  642. if (!cached_import_interface_id_.has_value()) {
  643. if (IsSameInterface(import_interface_id, interface_id_)) {
  644. cached_import_interface_id_ = import_interface_id;
  645. return true;
  646. }
  647. } else if (cached_import_interface_id_ == import_interface_id) {
  648. return true;
  649. }
  650. return false;
  651. }
  652. // Returns whether the given interfaces from two different IRs are the same.
  653. auto IsSameInterface(SemIR::InterfaceId import_interface_id,
  654. SemIR::InterfaceId local_interface_id) -> bool {
  655. // The names must be the same.
  656. if (import_ir_->names().GetAsStringIfIdentifier(
  657. import_ir_->interfaces().Get(import_interface_id).name_id) !=
  658. context_->names().GetAsStringIfIdentifier(
  659. context_->interfaces().Get(local_interface_id).name_id)) {
  660. return false;
  661. }
  662. // Compare the interfaces themselves.
  663. // TODO: Should we check the scope of the interface before doing this?
  664. auto local_version_of_import_interface_id =
  665. ImportInterface(*context_, import_ir_id_, import_interface_id);
  666. return local_version_of_import_interface_id == local_interface_id;
  667. }
  668. Context* context_;
  669. // The interface being looked up.
  670. SemIR::InterfaceId interface_id_;
  671. // The IR that we are currently importing impls from.
  672. SemIR::ImportIRId import_ir_id_;
  673. const SemIR::File* import_ir_;
  674. // The interface ID of `interface_id_` in `import_ir_`, if known.
  675. SemIR::InterfaceId cached_import_interface_id_;
  676. };
  677. } // namespace
  678. struct CandidateImpl {
  679. const SemIR::Impl* impl;
  680. // Used for sorting the candidates to find the most-specialized match.
  681. TypeStructure type_structure;
  682. };
  683. struct CandidateImpls {
  684. llvm::SmallVector<CandidateImpl> impls;
  685. bool consider_cpp_candidates = false;
  686. };
  687. // Returns the list of candidates impls for lookup to select from.
  688. static auto CollectCandidateImplsForQuery(
  689. Context& context, bool final_only, SemIR::ConstantId query_self_const_id,
  690. const TypeStructure& query_type_structure,
  691. SemIR::SpecificInterface& query_specific_interface) -> CandidateImpls {
  692. CandidateImpls candidates;
  693. auto import_irs = FindAssociatedImportIRs(context, query_self_const_id,
  694. query_specific_interface);
  695. for (auto import_ir_id : import_irs) {
  696. // If `Cpp` is an associated package, then we'll instead look for C++
  697. // operator overloads for certain well-known interfaces.
  698. if (import_ir_id == SemIR::ImportIRId::Cpp) {
  699. candidates.consider_cpp_candidates = true;
  700. continue;
  701. }
  702. // Instead of importing all impls, only import ones that are in some way
  703. // connected to this query.
  704. ImportImplFilter filter(context, import_ir_id, query_specific_interface);
  705. for (auto [import_impl_id, _] :
  706. context.import_irs().Get(import_ir_id).sem_ir->impls().enumerate()) {
  707. if (filter.IsRelevantImpl(import_impl_id)) {
  708. // TODO: Track the relevant impls and only consider those ones and any
  709. // local impls, rather than looping over all impls below.
  710. ImportImpl(context, import_ir_id, import_impl_id);
  711. }
  712. }
  713. }
  714. for (auto [id, impl] : context.impls().enumerate()) {
  715. CARBON_CHECK(impl.witness_id.has_value());
  716. if (final_only && !IsImplEffectivelyFinal(context, impl)) {
  717. continue;
  718. }
  719. // If the impl's interface_id differs from the query, then this impl can
  720. // not possibly provide the queried interface.
  721. if (impl.interface.interface_id != query_specific_interface.interface_id) {
  722. continue;
  723. }
  724. // When the impl's interface_id matches, but the interface is generic, the
  725. // impl may or may not match based on restrictions in the generic
  726. // parameters of the impl.
  727. //
  728. // As a shortcut, if the impl's constraint is not symbolic (does not
  729. // depend on any generic parameters), then we can determine whether we match
  730. // by looking if the specific ids match exactly.
  731. auto impl_interface_const_id =
  732. context.constant_values().Get(impl.constraint_id);
  733. if (!impl_interface_const_id.is_symbolic() &&
  734. impl.interface.specific_id != query_specific_interface.specific_id) {
  735. continue;
  736. }
  737. // Build the type structure used for choosing the best the candidate.
  738. auto type_structure =
  739. BuildTypeStructure(context, impl.self_id, impl.interface);
  740. if (!type_structure) {
  741. continue;
  742. }
  743. // TODO: We can skip the comparison here if the `impl_interface_const_id` is
  744. // not symbolic, since when the interface and specific ids match, and they
  745. // aren't symbolic, the structure will be identical.
  746. if (!query_type_structure.CompareStructure(
  747. TypeStructure::CompareTest::IsEqualToOrMoreSpecificThan,
  748. *type_structure)) {
  749. continue;
  750. }
  751. candidates.impls.push_back({&impl, std::move(*type_structure)});
  752. }
  753. auto compare = [](auto& lhs, auto& rhs) -> bool {
  754. return lhs.type_structure < rhs.type_structure;
  755. };
  756. // Stable sort is used so that impls that are seen first are preferred when
  757. // they have an equal priority ordering.
  758. // TODO: Allow Carbon code to provide a priority ordering explicitly. For
  759. // now they have all the same priority, so the priority is the order in
  760. // which they are found in code.
  761. llvm::stable_sort(candidates.impls, compare);
  762. return candidates;
  763. }
  764. // Record the query which found a final impl witness. It's illegal to
  765. // write a final impl afterward that would match the same query.
  766. static auto PoisonImplLookupQuery(Context& context, SemIR::LocId loc_id,
  767. EvalImplLookupMode mode,
  768. SemIR::LookupImplWitness eval_query,
  769. const EvalImplLookupResult& result,
  770. const SemIR::Impl& impl) -> void {
  771. if (mode == EvalImplLookupMode::RecheckPoisonedLookup) {
  772. return;
  773. }
  774. if (!result.has_final_value()) {
  775. return;
  776. }
  777. // If the impl was effectively final, then we don't need to poison here. A
  778. // change of query result will already be diagnosed at the point where the
  779. // new impl decl was written that changes the result.
  780. if (IsImplEffectivelyFinal(context, impl)) {
  781. return;
  782. }
  783. context.poisoned_concrete_impl_lookup_queries().push_back(
  784. {.loc_id = loc_id,
  785. .query = eval_query,
  786. .impl_witness = result.final_witness()});
  787. }
  788. auto EvalLookupSingleImplWitness(Context& context, SemIR::LocId loc_id,
  789. SemIR::LookupImplWitness eval_query,
  790. SemIR::InstId self_facet_value_inst_id,
  791. EvalImplLookupMode mode)
  792. -> EvalImplLookupResult {
  793. auto query_specific_interface =
  794. context.specific_interfaces().Get(eval_query.query_specific_interface_id);
  795. // Ensure specifics don't substitute in weird things for the query self.
  796. CARBON_CHECK(context.types().IsFacetType(
  797. context.insts().Get(eval_query.query_self_inst_id).type_id()));
  798. SemIR::ConstantId query_self_const_id =
  799. context.constant_values().Get(eval_query.query_self_inst_id);
  800. auto facet_lookup_result = LookupImplWitnessInSelfFacetValue(
  801. context, loc_id, self_facet_value_inst_id, query_specific_interface);
  802. if (facet_lookup_result.has_final_value()) {
  803. return facet_lookup_result;
  804. }
  805. // If the self type is a facet that provides a witness, then we are in an
  806. // `interface` or an `impl`. In both cases, we don't want to do any impl
  807. // lookups. The query will eventually resolve to a concrete witness when it
  808. // can get it from the self facet value, when it has a specific applied in the
  809. // future.
  810. //
  811. // In particular, this avoids a LookupImplWitness instruction in the eval
  812. // block of an impl declaration from doing impl lookup. Specifically the
  813. // lookup of the implicit .Self in `impl ... where .X`. If it does impl lookup
  814. // when the eval block is run, it finds the same `impl`, tries to build a
  815. // specific from it, which runs the eval block, creating a recursive loop that
  816. // crashes.
  817. if (facet_lookup_result.has_value()) {
  818. if (auto bind = context.insts().TryGetAs<SemIR::SymbolicBinding>(
  819. eval_query.query_self_inst_id)) {
  820. const auto& entity = context.entity_names().Get(bind->entity_name_id);
  821. if (entity.name_id == SemIR::NameId::PeriodSelf ||
  822. entity.name_id == SemIR::NameId::SelfType) {
  823. return facet_lookup_result;
  824. }
  825. }
  826. }
  827. auto query_type_structure = BuildTypeStructure(
  828. context, context.constant_values().GetInstId(query_self_const_id),
  829. query_specific_interface);
  830. if (!query_type_structure) {
  831. return EvalImplLookupResult::MakeNone();
  832. }
  833. // Check to see if this result is in the cache. But skip the cache if we're
  834. // re-checking a poisoned result and need to redo the lookup.
  835. auto impl_lookup_cache_key = Context::ImplLookupCacheKey{
  836. query_self_const_id, eval_query.query_specific_interface_id};
  837. if (mode != EvalImplLookupMode::RecheckPoisonedLookup) {
  838. if (auto result =
  839. context.impl_lookup_cache().Lookup(impl_lookup_cache_key)) {
  840. return EvalImplLookupResult::MakeFinal(result.value());
  841. }
  842. }
  843. // If the self value is a (symbolic) facet value that has a symbolic witness,
  844. // then we don't need to do impl lookup, except that we want to find any final
  845. // impls to return a concrete witness if possible. So we limit the query to
  846. // final impls only in that case. Note as in the CHECK above, the query can
  847. // not be concrete in this case, so only final impls can produce a concrete
  848. // witness for this query.
  849. auto candidates = CollectCandidateImplsForQuery(
  850. context, facet_lookup_result.has_value(), query_self_const_id,
  851. *query_type_structure, query_specific_interface);
  852. bool query_is_concrete =
  853. QueryIsConcrete(context, query_self_const_id, query_specific_interface);
  854. CARBON_CHECK(!query_is_concrete || !facet_lookup_result.has_value(),
  855. "Non-concrete facet lookup value for concrete query");
  856. // Perform a lookup for an `impl` that matches the query. If we don't find a
  857. // final impl, the self value may still have been a facet that provides a
  858. // symbolic witness in the `facet_lookup_result`, which we want to fall back
  859. // to. It records that an `impl` will exist for the query, but is yet unknown.
  860. struct LookupResult {
  861. EvalImplLookupResult result;
  862. const TypeStructure* impl_type_structure = nullptr;
  863. SemIR::LocId impl_loc_id = SemIR::LocId::None;
  864. };
  865. LookupResult lookup_result = {.result = facet_lookup_result};
  866. auto core_interface =
  867. GetCoreInterface(context, query_specific_interface.interface_id);
  868. // Consider a custom witness for core interfaces.
  869. // TODO: This needs to expand to more interfaces, and we might want to have
  870. // that dispatch in custom_witness.cpp instead of here.
  871. bool used_custom_witness = false;
  872. if (auto witness_id = LookupCustomWitness(
  873. context, loc_id, core_interface, query_self_const_id,
  874. eval_query.query_specific_interface_id);
  875. witness_id.has_value()) {
  876. lookup_result = {.result = EvalImplLookupResult::MakeFinal(witness_id)};
  877. used_custom_witness = true;
  878. }
  879. // Only consider candidates when a custom witness didn't apply.
  880. if (!used_custom_witness) {
  881. for (const auto& candidate : candidates.impls) {
  882. const auto& impl = *candidate.impl;
  883. // In deferred lookup for a symbolic impl witness, while building a
  884. // specific, there may be no stack yet as this may be the first lookup. If
  885. // further lookups are started as a result in deduce, they will build the
  886. // stack.
  887. if (!context.impl_lookup_stack().empty()) {
  888. context.impl_lookup_stack().back().impl_loc = impl.definition_id;
  889. }
  890. auto result = GetWitnessIdForImpl(context, loc_id, query_is_concrete,
  891. query_self_const_id,
  892. query_specific_interface, impl);
  893. if (result.has_value()) {
  894. PoisonImplLookupQuery(context, loc_id, mode, eval_query, result, impl);
  895. lookup_result = {.result = result,
  896. .impl_type_structure = &candidate.type_structure,
  897. .impl_loc_id = SemIR::LocId(impl.definition_id)};
  898. break;
  899. }
  900. }
  901. }
  902. if (query_is_concrete && candidates.consider_cpp_candidates &&
  903. core_interface != CoreInterface::Unknown) {
  904. // Also check for a C++ candidate that is a better match than whatever
  905. // `impl` we may have found in Carbon.
  906. auto cpp_witness_id = LookupCppImpl(
  907. context, loc_id, core_interface, query_self_const_id,
  908. eval_query.query_specific_interface_id,
  909. lookup_result.impl_type_structure, lookup_result.impl_loc_id);
  910. if (cpp_witness_id.has_value()) {
  911. lookup_result = {.result =
  912. EvalImplLookupResult::MakeFinal(cpp_witness_id)};
  913. }
  914. }
  915. if (mode != EvalImplLookupMode::RecheckPoisonedLookup &&
  916. lookup_result.result.has_final_value()) {
  917. context.impl_lookup_cache().Insert(impl_lookup_cache_key,
  918. lookup_result.result.final_witness());
  919. }
  920. return lookup_result.result;
  921. }
  922. auto LookupMatchesImpl(Context& context, SemIR::LocId loc_id,
  923. SemIR::ConstantId query_self_const_id,
  924. SemIR::SpecificInterface query_specific_interface,
  925. SemIR::ImplId target_impl) -> bool {
  926. if (query_self_const_id == SemIR::ErrorInst::ConstantId) {
  927. return false;
  928. }
  929. auto result = GetWitnessIdForImpl(
  930. context, loc_id, /*query_is_concrete=*/false, query_self_const_id,
  931. query_specific_interface, context.impls().Get(target_impl));
  932. return result.has_value();
  933. }
  934. } // namespace Carbon::Check