impl_lookup.cpp 28 KB

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