impl_lookup.cpp 26 KB

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