impl_lookup.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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_const_id = TryEvalInst(
  321. context, loc_id, SemIR::InstId::None,
  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. if (!witness_const_id.is_constant()) {
  333. return SemIR::InstId::None;
  334. }
  335. return context.constant_values().GetInstId(witness_const_id);
  336. }
  337. auto LookupImplWitness(Context& context, SemIR::LocId loc_id,
  338. SemIR::ConstantId query_self_const_id,
  339. SemIR::ConstantId query_facet_type_const_id)
  340. -> SemIR::InstBlockIdOrError {
  341. if (query_self_const_id == SemIR::ErrorInst::SingletonConstantId ||
  342. query_facet_type_const_id == SemIR::ErrorInst::SingletonConstantId) {
  343. return SemIR::InstBlockIdOrError::MakeError();
  344. }
  345. {
  346. // The query self value is a type value or a facet value.
  347. auto query_self_type_id =
  348. context.insts()
  349. .Get(context.constant_values().GetInstId(query_self_const_id))
  350. .type_id();
  351. CARBON_CHECK(context.types().Is<SemIR::TypeType>(query_self_type_id) ||
  352. context.types().Is<SemIR::FacetType>(query_self_type_id));
  353. // The query facet type value is indeed a facet type.
  354. CARBON_CHECK(context.insts().Is<SemIR::FacetType>(
  355. context.constant_values().GetInstId(query_facet_type_const_id)));
  356. }
  357. auto import_irs = FindAssociatedImportIRs(context, query_self_const_id,
  358. query_facet_type_const_id);
  359. for (auto import_ir : import_irs) {
  360. // TODO: Instead of importing all impls, only import ones that are in some
  361. // way connected to this query.
  362. for (auto impl_index : llvm::seq(
  363. context.import_irs().Get(import_ir).sem_ir->impls().size())) {
  364. // TODO: Track the relevant impls and only consider those ones and any
  365. // local impls, rather than looping over all impls below.
  366. ImportImpl(context, import_ir, SemIR::ImplId(impl_index));
  367. }
  368. }
  369. // If the self type is a FacetAccessType, work with the facet value directly,
  370. // which gives us the potential witnesses to avoid looking for impl
  371. // declarations. We will do the same for the impl declarations we try to match
  372. // so that we can compare the self constant values.
  373. query_self_const_id = UnwrapFacetAccessType(context, query_self_const_id);
  374. if (FindAndDiagnoseImplLookupCycle(context, context.impl_lookup_stack(),
  375. loc_id, query_self_const_id,
  376. query_facet_type_const_id)) {
  377. return SemIR::InstBlockIdOrError::MakeError();
  378. }
  379. bool has_other_requirements = false;
  380. auto interfaces = GetInterfacesFromConstantId(
  381. context, query_facet_type_const_id, has_other_requirements);
  382. if (has_other_requirements) {
  383. // TODO: Remove this when other requirements go away.
  384. return SemIR::InstBlockId::None;
  385. }
  386. if (interfaces.empty()) {
  387. return SemIR::InstBlockId::Empty;
  388. }
  389. auto& stack = context.impl_lookup_stack();
  390. stack.push_back({
  391. .query_self_const_id = query_self_const_id,
  392. .query_facet_type_const_id = query_facet_type_const_id,
  393. });
  394. // We need to find a witness for each interface in `interfaces`. Every
  395. // consumer of a facet type needs to agree on the order of interfaces used for
  396. // its witnesses.
  397. llvm::SmallVector<SemIR::InstId> result_witness_ids;
  398. for (const auto& interface : interfaces) {
  399. // TODO: Since both `interfaces` and `query_self_const_id` are sorted lists,
  400. // do an O(N+M) merge instead of O(N*M) nested loops.
  401. auto result_witness_id =
  402. FindWitnessInFacet(context, loc_id, query_self_const_id, interface);
  403. if (!result_witness_id.has_value()) {
  404. result_witness_id =
  405. FindWitnessInImpls(context, loc_id, query_self_const_id, interface);
  406. }
  407. if (result_witness_id.has_value()) {
  408. result_witness_ids.push_back(result_witness_id);
  409. } else {
  410. // At least one queried interface in the facet type has no witness for the
  411. // given type, we can stop looking for more.
  412. break;
  413. }
  414. }
  415. stack.pop_back();
  416. // TODO: Validate that the witness satisfies the other requirements in
  417. // `interface_const_id`.
  418. // All interfaces in the query facet type must have been found to be available
  419. // through some impl, or directly on the value's facet type if
  420. // `query_self_const_id` is a facet value.
  421. if (result_witness_ids.size() != interfaces.size()) {
  422. return SemIR::InstBlockId::None;
  423. }
  424. return context.inst_blocks().AddCanonical(result_witness_ids);
  425. }
  426. // Returns whether the query is concrete, it is false if the self type or
  427. // interface specifics have a symbolic dependency.
  428. static auto QueryIsConcrete(Context& context, SemIR::ConstantId self_const_id,
  429. SemIR::SpecificInterface& specific_interface)
  430. -> bool {
  431. if (!self_const_id.is_concrete()) {
  432. return false;
  433. }
  434. if (!specific_interface.specific_id.has_value()) {
  435. return true;
  436. }
  437. auto args_id =
  438. context.specifics().Get(specific_interface.specific_id).args_id;
  439. for (auto inst_id : context.inst_blocks().Get(args_id)) {
  440. if (!context.constant_values().Get(inst_id).is_concrete()) {
  441. return false;
  442. }
  443. }
  444. return true;
  445. }
  446. struct CandidateImpl {
  447. SemIR::ImplId impl_id;
  448. SemIR::InstId loc_inst_id;
  449. // Used for sorting the candidates to find the most-specialized match.
  450. TypeStructure type_structure;
  451. };
  452. // Returns the list of candidates impls for lookup to select from.
  453. static auto CollectCandidateImplsForQuery(
  454. Context& context, const TypeStructure& query_type_structure,
  455. SemIR::SpecificInterface& query_specific_interface)
  456. -> llvm::SmallVector<CandidateImpl> {
  457. llvm::SmallVector<CandidateImpl> candidate_impls;
  458. for (auto [id, impl] : context.impls().enumerate()) {
  459. // If the impl's interface_id differs from the query, then this impl can
  460. // not possibly provide the queried interface.
  461. if (impl.interface.interface_id != query_specific_interface.interface_id) {
  462. continue;
  463. }
  464. // When the impl's interface_id matches, but the interface is generic, the
  465. // impl may or may not match based on restrictions in the generic
  466. // parameters of the impl.
  467. //
  468. // As a shortcut, if the impl's constraint is not symbolic (does not
  469. // depend on any generic parameters), then we can determine whether we match
  470. // by looking if the specific ids match exactly.
  471. auto impl_interface_const_id =
  472. context.constant_values().Get(impl.constraint_id);
  473. if (!impl_interface_const_id.is_symbolic() &&
  474. impl.interface.specific_id != query_specific_interface.specific_id) {
  475. continue;
  476. }
  477. // This check comes first to avoid deduction with an invalid impl. We use
  478. // an error value to indicate an error during creation of the impl, such
  479. // as a recursive impl which will cause deduction to recurse infinitely.
  480. if (impl.witness_id == SemIR::ErrorInst::SingletonInstId) {
  481. continue;
  482. }
  483. CARBON_CHECK(impl.witness_id.has_value());
  484. // Build the type structure used for choosing the best the candidate.
  485. auto type_structure =
  486. BuildTypeStructure(context, impl.self_id, impl.interface);
  487. // TODO: We can skip the comparison here if the `impl_interface_const_id` is
  488. // not symbolic, since when the interface and specific ids match, and they
  489. // aren't symbolic, the structure will be identical.
  490. if (!query_type_structure.IsCompatibleWith(type_structure)) {
  491. continue;
  492. }
  493. candidate_impls.push_back(
  494. {id, impl.definition_id, std::move(type_structure)});
  495. }
  496. auto compare = [](auto& lhs, auto& rhs) -> bool {
  497. // TODO: Allow Carbon code to provide a priority ordering explicitly. For
  498. // now they have all the same priority, so the priority is the order in
  499. // which they are found in code.
  500. // Sort by their type structures. Higher value in type structure comes
  501. // first, so we use `>` comparison.
  502. return lhs.type_structure > rhs.type_structure;
  503. };
  504. // Stable sort is used so that impls that are seen first are preferred when
  505. // they have an equal priority ordering.
  506. llvm::stable_sort(candidate_impls, compare);
  507. return candidate_impls;
  508. }
  509. auto EvalLookupSingleImplWitness(Context& context, SemIR::LocId loc_id,
  510. SemIR::LookupImplWitness eval_query)
  511. -> EvalImplLookupResult {
  512. SemIR::ConstantId query_self_const_id =
  513. context.constant_values().Get(eval_query.query_self_inst_id);
  514. SemIR::SpecificInterfaceId query_specific_interface_id =
  515. eval_query.query_specific_interface_id;
  516. // NOTE: Do not retain this reference to the SpecificInterface obtained from a
  517. // value store by SpecificInterfaceId. Doing impl lookup does deduce which can
  518. // do more impl lookups, and impl lookup can add a new SpecificInterface to
  519. // the store which can reallocate and invalidate any references held here into
  520. // the store.
  521. auto query_specific_interface =
  522. context.specific_interfaces().Get(query_specific_interface_id);
  523. // When the query is a concrete FacetValue, we want to look through it at the
  524. // underlying type to find all interfaces it implements. This supports
  525. // conversion from a FacetValue to any other possible FacetValue, since
  526. // conversion depends on impl lookup to verify it is a valid type change. See
  527. // https://github.com/carbon-language/carbon-lang/issues/5137. We can't do
  528. // this step earlier than inside impl lookup since:
  529. // - We want the converted facet value to be preserved in
  530. // `FindWitnessInFacet()` to avoid looking for impl declarations.
  531. // - The constant self value may be modified during constant evaluation as a
  532. // more specific value is found.
  533. if (auto facet_value = context.insts().TryGetAs<SemIR::FacetValue>(
  534. context.constant_values().GetInstId(query_self_const_id))) {
  535. query_self_const_id =
  536. context.constant_values().Get(facet_value->type_inst_id);
  537. // If the FacetValue points to a FacetAccessType, we need to unwrap that for
  538. // comparison with the impl's self type.
  539. query_self_const_id = UnwrapFacetAccessType(context, query_self_const_id);
  540. }
  541. auto query_type_structure = BuildTypeStructure(
  542. context, context.constant_values().GetInstId(query_self_const_id),
  543. query_specific_interface);
  544. bool query_is_concrete =
  545. QueryIsConcrete(context, query_self_const_id, query_specific_interface);
  546. auto candidate_impls = CollectCandidateImplsForQuery(
  547. context, query_type_structure, query_specific_interface);
  548. for (const auto& candidate : candidate_impls) {
  549. // In deferred lookup for a symbolic impl witness, while building a
  550. // specific, there may be no stack yet as this may be the first lookup. If
  551. // further lookups are started as a result in deduce, they will build the
  552. // stack.
  553. //
  554. // NOTE: Don't retain a reference into the stack, it may be invalidated if
  555. // we do further impl lookups when GetWitnessIdForImpl() does deduction.
  556. if (!context.impl_lookup_stack().empty()) {
  557. context.impl_lookup_stack().back().impl_loc = candidate.loc_inst_id;
  558. }
  559. // NOTE: GetWitnessIdForImpl() does deduction, which can cause new impls
  560. // to be imported, invalidating any pointer into `context.impls()`.
  561. auto result = GetWitnessIdForImpl(
  562. context, loc_id, query_is_concrete, query_self_const_id,
  563. query_specific_interface, candidate.impl_id);
  564. if (result.has_value()) {
  565. return result;
  566. }
  567. }
  568. return EvalImplLookupResult::MakeNone();
  569. }
  570. } // namespace Carbon::Check