impl_lookup.cpp 50 KB

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