impl_lookup.cpp 27 KB

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