impl_lookup.cpp 29 KB

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