impl_lookup.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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 <variant>
  7. #include "toolchain/base/kind_switch.h"
  8. #include "toolchain/check/deduce.h"
  9. #include "toolchain/check/diagnostic_helpers.h"
  10. #include "toolchain/check/eval.h"
  11. #include "toolchain/check/generic.h"
  12. #include "toolchain/check/import_ref.h"
  13. #include "toolchain/check/inst.h"
  14. #include "toolchain/check/type.h"
  15. #include "toolchain/check/type_completion.h"
  16. #include "toolchain/check/type_structure.h"
  17. #include "toolchain/sem_ir/facet_type_info.h"
  18. #include "toolchain/sem_ir/ids.h"
  19. #include "toolchain/sem_ir/impl.h"
  20. #include "toolchain/sem_ir/inst.h"
  21. #include "toolchain/sem_ir/typed_insts.h"
  22. namespace Carbon::Check {
  23. static auto FindAssociatedImportIRs(Context& context,
  24. SemIR::ConstantId query_self_const_id,
  25. SemIR::ConstantId query_facet_type_const_id)
  26. -> llvm::SmallVector<SemIR::ImportIRId> {
  27. llvm::SmallVector<SemIR::ImportIRId> result;
  28. // Add an entity to our result.
  29. auto add_entity = [&](const SemIR::EntityWithParamsBase& entity) {
  30. // We will look for impls in the import IR associated with the first owning
  31. // declaration.
  32. auto decl_id = entity.first_owning_decl_id;
  33. if (!decl_id.has_value()) {
  34. return;
  35. }
  36. if (auto ir_id = GetCanonicalImportIRInst(context, decl_id).ir_id;
  37. ir_id.has_value()) {
  38. result.push_back(ir_id);
  39. }
  40. };
  41. llvm::SmallVector<SemIR::InstId> worklist;
  42. worklist.push_back(context.constant_values().GetInstId(query_self_const_id));
  43. if (query_facet_type_const_id.has_value()) {
  44. worklist.push_back(
  45. context.constant_values().GetInstId(query_facet_type_const_id));
  46. }
  47. // Push the contents of an instruction block onto our worklist.
  48. auto push_block = [&](SemIR::InstBlockId block_id) {
  49. if (block_id.has_value()) {
  50. llvm::append_range(worklist, context.inst_blocks().Get(block_id));
  51. }
  52. };
  53. // Add the arguments of a specific to the worklist.
  54. auto push_args = [&](SemIR::SpecificId specific_id) {
  55. if (specific_id.has_value()) {
  56. push_block(context.specifics().Get(specific_id).args_id);
  57. }
  58. };
  59. while (!worklist.empty()) {
  60. auto inst_id = worklist.pop_back_val();
  61. // Visit the operands of the constant.
  62. auto inst = context.insts().Get(inst_id);
  63. for (auto arg : {inst.arg0_and_kind(), inst.arg1_and_kind()}) {
  64. CARBON_KIND_SWITCH(arg) {
  65. case CARBON_KIND(SemIR::InstId inst_id): {
  66. if (inst_id.has_value()) {
  67. worklist.push_back(inst_id);
  68. }
  69. break;
  70. }
  71. case CARBON_KIND(SemIR::InstBlockId inst_block_id): {
  72. push_block(inst_block_id);
  73. break;
  74. }
  75. case CARBON_KIND(SemIR::ClassId class_id): {
  76. add_entity(context.classes().Get(class_id));
  77. break;
  78. }
  79. case CARBON_KIND(SemIR::InterfaceId interface_id): {
  80. add_entity(context.interfaces().Get(interface_id));
  81. break;
  82. }
  83. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  84. const auto& facet_type_info =
  85. context.facet_types().Get(facet_type_id);
  86. for (const auto& impl : facet_type_info.extend_constraints) {
  87. add_entity(context.interfaces().Get(impl.interface_id));
  88. push_args(impl.specific_id);
  89. }
  90. for (const auto& impl : facet_type_info.self_impls_constraints) {
  91. add_entity(context.interfaces().Get(impl.interface_id));
  92. push_args(impl.specific_id);
  93. }
  94. break;
  95. }
  96. case CARBON_KIND(SemIR::FunctionId function_id): {
  97. add_entity(context.functions().Get(function_id));
  98. break;
  99. }
  100. case CARBON_KIND(SemIR::SpecificId specific_id): {
  101. push_args(specific_id);
  102. break;
  103. }
  104. default: {
  105. break;
  106. }
  107. }
  108. }
  109. }
  110. // Deduplicate.
  111. llvm::sort(result, [](SemIR::ImportIRId a, SemIR::ImportIRId b) {
  112. return a.index < b.index;
  113. });
  114. result.erase(llvm::unique(result), result.end());
  115. return result;
  116. }
  117. // Returns true if a cycle was found and diagnosed.
  118. static auto FindAndDiagnoseImplLookupCycle(
  119. Context& context,
  120. const llvm::SmallVector<Context::ImplLookupStackEntry>& stack,
  121. SemIR::LocId loc_id, SemIR::ConstantId query_self_const_id,
  122. SemIR::ConstantId query_facet_type_const_id) -> bool {
  123. // Deduction of the interface parameters can do further impl lookups, and we
  124. // need to ensure we terminate.
  125. //
  126. // https://docs.carbon-lang.dev/docs/design/generics/details.html#acyclic-rule
  127. // - We look for violations of the acyclic rule by seeing if a previous lookup
  128. // had all the same type inputs.
  129. // - The `query_facet_type_const_id` encodes the entire facet type being
  130. // looked up, including any specific parameters for a generic interface.
  131. //
  132. // TODO: Implement the termination rule, which requires looking at the
  133. // complexity of the types on the top of (or throughout?) the stack:
  134. // https://docs.carbon-lang.dev/docs/design/generics/details.html#termination-rule
  135. for (auto [i, entry] : llvm::enumerate(stack)) {
  136. if (entry.query_self_const_id == query_self_const_id &&
  137. entry.query_facet_type_const_id == query_facet_type_const_id) {
  138. auto facet_type_type_id =
  139. context.types().GetTypeIdForTypeConstantId(query_facet_type_const_id);
  140. CARBON_DIAGNOSTIC(ImplLookupCycle, Error,
  141. "cycle found in search for impl of {0} for type {1}",
  142. SemIR::TypeId, SemIR::TypeId);
  143. auto builder = context.emitter().Build(
  144. loc_id, ImplLookupCycle, facet_type_type_id,
  145. context.types().GetTypeIdForTypeConstantId(query_self_const_id));
  146. for (const auto& active_entry : llvm::drop_begin(stack, i)) {
  147. if (active_entry.impl_loc.has_value()) {
  148. CARBON_DIAGNOSTIC(ImplLookupCycleNote, Note,
  149. "determining if this impl clause matches", );
  150. builder.Note(active_entry.impl_loc, ImplLookupCycleNote);
  151. }
  152. }
  153. builder.Emit();
  154. return true;
  155. }
  156. }
  157. return false;
  158. }
  159. // If the constant value is a FacetAccessType instruction, this returns the
  160. // value of the facet value it points to instead.
  161. static auto UnwrapFacetAccessType(Context& context, SemIR::ConstantId id)
  162. -> SemIR::ConstantId {
  163. // If the self type is a FacetAccessType, work with the facet value directly,
  164. // which gives us the potential witnesses to avoid looking for impl
  165. // declarations. We will do the same for the impl declarations we try to match
  166. // so that we can compare the self constant values.
  167. if (auto access = context.insts().TryGetAs<SemIR::FacetAccessType>(
  168. context.constant_values().GetInstId(id))) {
  169. return context.constant_values().Get(access->facet_value_inst_id);
  170. }
  171. return id;
  172. }
  173. // Gets the set of `SpecificInterface`s that are required by a facet type
  174. // (as a constant value).
  175. static auto GetInterfacesFromConstantId(
  176. Context& context, SemIR::ConstantId query_facet_type_const_id,
  177. bool& has_other_requirements)
  178. -> llvm::SmallVector<SemIR::SpecificInterface> {
  179. auto facet_type_inst_id =
  180. context.constant_values().GetInstId(query_facet_type_const_id);
  181. auto facet_type_inst =
  182. context.insts().GetAs<SemIR::FacetType>(facet_type_inst_id);
  183. const auto& facet_type_info =
  184. context.facet_types().Get(facet_type_inst.facet_type_id);
  185. has_other_requirements = facet_type_info.other_requirements;
  186. auto identified_id = RequireIdentifiedFacetType(context, facet_type_inst);
  187. auto interfaces_array_ref =
  188. context.identified_facet_types().Get(identified_id).required_interfaces();
  189. // Returns a copy to avoid use-after-free when the identified_facet_types
  190. // store resizes.
  191. return {interfaces_array_ref.begin(), interfaces_array_ref.end()};
  192. }
  193. static auto GetWitnessIdForImpl(Context& context, SemIR::LocId loc_id,
  194. bool query_is_concrete,
  195. SemIR::ConstantId query_self_const_id,
  196. const SemIR::SpecificInterface& interface,
  197. SemIR::ImplId impl_id) -> EvalImplLookupResult {
  198. // The impl may have generic arguments, in which case we need to deduce them
  199. // to find what they are given the specific type and interface query. We use
  200. // that specific to map values in the impl to the deduced values.
  201. auto specific_id = SemIR::SpecificId::None;
  202. {
  203. // DeduceImplArguments can import new impls which can invalidate any
  204. // pointers into `context.impls()`.
  205. const SemIR::Impl& impl = context.impls().Get(impl_id);
  206. if (impl.generic_id.has_value()) {
  207. specific_id =
  208. DeduceImplArguments(context, loc_id,
  209. {.self_id = impl.self_id,
  210. .generic_id = impl.generic_id,
  211. .specific_id = impl.interface.specific_id},
  212. query_self_const_id, interface.specific_id);
  213. if (!specific_id.has_value()) {
  214. return EvalImplLookupResult::MakeNone();
  215. }
  216. }
  217. }
  218. // Get a pointer again after DeduceImplArguments() is complete.
  219. const SemIR::Impl& impl = context.impls().Get(impl_id);
  220. // The self type of the impl must match the type in the query, or this is an
  221. // `impl T as ...` for some other type `T` and should not be considered.
  222. auto deduced_self_const_id = SemIR::GetConstantValueInSpecific(
  223. context.sem_ir(), specific_id, impl.self_id);
  224. // In a generic `impl forall` the self type can be a FacetAccessType, which
  225. // will not be the same constant value as a query facet value. We move through
  226. // to the facet value here, and if the query was a FacetAccessType we did the
  227. // same there so they still match.
  228. deduced_self_const_id = UnwrapFacetAccessType(context, deduced_self_const_id);
  229. if (query_self_const_id != deduced_self_const_id) {
  230. return EvalImplLookupResult::MakeNone();
  231. }
  232. // The impl's constraint is a facet type which it is implementing for the self
  233. // type: the `I` in `impl ... as I`. The deduction step may be unable to be
  234. // fully applied to the types in the constraint and result in an error here,
  235. // in which case it does not match the query.
  236. auto deduced_constraint_id =
  237. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  238. context.sem_ir(), specific_id, impl.constraint_id));
  239. if (deduced_constraint_id == SemIR::ErrorInst::SingletonInstId) {
  240. return EvalImplLookupResult::MakeNone();
  241. }
  242. auto deduced_constraint_facet_type_id =
  243. context.insts()
  244. .GetAs<SemIR::FacetType>(deduced_constraint_id)
  245. .facet_type_id;
  246. const auto& deduced_constraint_facet_type_info =
  247. context.facet_types().Get(deduced_constraint_facet_type_id);
  248. CARBON_CHECK(deduced_constraint_facet_type_info.extend_constraints.size() ==
  249. 1);
  250. if (deduced_constraint_facet_type_info.other_requirements) {
  251. // TODO: Remove this when other requirements goes away.
  252. return EvalImplLookupResult::MakeNone();
  253. }
  254. // The specifics in the queried interface must match the deduced specifics in
  255. // the impl's constraint facet type.
  256. auto impl_interface_specific_id =
  257. deduced_constraint_facet_type_info.extend_constraints[0].specific_id;
  258. auto query_interface_specific_id = interface.specific_id;
  259. if (impl_interface_specific_id != query_interface_specific_id) {
  260. return EvalImplLookupResult::MakeNone();
  261. }
  262. LoadImportRef(context, impl.witness_id);
  263. if (specific_id.has_value()) {
  264. // We need a definition of the specific `impl` so we can access its
  265. // witness.
  266. ResolveSpecificDefinition(context, loc_id, specific_id);
  267. }
  268. bool impl_is_effectively_final =
  269. // TODO: impl.is_final ||
  270. (context.constant_values().Get(impl.self_id).is_concrete() &&
  271. context.constant_values().Get(impl.constraint_id).is_concrete());
  272. if (query_is_concrete || impl_is_effectively_final) {
  273. return EvalImplLookupResult::MakeFinal(
  274. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  275. context.sem_ir(), specific_id, impl.witness_id)));
  276. } else {
  277. return EvalImplLookupResult::MakeNonFinal();
  278. }
  279. }
  280. // In the case where `facet_const_id` is a facet, see if its facet type requires
  281. // that `specific_interface` is implemented. If so, return the witness from the
  282. // facet.
  283. static auto FindWitnessInFacet(
  284. Context& context, SemIR::LocId loc_id, SemIR::ConstantId facet_const_id,
  285. const SemIR::SpecificInterface& specific_interface) -> SemIR::InstId {
  286. SemIR::InstId facet_inst_id =
  287. context.constant_values().GetInstId(facet_const_id);
  288. SemIR::TypeId facet_type_id = context.insts().Get(facet_inst_id).type_id();
  289. if (auto facet_type_inst =
  290. context.types().TryGetAs<SemIR::FacetType>(facet_type_id)) {
  291. auto identified_id = RequireIdentifiedFacetType(context, *facet_type_inst);
  292. const auto& identified =
  293. context.identified_facet_types().Get(identified_id);
  294. for (auto [index, interface] :
  295. llvm::enumerate(identified.required_interfaces())) {
  296. if (interface == specific_interface) {
  297. auto witness_id =
  298. GetOrAddInst(context, loc_id,
  299. SemIR::FacetAccessWitness{
  300. .type_id = GetSingletonType(
  301. context, SemIR::WitnessType::SingletonInstId),
  302. .facet_value_inst_id = facet_inst_id,
  303. .index = SemIR::ElementIndex(index)});
  304. return witness_id;
  305. }
  306. }
  307. }
  308. return SemIR::InstId::None;
  309. }
  310. // Begin a search for an impl declaration matching the query. We do this by
  311. // creating an LookupImplWitness instruction and evaluating. If it's able to
  312. // find a final concrete impl, then it will evaluate to that `ImplWitness` but
  313. // if not, it will evaluate to itself as a symbolic witness to be further
  314. // evaluated with a more specific query when building a specific for the generic
  315. // context the query came from.
  316. static auto FindWitnessInImpls(Context& context, SemIR::LocId loc_id,
  317. SemIR::ConstantId query_self_const_id,
  318. SemIR::SpecificInterface interface)
  319. -> SemIR::InstId {
  320. auto witness_id = AddInstInNoBlock(
  321. context, loc_id,
  322. SemIR::LookupImplWitness{
  323. .type_id =
  324. GetSingletonType(context, SemIR::WitnessType::SingletonInstId),
  325. .query_self_inst_id =
  326. context.constant_values().GetInstId(query_self_const_id),
  327. .query_specific_interface_id =
  328. context.specific_interfaces().Add(interface),
  329. });
  330. // We use a NotConstant result from eval to communicate back an impl
  331. // lookup failure. See `EvalConstantInst()` for `LookupImplWitness`.
  332. auto witness_const_id = context.constant_values().Get(witness_id);
  333. if (!witness_const_id.is_constant()) {
  334. return SemIR::InstId::None;
  335. }
  336. return context.constant_values().GetInstId(witness_const_id);
  337. }
  338. auto LookupImplWitness(Context& context, SemIR::LocId loc_id,
  339. SemIR::ConstantId query_self_const_id,
  340. SemIR::ConstantId query_facet_type_const_id)
  341. -> SemIR::InstBlockIdOrError {
  342. if (query_self_const_id == SemIR::ErrorInst::SingletonConstantId ||
  343. query_facet_type_const_id == SemIR::ErrorInst::SingletonConstantId) {
  344. return SemIR::InstBlockIdOrError::MakeError();
  345. }
  346. {
  347. // The query self value is a type value or a facet value.
  348. auto query_self_type_id =
  349. context.insts()
  350. .Get(context.constant_values().GetInstId(query_self_const_id))
  351. .type_id();
  352. CARBON_CHECK(context.types().Is<SemIR::TypeType>(query_self_type_id) ||
  353. context.types().Is<SemIR::FacetType>(query_self_type_id));
  354. // The query facet type value is indeed a facet type.
  355. CARBON_CHECK(context.insts().Is<SemIR::FacetType>(
  356. context.constant_values().GetInstId(query_facet_type_const_id)));
  357. }
  358. auto import_irs = FindAssociatedImportIRs(context, query_self_const_id,
  359. query_facet_type_const_id);
  360. for (auto import_ir : import_irs) {
  361. // TODO: Instead of importing all impls, only import ones that are in some
  362. // way connected to this query.
  363. for (auto impl_index : llvm::seq(
  364. context.import_irs().Get(import_ir).sem_ir->impls().size())) {
  365. // TODO: Track the relevant impls and only consider those ones and any
  366. // local impls, rather than looping over all impls below.
  367. ImportImpl(context, import_ir, SemIR::ImplId(impl_index));
  368. }
  369. }
  370. // If the self type is a FacetAccessType, work with the facet value directly,
  371. // which gives us the potential witnesses to avoid looking for impl
  372. // declarations. We will do the same for the impl declarations we try to match
  373. // so that we can compare the self constant values.
  374. query_self_const_id = UnwrapFacetAccessType(context, query_self_const_id);
  375. if (FindAndDiagnoseImplLookupCycle(context, context.impl_lookup_stack(),
  376. loc_id, query_self_const_id,
  377. query_facet_type_const_id)) {
  378. return SemIR::InstBlockIdOrError::MakeError();
  379. }
  380. bool has_other_requirements = false;
  381. auto interfaces = GetInterfacesFromConstantId(
  382. context, query_facet_type_const_id, has_other_requirements);
  383. if (has_other_requirements) {
  384. // TODO: Remove this when other requirements go away.
  385. return SemIR::InstBlockId::None;
  386. }
  387. if (interfaces.empty()) {
  388. return SemIR::InstBlockId::Empty;
  389. }
  390. auto& stack = context.impl_lookup_stack();
  391. stack.push_back({
  392. .query_self_const_id = query_self_const_id,
  393. .query_facet_type_const_id = query_facet_type_const_id,
  394. });
  395. // We need to find a witness for each interface in `interfaces`. Every
  396. // consumer of a facet type needs to agree on the order of interfaces used for
  397. // its witnesses.
  398. llvm::SmallVector<SemIR::InstId> result_witness_ids;
  399. for (const auto& interface : interfaces) {
  400. // TODO: Since both `interfaces` and `query_self_const_id` are sorted lists,
  401. // do an O(N+M) merge instead of O(N*M) nested loops.
  402. auto result_witness_id =
  403. FindWitnessInFacet(context, loc_id, query_self_const_id, interface);
  404. if (!result_witness_id.has_value()) {
  405. result_witness_id =
  406. FindWitnessInImpls(context, loc_id, query_self_const_id, interface);
  407. }
  408. if (result_witness_id.has_value()) {
  409. result_witness_ids.push_back(result_witness_id);
  410. } else {
  411. // At least one queried interface in the facet type has no witness for the
  412. // given type, we can stop looking for more.
  413. break;
  414. }
  415. }
  416. stack.pop_back();
  417. // TODO: Validate that the witness satisfies the other requirements in
  418. // `interface_const_id`.
  419. // All interfaces in the query facet type must have been found to be available
  420. // through some impl, or directly on the value's facet type if
  421. // `query_self_const_id` is a facet value.
  422. if (result_witness_ids.size() != interfaces.size()) {
  423. return SemIR::InstBlockId::None;
  424. }
  425. return context.inst_blocks().AddCanonical(result_witness_ids);
  426. }
  427. // Returns whether the query is concrete, it is false if the self type or
  428. // interface specifics have a symbolic dependency.
  429. static auto QueryIsConcrete(Context& context, SemIR::ConstantId self_const_id,
  430. SemIR::SpecificInterface& specific_interface)
  431. -> bool {
  432. if (!self_const_id.is_concrete()) {
  433. return false;
  434. }
  435. if (!specific_interface.specific_id.has_value()) {
  436. return true;
  437. }
  438. auto args_id =
  439. context.specifics().Get(specific_interface.specific_id).args_id;
  440. for (auto inst_id : context.inst_blocks().Get(args_id)) {
  441. if (!context.constant_values().Get(inst_id).is_concrete()) {
  442. return false;
  443. }
  444. }
  445. return true;
  446. }
  447. struct CandidateImpl {
  448. SemIR::ImplId impl_id;
  449. SemIR::InstId loc_inst_id;
  450. // Used for sorting the candidates to find the most-specialized match.
  451. TypeStructure type_structure;
  452. };
  453. // Returns the list of candidates impls for lookup to select from.
  454. static auto CollectCandidateImplsForQuery(
  455. Context& context, const TypeStructure& query_type_structure,
  456. SemIR::SpecificInterface& query_specific_interface)
  457. -> llvm::SmallVector<CandidateImpl> {
  458. llvm::SmallVector<CandidateImpl> candidate_impls;
  459. for (auto [id, impl] : context.impls().enumerate()) {
  460. // If the impl's interface_id differs from the query, then this impl can
  461. // not possibly provide the queried interface.
  462. if (impl.interface.interface_id != query_specific_interface.interface_id) {
  463. continue;
  464. }
  465. // When the impl's interface_id matches, but the interface is generic, the
  466. // impl may or may not match based on restrictions in the generic
  467. // parameters of the impl.
  468. //
  469. // As a shortcut, if the impl's constraint is not symbolic (does not
  470. // depend on any generic parameters), then we can determine whether we match
  471. // by looking if the specific ids match exactly.
  472. auto impl_interface_const_id =
  473. context.constant_values().Get(impl.constraint_id);
  474. if (!impl_interface_const_id.is_symbolic() &&
  475. impl.interface.specific_id != query_specific_interface.specific_id) {
  476. continue;
  477. }
  478. // This check comes first to avoid deduction with an invalid impl. We use
  479. // an error value to indicate an error during creation of the impl, such
  480. // as a recursive impl which will cause deduction to recurse infinitely.
  481. if (impl.witness_id == SemIR::ErrorInst::SingletonInstId) {
  482. continue;
  483. }
  484. CARBON_CHECK(impl.witness_id.has_value());
  485. // Build the type structure used for choosing the best the candidate.
  486. auto type_structure =
  487. BuildTypeStructure(context, impl.self_id, impl.interface);
  488. // TODO: We can skip the comparison here if the `impl_interface_const_id` is
  489. // not symbolic, since when the interface and specific ids match, and they
  490. // aren't symbolic, the structure will be identical.
  491. if (!query_type_structure.IsCompatibleWith(type_structure)) {
  492. continue;
  493. }
  494. candidate_impls.push_back(
  495. {id, impl.definition_id, std::move(type_structure)});
  496. }
  497. auto compare = [](auto& lhs, auto& rhs) -> bool {
  498. // TODO: Allow Carbon code to provide a priority ordering explicitly. For
  499. // now they have all the same priority, so the priority is the order in
  500. // which they are found in code.
  501. // Sort by their type structures. Higher value in type structure comes
  502. // first, so we use `>` comparison.
  503. return lhs.type_structure > rhs.type_structure;
  504. };
  505. // Stable sort is used so that impls that are seen first are preferred when
  506. // they have an equal priority ordering.
  507. llvm::stable_sort(candidate_impls, compare);
  508. return candidate_impls;
  509. }
  510. auto EvalLookupSingleImplWitness(Context& context, SemIR::LocId loc_id,
  511. SemIR::LookupImplWitness eval_query)
  512. -> EvalImplLookupResult {
  513. SemIR::ConstantId query_self_const_id =
  514. context.constant_values().Get(eval_query.query_self_inst_id);
  515. SemIR::SpecificInterfaceId query_specific_interface_id =
  516. eval_query.query_specific_interface_id;
  517. // NOTE: Do not retain this reference to the SpecificInterface obtained from a
  518. // value store by SpecificInterfaceId. Doing impl lookup does deduce which can
  519. // do more impl lookups, and impl lookup can add a new SpecificInterface to
  520. // the store which can reallocate and invalidate any references held here into
  521. // the store.
  522. auto query_specific_interface =
  523. context.specific_interfaces().Get(query_specific_interface_id);
  524. // When the query is a concrete FacetValue, we want to look through it at the
  525. // underlying type to find all interfaces it implements. This supports
  526. // conversion from a FacetValue to any other possible FacetValue, since
  527. // conversion depends on impl lookup to verify it is a valid type change. See
  528. // https://github.com/carbon-language/carbon-lang/issues/5137. We can't do
  529. // this step earlier than inside impl lookup since:
  530. // - We want the converted facet value to be preserved in
  531. // `FindWitnessInFacet()` to avoid looking for impl declarations.
  532. // - The constant self value may be modified during constant evaluation as a
  533. // more specific value is found.
  534. if (auto facet_value = context.insts().TryGetAs<SemIR::FacetValue>(
  535. context.constant_values().GetInstId(query_self_const_id))) {
  536. query_self_const_id =
  537. context.constant_values().Get(facet_value->type_inst_id);
  538. // If the FacetValue points to a FacetAccessType, we need to unwrap that for
  539. // comparison with the impl's self type.
  540. query_self_const_id = UnwrapFacetAccessType(context, query_self_const_id);
  541. }
  542. auto query_type_structure = BuildTypeStructure(
  543. context, context.constant_values().GetInstId(query_self_const_id),
  544. query_specific_interface);
  545. bool query_is_concrete =
  546. QueryIsConcrete(context, query_self_const_id, query_specific_interface);
  547. auto candidate_impls = CollectCandidateImplsForQuery(
  548. context, query_type_structure, query_specific_interface);
  549. for (const auto& candidate : candidate_impls) {
  550. // In deferred lookup for a symbolic impl witness, while building a
  551. // specific, there may be no stack yet as this may be the first lookup. If
  552. // further lookups are started as a result in deduce, they will build the
  553. // stack.
  554. //
  555. // NOTE: Don't retain a reference into the stack, it may be invalidated if
  556. // we do further impl lookups when GetWitnessIdForImpl() does deduction.
  557. if (!context.impl_lookup_stack().empty()) {
  558. context.impl_lookup_stack().back().impl_loc = candidate.loc_inst_id;
  559. }
  560. // NOTE: GetWitnessIdForImpl() does deduction, which can cause new impls
  561. // to be imported, invalidating any pointer into `context.impls()`.
  562. auto result = GetWitnessIdForImpl(
  563. context, loc_id, query_is_concrete, query_self_const_id,
  564. query_specific_interface, candidate.impl_id);
  565. if (result.has_value()) {
  566. return result;
  567. }
  568. }
  569. return EvalImplLookupResult::MakeNone();
  570. }
  571. } // namespace Carbon::Check