impl_lookup.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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. const SemIR::Impl& impl = context.impls().Get(impl_id);
  194. // The impl may have generic arguments, in which case we need to deduce them
  195. // to find what they are given the specific type and interface query. We use
  196. // that specific to map values in the impl to the deduced values.
  197. auto specific_id = SemIR::SpecificId::None;
  198. if (impl.generic_id.has_value()) {
  199. specific_id = DeduceImplArguments(
  200. context, loc_id, impl, query_self_const_id, interface.specific_id);
  201. if (!specific_id.has_value()) {
  202. return EvalImplLookupResult::MakeNone();
  203. }
  204. }
  205. // The self type of the impl must match the type in the query, or this is an
  206. // `impl T as ...` for some other type `T` and should not be considered.
  207. auto deduced_self_const_id = SemIR::GetConstantValueInSpecific(
  208. context.sem_ir(), specific_id, impl.self_id);
  209. // In a generic `impl forall` the self type can be a FacetAccessType, which
  210. // will not be the same constant value as a query facet value. We move through
  211. // to the facet value here, and if the query was a FacetAccessType we did the
  212. // same there so they still match.
  213. deduced_self_const_id =
  214. GetCanonicalizedFacetOrTypeValue(context, deduced_self_const_id);
  215. if (query_self_const_id != deduced_self_const_id) {
  216. return EvalImplLookupResult::MakeNone();
  217. }
  218. // The impl's constraint is a facet type which it is implementing for the self
  219. // type: the `I` in `impl ... as I`. The deduction step may be unable to be
  220. // fully applied to the types in the constraint and result in an error here,
  221. // in which case it does not match the query.
  222. auto deduced_constraint_id =
  223. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  224. context.sem_ir(), specific_id, impl.constraint_id));
  225. if (deduced_constraint_id == SemIR::ErrorInst::InstId) {
  226. return EvalImplLookupResult::MakeNone();
  227. }
  228. auto deduced_constraint_facet_type_id =
  229. context.insts()
  230. .GetAs<SemIR::FacetType>(deduced_constraint_id)
  231. .facet_type_id;
  232. const auto& deduced_constraint_facet_type_info =
  233. context.facet_types().Get(deduced_constraint_facet_type_id);
  234. CARBON_CHECK(deduced_constraint_facet_type_info.extend_constraints.size() ==
  235. 1);
  236. if (deduced_constraint_facet_type_info.other_requirements) {
  237. // TODO: Remove this when other requirements goes away.
  238. return EvalImplLookupResult::MakeNone();
  239. }
  240. // The specifics in the queried interface must match the deduced specifics in
  241. // the impl's constraint facet type.
  242. auto impl_interface_specific_id =
  243. deduced_constraint_facet_type_info.extend_constraints[0].specific_id;
  244. auto query_interface_specific_id = interface.specific_id;
  245. if (impl_interface_specific_id != query_interface_specific_id) {
  246. return EvalImplLookupResult::MakeNone();
  247. }
  248. LoadImportRef(context, impl.witness_id);
  249. if (specific_id.has_value()) {
  250. // We need a definition of the specific `impl` so we can access its
  251. // witness.
  252. ResolveSpecificDefinition(context, loc_id, specific_id);
  253. }
  254. if (query_is_concrete || impl.is_final) {
  255. // TODO: These final results should be cached somehow. Positive (non-None)
  256. // results could be cached globally, as they can not change. But
  257. // negative results can change after a final impl is written, so
  258. // they can only be cached in a limited way, or the cache needs to
  259. // be invalidated by writing a final impl that would match.
  260. return EvalImplLookupResult::MakeFinal(
  261. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  262. context.sem_ir(), specific_id, impl.witness_id)));
  263. } else {
  264. return EvalImplLookupResult::MakeNonFinal();
  265. }
  266. }
  267. // Unwraps a FacetAccessType to move from a value of type `TypeType` to a facet
  268. // value of type `FacetType` if possible.
  269. //
  270. // Generally `GetCanonicalizedFacetOrTypeValue()` is what you want to call
  271. // instead, as this only does part of that operation, potentially returning a
  272. // non-canonical facet value.
  273. static auto UnwrapFacetAccessType(Context& context, SemIR::InstId inst_id)
  274. -> SemIR::InstId {
  275. if (auto access = context.insts().TryGetAs<SemIR::FacetAccessType>(inst_id)) {
  276. return access->facet_value_inst_id;
  277. }
  278. return inst_id;
  279. }
  280. // Finds a lookup result from `query_self_inst_id` if it is a facet value that
  281. // names the query interface in its facet type. Note that `query_self_inst_id`
  282. // is allowed to be a non-canonical facet value in order to find a concrete
  283. // witness, so it's not referenced as a constant value.
  284. static auto LookupImplWitnessInSelfFacetValue(
  285. Context& context, SemIR::InstId query_self_inst_id,
  286. SemIR::SpecificInterface query_specific_interface) -> EvalImplLookupResult {
  287. // Unwrap FacetAccessType without getting the canonical facet value from the
  288. // self value, as we want to preserve the non-canonical `FacetValue`
  289. // instruction which can contain the concrete witness.
  290. query_self_inst_id = UnwrapFacetAccessType(context, query_self_inst_id);
  291. auto facet_type = context.types().TryGetAs<SemIR::FacetType>(
  292. context.insts().Get(query_self_inst_id).type_id());
  293. if (!facet_type) {
  294. return EvalImplLookupResult::MakeNone();
  295. }
  296. // The position of the interface in `required_interfaces()` is also the
  297. // position of the witness for that interface in `FacetValue`.
  298. auto identified_id = RequireIdentifiedFacetType(context, *facet_type);
  299. auto facet_type_required_interfaces =
  300. llvm::enumerate(context.identified_facet_types()
  301. .Get(identified_id)
  302. .required_interfaces());
  303. auto it = llvm::find_if(facet_type_required_interfaces, [=](auto e) {
  304. return e.value() == query_specific_interface;
  305. });
  306. if (it == facet_type_required_interfaces.end()) {
  307. return EvalImplLookupResult::MakeNone();
  308. }
  309. auto index = (*it).index();
  310. if (auto facet_value =
  311. context.insts().TryGetAs<SemIR::FacetValue>(query_self_inst_id)) {
  312. auto witness_id =
  313. context.inst_blocks().Get(facet_value->witnesses_block_id)[index];
  314. if (context.insts().Is<SemIR::ImplWitness>(witness_id)) {
  315. return EvalImplLookupResult::MakeFinal(witness_id);
  316. }
  317. }
  318. return EvalImplLookupResult::MakeNonFinal();
  319. }
  320. // Begin a search for an impl declaration matching the query. We do this by
  321. // creating an LookupImplWitness instruction and evaluating. If it's able to
  322. // find a final concrete impl, then it will evaluate to that `ImplWitness` but
  323. // if not, it will evaluate to itself as a symbolic witness to be further
  324. // evaluated with a more specific query when building a specific for the generic
  325. // context the query came from.
  326. static auto GetOrAddLookupImplWitness(Context& context, SemIR::LocId loc_id,
  327. SemIR::ConstantId query_self_const_id,
  328. SemIR::SpecificInterface interface)
  329. -> SemIR::InstId {
  330. auto witness_const_id = EvalOrAddInst(
  331. context, context.insts().GetLocIdForDesugaring(loc_id),
  332. SemIR::LookupImplWitness{
  333. .type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  334. .query_self_inst_id =
  335. context.constant_values().GetInstId(query_self_const_id),
  336. .query_specific_interface_id =
  337. context.specific_interfaces().Add(interface),
  338. });
  339. // We use a NotConstant result from eval to communicate back an impl
  340. // lookup failure. See `EvalConstantInst()` for `LookupImplWitness`.
  341. if (!witness_const_id.is_constant()) {
  342. return SemIR::InstId::None;
  343. }
  344. return context.constant_values().GetInstId(witness_const_id);
  345. }
  346. auto LookupImplWitness(Context& context, SemIR::LocId loc_id,
  347. SemIR::ConstantId query_self_const_id,
  348. SemIR::ConstantId query_facet_type_const_id)
  349. -> SemIR::InstBlockIdOrError {
  350. if (query_self_const_id == SemIR::ErrorInst::ConstantId ||
  351. query_facet_type_const_id == SemIR::ErrorInst::ConstantId) {
  352. return SemIR::InstBlockIdOrError::MakeError();
  353. }
  354. {
  355. // The query self value is a type value or a facet value.
  356. auto query_self_type_id =
  357. context.insts()
  358. .Get(context.constant_values().GetInstId(query_self_const_id))
  359. .type_id();
  360. CARBON_CHECK(context.types().Is<SemIR::TypeType>(query_self_type_id) ||
  361. context.types().Is<SemIR::FacetType>(query_self_type_id));
  362. // The query facet type value is indeed a facet type.
  363. CARBON_CHECK(context.insts().Is<SemIR::FacetType>(
  364. context.constant_values().GetInstId(query_facet_type_const_id)));
  365. }
  366. auto import_irs = FindAssociatedImportIRs(context, query_self_const_id,
  367. query_facet_type_const_id);
  368. for (auto import_ir : import_irs) {
  369. // TODO: Instead of importing all impls, only import ones that are in some
  370. // way connected to this query.
  371. for (auto [import_impl_id, _] :
  372. context.import_irs().Get(import_ir).sem_ir->impls().enumerate()) {
  373. // TODO: Track the relevant impls and only consider those ones and any
  374. // local impls, rather than looping over all impls below.
  375. ImportImpl(context, import_ir, import_impl_id);
  376. }
  377. }
  378. if (FindAndDiagnoseImplLookupCycle(context, context.impl_lookup_stack(),
  379. loc_id, query_self_const_id,
  380. query_facet_type_const_id)) {
  381. return SemIR::InstBlockIdOrError::MakeError();
  382. }
  383. bool has_other_requirements = false;
  384. auto interfaces = GetInterfacesFromConstantId(
  385. context, query_facet_type_const_id, has_other_requirements);
  386. if (has_other_requirements) {
  387. // TODO: Remove this when other requirements go away.
  388. return SemIR::InstBlockId::None;
  389. }
  390. if (interfaces.empty()) {
  391. return SemIR::InstBlockId::Empty;
  392. }
  393. auto& stack = context.impl_lookup_stack();
  394. stack.push_back({
  395. .query_self_const_id = query_self_const_id,
  396. .query_facet_type_const_id = query_facet_type_const_id,
  397. });
  398. // We need to find a witness for each interface in `interfaces`. Every
  399. // consumer of a facet type needs to agree on the order of interfaces used for
  400. // its witnesses.
  401. llvm::SmallVector<SemIR::InstId> result_witness_ids;
  402. for (const auto& interface : interfaces) {
  403. // TODO: Since both `interfaces` and `query_self_const_id` are sorted lists,
  404. // do an O(N+M) merge instead of O(N*M) nested loops.
  405. auto result_witness_id = GetOrAddLookupImplWitness(
  406. context, loc_id, query_self_const_id, interface);
  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. // All interfaces in the query facet type must have been found to be available
  417. // through some impl, or directly on the value's facet type if
  418. // `query_self_const_id` is a facet value.
  419. if (result_witness_ids.size() != interfaces.size()) {
  420. return SemIR::InstBlockId::None;
  421. }
  422. // TODO: Validate that the witness satisfies the other requirements in
  423. // `interface_const_id`.
  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. const 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, bool final_only,
  455. const TypeStructure& query_type_structure,
  456. SemIR::SpecificInterface& query_specific_interface)
  457. -> llvm::SmallVector<CandidateImpl> {
  458. llvm::SmallVector<CandidateImpl> candidate_impls;
  459. for (auto [id, impl] : context.impls().enumerate()) {
  460. if (final_only && !IsImplEffectivelyFinal(context, impl)) {
  461. continue;
  462. }
  463. // If the impl's interface_id differs from the query, then this impl can
  464. // not possibly provide the queried interface.
  465. if (impl.interface.interface_id != query_specific_interface.interface_id) {
  466. continue;
  467. }
  468. // When the impl's interface_id matches, but the interface is generic, the
  469. // impl may or may not match based on restrictions in the generic
  470. // parameters of the impl.
  471. //
  472. // As a shortcut, if the impl's constraint is not symbolic (does not
  473. // depend on any generic parameters), then we can determine whether we match
  474. // by looking if the specific ids match exactly.
  475. auto impl_interface_const_id =
  476. context.constant_values().Get(impl.constraint_id);
  477. if (!impl_interface_const_id.is_symbolic() &&
  478. impl.interface.specific_id != query_specific_interface.specific_id) {
  479. continue;
  480. }
  481. // This check comes first to avoid deduction with an invalid impl. We use
  482. // an error value to indicate an error during creation of the impl, such
  483. // as a recursive impl which will cause deduction to recurse infinitely.
  484. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  485. continue;
  486. }
  487. CARBON_CHECK(impl.witness_id.has_value());
  488. // Build the type structure used for choosing the best the candidate.
  489. auto type_structure =
  490. BuildTypeStructure(context, impl.self_id, impl.interface);
  491. // TODO: We can skip the comparison here if the `impl_interface_const_id` is
  492. // not symbolic, since when the interface and specific ids match, and they
  493. // aren't symbolic, the structure will be identical.
  494. if (!query_type_structure.CompareStructure(
  495. TypeStructure::CompareTest::IsEqualToOrMoreSpecificThan,
  496. type_structure)) {
  497. continue;
  498. }
  499. candidate_impls.push_back(
  500. {id, impl.definition_id, std::move(type_structure)});
  501. }
  502. auto compare = [](auto& lhs, auto& rhs) -> bool {
  503. return lhs.type_structure < rhs.type_structure;
  504. };
  505. // Stable sort is used so that impls that are seen first are preferred when
  506. // they have an equal priority ordering.
  507. // TODO: Allow Carbon code to provide a priority ordering explicitly. For
  508. // now they have all the same priority, so the priority is the order in
  509. // which they are found in code.
  510. llvm::stable_sort(candidate_impls, compare);
  511. return candidate_impls;
  512. }
  513. auto EvalLookupSingleImplWitness(Context& context, SemIR::LocId loc_id,
  514. SemIR::LookupImplWitness eval_query,
  515. SemIR::InstId non_canonical_query_self_inst_id,
  516. bool poison_concrete_results)
  517. -> EvalImplLookupResult {
  518. auto query_specific_interface =
  519. context.specific_interfaces().Get(eval_query.query_specific_interface_id);
  520. auto facet_lookup_result = LookupImplWitnessInSelfFacetValue(
  521. context, non_canonical_query_self_inst_id, query_specific_interface);
  522. if (facet_lookup_result.has_concrete_value()) {
  523. return facet_lookup_result;
  524. }
  525. // If the self type is a facet that provides a witness, then we are in an
  526. // `interface` or an `impl`. In both cases, we don't want to do any impl
  527. // lookups. The query will eventually resolve to a concrete witness when it
  528. // can get it from the self facet value, when it has a specific applied in the
  529. // future.
  530. //
  531. // In particular, this avoids a LookupImplWitness instruction in the eval
  532. // block of an impl declaration from doing impl lookup. Specifically the
  533. // lookup of the implicit .Self in `impl ... where .X`. If it does impl lookup
  534. // when the eval block is run, it finds the same `impl`, tries to build a
  535. // specific from it, which runs the eval block, creating a recursive loop that
  536. // crashes.
  537. bool self_facet_provides_witness = facet_lookup_result.has_value();
  538. if (self_facet_provides_witness) {
  539. if (auto bind = context.insts().TryGetAs<SemIR::BindSymbolicName>(
  540. eval_query.query_self_inst_id)) {
  541. const auto& entity = context.entity_names().Get(bind->entity_name_id);
  542. if (entity.name_id == SemIR::NameId::PeriodSelf ||
  543. entity.name_id == SemIR::NameId::SelfType) {
  544. return EvalImplLookupResult::MakeNonFinal();
  545. }
  546. }
  547. }
  548. SemIR::ConstantId query_self_const_id =
  549. context.constant_values().Get(eval_query.query_self_inst_id);
  550. auto query_type_structure = BuildTypeStructure(
  551. context, context.constant_values().GetInstId(query_self_const_id),
  552. query_specific_interface);
  553. bool query_is_concrete =
  554. QueryIsConcrete(context, query_self_const_id, query_specific_interface);
  555. // If we have a symbolic witness in the self query, then the query can not be
  556. // concrete: the query includes a symbolic self value.
  557. CARBON_CHECK(!self_facet_provides_witness || !query_is_concrete);
  558. // If the self value is a (symbolic) facet value that has a symbolic witness,
  559. // then we don't need to do impl lookup, except that we want to find any final
  560. // impls to return a concrete witness if possible. So we limit the query to
  561. // final impls only in that case. Note as in the CHECK above, the query can
  562. // not be concrete in this case, so only final impls can produce a concrete
  563. // witness for this query.
  564. auto candidate_impls = CollectCandidateImplsForQuery(
  565. context, self_facet_provides_witness, query_type_structure,
  566. query_specific_interface);
  567. for (const auto& candidate : candidate_impls) {
  568. // In deferred lookup for a symbolic impl witness, while building a
  569. // specific, there may be no stack yet as this may be the first lookup. If
  570. // further lookups are started as a result in deduce, they will build the
  571. // stack.
  572. //
  573. // NOTE: Don't retain a reference into the stack, it may be invalidated if
  574. // we do further impl lookups when GetWitnessIdForImpl() does deduction.
  575. if (!context.impl_lookup_stack().empty()) {
  576. context.impl_lookup_stack().back().impl_loc = candidate.loc_inst_id;
  577. }
  578. auto result = GetWitnessIdForImpl(
  579. context, loc_id, query_is_concrete, query_self_const_id,
  580. query_specific_interface, candidate.impl_id);
  581. if (result.has_value()) {
  582. // Record the query which found a concrete impl witness. It's illegal to
  583. // write a final impl afterward that would match the same query.
  584. //
  585. // If the impl was effectively final, then we don't need to poison here. A
  586. // change of query result will already be diagnosed at the point where the
  587. // new impl decl was written that changes the result.
  588. if (poison_concrete_results && result.has_concrete_value() &&
  589. !IsImplEffectivelyFinal(context,
  590. context.impls().Get(candidate.impl_id))) {
  591. context.poisoned_concrete_impl_lookup_queries().push_back(
  592. {.loc_id = loc_id,
  593. .query = eval_query,
  594. .non_canonical_query_self_inst_id =
  595. non_canonical_query_self_inst_id,
  596. .impl_witness = result.concrete_witness()});
  597. }
  598. return result;
  599. }
  600. }
  601. if (self_facet_provides_witness) {
  602. // If we did not find a final impl, but the self value is a facet that
  603. // provides a symbolic witness, when we record that an impl will exist for
  604. // the specific, but is yet unknown.
  605. return EvalImplLookupResult::MakeNonFinal();
  606. }
  607. return EvalImplLookupResult::MakeNone();
  608. }
  609. auto LookupMatchesImpl(Context& context, SemIR::LocId loc_id,
  610. SemIR::ConstantId query_self_const_id,
  611. SemIR::SpecificInterface query_specific_interface,
  612. SemIR::ImplId target_impl) -> bool {
  613. if (query_self_const_id == SemIR::ErrorInst::ConstantId) {
  614. return false;
  615. }
  616. auto result = GetWitnessIdForImpl(
  617. context, loc_id, /*query_is_concrete=*/false, query_self_const_id,
  618. query_specific_interface, target_impl);
  619. return result.has_value();
  620. }
  621. } // namespace Carbon::Check