impl_lookup.cpp 43 KB

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