impl_lookup.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  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/generic.h"
  16. #include "toolchain/check/impl.h"
  17. #include "toolchain/check/import_ref.h"
  18. #include "toolchain/check/inst.h"
  19. #include "toolchain/check/period_self.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/type_iterator.h"
  29. #include "toolchain/sem_ir/typed_insts.h"
  30. namespace Carbon::Check {
  31. // Returns IRs which are allowed to define an `impl` involving the arguments.
  32. // This is limited by the orphan rule.
  33. static auto FindAssociatedImportIRs(
  34. Context& context, SemIR::ConstantId query_self_const_id,
  35. SemIR::SpecificInterface query_specific_interface)
  36. -> llvm::SmallVector<SemIR::ImportIRId> {
  37. llvm::SmallVector<SemIR::ImportIRId> result;
  38. // Add an entity to our result.
  39. auto add_entity = [&](const SemIR::EntityWithParamsBase& entity) {
  40. // We will look for impls in the import IR associated with the first owning
  41. // declaration.
  42. auto decl_id = entity.first_owning_decl_id;
  43. if (!decl_id.has_value()) {
  44. return;
  45. }
  46. auto import_ir_inst = GetCanonicalImportIRInst(context, decl_id);
  47. const auto* sem_ir = &context.sem_ir();
  48. if (import_ir_inst.ir_id().has_value()) {
  49. sem_ir = context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  50. }
  51. // For an instruction imported from C++, `GetCanonicalImportIRInst` returns
  52. // the final Carbon import instruction, so go one extra step to check for a
  53. // C++ import.
  54. if (auto import_ir_inst_id =
  55. sem_ir->insts().GetImportSource(import_ir_inst.inst_id());
  56. import_ir_inst_id.has_value()) {
  57. result.push_back(
  58. sem_ir->import_ir_insts().Get(import_ir_inst_id).ir_id());
  59. } else if (import_ir_inst.ir_id().has_value()) {
  60. result.push_back(import_ir_inst.ir_id());
  61. }
  62. };
  63. llvm::SmallVector<SemIR::InstId> worklist;
  64. // Push the contents of an instruction block onto our worklist.
  65. auto push_block = [&](SemIR::InstBlockId block_id) {
  66. if (block_id.has_value()) {
  67. llvm::append_range(worklist, context.inst_blocks().Get(block_id));
  68. }
  69. };
  70. // Add the arguments of a specific to the worklist.
  71. auto push_args = [&](SemIR::SpecificId specific_id) {
  72. if (specific_id.has_value()) {
  73. push_block(context.specifics().Get(specific_id).args_id);
  74. }
  75. };
  76. worklist.push_back(context.constant_values().GetInstId(query_self_const_id));
  77. add_entity(context.interfaces().Get(query_specific_interface.interface_id));
  78. push_args(query_specific_interface.specific_id);
  79. while (!worklist.empty()) {
  80. auto inst_id = worklist.pop_back_val();
  81. // Visit the operands of the constant.
  82. auto inst = context.insts().Get(inst_id);
  83. for (auto arg : {inst.arg0_and_kind(), inst.arg1_and_kind()}) {
  84. CARBON_KIND_SWITCH(arg) {
  85. case CARBON_KIND(SemIR::InstId inst_id): {
  86. if (inst_id.has_value()) {
  87. worklist.push_back(inst_id);
  88. }
  89. break;
  90. }
  91. case CARBON_KIND(SemIR::TypeInstId inst_id): {
  92. if (inst_id.has_value()) {
  93. worklist.push_back(inst_id);
  94. }
  95. break;
  96. }
  97. case CARBON_KIND(SemIR::InstBlockId inst_block_id): {
  98. push_block(inst_block_id);
  99. break;
  100. }
  101. case CARBON_KIND(SemIR::ClassId class_id): {
  102. add_entity(context.classes().Get(class_id));
  103. break;
  104. }
  105. case CARBON_KIND(SemIR::InterfaceId interface_id): {
  106. add_entity(context.interfaces().Get(interface_id));
  107. break;
  108. }
  109. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  110. const auto& facet_type_info =
  111. context.facet_types().Get(facet_type_id);
  112. for (const auto& impl : facet_type_info.extend_constraints) {
  113. add_entity(context.interfaces().Get(impl.interface_id));
  114. push_args(impl.specific_id);
  115. }
  116. for (const auto& impl : facet_type_info.self_impls_constraints) {
  117. add_entity(context.interfaces().Get(impl.interface_id));
  118. push_args(impl.specific_id);
  119. }
  120. break;
  121. }
  122. case CARBON_KIND(SemIR::FunctionId function_id): {
  123. add_entity(context.functions().Get(function_id));
  124. break;
  125. }
  126. case CARBON_KIND(SemIR::SpecificId specific_id): {
  127. push_args(specific_id);
  128. break;
  129. }
  130. default: {
  131. break;
  132. }
  133. }
  134. }
  135. }
  136. // Deduplicate.
  137. llvm::sort(result, [](SemIR::ImportIRId a, SemIR::ImportIRId b) {
  138. return a.index < b.index;
  139. });
  140. result.erase(llvm::unique(result), result.end());
  141. return result;
  142. }
  143. // Returns true if a cycle was found and diagnosed.
  144. static auto FindAndDiagnoseImplLookupCycle(
  145. Context& context, 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 diagnose) -> 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. if (diagnose && !stack.back().diagnosed_cycle) {
  164. auto facet_type_type_id = context.types().GetTypeIdForTypeConstantId(
  165. query_facet_type_const_id);
  166. CARBON_DIAGNOSTIC(ImplLookupCycle, Error,
  167. "cycle found in search for impl of {0} for type {1}",
  168. SemIR::TypeId, SemIR::TypeId);
  169. auto builder = context.emitter().Build(
  170. loc_id, ImplLookupCycle, facet_type_type_id,
  171. context.types().GetTypeIdForTypeConstantId(query_self_const_id));
  172. for (const auto& active_entry : llvm::drop_begin(stack, i)) {
  173. if (active_entry.impl_loc.has_value()) {
  174. CARBON_DIAGNOSTIC(ImplLookupCycleNote, Note,
  175. "determining if this impl clause matches", );
  176. builder.Note(active_entry.impl_loc, ImplLookupCycleNote);
  177. }
  178. }
  179. builder.Emit();
  180. }
  181. stack.back().diagnosed_cycle = true;
  182. return true;
  183. }
  184. }
  185. return false;
  186. }
  187. struct RequiredImplsFromConstraint {
  188. llvm::ArrayRef<SemIR::IdentifiedFacetType::RequiredImpl> req_impls;
  189. bool other_requirements;
  190. };
  191. // Gets the set of `SpecificInterface`s that are required by a facet type
  192. // (as a constant value), and any special requirements.
  193. static auto GetRequiredImplsFromConstraint(
  194. Context& context, SemIR::LocId loc_id,
  195. SemIR::ConstantId query_self_const_id,
  196. SemIR::ConstantId query_facet_type_const_id, bool diagnose)
  197. -> std::optional<RequiredImplsFromConstraint> {
  198. auto facet_type_inst_id =
  199. context.constant_values().GetInstId(query_facet_type_const_id);
  200. auto facet_type_inst =
  201. context.insts().GetAs<SemIR::FacetType>(facet_type_inst_id);
  202. const auto& facet_type_info =
  203. context.facet_types().Get(facet_type_inst.facet_type_id);
  204. auto identified_id = RequireIdentifiedFacetType(
  205. context, loc_id, query_self_const_id, facet_type_inst,
  206. [&](auto& builder) {
  207. CARBON_DIAGNOSTIC(ImplLookupInUnidentifiedFacetType, Context,
  208. "facet type {0} can not be identified", InstIdAsType);
  209. builder.Context(loc_id, ImplLookupInUnidentifiedFacetType,
  210. facet_type_inst_id);
  211. },
  212. diagnose);
  213. if (!identified_id.has_value()) {
  214. return std::nullopt;
  215. }
  216. return {
  217. {.req_impls =
  218. context.identified_facet_types().Get(identified_id).required_impls(),
  219. .other_requirements = facet_type_info.other_requirements}};
  220. }
  221. static auto TreatImplAsFinal(Context& context, const SemIR::Impl& impl)
  222. -> bool {
  223. // Lookups for the impl inside its own definition treat the impl as final.
  224. // Nothing can specialize those lookups further, and it resolves any accesses
  225. // of associated constants to their concrete values.
  226. return IsImplEffectivelyFinal(context, impl) || impl.is_being_defined();
  227. }
  228. // Given a (possibly generic) `impl`, deduce a specific `impl` from the query
  229. // self and specific for the interface. Return the witness ID of the `impl` of
  230. // the resulting specific `impl`, if its specific interface matches the query.
  231. //
  232. // Note the witness also has the specific for the `impl` applied to it.
  233. static auto TryGetSpecificWitnessIdForImpl(
  234. Context& context, SemIR::LocId loc_id,
  235. SemIR::ConstantId query_self_const_id,
  236. const SemIR::SpecificInterface& interface, const SemIR::Impl& impl)
  237. -> SemIR::ConstantId {
  238. // The impl may have generic arguments, in which case we need to deduce them
  239. // to find what they are given the specific type and interface query. We use
  240. // that specific to map values in the impl to the deduced values.
  241. auto specific_id = SemIR::SpecificId::None;
  242. if (impl.generic_id.has_value()) {
  243. specific_id = DeduceImplArguments(
  244. context, loc_id, impl, query_self_const_id, interface.specific_id);
  245. if (!specific_id.has_value()) {
  246. return SemIR::ConstantId::None;
  247. }
  248. }
  249. // The self type of the impl must match the type in the query, or this is an
  250. // `impl T as ...` for some other type `T` and should not be considered.
  251. auto noncanonical_deduced_self_const_id = SemIR::GetConstantValueInSpecific(
  252. context.sem_ir(), specific_id, impl.self_id);
  253. // In a generic `impl forall` the self type can be a FacetAccessType, which
  254. // will not be the same constant value as a query facet value. We move through
  255. // to the facet value here, and if the query was a FacetAccessType we did the
  256. // same there so they still match.
  257. auto deduced_self_const_id =
  258. GetCanonicalFacetOrTypeValue(context, noncanonical_deduced_self_const_id);
  259. if (query_self_const_id != deduced_self_const_id) {
  260. return SemIR::ConstantId::None;
  261. }
  262. // The impl's constraint is a facet type which it is implementing for the self
  263. // type: the `I` in `impl ... as I`. The deduction step may be unable to be
  264. // fully applied to the types in the constraint and result in an error here,
  265. // in which case it does not match the query.
  266. auto deduced_constraint_id = SemIR::GetConstantValueInSpecific(
  267. context.sem_ir(), specific_id, impl.constraint_id);
  268. if (deduced_constraint_id == SemIR::ErrorInst::ConstantId) {
  269. return SemIR::ConstantId::None;
  270. }
  271. auto deduced_constraint_facet_type_id =
  272. context.constant_values()
  273. .GetInstAs<SemIR::FacetType>(deduced_constraint_id)
  274. .facet_type_id;
  275. const auto& deduced_constraint_facet_type_info =
  276. context.facet_types().Get(deduced_constraint_facet_type_id);
  277. CARBON_CHECK(deduced_constraint_facet_type_info.extend_constraints.size() ==
  278. 1);
  279. if (deduced_constraint_facet_type_info.other_requirements) {
  280. return SemIR::ConstantId::None;
  281. }
  282. // The specifics in the queried interface must match the deduced specifics in
  283. // the impl's constraint facet type.
  284. auto impl_interface_specific_id =
  285. deduced_constraint_facet_type_info.extend_constraints[0].specific_id;
  286. auto query_interface_specific_id = interface.specific_id;
  287. if (impl_interface_specific_id != query_interface_specific_id) {
  288. return SemIR::ConstantId::None;
  289. }
  290. LoadImportRef(context, impl.witness_id);
  291. if (!impl.is_being_defined() && specific_id.has_value()) {
  292. // If the impl definition can be resolved, eval will do it immediately;
  293. // otherwise, it can be resolved by further specialization. This is used to
  294. // resolve dependency chains when `MakeFinal` is returned without a concrete
  295. // definition; particularly final impls with symbolic constants.
  296. //
  297. // Note we do not do this for lookups _inside_ the definition of the impl,
  298. // as that creates a cycle where resolving the definition must resolve the
  299. // definition.
  300. AddInstInNoBlock(
  301. context, loc_id,
  302. SemIR::RequireSpecificDefinition{
  303. .type_id = GetSingletonType(
  304. context, SemIR::RequireSpecificDefinitionType::TypeInstId),
  305. .specific_id = specific_id});
  306. }
  307. return SemIR::GetConstantValueInSpecific(context.sem_ir(), specific_id,
  308. impl.witness_id);
  309. }
  310. // Identify the facet type of the query self. It is allowed to be partially
  311. // identified.
  312. static auto IdentifyQuerySelfFacetType(Context& context, SemIR::LocId loc_id,
  313. SemIR::ConstantId query_self_const_id)
  314. -> SemIR::IdentifiedFacetTypeId {
  315. auto query_self_inst_id =
  316. context.constant_values().GetInstId(query_self_const_id);
  317. auto facet_type = context.types().TryGetAs<SemIR::FacetType>(
  318. context.insts().Get(query_self_inst_id).type_id());
  319. if (!facet_type) {
  320. return SemIR::IdentifiedFacetTypeId::None;
  321. }
  322. return TryToIdentifyFacetType(context, loc_id, query_self_const_id,
  323. *facet_type,
  324. /*allow_partially_identified=*/true);
  325. }
  326. // Given a query `orig_inst_self` and `orig_interface`, try find a matching
  327. // witness from impl lookup to use for the query.
  328. static auto TryFindMatchingWitnessFromImplLookup(
  329. Context& context, SemIR::LocId loc_id,
  330. SemIR::ConstantId canonical_query_self_const_id,
  331. llvm::ArrayRef<SemIR::IdentifiedFacetType::RequiredImpl> req_impls,
  332. llvm::ArrayRef<SemIR::InstId> found_witness_inst_ids,
  333. SemIR::ConstantId orig_const_self, SemIR::SpecificInterface orig_interface)
  334. -> SemIR::InstId {
  335. // The `req_impls` come from an IdentifiedFacetType so they have `.Self`
  336. // replaced. We need to do the same for the self and interface in the
  337. // `orig_witness` for comparing with them.
  338. SubstPeriodSelfCallbacks callbacks(&context, loc_id,
  339. canonical_query_self_const_id);
  340. orig_const_self = SubstPeriodSelf(context, callbacks, orig_const_self);
  341. orig_interface = SubstPeriodSelf(context, callbacks, orig_interface);
  342. // Witnesses have a canonicalized self value. Perform the same
  343. // canonicalization here so that we can compare them.
  344. orig_const_self =
  345. GetCanonicalQuerySelfForLookupImplWitness(context, orig_const_self);
  346. for (auto [req_impl, found_witness_inst_id] :
  347. llvm::zip_equal(req_impls, found_witness_inst_ids)) {
  348. auto [req_const_self, req_interface] = req_impl;
  349. if (req_const_self == orig_const_self && req_interface == orig_interface) {
  350. return found_witness_inst_id;
  351. }
  352. }
  353. return SemIR::InstId::None;
  354. }
  355. class SubstPeriodSelfInRewriteCallbacks : public SubstPeriodSelfCallbacks {
  356. public:
  357. explicit SubstPeriodSelfInRewriteCallbacks(
  358. Context* context, SemIR::LocId loc_id,
  359. SemIR::ConstantId period_self_replacement_id,
  360. llvm::ArrayRef<SemIR::IdentifiedFacetType::RequiredImpl> req_impls,
  361. llvm::ArrayRef<SemIR::InstId> witness_inst_ids)
  362. : SubstPeriodSelfCallbacks(context, loc_id, period_self_replacement_id),
  363. req_impls_(req_impls),
  364. witness_inst_ids_(witness_inst_ids) {}
  365. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst)
  366. -> SemIR::InstId override {
  367. // When rebuilding a witness where `.Self` was replaced, use a witness we
  368. // found in impl lookup instead of performing impl lookup again.
  369. if (auto lookup = new_inst.TryAs<SemIR::LookupImplWitness>()) {
  370. auto witness = TryFindMatchingWitnessFromImplLookup(
  371. context(), loc_id(), period_self_replacement_id(), req_impls_,
  372. witness_inst_ids_,
  373. context().constant_values().Get(lookup->query_self_inst_id),
  374. context().specific_interfaces().Get(
  375. lookup->query_specific_interface_id));
  376. if (witness.has_value()) {
  377. return witness;
  378. }
  379. }
  380. return SubstPeriodSelfCallbacks::Rebuild(orig_inst_id, new_inst);
  381. }
  382. private:
  383. llvm::ArrayRef<SemIR::IdentifiedFacetType::RequiredImpl> req_impls_;
  384. llvm::ArrayRef<SemIR::InstId> witness_inst_ids_;
  385. };
  386. static auto VerifyQueryFacetTypeConstraints(
  387. Context& context, SemIR::LocId loc_id,
  388. SemIR::ConstantId query_self_const_id,
  389. SemIR::ConstantId query_facet_type_const_id,
  390. llvm::ArrayRef<SemIR::IdentifiedFacetType::RequiredImpl> req_impls,
  391. llvm::ArrayRef<SemIR::InstId> witness_inst_ids) -> bool {
  392. const auto& facet_type_info = context.facet_types().Get(
  393. context.constant_values()
  394. .GetInstAs<SemIR::FacetType>(query_facet_type_const_id)
  395. .facet_type_id);
  396. if (!facet_type_info.rewrite_constraints.empty()) {
  397. SubstPeriodSelfInRewriteCallbacks callbacks(
  398. &context, loc_id, query_self_const_id, req_impls, witness_inst_ids);
  399. for (const auto& rewrite : facet_type_info.rewrite_constraints) {
  400. // Replace `.Self` in rewrite constraints with the query self in order to
  401. // find the provided values of rewrite constraints from the query. This
  402. // includes replacing `.Self` in LookupImplWitness instructions.
  403. //
  404. // When we have found a witness in impl lookup for the query in a
  405. // LookupImplWitness insts, we need to use that witness directly instead
  406. // of rebuilding (and reevaluating) the LookupImplWitness which will
  407. // execute another impl lookup.
  408. auto lhs_id = context.constant_values().GetInstId(SubstPeriodSelf(
  409. context, callbacks, context.constant_values().Get(rewrite.lhs_id)));
  410. auto rhs_id = context.constant_values().GetInstId(SubstPeriodSelf(
  411. context, callbacks, context.constant_values().Get(rewrite.rhs_id)));
  412. if (lhs_id != rhs_id) {
  413. // TODO: Provide a diagnostic note and location for which rewrite
  414. // constraint was not satisfied, if a diagnostic is going to be
  415. // displayed for the LookupImplWitness() failure. This may require
  416. // plumbing through a callback that lets us add a Note to another
  417. // diagnostic.
  418. return false;
  419. }
  420. }
  421. }
  422. // TODO: Validate that the witnesses satisfy the other requirements in the
  423. // `facet_type_info`.
  424. return true;
  425. }
  426. // Returns whether the query is concrete, it is false if the self type or
  427. // interface specifics have a symbolic dependency.
  428. static auto QueryIsConcrete(Context& context, SemIR::ConstantId self_const_id,
  429. const SemIR::SpecificInterface& specific_interface)
  430. -> bool {
  431. if (!self_const_id.is_concrete()) {
  432. return false;
  433. }
  434. if (!specific_interface.specific_id.has_value()) {
  435. return true;
  436. }
  437. auto args_id =
  438. context.specifics().Get(specific_interface.specific_id).args_id;
  439. for (auto inst_id : context.inst_blocks().Get(args_id)) {
  440. if (!context.constant_values().Get(inst_id).is_concrete()) {
  441. return false;
  442. }
  443. }
  444. return true;
  445. }
  446. namespace {
  447. // A class to filter imported impls based on whether they could possibly match a
  448. // query, prior to importing them. For now we only consider impls that are for
  449. // an interface that's being queried.
  450. //
  451. // TODO: There's a lot more we could do to filter out impls that can't possibly
  452. // match.
  453. class ImportImplFilter {
  454. public:
  455. explicit ImportImplFilter(Context& context, SemIR::ImportIRId import_ir_id,
  456. SemIR::SpecificInterface interface)
  457. : context_(&context),
  458. interface_id_(interface.interface_id),
  459. import_ir_id_(import_ir_id),
  460. import_ir_(context_->import_irs().Get(import_ir_id).sem_ir),
  461. cached_import_interface_id_(SemIR::InterfaceId::None) {}
  462. // Returns whether the given impl is potentially relevant for the current
  463. // query.
  464. auto IsRelevantImpl(SemIR::ImplId import_impl_id) -> bool {
  465. auto impl_interface_id =
  466. import_ir_->impls().Get(import_impl_id).interface.interface_id;
  467. if (!impl_interface_id.has_value()) {
  468. // This indicates that an error occurred when type-checking the impl.
  469. // TODO: Use an explicit error value for this rather than None.
  470. return false;
  471. }
  472. return IsRelevantInterface(impl_interface_id);
  473. }
  474. private:
  475. // Returns whether an impl for the given interface might be relevant to the
  476. // current query.
  477. auto IsRelevantInterface(SemIR::InterfaceId import_interface_id) -> bool {
  478. if (!cached_import_interface_id_.has_value()) {
  479. if (IsSameInterface(import_interface_id, interface_id_)) {
  480. cached_import_interface_id_ = import_interface_id;
  481. return true;
  482. }
  483. } else if (cached_import_interface_id_ == import_interface_id) {
  484. return true;
  485. }
  486. return false;
  487. }
  488. // Returns whether the given interfaces from two different IRs are the same.
  489. auto IsSameInterface(SemIR::InterfaceId import_interface_id,
  490. SemIR::InterfaceId local_interface_id) -> bool {
  491. // The names must be the same.
  492. if (import_ir_->names().GetAsStringIfIdentifier(
  493. import_ir_->interfaces().Get(import_interface_id).name_id) !=
  494. context_->names().GetAsStringIfIdentifier(
  495. context_->interfaces().Get(local_interface_id).name_id)) {
  496. return false;
  497. }
  498. // Compare the interfaces themselves.
  499. // TODO: Should we check the scope of the interface before doing this?
  500. auto local_version_of_import_interface_id =
  501. ImportInterface(*context_, import_ir_id_, import_interface_id);
  502. return local_version_of_import_interface_id == local_interface_id;
  503. }
  504. Context* context_;
  505. // The interface being looked up.
  506. SemIR::InterfaceId interface_id_;
  507. // The IR that we are currently importing impls from.
  508. SemIR::ImportIRId import_ir_id_;
  509. const SemIR::File* import_ir_;
  510. // The interface ID of `interface_id_` in `import_ir_`, if known.
  511. SemIR::InterfaceId cached_import_interface_id_;
  512. };
  513. } // namespace
  514. struct CandidateImpl {
  515. const SemIR::Impl* impl;
  516. // Used for sorting the candidates to find the most-specialized match.
  517. TypeStructure type_structure;
  518. };
  519. struct CandidateImpls {
  520. llvm::SmallVector<CandidateImpl> impls;
  521. bool consider_cpp_candidates = false;
  522. };
  523. // Returns the list of candidates impls for lookup to select from.
  524. static auto CollectCandidateImplsForQuery(
  525. Context& context, bool final_only, SemIR::ConstantId query_self_const_id,
  526. const TypeStructure& query_type_structure,
  527. SemIR::SpecificInterface& query_specific_interface) -> CandidateImpls {
  528. CandidateImpls candidates;
  529. auto import_irs = FindAssociatedImportIRs(context, query_self_const_id,
  530. query_specific_interface);
  531. for (auto import_ir_id : import_irs) {
  532. // If `Cpp` is an associated package, then we'll instead look for C++
  533. // operator overloads for certain well-known interfaces.
  534. if (import_ir_id == SemIR::ImportIRId::Cpp) {
  535. candidates.consider_cpp_candidates = true;
  536. continue;
  537. }
  538. // Instead of importing all impls, only import ones that are in some way
  539. // connected to this query.
  540. ImportImplFilter filter(context, import_ir_id, query_specific_interface);
  541. for (auto [import_impl_id, _] :
  542. context.import_irs().Get(import_ir_id).sem_ir->impls().enumerate()) {
  543. if (filter.IsRelevantImpl(import_impl_id)) {
  544. // TODO: Track the relevant impls and only consider those ones and any
  545. // local impls, rather than looping over all impls below.
  546. ImportImpl(context, import_ir_id, import_impl_id);
  547. }
  548. }
  549. }
  550. for (auto [id, impl] : context.impls().enumerate()) {
  551. CARBON_CHECK(impl.witness_id.has_value());
  552. if (final_only && !TreatImplAsFinal(context, impl)) {
  553. continue;
  554. }
  555. // If the impl's interface_id differs from the query, then this impl can
  556. // not possibly provide the queried interface.
  557. if (impl.interface.interface_id != query_specific_interface.interface_id) {
  558. continue;
  559. }
  560. // When the impl's interface_id matches, but the interface is generic, the
  561. // impl may or may not match based on restrictions in the generic
  562. // parameters of the impl.
  563. //
  564. // As a shortcut, if the impl's constraint is not symbolic (does not
  565. // depend on any generic parameters), then we can determine whether we match
  566. // by looking if the specific ids match exactly.
  567. auto impl_interface_const_id =
  568. context.constant_values().Get(impl.constraint_id);
  569. if (!impl_interface_const_id.is_symbolic() &&
  570. impl.interface.specific_id != query_specific_interface.specific_id) {
  571. continue;
  572. }
  573. // Build the type structure used for choosing the best the candidate.
  574. auto type_structure =
  575. BuildTypeStructure(context, impl.self_id, impl.interface);
  576. if (!type_structure) {
  577. continue;
  578. }
  579. // TODO: We can skip the comparison here if the `impl_interface_const_id` is
  580. // not symbolic, since when the interface and specific ids match, and they
  581. // aren't symbolic, the structure will be identical.
  582. if (!query_type_structure.CompareStructure(
  583. TypeStructure::CompareTest::IsEqualToOrMoreSpecificThan,
  584. *type_structure)) {
  585. continue;
  586. }
  587. candidates.impls.push_back({&impl, std::move(*type_structure)});
  588. }
  589. auto compare = [](auto& lhs, auto& rhs) -> bool {
  590. return lhs.type_structure < rhs.type_structure;
  591. };
  592. // Stable sort is used so that impls that are seen first are preferred when
  593. // they have an equal priority ordering.
  594. // TODO: Allow Carbon code to provide a priority ordering explicitly. For
  595. // now they have all the same priority, so the priority is the order in
  596. // which they are found in code.
  597. llvm::stable_sort(candidates.impls, compare);
  598. return candidates;
  599. }
  600. class IndexInFacetValue {
  601. public:
  602. static const IndexInFacetValue None;
  603. static const IndexInFacetValue Unstable;
  604. explicit constexpr IndexInFacetValue(int32_t index) : index_(index) {}
  605. // Returns whether the value represents a successful attempt to find the index
  606. // of an interface in a FacetValue. Returns true regardless of whether the
  607. // index is stable and able to be used or not.
  608. auto WasFound() const -> bool { return index_ != None.index_; }
  609. // Gets the stable index which can be used to index into the witness table in
  610. // a FacetValue, if there is one. Otherwise, returns -1.
  611. auto GetStableIndex() const -> int32_t {
  612. if (index_ == Unstable.index_) {
  613. return None.index_;
  614. }
  615. return index_;
  616. }
  617. private:
  618. int32_t index_;
  619. };
  620. inline constexpr auto IndexInFacetValue::None = IndexInFacetValue(-1);
  621. inline constexpr auto IndexInFacetValue::Unstable = IndexInFacetValue(-2);
  622. // Looks in the facet type of the query self facet value and returns the index
  623. // of `query_specific_interface` in the defined interface order for that facet
  624. // type. The order comes from the `query_self_type_identified_id` which must be
  625. // the IdentifiedFacetType of the type of `query_self_const_id `.
  626. //
  627. // If the query self is not a facet value, the IdentifiedFacetType would be
  628. // None.
  629. //
  630. // The IdentifiedFacetType must not be partially identified in order to find an
  631. // index, as that implies the interface order is not yet stable. In that case,
  632. // no index will be found.
  633. //
  634. // If the `query_specific_interface` is not part of the facet type of the query
  635. // self, returns -1 to indicate it was not found.
  636. static auto IndexOfImplWitnessInSelfFacetValue(
  637. Context& context, SemIR::ConstantId query_self_const_id,
  638. SemIR::IdentifiedFacetTypeId query_self_type_identified_id,
  639. SemIR::SpecificInterface query_specific_interface) -> IndexInFacetValue {
  640. if (!query_self_type_identified_id.has_value()) {
  641. return IndexInFacetValue::None;
  642. }
  643. // The self in the identified facet type is a canonicalized facet value, so we
  644. // canonicalize the query for comparison.
  645. auto canonical_query_self_const_id =
  646. GetCanonicalFacetOrTypeValue(context, query_self_const_id);
  647. const auto& identified =
  648. context.identified_facet_types().Get(query_self_type_identified_id);
  649. auto facet_type_req_impls = llvm::enumerate(identified.required_impls());
  650. auto it = llvm::find_if(facet_type_req_impls, [&](auto e) {
  651. auto [req_self, req_specific_interface] = e.value();
  652. return req_self == canonical_query_self_const_id &&
  653. req_specific_interface == query_specific_interface;
  654. });
  655. if (it == facet_type_req_impls.end()) {
  656. return IndexInFacetValue::None;
  657. }
  658. if (identified.partially_identified()) {
  659. return IndexInFacetValue::Unstable;
  660. }
  661. return IndexInFacetValue(static_cast<int32_t>((*it).index()));
  662. }
  663. static auto FindFinalWitnessFromSelfFacetValue(
  664. Context& context, SemIR::ConstantId query_self_const_id,
  665. SemIR::IdentifiedFacetTypeId query_self_type_identified_id,
  666. SemIR::SpecificInterface query_specific_interface) -> SemIR::InstId {
  667. auto facet_value = context.constant_values().TryGetInstAs<SemIR::FacetValue>(
  668. query_self_const_id);
  669. if (!facet_value) {
  670. return SemIR::InstId::None;
  671. }
  672. auto index_in_facet_value = IndexOfImplWitnessInSelfFacetValue(
  673. context, query_self_const_id, query_self_type_identified_id,
  674. query_specific_interface);
  675. auto stable_index = index_in_facet_value.GetStableIndex();
  676. if (stable_index < 0) {
  677. return SemIR::InstId::None;
  678. }
  679. auto witness_id =
  680. context.inst_blocks().Get(facet_value->witnesses_block_id)[stable_index];
  681. if (context.insts().Is<SemIR::LookupImplWitness>(witness_id)) {
  682. // Did not find a final witness.
  683. return SemIR::InstId::None;
  684. }
  685. return witness_id;
  686. }
  687. static auto FindNonFinalWitness(
  688. Context& context, SemIR::LocId loc_id,
  689. SemIR::ConstantId query_self_const_id,
  690. SemIR::IdentifiedFacetTypeId query_self_type_identified_id,
  691. SemIR::SpecificInterface query_specific_interface) -> bool {
  692. auto index = IndexOfImplWitnessInSelfFacetValue(context, query_self_const_id,
  693. query_self_type_identified_id,
  694. query_specific_interface);
  695. if (index.WasFound()) {
  696. return true;
  697. }
  698. // TODO: Remove SpecificInterfaceId from LookupCustomWitness apis, switch to
  699. // just SpecificInterface.
  700. auto query_specific_interface_id =
  701. context.specific_interfaces().Add(query_specific_interface);
  702. // Consider a custom witness for core interfaces.
  703. // TODO: This needs to expand to more interfaces, and we might want to have
  704. // that dispatch in custom_witness.cpp instead of here.
  705. auto core_interface =
  706. GetCoreInterface(context, query_specific_interface.interface_id);
  707. if (auto witness_id = LookupCustomWitness(
  708. context, loc_id, core_interface, query_self_const_id,
  709. query_specific_interface_id, false)) {
  710. // If there's a final witness, we would have already found it via evaluating
  711. // the LookupImplWitness instruction.
  712. CARBON_CHECK(!witness_id->has_value());
  713. return true;
  714. }
  715. auto query_type_structure = BuildTypeStructure(
  716. context, context.constant_values().GetInstId(query_self_const_id),
  717. query_specific_interface);
  718. // We looked for errors in the query self and facet type already, and we're
  719. // not dealing with monomorphizations here.
  720. CARBON_CHECK(query_type_structure, "error in impl lookup query");
  721. auto candidates = CollectCandidateImplsForQuery(
  722. context, /*final_only=*/false, query_self_const_id, *query_type_structure,
  723. query_specific_interface);
  724. for (const auto& candidate : candidates.impls) {
  725. const auto& impl = *candidate.impl;
  726. context.impl_lookup_stack().back().impl_loc = impl.definition_id;
  727. auto witness_id = TryGetSpecificWitnessIdForImpl(
  728. context, loc_id, query_self_const_id, query_specific_interface, impl);
  729. if (witness_id.has_value()) {
  730. // We looked for errors in the query self and facet type already, and
  731. // we're not dealing with monomorphizations here.
  732. CARBON_CHECK(witness_id != SemIR::ErrorInst::ConstantId,
  733. "error in impl lookup query");
  734. return true;
  735. }
  736. }
  737. // C++ interop only provides final witnesses, so we don't look for a witness
  738. // from C++ here. Those are found in eval of the `LookupImplWitness`
  739. // instruction.
  740. return false;
  741. }
  742. auto LookupImplWitness(Context& context, SemIR::LocId loc_id,
  743. SemIR::ConstantId query_self_const_id,
  744. SemIR::ConstantId query_facet_type_const_id,
  745. bool diagnose) -> SemIR::InstBlockIdOrError {
  746. if (query_self_const_id == SemIR::ErrorInst::ConstantId ||
  747. query_facet_type_const_id == SemIR::ErrorInst::ConstantId) {
  748. return SemIR::InstBlockIdOrError::MakeError();
  749. }
  750. {
  751. // The query self value is a type value or a facet value.
  752. auto query_self_type_id =
  753. context.insts()
  754. .Get(context.constant_values().GetInstId(query_self_const_id))
  755. .type_id();
  756. CARBON_CHECK((context.types().IsOneOf<SemIR::TypeType, SemIR::FacetType>(
  757. query_self_type_id)));
  758. // The query facet type value is indeed a facet type.
  759. CARBON_CHECK(context.constant_values().InstIs<SemIR::FacetType>(
  760. query_facet_type_const_id));
  761. }
  762. auto req_impls_from_constraint =
  763. GetRequiredImplsFromConstraint(context, loc_id, query_self_const_id,
  764. query_facet_type_const_id, diagnose);
  765. if (!req_impls_from_constraint) {
  766. return SemIR::InstBlockIdOrError::MakeError();
  767. }
  768. auto [req_impls, other_requirements] = *req_impls_from_constraint;
  769. if (other_requirements) {
  770. // TODO: Remove this when other requirements go away.
  771. return SemIR::InstBlockId::None;
  772. }
  773. if (req_impls.empty()) {
  774. return SemIR::InstBlockId::Empty;
  775. }
  776. // Cycles are diagnosed even if they are found when diagnostics are otherwise
  777. // being suppressed (such as during deduce).
  778. if (FindAndDiagnoseImplLookupCycle(context, context.impl_lookup_stack(),
  779. loc_id, query_self_const_id,
  780. query_facet_type_const_id, true)) {
  781. return SemIR::InstBlockIdOrError::MakeError();
  782. }
  783. auto& stack = context.impl_lookup_stack();
  784. stack.push_back({
  785. .query_self_const_id = query_self_const_id,
  786. .query_facet_type_const_id = query_facet_type_const_id,
  787. .diagnosed_cycle = stack.empty() ? false : stack.back().diagnosed_cycle,
  788. });
  789. // We need to find a witness for each self+interface pair in `req_impls`.
  790. //
  791. // Every consumer of a facet type needs to agree on the order of interfaces
  792. // used for its witnesses, which is done by following the order in the
  793. // IdentifiedFacetType of the query facet type, and this is represented in the
  794. // order of the interfaces in `req_impls`.
  795. llvm::SmallVector<SemIR::InstId> result_witness_ids;
  796. for (const auto& req_impl : req_impls) {
  797. // Identify the type of the requirement's self up front, if it's a facet, so
  798. // we only have to do this once.
  799. auto req_self_type_identified_id =
  800. IdentifyQuerySelfFacetType(context, loc_id, req_impl.self_facet_value);
  801. // If the self facet contains a final witness for the required interface, we
  802. // use that and avoid any further work. This is strictly an optimization,
  803. // since that same final witness should be found by evaluating a
  804. // LookupImplWitness instruction for the required self+interface pair.
  805. auto result_witness_id = FindFinalWitnessFromSelfFacetValue(
  806. context, req_impl.self_facet_value, req_self_type_identified_id,
  807. req_impl.specific_interface);
  808. if (result_witness_id.has_value()) {
  809. // Found a final witness, use it.
  810. result_witness_ids.push_back(result_witness_id);
  811. continue;
  812. }
  813. auto witness_const_id = EvalOrAddInst<SemIR::LookupImplWitness>(
  814. context, context.insts().GetLocIdForDesugaring(loc_id),
  815. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  816. .query_self_inst_id =
  817. context.constant_values().GetInstId(req_impl.self_facet_value),
  818. .query_specific_interface_id =
  819. context.specific_interfaces().Add(req_impl.specific_interface)});
  820. result_witness_id = context.constant_values().GetInstId(witness_const_id);
  821. if (!context.insts().Is<SemIR::LookupImplWitness>(result_witness_id)) {
  822. // Found a final witness, use it.
  823. result_witness_ids.push_back(result_witness_id);
  824. continue;
  825. }
  826. if (QueryIsConcrete(context, req_impl.self_facet_value,
  827. req_impl.specific_interface)) {
  828. // Failed to find a final witness for a concrete query. There won't be a
  829. // non-final witness, as any witness would have been treated as final.
  830. break;
  831. }
  832. // Did not find a final witness. If we find a non-final witness, then we use
  833. // the `LookupImplWitness` as our witness so that monomorphization can
  834. // produce a final witness later.
  835. if (!FindNonFinalWitness(context, loc_id, req_impl.self_facet_value,
  836. req_self_type_identified_id,
  837. req_impl.specific_interface)) {
  838. // At least one queried interface in the facet type has no witness for the
  839. // given type, we can stop looking for more.
  840. break;
  841. }
  842. // Save the non-final witness, which will eventually resolve to a final
  843. // witness as specifics are applied to make the query more concrete.
  844. result_witness_ids.push_back(result_witness_id);
  845. }
  846. auto pop = stack.pop_back_val();
  847. if (pop.diagnosed_cycle && !stack.empty()) {
  848. stack.back().diagnosed_cycle = true;
  849. }
  850. // All interfaces in the query facet type must have been found to be available
  851. // through some impl, or directly on the value's facet type if
  852. // `query_self_const_id` is a facet value.
  853. if (result_witness_ids.size() != req_impls.size()) {
  854. return SemIR::InstBlockId::None;
  855. }
  856. // Verify rewrite constraints in the query constraint are satisfied after
  857. // applying the rewrites from the found witnesses.
  858. if (!VerifyQueryFacetTypeConstraints(context, loc_id, query_self_const_id,
  859. query_facet_type_const_id, req_impls,
  860. result_witness_ids)) {
  861. return SemIR::InstBlockId::None;
  862. }
  863. return context.inst_blocks().AddCanonical(result_witness_ids);
  864. }
  865. auto GetCanonicalQuerySelfForLookupImplWitness(Context& context,
  866. SemIR::ConstantId self,
  867. SemIR::InstId* out_facet_value)
  868. -> SemIR::ConstantId {
  869. auto self_inst_id = context.constant_values().GetInstId(self);
  870. // If the monomorphized query self is a FacetValue, we may get a witness from
  871. // it under limited circumstances. If no final witness is found though, we
  872. // don't need to preserve it for future evaluations, so we strip it from the
  873. // LookupImplWitness instruction to reduce the number of distinct constant
  874. // values.
  875. if (auto facet_value =
  876. context.insts().TryGetAs<SemIR::FacetValue>(self_inst_id)) {
  877. if (out_facet_value) {
  878. *out_facet_value = self_inst_id;
  879. }
  880. self_inst_id = facet_value->type_inst_id;
  881. }
  882. // The self value is canonicalized in order to produce a canonical
  883. // LookupImplWitness instruction, avoiding multiple constant values for
  884. // `<facet value>` and `<facet value> as type`, which always have the same
  885. // lookup result.
  886. return GetCanonicalFacetOrTypeValue(
  887. context, context.constant_values().Get(self_inst_id));
  888. }
  889. // Record the query which found a final impl witness. It's illegal to
  890. // write a final impl afterward that would match the same query.
  891. static auto PoisonImplLookupQuery(Context& context, SemIR::LocId loc_id,
  892. EvalImplLookupMode mode,
  893. SemIR::LookupImplWitness eval_query,
  894. SemIR::ConstantId witness_id,
  895. const SemIR::Impl& impl) -> void {
  896. if (mode == EvalImplLookupMode::RecheckPoisonedLookup) {
  897. return;
  898. }
  899. // If the impl was effectively final, then we don't need to poison here. A
  900. // change of query result will already be diagnosed at the point where the
  901. // new impl decl was written that changes the result.
  902. if (TreatImplAsFinal(context, impl)) {
  903. return;
  904. }
  905. context.poisoned_concrete_impl_lookup_queries().push_back(
  906. {.loc_id = loc_id, .query = eval_query, .witness_id = witness_id});
  907. }
  908. // Return whether the `FacetType` in `type_id` extends a single interface, and
  909. // that it matches `specific_interface`.
  910. static auto FacetTypeIsSingleInterface(
  911. Context& context, SemIR::TypeId type_id,
  912. SemIR::SpecificInterface specific_interface) -> bool {
  913. auto facet_type = context.types().GetAs<SemIR::FacetType>(type_id);
  914. const auto& facet_type_info =
  915. context.facet_types().Get(facet_type.facet_type_id);
  916. if (auto single = facet_type_info.TryAsSingleExtend()) {
  917. if (auto* si = std::get_if<SemIR::SpecificInterface>(&*single)) {
  918. return *si == specific_interface;
  919. }
  920. }
  921. return false;
  922. }
  923. auto EvalLookupSingleFinalWitness(Context& context, SemIR::LocId loc_id,
  924. SemIR::LookupImplWitness eval_query,
  925. SemIR::InstId self_facet_value_inst_id,
  926. EvalImplLookupMode mode)
  927. -> SemIR::ConstantId {
  928. auto query_specific_interface =
  929. context.specific_interfaces().Get(eval_query.query_specific_interface_id);
  930. // Ensure specifics don't substitute in weird things for the query self.
  931. CARBON_CHECK(context.types().IsFacetType(
  932. context.insts().Get(eval_query.query_self_inst_id).type_id()));
  933. SemIR::ConstantId query_self_const_id =
  934. context.constant_values().Get(eval_query.query_self_inst_id);
  935. // If the query self is monomorphized as a FacetValue, we can't use its
  936. // witnesses in general, since we are not allowed to identify facet types in
  937. // monomorphization. And we need to identify it to know which witness is for
  938. // which interface.
  939. //
  940. // However, if the facet type has only a single interface and it matches the
  941. // query, then we can use the witness, since there is only one.
  942. //
  943. // This looks like an optimization, but it's done to prefer the FacetValue's
  944. // witness over the cached value for monomorphizations of `Self` inside an
  945. // `impl` definition. If a final witness was previously found for the same
  946. // type as the monomorphized `Self`, the cache would reuse it. But associated
  947. // constants may differ in that witness from the current `impl`'s witness
  948. // which leads to inconsistency within the impl definition.
  949. //
  950. // By preferring the impl's FacetValue, the `impl` remains self-consistent
  951. // even if it's ultimately not valid due to a conflict. When a conflict with
  952. // another `impl` does exist, a poisoning error will occur showing the two
  953. // `impl`s are in disagreement for a concrete value, as the poisoning lookup
  954. // does not preserve the FacetValue.
  955. if (auto facet_value = context.insts().TryGetAsIfValid<SemIR::FacetValue>(
  956. self_facet_value_inst_id)) {
  957. if (FacetTypeIsSingleInterface(context, facet_value->type_id,
  958. query_specific_interface)) {
  959. auto witnesses =
  960. context.inst_blocks().Get(facet_value->witnesses_block_id);
  961. CARBON_CHECK(witnesses.size() == 1);
  962. auto witness_inst_id = witnesses.front();
  963. // Only use the witness in monomoprhization if it's a final witness.
  964. if (!context.insts().Is<SemIR::LookupImplWitness>(witness_inst_id)) {
  965. return context.constant_values().Get(witness_inst_id);
  966. }
  967. }
  968. }
  969. // If the query is on `.Self` and looking for the same interface as `.Self`
  970. // provides, do not look for a witness in monomorphization - a non-final
  971. // witness will be found from the facet type. This happens inside an `impl`
  972. // declaration, and we must avoid finding that same `impl` and trying to
  973. // deduce `.Self` for it, as that results in a specific declaration for the
  974. // `impl` which evaluates this lookup again, producing a cycle.
  975. //
  976. // If the query is for `.Self` and for the facet type of `.Self`, then there
  977. // is no final witness yet.
  978. if (auto bind = context.insts().TryGetAs<SemIR::SymbolicBinding>(
  979. eval_query.query_self_inst_id)) {
  980. const auto& entity = context.entity_names().Get(bind->entity_name_id);
  981. if (entity.name_id == SemIR::NameId::PeriodSelf) {
  982. if (FacetTypeIsSingleInterface(context, bind->type_id,
  983. query_specific_interface)) {
  984. return SemIR::ConstantId::None;
  985. }
  986. }
  987. }
  988. // Check to see if this result is in the cache. But skip the cache if we're
  989. // re-checking a poisoned result and need to redo the lookup.
  990. auto impl_lookup_cache_key = Context::ImplLookupCacheKey{
  991. query_self_const_id, eval_query.query_specific_interface_id};
  992. if (mode != EvalImplLookupMode::RecheckPoisonedLookup) {
  993. if (auto result =
  994. context.impl_lookup_cache().Lookup(impl_lookup_cache_key)) {
  995. return result.value();
  996. }
  997. }
  998. bool query_is_concrete =
  999. QueryIsConcrete(context, query_self_const_id, query_specific_interface);
  1000. auto query_type_structure = BuildTypeStructure(
  1001. context, context.constant_values().GetInstId(query_self_const_id),
  1002. query_specific_interface);
  1003. if (!query_type_structure) {
  1004. // TODO: We should return an error here; an error was found in the type
  1005. // structure.
  1006. return SemIR::ConstantId::None;
  1007. }
  1008. // We only want to return final witneses in monomorphization. If the query is
  1009. // concrete, we can find all impls, otherwise we want only (effectively) final
  1010. // impls.
  1011. auto candidates = CollectCandidateImplsForQuery(
  1012. context, /*final_only=*/!query_is_concrete, query_self_const_id,
  1013. *query_type_structure, query_specific_interface);
  1014. struct LookupResult {
  1015. SemIR::ConstantId witness_id = SemIR::ConstantId::None;
  1016. // Holds a pointer into `candidates`.
  1017. const TypeStructure* impl_type_structure = nullptr;
  1018. SemIR::LocId impl_loc_id = SemIR::LocId::None;
  1019. };
  1020. LookupResult lookup_result;
  1021. auto core_interface =
  1022. GetCoreInterface(context, query_specific_interface.interface_id);
  1023. // Consider a custom witness for core interfaces.
  1024. // TODO: This needs to expand to more interfaces, and we might want to have
  1025. // that dispatch in custom_witness.cpp instead of here.
  1026. bool used_custom_witness = false;
  1027. if (auto witness_inst_id = LookupCustomWitness(
  1028. context, loc_id, core_interface, query_self_const_id,
  1029. eval_query.query_specific_interface_id, true)) {
  1030. if (witness_inst_id->has_value()) {
  1031. lookup_result = {.witness_id =
  1032. context.constant_values().Get(*witness_inst_id)};
  1033. used_custom_witness = true;
  1034. }
  1035. }
  1036. // Only consider candidates when a custom witness didn't apply.
  1037. if (!used_custom_witness) {
  1038. for (const auto& candidate : candidates.impls) {
  1039. const auto& impl = *candidate.impl;
  1040. // In monomorphization, while resolving a specific, there may be no stack
  1041. // yet as this may be the first lookup. If further lookups are started as
  1042. // a result in deduce, they will build the stack.
  1043. if (!context.impl_lookup_stack().empty()) {
  1044. context.impl_lookup_stack().back().impl_loc = impl.definition_id;
  1045. }
  1046. auto witness_id = TryGetSpecificWitnessIdForImpl(
  1047. context, loc_id, query_self_const_id, query_specific_interface, impl);
  1048. if (witness_id.has_value()) {
  1049. PoisonImplLookupQuery(context, loc_id, mode, eval_query, witness_id,
  1050. impl);
  1051. lookup_result = {.witness_id = witness_id,
  1052. .impl_type_structure = &candidate.type_structure,
  1053. .impl_loc_id = SemIR::LocId(impl.definition_id)};
  1054. break;
  1055. }
  1056. }
  1057. }
  1058. if (query_is_concrete && candidates.consider_cpp_candidates &&
  1059. core_interface != SemIR::CoreInterface::Unknown) {
  1060. // Also check for a C++ candidate that is a better match than whatever
  1061. // `impl` we may have found in Carbon.
  1062. auto cpp_witness_id = LookupCppImpl(
  1063. context, loc_id, core_interface, query_self_const_id,
  1064. eval_query.query_specific_interface_id,
  1065. lookup_result.impl_type_structure, lookup_result.impl_loc_id);
  1066. if (cpp_witness_id.has_value()) {
  1067. lookup_result = {.witness_id =
  1068. context.constant_values().Get(cpp_witness_id)};
  1069. }
  1070. }
  1071. if (mode != EvalImplLookupMode::RecheckPoisonedLookup &&
  1072. lookup_result.witness_id.has_value()) {
  1073. context.impl_lookup_cache().Insert(impl_lookup_cache_key,
  1074. lookup_result.witness_id);
  1075. }
  1076. return lookup_result.witness_id;
  1077. }
  1078. auto LookupMatchesImpl(Context& context, SemIR::LocId loc_id,
  1079. SemIR::ConstantId query_self_const_id,
  1080. SemIR::SpecificInterface query_specific_interface,
  1081. SemIR::ImplId target_impl) -> bool {
  1082. if (query_self_const_id == SemIR::ErrorInst::ConstantId) {
  1083. return false;
  1084. }
  1085. auto witness_id = TryGetSpecificWitnessIdForImpl(
  1086. context, loc_id, query_self_const_id, query_specific_interface,
  1087. context.impls().Get(target_impl));
  1088. // TODO: If this fails, it would be because there is an error in the specific
  1089. // interface. Should we check for that and return false?
  1090. CARBON_CHECK(witness_id != SemIR::ErrorInst::ConstantId,
  1091. "error in lookup specific interface");
  1092. return witness_id.has_value();
  1093. }
  1094. } // namespace Carbon::Check