impl_lookup.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  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, llvm::SmallVector<Context::ImplLookupStackEntry>& stack,
  145. SemIR::LocId loc_id, SemIR::ConstantId query_self_const_id,
  146. SemIR::ConstantId query_facet_type_const_id, bool diagnose) -> bool {
  147. // Deduction of the interface parameters can do further impl lookups, and we
  148. // need to ensure we terminate.
  149. //
  150. // https://docs.carbon-lang.dev/docs/design/generics/details.html#acyclic-rule
  151. // - We look for violations of the acyclic rule by seeing if a previous lookup
  152. // had all the same type inputs.
  153. // - The `query_facet_type_const_id` encodes the entire facet type being
  154. // looked up, including any specific parameters for a generic interface.
  155. //
  156. // TODO: Implement the termination rule, which requires looking at the
  157. // complexity of the types on the top of (or throughout?) the stack:
  158. // https://docs.carbon-lang.dev/docs/design/generics/details.html#termination-rule
  159. for (auto [i, entry] : llvm::enumerate(stack)) {
  160. if (entry.query_self_const_id == query_self_const_id &&
  161. entry.query_facet_type_const_id == query_facet_type_const_id) {
  162. if (diagnose && !stack.back().diagnosed_cycle) {
  163. auto facet_type_type_id = context.types().GetTypeIdForTypeConstantId(
  164. 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. }
  180. stack.back().diagnosed_cycle = true;
  181. return true;
  182. }
  183. }
  184. return false;
  185. }
  186. struct RequiredImplsFromConstraint {
  187. llvm::ArrayRef<SemIR::IdentifiedFacetType::RequiredImpl> req_impls;
  188. bool other_requirements;
  189. };
  190. // Gets the set of `SpecificInterface`s that are required by a facet type
  191. // (as a constant value), and any special requirements.
  192. static auto GetRequiredImplsFromConstraint(
  193. Context& context, SemIR::LocId loc_id,
  194. SemIR::ConstantId query_self_const_id,
  195. SemIR::ConstantId query_facet_type_const_id, bool diagnose)
  196. -> std::optional<RequiredImplsFromConstraint> {
  197. auto facet_type_inst_id =
  198. context.constant_values().GetInstId(query_facet_type_const_id);
  199. auto facet_type_inst =
  200. context.insts().GetAs<SemIR::FacetType>(facet_type_inst_id);
  201. const auto& facet_type_info =
  202. context.facet_types().Get(facet_type_inst.facet_type_id);
  203. auto identified_id = RequireIdentifiedFacetType(
  204. context, loc_id, query_self_const_id, facet_type_inst,
  205. [&](auto& builder) {
  206. CARBON_DIAGNOSTIC(ImplLookupInUnidentifiedFacetType, Context,
  207. "facet type {0} can not be identified", InstIdAsType);
  208. builder.Context(loc_id, ImplLookupInUnidentifiedFacetType,
  209. facet_type_inst_id);
  210. },
  211. diagnose);
  212. if (!identified_id.has_value()) {
  213. return std::nullopt;
  214. }
  215. return {
  216. {.req_impls =
  217. context.identified_facet_types().Get(identified_id).required_impls(),
  218. .other_requirements = facet_type_info.other_requirements}};
  219. }
  220. static auto TreatImplAsFinal(Context& context, const SemIR::Impl& impl)
  221. -> bool {
  222. // Lookups for the impl inside its own definition treat the impl as final.
  223. // Nothing can specialize those lookups further, and it resolves any accesses
  224. // of associated constants to their concrete values.
  225. return IsImplEffectivelyFinal(context, impl) || impl.is_being_defined();
  226. }
  227. // Given a (possibly generic) `impl`, deduce a specific `impl` from the query
  228. // self and specific for the interface. Return the witness ID of the `impl` of
  229. // the resulting specific `impl`, if its specific interface matches the query.
  230. //
  231. // Note the witness also has the specific for the `impl` applied to it.
  232. static auto TryGetSpecificWitnessIdForImpl(
  233. Context& context, SemIR::LocId loc_id,
  234. SemIR::ConstantId query_self_const_id,
  235. const SemIR::SpecificInterface& interface, const SemIR::Impl& impl)
  236. -> SemIR::ConstantId {
  237. // The impl may have generic arguments, in which case we need to deduce them
  238. // to find what they are given the specific type and interface query. We use
  239. // that specific to map values in the impl to the deduced values.
  240. auto specific_id = SemIR::SpecificId::None;
  241. if (impl.generic_id.has_value()) {
  242. specific_id = DeduceImplArguments(
  243. context, loc_id, impl, query_self_const_id, interface.specific_id);
  244. if (!specific_id.has_value()) {
  245. return SemIR::ConstantId::None;
  246. }
  247. }
  248. // The self type of the impl must match the type in the query, or this is an
  249. // `impl T as ...` for some other type `T` and should not be considered.
  250. auto noncanonical_deduced_self_const_id = SemIR::GetConstantValueInSpecific(
  251. context.sem_ir(), specific_id, impl.self_id);
  252. // In a generic `impl forall` the self type can be a FacetAccessType, which
  253. // will not be the same constant value as a query facet value. We move through
  254. // to the facet value here, and if the query was a FacetAccessType we did the
  255. // same there so they still match.
  256. auto deduced_self_const_id =
  257. GetCanonicalFacetOrTypeValue(context, noncanonical_deduced_self_const_id);
  258. if (query_self_const_id != deduced_self_const_id) {
  259. return SemIR::ConstantId::None;
  260. }
  261. // The impl's constraint is a facet type which it is implementing for the self
  262. // type: the `I` in `impl ... as I`. The deduction step may be unable to be
  263. // fully applied to the types in the constraint and result in an error here,
  264. // in which case it does not match the query.
  265. auto deduced_constraint_id =
  266. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  267. context.sem_ir(), specific_id, impl.constraint_id));
  268. if (deduced_constraint_id == SemIR::ErrorInst::InstId) {
  269. return SemIR::ConstantId::None;
  270. }
  271. auto deduced_constraint_facet_type_id =
  272. context.insts()
  273. .GetAs<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. // Substitutes witnesess in place of `LookupImplWitness` queries into `.Self`,
  327. // when the witness is for the same interface as the one `.Self` is referring
  328. // to.
  329. //
  330. // This allows access to the `FacetType` and its constraints from the witness,
  331. // and allows `ImplWitnessAccess` instructions to be immediately resolved to a
  332. // more specific value when possible.
  333. class SubstWitnessesCallbacks : public SubstInstCallbacks {
  334. public:
  335. // `context` must not be null.
  336. explicit SubstWitnessesCallbacks(
  337. Context* context, SemIR::LocId loc_id,
  338. SemIR::ConstantId query_self_const_id,
  339. llvm::ArrayRef<SemIR::IdentifiedFacetType::RequiredImpl> req_impls,
  340. llvm::ArrayRef<SemIR::InstId> witness_inst_ids)
  341. : SubstInstCallbacks(context),
  342. loc_id_(loc_id),
  343. canonical_query_self_const_id_(
  344. GetCanonicalFacetOrTypeValue(*context, query_self_const_id)),
  345. req_impls_(req_impls),
  346. witness_inst_ids_(witness_inst_ids) {}
  347. auto Subst(SemIR::InstId& inst_id) -> SubstResult override {
  348. // `FacetType` can be concrete even when it has rewrite constraints that
  349. // have a symbolic dependency on `.Self`. See use of
  350. // `GetConstantValueIgnoringPeriodSelf` in eval. So in order to recurse into
  351. // `FacetType` we must check for it before the `is_concrete` early return.
  352. if (context().insts().Is<SemIR::FacetType>(inst_id)) {
  353. ++facet_type_depth_;
  354. return SubstOperands;
  355. }
  356. if (context().constant_values().Get(inst_id).is_concrete()) {
  357. return FullySubstituted;
  358. }
  359. auto access = context().insts().TryGetAs<SemIR::ImplWitnessAccess>(inst_id);
  360. if (!access) {
  361. return SubstOperands;
  362. }
  363. auto lookup =
  364. context().insts().GetAs<SemIR::LookupImplWitness>(access->witness_id);
  365. auto bind_name = context().insts().TryGetAs<SemIR::SymbolicBinding>(
  366. lookup.query_self_inst_id);
  367. if (!bind_name) {
  368. return SubstOperands;
  369. }
  370. const auto& self_entity_name =
  371. context().entity_names().Get(bind_name->entity_name_id);
  372. if (self_entity_name.name_id != SemIR::NameId::PeriodSelf) {
  373. return SubstOperands;
  374. }
  375. // TODO: Once we are numbering `EntityName`, (see the third model in
  376. // https://docs.google.com/document/d/1Yt-i5AmF76LSvD4TrWRIAE_92kii6j5yFiW-S7ahzlg/edit?tab=t.0#heading=h.7urbxcq23olv)
  377. // then verify that the index here is equal to the `facet_type_depth_`,
  378. // which would mean that it is a reference to the top-level `Self`, which is
  379. // being replaced with the impl lookup query self facet value (and then we
  380. // use the witness derived from it).
  381. //
  382. // For now, we only substitute if depth == 0, which is incorrect inside
  383. // nested facet types, as it can miss references in specifics up to the top
  384. // level facet value.
  385. if (facet_type_depth_ > 0) {
  386. return SubstOperands;
  387. }
  388. auto witness_id =
  389. FindWitnessForInterface(lookup.query_specific_interface_id);
  390. if (!witness_id.has_value()) {
  391. return SubstOperands;
  392. }
  393. inst_id = RebuildNewInst(
  394. context().insts().GetLocIdForDesugaring(loc_id_),
  395. SemIR::ImplWitnessAccess{.type_id = GetSingletonType(
  396. context(), SemIR::WitnessType::TypeInstId),
  397. .witness_id = witness_id,
  398. .index = access->index});
  399. // Once we replace a witness, we either have a concrete value or some
  400. // reference to an associated constant that came from the witness's facet
  401. // type. We don't want to substitute into the witness's facet type, so we
  402. // don't recurse on whatever came from the witness.
  403. return FullySubstituted;
  404. }
  405. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst)
  406. -> SemIR::InstId override {
  407. if (context().insts().Is<SemIR::FacetType>(orig_inst_id)) {
  408. --facet_type_depth_;
  409. }
  410. return RebuildNewInst(loc_id_, new_inst);
  411. }
  412. auto ReuseUnchanged(SemIR::InstId orig_inst_id) -> SemIR::InstId override {
  413. if (context().insts().Is<SemIR::FacetType>(orig_inst_id)) {
  414. --facet_type_depth_;
  415. }
  416. return orig_inst_id;
  417. }
  418. private:
  419. auto FindWitnessForInterface(SemIR::SpecificInterfaceId specific_interface_id)
  420. -> SemIR::InstId {
  421. auto lookup_query_interface =
  422. context().specific_interfaces().Get(specific_interface_id);
  423. for (auto [req_impl, witness_inst_id] :
  424. llvm::zip_equal(req_impls_, witness_inst_ids_)) {
  425. auto [req_self, req_interface] = req_impl;
  426. // The `LookupImplWitness` is for `.Self`, so if the witness is for some
  427. // type other than the query self, we can't use it for `.Self`.
  428. if (req_self != canonical_query_self_const_id_) {
  429. continue;
  430. }
  431. // If the `LookupImplWitness` for `.Self` is not looking for the same
  432. // interface as we have a witness for, this is not the right witness to
  433. // use to replace the lookup for `.Self`.
  434. if (req_interface.interface_id != lookup_query_interface.interface_id) {
  435. continue;
  436. }
  437. return witness_inst_id;
  438. }
  439. return SemIR::InstId::None;
  440. }
  441. SemIR::LocId loc_id_;
  442. SemIR::ConstantId canonical_query_self_const_id_;
  443. llvm::ArrayRef<SemIR::IdentifiedFacetType::RequiredImpl> req_impls_;
  444. llvm::ArrayRef<SemIR::InstId> witness_inst_ids_;
  445. int facet_type_depth_ = 0;
  446. };
  447. static auto VerifyQueryFacetTypeConstraints(
  448. Context& context, SemIR::LocId loc_id,
  449. SemIR::ConstantId query_self_const_id,
  450. SemIR::ConstantId query_facet_type_const_id,
  451. llvm::ArrayRef<SemIR::IdentifiedFacetType::RequiredImpl> req_impls,
  452. llvm::ArrayRef<SemIR::InstId> witness_inst_ids) -> bool {
  453. SemIR::InstId query_facet_type_inst_id =
  454. context.constant_values().GetInstId(query_facet_type_const_id);
  455. CARBON_CHECK(context.insts().Is<SemIR::FacetType>(query_facet_type_inst_id));
  456. const auto& facet_type_info = context.facet_types().Get(
  457. context.insts()
  458. .GetAs<SemIR::FacetType>(query_facet_type_inst_id)
  459. .facet_type_id);
  460. if (!facet_type_info.rewrite_constraints.empty()) {
  461. auto callbacks = SubstWitnessesCallbacks(
  462. &context, loc_id, query_self_const_id, req_impls, witness_inst_ids);
  463. for (const auto& rewrite : facet_type_info.rewrite_constraints) {
  464. auto lhs_id = SubstInst(context, rewrite.lhs_id, callbacks);
  465. auto rhs_id = SubstInst(context, rewrite.rhs_id, callbacks);
  466. if (lhs_id != rhs_id) {
  467. // TODO: Provide a diagnostic note and location for which rewrite
  468. // constraint was not satisfied, if a diagnostic is going to be
  469. // displayed for the LookupImplWitessFailure. This will require plumbing
  470. // through a callback that lets us add a Note to another diagnostic.
  471. return false;
  472. }
  473. }
  474. }
  475. // TODO: Validate that the witnesses satisfy the other requirements in the
  476. // `facet_type_info`.
  477. return true;
  478. }
  479. // Returns whether the query is concrete, it is false if the self type or
  480. // interface specifics have a symbolic dependency.
  481. static auto QueryIsConcrete(Context& context, SemIR::ConstantId self_const_id,
  482. const SemIR::SpecificInterface& specific_interface)
  483. -> bool {
  484. if (!self_const_id.is_concrete()) {
  485. return false;
  486. }
  487. if (!specific_interface.specific_id.has_value()) {
  488. return true;
  489. }
  490. auto args_id =
  491. context.specifics().Get(specific_interface.specific_id).args_id;
  492. for (auto inst_id : context.inst_blocks().Get(args_id)) {
  493. if (!context.constant_values().Get(inst_id).is_concrete()) {
  494. return false;
  495. }
  496. }
  497. return true;
  498. }
  499. namespace {
  500. // A class to filter imported impls based on whether they could possibly match a
  501. // query, prior to importing them. For now we only consider impls that are for
  502. // an interface that's being queried.
  503. //
  504. // TODO: There's a lot more we could do to filter out impls that can't possibly
  505. // match.
  506. class ImportImplFilter {
  507. public:
  508. explicit ImportImplFilter(Context& context, SemIR::ImportIRId import_ir_id,
  509. SemIR::SpecificInterface interface)
  510. : context_(&context),
  511. interface_id_(interface.interface_id),
  512. import_ir_id_(import_ir_id),
  513. import_ir_(context_->import_irs().Get(import_ir_id).sem_ir),
  514. cached_import_interface_id_(SemIR::InterfaceId::None) {}
  515. // Returns whether the given impl is potentially relevant for the current
  516. // query.
  517. auto IsRelevantImpl(SemIR::ImplId import_impl_id) -> bool {
  518. auto impl_interface_id =
  519. import_ir_->impls().Get(import_impl_id).interface.interface_id;
  520. if (!impl_interface_id.has_value()) {
  521. // This indicates that an error occurred when type-checking the impl.
  522. // TODO: Use an explicit error value for this rather than None.
  523. return false;
  524. }
  525. return IsRelevantInterface(impl_interface_id);
  526. }
  527. private:
  528. // Returns whether an impl for the given interface might be relevant to the
  529. // current query.
  530. auto IsRelevantInterface(SemIR::InterfaceId import_interface_id) -> bool {
  531. if (!cached_import_interface_id_.has_value()) {
  532. if (IsSameInterface(import_interface_id, interface_id_)) {
  533. cached_import_interface_id_ = import_interface_id;
  534. return true;
  535. }
  536. } else if (cached_import_interface_id_ == import_interface_id) {
  537. return true;
  538. }
  539. return false;
  540. }
  541. // Returns whether the given interfaces from two different IRs are the same.
  542. auto IsSameInterface(SemIR::InterfaceId import_interface_id,
  543. SemIR::InterfaceId local_interface_id) -> bool {
  544. // The names must be the same.
  545. if (import_ir_->names().GetAsStringIfIdentifier(
  546. import_ir_->interfaces().Get(import_interface_id).name_id) !=
  547. context_->names().GetAsStringIfIdentifier(
  548. context_->interfaces().Get(local_interface_id).name_id)) {
  549. return false;
  550. }
  551. // Compare the interfaces themselves.
  552. // TODO: Should we check the scope of the interface before doing this?
  553. auto local_version_of_import_interface_id =
  554. ImportInterface(*context_, import_ir_id_, import_interface_id);
  555. return local_version_of_import_interface_id == local_interface_id;
  556. }
  557. Context* context_;
  558. // The interface being looked up.
  559. SemIR::InterfaceId interface_id_;
  560. // The IR that we are currently importing impls from.
  561. SemIR::ImportIRId import_ir_id_;
  562. const SemIR::File* import_ir_;
  563. // The interface ID of `interface_id_` in `import_ir_`, if known.
  564. SemIR::InterfaceId cached_import_interface_id_;
  565. };
  566. } // namespace
  567. struct CandidateImpl {
  568. const SemIR::Impl* impl;
  569. // Used for sorting the candidates to find the most-specialized match.
  570. TypeStructure type_structure;
  571. };
  572. struct CandidateImpls {
  573. llvm::SmallVector<CandidateImpl> impls;
  574. bool consider_cpp_candidates = false;
  575. };
  576. // Returns the list of candidates impls for lookup to select from.
  577. static auto CollectCandidateImplsForQuery(
  578. Context& context, bool final_only, SemIR::ConstantId query_self_const_id,
  579. const TypeStructure& query_type_structure,
  580. SemIR::SpecificInterface& query_specific_interface) -> CandidateImpls {
  581. CandidateImpls candidates;
  582. auto import_irs = FindAssociatedImportIRs(context, query_self_const_id,
  583. query_specific_interface);
  584. for (auto import_ir_id : import_irs) {
  585. // If `Cpp` is an associated package, then we'll instead look for C++
  586. // operator overloads for certain well-known interfaces.
  587. if (import_ir_id == SemIR::ImportIRId::Cpp) {
  588. candidates.consider_cpp_candidates = true;
  589. continue;
  590. }
  591. // Instead of importing all impls, only import ones that are in some way
  592. // connected to this query.
  593. ImportImplFilter filter(context, import_ir_id, query_specific_interface);
  594. for (auto [import_impl_id, _] :
  595. context.import_irs().Get(import_ir_id).sem_ir->impls().enumerate()) {
  596. if (filter.IsRelevantImpl(import_impl_id)) {
  597. // TODO: Track the relevant impls and only consider those ones and any
  598. // local impls, rather than looping over all impls below.
  599. ImportImpl(context, import_ir_id, import_impl_id);
  600. }
  601. }
  602. }
  603. for (auto [id, impl] : context.impls().enumerate()) {
  604. CARBON_CHECK(impl.witness_id.has_value());
  605. if (final_only && !TreatImplAsFinal(context, impl)) {
  606. continue;
  607. }
  608. // If the impl's interface_id differs from the query, then this impl can
  609. // not possibly provide the queried interface.
  610. if (impl.interface.interface_id != query_specific_interface.interface_id) {
  611. continue;
  612. }
  613. // When the impl's interface_id matches, but the interface is generic, the
  614. // impl may or may not match based on restrictions in the generic
  615. // parameters of the impl.
  616. //
  617. // As a shortcut, if the impl's constraint is not symbolic (does not
  618. // depend on any generic parameters), then we can determine whether we match
  619. // by looking if the specific ids match exactly.
  620. auto impl_interface_const_id =
  621. context.constant_values().Get(impl.constraint_id);
  622. if (!impl_interface_const_id.is_symbolic() &&
  623. impl.interface.specific_id != query_specific_interface.specific_id) {
  624. continue;
  625. }
  626. // Build the type structure used for choosing the best the candidate.
  627. auto type_structure =
  628. BuildTypeStructure(context, impl.self_id, impl.interface);
  629. if (!type_structure) {
  630. continue;
  631. }
  632. // TODO: We can skip the comparison here if the `impl_interface_const_id` is
  633. // not symbolic, since when the interface and specific ids match, and they
  634. // aren't symbolic, the structure will be identical.
  635. if (!query_type_structure.CompareStructure(
  636. TypeStructure::CompareTest::IsEqualToOrMoreSpecificThan,
  637. *type_structure)) {
  638. continue;
  639. }
  640. candidates.impls.push_back({&impl, std::move(*type_structure)});
  641. }
  642. auto compare = [](auto& lhs, auto& rhs) -> bool {
  643. return lhs.type_structure < rhs.type_structure;
  644. };
  645. // Stable sort is used so that impls that are seen first are preferred when
  646. // they have an equal priority ordering.
  647. // TODO: Allow Carbon code to provide a priority ordering explicitly. For
  648. // now they have all the same priority, so the priority is the order in
  649. // which they are found in code.
  650. llvm::stable_sort(candidates.impls, compare);
  651. return candidates;
  652. }
  653. class IndexInFacetValue {
  654. public:
  655. static const IndexInFacetValue None;
  656. static const IndexInFacetValue Unstable;
  657. explicit constexpr IndexInFacetValue(int32_t index) : index_(index) {}
  658. // Returns whether the value represents a successful attempt to find the index
  659. // of an interface in a FacetValue. Returns true regardless of whether the
  660. // index is stable and able to be used or not.
  661. auto WasFound() const -> bool { return index_ != None.index_; }
  662. // Gets the stable index which can be used to index into the witness table in
  663. // a FacetValue, if there is one. Otherwise, returns -1.
  664. auto GetStableIndex() const -> int32_t {
  665. if (index_ == Unstable.index_) {
  666. return None.index_;
  667. }
  668. return index_;
  669. }
  670. private:
  671. int32_t index_;
  672. };
  673. inline constexpr auto IndexInFacetValue::None = IndexInFacetValue(-1);
  674. inline constexpr auto IndexInFacetValue::Unstable = IndexInFacetValue(-2);
  675. // Looks in the facet type of the query self facet value and returns the index
  676. // of `query_specific_interface` in the defined interface order for that facet
  677. // type. The order comes from the `query_self_type_identified_id` which must be
  678. // the IdentifiedFacetType of the type of `query_self_const_id `.
  679. //
  680. // If the query self is not a facet value, the IdentifiedFacetType would be
  681. // None.
  682. //
  683. // The IdentifiedFacetType must not be partially identified in order to find an
  684. // index, as that implies the interface order is not yet stable. In that case,
  685. // no index will be found.
  686. //
  687. // If the `query_specific_interface` is not part of the facet type of the query
  688. // self, returns -1 to indicate it was not found.
  689. static auto IndexOfImplWitnessInSelfFacetValue(
  690. Context& context, SemIR::ConstantId query_self_const_id,
  691. SemIR::IdentifiedFacetTypeId query_self_type_identified_id,
  692. SemIR::SpecificInterface query_specific_interface) -> IndexInFacetValue {
  693. if (!query_self_type_identified_id.has_value()) {
  694. return IndexInFacetValue::None;
  695. }
  696. // The self in the identified facet type is a canonicalized facet value, so we
  697. // canonicalize the query for comparison.
  698. auto canonical_query_self_const_id =
  699. GetCanonicalFacetOrTypeValue(context, query_self_const_id);
  700. const auto& identified =
  701. context.identified_facet_types().Get(query_self_type_identified_id);
  702. auto facet_type_req_impls = llvm::enumerate(identified.required_impls());
  703. auto it = llvm::find_if(facet_type_req_impls, [&](auto e) {
  704. auto [req_self, req_specific_interface] = e.value();
  705. return req_self == canonical_query_self_const_id &&
  706. req_specific_interface == query_specific_interface;
  707. });
  708. if (it == facet_type_req_impls.end()) {
  709. return IndexInFacetValue::None;
  710. }
  711. if (identified.partially_identified()) {
  712. return IndexInFacetValue::Unstable;
  713. }
  714. return IndexInFacetValue(static_cast<int32_t>((*it).index()));
  715. }
  716. static auto FindFinalWitnessFromSelfFacetValue(
  717. Context& context, SemIR::ConstantId query_self_const_id,
  718. SemIR::IdentifiedFacetTypeId query_self_type_identified_id,
  719. SemIR::SpecificInterface query_specific_interface) -> SemIR::InstId {
  720. // TODO: Add and use constant_values().GetAs<SemIR::FacetType>().
  721. auto query_self_inst_id =
  722. context.constant_values().GetInstId(query_self_const_id);
  723. auto facet_value =
  724. context.insts().TryGetAs<SemIR::FacetValue>(query_self_inst_id);
  725. if (!facet_value) {
  726. return SemIR::InstId::None;
  727. }
  728. auto index_in_facet_value = IndexOfImplWitnessInSelfFacetValue(
  729. context, query_self_const_id, query_self_type_identified_id,
  730. query_specific_interface);
  731. auto stable_index = index_in_facet_value.GetStableIndex();
  732. if (stable_index < 0) {
  733. return SemIR::InstId::None;
  734. }
  735. auto witness_id =
  736. context.inst_blocks().Get(facet_value->witnesses_block_id)[stable_index];
  737. if (context.insts().Is<SemIR::LookupImplWitness>(witness_id)) {
  738. // Did not find a final witness.
  739. return SemIR::InstId::None;
  740. }
  741. return witness_id;
  742. }
  743. static auto FindNonFinalWitness(
  744. Context& context, SemIR::LocId loc_id,
  745. SemIR::ConstantId query_self_const_id,
  746. SemIR::IdentifiedFacetTypeId query_self_type_identified_id,
  747. SemIR::SpecificInterface query_specific_interface) -> bool {
  748. auto index = IndexOfImplWitnessInSelfFacetValue(context, query_self_const_id,
  749. query_self_type_identified_id,
  750. query_specific_interface);
  751. if (index.WasFound()) {
  752. return true;
  753. }
  754. // TODO: Remove SpecificInterfaceId from LookupCustomWitness apis, switch to
  755. // just SpecificInterface.
  756. auto query_specific_interface_id =
  757. context.specific_interfaces().Add(query_specific_interface);
  758. // Consider a custom witness for core interfaces.
  759. // TODO: This needs to expand to more interfaces, and we might want to have
  760. // that dispatch in custom_witness.cpp instead of here.
  761. auto core_interface =
  762. GetCoreInterface(context, query_specific_interface.interface_id);
  763. if (auto witness_id = LookupCustomWitness(
  764. context, loc_id, core_interface, query_self_const_id,
  765. query_specific_interface_id, false)) {
  766. // If there's a final witness, we would have already found it via evaluating
  767. // the LookupImplWitness instruction.
  768. CARBON_CHECK(!witness_id->has_value());
  769. return true;
  770. }
  771. auto query_type_structure = BuildTypeStructure(
  772. context, context.constant_values().GetInstId(query_self_const_id),
  773. query_specific_interface);
  774. // We looked for errors in the query self and facet type already, and we're
  775. // not dealing with monomorphizations here.
  776. CARBON_CHECK(query_type_structure, "error in impl lookup query");
  777. auto candidates = CollectCandidateImplsForQuery(
  778. context, /*final_only=*/false, query_self_const_id, *query_type_structure,
  779. query_specific_interface);
  780. for (const auto& candidate : candidates.impls) {
  781. const auto& impl = *candidate.impl;
  782. context.impl_lookup_stack().back().impl_loc = impl.definition_id;
  783. auto witness_id = TryGetSpecificWitnessIdForImpl(
  784. context, loc_id, query_self_const_id, query_specific_interface, impl);
  785. if (witness_id.has_value()) {
  786. // We looked for errors in the query self and facet type already, and
  787. // we're not dealing with monomorphizations here.
  788. CARBON_CHECK(witness_id != SemIR::ErrorInst::ConstantId,
  789. "error in impl lookup query");
  790. return true;
  791. }
  792. }
  793. // C++ interop only provides final witnesses, so we don't look for a witness
  794. // from C++ here. Those are found in eval of the `LookupImplWitness`
  795. // instruction.
  796. return false;
  797. }
  798. auto LookupImplWitness(Context& context, SemIR::LocId loc_id,
  799. SemIR::ConstantId query_self_const_id,
  800. SemIR::ConstantId query_facet_type_const_id,
  801. bool diagnose) -> SemIR::InstBlockIdOrError {
  802. if (query_self_const_id == SemIR::ErrorInst::ConstantId ||
  803. query_facet_type_const_id == SemIR::ErrorInst::ConstantId) {
  804. return SemIR::InstBlockIdOrError::MakeError();
  805. }
  806. {
  807. // The query self value is a type value or a facet value.
  808. auto query_self_type_id =
  809. context.insts()
  810. .Get(context.constant_values().GetInstId(query_self_const_id))
  811. .type_id();
  812. CARBON_CHECK((context.types().IsOneOf<SemIR::TypeType, SemIR::FacetType>(
  813. query_self_type_id)));
  814. // The query facet type value is indeed a facet type.
  815. CARBON_CHECK(context.insts().Is<SemIR::FacetType>(
  816. context.constant_values().GetInstId(query_facet_type_const_id)));
  817. }
  818. auto req_impls_from_constraint =
  819. GetRequiredImplsFromConstraint(context, loc_id, query_self_const_id,
  820. query_facet_type_const_id, diagnose);
  821. if (!req_impls_from_constraint) {
  822. return SemIR::InstBlockIdOrError::MakeError();
  823. }
  824. auto [req_impls, other_requirements] = *req_impls_from_constraint;
  825. if (other_requirements) {
  826. // TODO: Remove this when other requirements go away.
  827. return SemIR::InstBlockId::None;
  828. }
  829. if (req_impls.empty()) {
  830. return SemIR::InstBlockId::Empty;
  831. }
  832. // Cycles are diagnosed even if they are found when diagnostics are otherwise
  833. // being suppressed (such as during deduce).
  834. if (FindAndDiagnoseImplLookupCycle(context, context.impl_lookup_stack(),
  835. loc_id, query_self_const_id,
  836. query_facet_type_const_id, true)) {
  837. return SemIR::InstBlockIdOrError::MakeError();
  838. }
  839. auto& stack = context.impl_lookup_stack();
  840. stack.push_back({
  841. .query_self_const_id = query_self_const_id,
  842. .query_facet_type_const_id = query_facet_type_const_id,
  843. .diagnosed_cycle = stack.empty() ? false : stack.back().diagnosed_cycle,
  844. });
  845. // We need to find a witness for each self+interface pair in `req_impls`.
  846. //
  847. // Every consumer of a facet type needs to agree on the order of interfaces
  848. // used for its witnesses, which is done by following the order in the
  849. // IdentifiedFacetType of the query facet type, and this is represented in the
  850. // order of the interfaces in `req_impls`.
  851. llvm::SmallVector<SemIR::InstId> result_witness_ids;
  852. for (const auto& req_impl : req_impls) {
  853. // Identify the type of the requirement's self up front, if it's a facet, so
  854. // we only have to do this once.
  855. auto req_self_type_identified_id =
  856. IdentifyQuerySelfFacetType(context, loc_id, req_impl.self_facet_value);
  857. // If the self facet contains a final witness for the required interface, we
  858. // use that and avoid any further work. This is strictly an optimization,
  859. // since that same final witness should be found by evaluating a
  860. // LookupImplWitness instruction for the required self+interface pair.
  861. auto result_witness_id = FindFinalWitnessFromSelfFacetValue(
  862. context, req_impl.self_facet_value, req_self_type_identified_id,
  863. req_impl.specific_interface);
  864. if (result_witness_id.has_value()) {
  865. // Found a final witness, use it.
  866. result_witness_ids.push_back(result_witness_id);
  867. continue;
  868. }
  869. auto witness_const_id = EvalOrAddInst<SemIR::LookupImplWitness>(
  870. context, context.insts().GetLocIdForDesugaring(loc_id),
  871. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  872. .query_self_inst_id =
  873. context.constant_values().GetInstId(req_impl.self_facet_value),
  874. .query_specific_interface_id =
  875. context.specific_interfaces().Add(req_impl.specific_interface)});
  876. result_witness_id = context.constant_values().GetInstId(witness_const_id);
  877. if (!context.insts().Is<SemIR::LookupImplWitness>(result_witness_id)) {
  878. // Found a final witness, use it.
  879. result_witness_ids.push_back(result_witness_id);
  880. continue;
  881. }
  882. if (QueryIsConcrete(context, req_impl.self_facet_value,
  883. req_impl.specific_interface)) {
  884. // Failed to find a final witness for a concrete query. There won't be a
  885. // non-final witness, as any witness would have been treated as final.
  886. break;
  887. }
  888. // Did not find a final witness. If we find a non-final witness, then we use
  889. // the `LookupImplWitness` as our witness so that monomorphization can
  890. // produce a final witness later.
  891. if (!FindNonFinalWitness(context, loc_id, req_impl.self_facet_value,
  892. req_self_type_identified_id,
  893. req_impl.specific_interface)) {
  894. // At least one queried interface in the facet type has no witness for the
  895. // given type, we can stop looking for more.
  896. //
  897. // TODO: The LookupImplWitness won't be used. We should find a way to
  898. // discard it, which would remove it from the generic eval block if the
  899. // lookup is within a generic context.
  900. break;
  901. }
  902. // Save the non-final witness, which will eventually resolve to a final
  903. // witness as specifics are applied to make the query more concrete.
  904. result_witness_ids.push_back(result_witness_id);
  905. }
  906. auto pop = stack.pop_back_val();
  907. if (pop.diagnosed_cycle && !stack.empty()) {
  908. stack.back().diagnosed_cycle = true;
  909. }
  910. // All interfaces in the query facet type must have been found to be available
  911. // through some impl, or directly on the value's facet type if
  912. // `query_self_const_id` is a facet value.
  913. if (result_witness_ids.size() != req_impls.size()) {
  914. return SemIR::InstBlockId::None;
  915. }
  916. // Verify rewrite constraints in the query constraint are satisfied after
  917. // applying the rewrites from the found witnesses.
  918. if (!VerifyQueryFacetTypeConstraints(context, loc_id, query_self_const_id,
  919. query_facet_type_const_id, req_impls,
  920. result_witness_ids)) {
  921. return SemIR::InstBlockId::None;
  922. }
  923. return context.inst_blocks().AddCanonical(result_witness_ids);
  924. }
  925. // Record the query which found a final impl witness. It's illegal to
  926. // write a final impl afterward that would match the same query.
  927. static auto PoisonImplLookupQuery(Context& context, SemIR::LocId loc_id,
  928. EvalImplLookupMode mode,
  929. SemIR::LookupImplWitness eval_query,
  930. SemIR::ConstantId witness_id,
  931. const SemIR::Impl& impl) -> void {
  932. if (mode == EvalImplLookupMode::RecheckPoisonedLookup) {
  933. return;
  934. }
  935. // If the impl was effectively final, then we don't need to poison here. A
  936. // change of query result will already be diagnosed at the point where the
  937. // new impl decl was written that changes the result.
  938. if (TreatImplAsFinal(context, impl)) {
  939. return;
  940. }
  941. context.poisoned_concrete_impl_lookup_queries().push_back(
  942. {.loc_id = loc_id, .query = eval_query, .witness_id = witness_id});
  943. }
  944. // Return whether the `FacetType` in `type_id` extends a single interface, and
  945. // that it matches `specific_interface`.
  946. static auto FacetTypeIsSingleInterface(
  947. Context& context, SemIR::TypeId type_id,
  948. SemIR::SpecificInterface specific_interface) -> bool {
  949. auto facet_type = context.types().GetAs<SemIR::FacetType>(type_id);
  950. const auto& facet_type_info =
  951. context.facet_types().Get(facet_type.facet_type_id);
  952. if (auto single = facet_type_info.TryAsSingleExtend()) {
  953. if (auto* si = std::get_if<SemIR::SpecificInterface>(&*single)) {
  954. return *si == specific_interface;
  955. }
  956. }
  957. return false;
  958. }
  959. auto EvalLookupSingleFinalWitness(Context& context, SemIR::LocId loc_id,
  960. SemIR::LookupImplWitness eval_query,
  961. SemIR::InstId self_facet_value_inst_id,
  962. EvalImplLookupMode mode)
  963. -> SemIR::ConstantId {
  964. auto query_specific_interface =
  965. context.specific_interfaces().Get(eval_query.query_specific_interface_id);
  966. // Ensure specifics don't substitute in weird things for the query self.
  967. CARBON_CHECK(context.types().IsFacetType(
  968. context.insts().Get(eval_query.query_self_inst_id).type_id()));
  969. SemIR::ConstantId query_self_const_id =
  970. context.constant_values().Get(eval_query.query_self_inst_id);
  971. // If the query self is monomorphized as a FacetValue, we can't use its
  972. // witnesses in general, since we are not allowed to identify facet types in
  973. // monomorphization. And we need to identify it to know which witness is for
  974. // which interface.
  975. //
  976. // However, if the facet type has only a single interface and it matches the
  977. // query, then we can use the witness, since there is only one.
  978. //
  979. // This looks like an optimization, but it's done to prefer the FacetValue's
  980. // witness over the cached value for monomorphizations of `Self` inside an
  981. // `impl` definition. If a final witness was previously found for the same
  982. // type as the monomorphized `Self`, the cache would reuse it. But associated
  983. // constants may differ in that witness from the current `impl`'s witness
  984. // which leads to inconsistency within the impl definition.
  985. //
  986. // By preferring the impl's FacetValue, the `impl` remains self-consistent
  987. // even if it's ultimately not valid due to a conflict. When a conflict with
  988. // another `impl` does exist, a poisoning error will occur showing the two
  989. // `impl`s are in disagreement for a concrete value, as the poisoning lookup
  990. // does not preserve the FacetValue.
  991. if (auto facet_value = context.insts().TryGetAsIfValid<SemIR::FacetValue>(
  992. self_facet_value_inst_id)) {
  993. if (FacetTypeIsSingleInterface(context, facet_value->type_id,
  994. query_specific_interface)) {
  995. auto witnesses =
  996. context.inst_blocks().Get(facet_value->witnesses_block_id);
  997. CARBON_CHECK(witnesses.size() == 1);
  998. auto witness_inst_id = witnesses.front();
  999. // Only use the witness in monomoprhization if it's a final witness.
  1000. if (!context.insts().Is<SemIR::LookupImplWitness>(witness_inst_id)) {
  1001. return context.constant_values().Get(witness_inst_id);
  1002. }
  1003. }
  1004. }
  1005. // If the query is on `.Self` and looking for the same interface as `.Self`
  1006. // provides, do not look for a witness in monomorphization - a non-final
  1007. // witness will be found from the facet type. This happens inside an `impl`
  1008. // declaration, and we must avoid finding that same `impl` and trying to
  1009. // deduce `.Self` for it, as that results in a specific declaration for the
  1010. // `impl` which evaluates this lookup again, producing a cycle.
  1011. //
  1012. // If the query is for `.Self` and for the facet type of `.Self`, then there
  1013. // is no final witness yet.
  1014. if (auto bind = context.insts().TryGetAs<SemIR::SymbolicBinding>(
  1015. eval_query.query_self_inst_id)) {
  1016. const auto& entity = context.entity_names().Get(bind->entity_name_id);
  1017. if (entity.name_id == SemIR::NameId::PeriodSelf) {
  1018. if (FacetTypeIsSingleInterface(context, bind->type_id,
  1019. query_specific_interface)) {
  1020. return SemIR::ConstantId::None;
  1021. }
  1022. }
  1023. }
  1024. // Check to see if this result is in the cache. But skip the cache if we're
  1025. // re-checking a poisoned result and need to redo the lookup.
  1026. auto impl_lookup_cache_key = Context::ImplLookupCacheKey{
  1027. query_self_const_id, eval_query.query_specific_interface_id};
  1028. if (mode != EvalImplLookupMode::RecheckPoisonedLookup) {
  1029. if (auto result =
  1030. context.impl_lookup_cache().Lookup(impl_lookup_cache_key)) {
  1031. return result.value();
  1032. }
  1033. }
  1034. bool query_is_concrete =
  1035. QueryIsConcrete(context, query_self_const_id, query_specific_interface);
  1036. auto query_type_structure = BuildTypeStructure(
  1037. context, context.constant_values().GetInstId(query_self_const_id),
  1038. query_specific_interface);
  1039. if (!query_type_structure) {
  1040. // TODO: We should return an error here; an error was found in the type
  1041. // structure.
  1042. return SemIR::ConstantId::None;
  1043. }
  1044. // We only want to return final witneses in monomorphization. If the query is
  1045. // concrete, we can find all impls, otherwise we want only (effectively) final
  1046. // impls.
  1047. auto candidates = CollectCandidateImplsForQuery(
  1048. context, /*final_only=*/!query_is_concrete, query_self_const_id,
  1049. *query_type_structure, query_specific_interface);
  1050. struct LookupResult {
  1051. SemIR::ConstantId witness_id = SemIR::ConstantId::None;
  1052. // Holds a pointer into `candidates`.
  1053. const TypeStructure* impl_type_structure = nullptr;
  1054. SemIR::LocId impl_loc_id = SemIR::LocId::None;
  1055. };
  1056. LookupResult lookup_result;
  1057. auto core_interface =
  1058. GetCoreInterface(context, query_specific_interface.interface_id);
  1059. // Consider a custom witness for core interfaces.
  1060. // TODO: This needs to expand to more interfaces, and we might want to have
  1061. // that dispatch in custom_witness.cpp instead of here.
  1062. bool used_custom_witness = false;
  1063. if (auto witness_inst_id = LookupCustomWitness(
  1064. context, loc_id, core_interface, query_self_const_id,
  1065. eval_query.query_specific_interface_id, true)) {
  1066. if (witness_inst_id->has_value()) {
  1067. lookup_result = {.witness_id =
  1068. context.constant_values().Get(*witness_inst_id)};
  1069. used_custom_witness = true;
  1070. }
  1071. }
  1072. // Only consider candidates when a custom witness didn't apply.
  1073. if (!used_custom_witness) {
  1074. for (const auto& candidate : candidates.impls) {
  1075. const auto& impl = *candidate.impl;
  1076. // In monomorphization, while resolving a specific, there may be no stack
  1077. // yet as this may be the first lookup. If further lookups are started as
  1078. // a result in deduce, they will build the stack.
  1079. if (!context.impl_lookup_stack().empty()) {
  1080. context.impl_lookup_stack().back().impl_loc = impl.definition_id;
  1081. }
  1082. auto witness_id = TryGetSpecificWitnessIdForImpl(
  1083. context, loc_id, query_self_const_id, query_specific_interface, impl);
  1084. if (witness_id.has_value()) {
  1085. PoisonImplLookupQuery(context, loc_id, mode, eval_query, witness_id,
  1086. impl);
  1087. lookup_result = {.witness_id = witness_id,
  1088. .impl_type_structure = &candidate.type_structure,
  1089. .impl_loc_id = SemIR::LocId(impl.definition_id)};
  1090. break;
  1091. }
  1092. }
  1093. }
  1094. if (query_is_concrete && candidates.consider_cpp_candidates &&
  1095. core_interface != CoreInterface::Unknown) {
  1096. // Also check for a C++ candidate that is a better match than whatever
  1097. // `impl` we may have found in Carbon.
  1098. auto cpp_witness_id = LookupCppImpl(
  1099. context, loc_id, core_interface, query_self_const_id,
  1100. eval_query.query_specific_interface_id,
  1101. lookup_result.impl_type_structure, lookup_result.impl_loc_id);
  1102. if (cpp_witness_id.has_value()) {
  1103. lookup_result = {.witness_id =
  1104. context.constant_values().Get(cpp_witness_id)};
  1105. }
  1106. }
  1107. if (mode != EvalImplLookupMode::RecheckPoisonedLookup &&
  1108. lookup_result.witness_id.has_value()) {
  1109. context.impl_lookup_cache().Insert(impl_lookup_cache_key,
  1110. lookup_result.witness_id);
  1111. }
  1112. return lookup_result.witness_id;
  1113. }
  1114. auto LookupMatchesImpl(Context& context, SemIR::LocId loc_id,
  1115. SemIR::ConstantId query_self_const_id,
  1116. SemIR::SpecificInterface query_specific_interface,
  1117. SemIR::ImplId target_impl) -> bool {
  1118. if (query_self_const_id == SemIR::ErrorInst::ConstantId) {
  1119. return false;
  1120. }
  1121. auto witness_id = TryGetSpecificWitnessIdForImpl(
  1122. context, loc_id, query_self_const_id, query_specific_interface,
  1123. context.impls().Get(target_impl));
  1124. // TODO: If this fails, it would be because there is an error in the specific
  1125. // interface. Should we check for that and return false?
  1126. CARBON_CHECK(witness_id != SemIR::ErrorInst::ConstantId,
  1127. "error in lookup specific interface");
  1128. return witness_id.has_value();
  1129. }
  1130. } // namespace Carbon::Check