impl_lookup.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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. bool is_effectively_final = query_is_concrete || impl.is_final;
  259. auto witness_id = impl.witness_id;
  260. // Note that this invalidates our `impl` reference. Don't use it again after
  261. // this point.
  262. LoadImportRef(context, witness_id);
  263. if (specific_id.has_value()) {
  264. // We need a definition of the specific `impl` so we can access its
  265. // witness.
  266. ResolveSpecificDefinition(context, loc_id, specific_id);
  267. }
  268. if (is_effectively_final) {
  269. // TODO: These final results should be cached somehow. Positive (non-None)
  270. // results could be cached globally, as they can not change. But
  271. // negative results can change after a final impl is written, so
  272. // they can only be cached in a limited way, or the cache needs to
  273. // be invalidated by writing a final impl that would match.
  274. return EvalImplLookupResult::MakeFinal(
  275. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  276. context.sem_ir(), specific_id, witness_id)));
  277. } else {
  278. return EvalImplLookupResult::MakeNonFinal();
  279. }
  280. }
  281. // Unwraps a FacetAccessType to move from a value of type `TypeType` to a facet
  282. // value of type `FacetType` if possible.
  283. //
  284. // Generally `GetCanonicalizedFacetOrTypeValue()` is what you want to call
  285. // instead, as this only does part of that operation, potentially returning a
  286. // non-canonical facet value.
  287. static auto UnwrapFacetAccessType(Context& context, SemIR::InstId inst_id)
  288. -> SemIR::InstId {
  289. if (auto access = context.insts().TryGetAs<SemIR::FacetAccessType>(inst_id)) {
  290. return access->facet_value_inst_id;
  291. }
  292. return inst_id;
  293. }
  294. // Finds a lookup result from `query_self_inst_id` if it is a facet value that
  295. // names the query interface in its facet type. Note that `query_self_inst_id`
  296. // is allowed to be a non-canonical facet value in order to find a concrete
  297. // witness, so it's not referenced as a constant value.
  298. static auto LookupImplWitnessInSelfFacetValue(
  299. Context& context, SemIR::InstId query_self_inst_id,
  300. SemIR::SpecificInterface query_specific_interface) -> EvalImplLookupResult {
  301. // Unwrap FacetAccessType without getting the canonical facet value from the
  302. // self value, as we want to preserve the non-canonical `FacetValue`
  303. // instruction which can contain the concrete witness.
  304. query_self_inst_id = UnwrapFacetAccessType(context, query_self_inst_id);
  305. auto facet_type = context.types().TryGetAs<SemIR::FacetType>(
  306. context.insts().Get(query_self_inst_id).type_id());
  307. if (!facet_type) {
  308. return EvalImplLookupResult::MakeNone();
  309. }
  310. // The position of the interface in `required_interfaces()` is also the
  311. // position of the witness for that interface in `FacetValue`.
  312. auto identified_id = RequireIdentifiedFacetType(context, *facet_type);
  313. auto facet_type_required_interfaces =
  314. llvm::enumerate(context.identified_facet_types()
  315. .Get(identified_id)
  316. .required_interfaces());
  317. auto it = llvm::find_if(facet_type_required_interfaces, [=](auto e) {
  318. return e.value() == query_specific_interface;
  319. });
  320. if (it == facet_type_required_interfaces.end()) {
  321. return EvalImplLookupResult::MakeNone();
  322. }
  323. auto index = (*it).index();
  324. if (auto facet_value =
  325. context.insts().TryGetAs<SemIR::FacetValue>(query_self_inst_id)) {
  326. auto witness_id =
  327. context.inst_blocks().Get(facet_value->witnesses_block_id)[index];
  328. if (context.insts().Is<SemIR::ImplWitness>(witness_id)) {
  329. return EvalImplLookupResult::MakeFinal(witness_id);
  330. }
  331. }
  332. return EvalImplLookupResult::MakeNonFinal();
  333. }
  334. // Begin a search for an impl declaration matching the query. We do this by
  335. // creating an LookupImplWitness instruction and evaluating. If it's able to
  336. // find a final concrete impl, then it will evaluate to that `ImplWitness` but
  337. // if not, it will evaluate to itself as a symbolic witness to be further
  338. // evaluated with a more specific query when building a specific for the generic
  339. // context the query came from.
  340. static auto GetOrAddLookupImplWitness(Context& context, SemIR::LocId loc_id,
  341. SemIR::ConstantId query_self_const_id,
  342. SemIR::SpecificInterface interface)
  343. -> SemIR::InstId {
  344. auto witness_const_id = EvalOrAddInst(
  345. context, context.insts().GetCanonicalLocId(loc_id).ToImplicit(),
  346. SemIR::LookupImplWitness{
  347. .type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  348. .query_self_inst_id =
  349. context.constant_values().GetInstId(query_self_const_id),
  350. .query_specific_interface_id =
  351. context.specific_interfaces().Add(interface),
  352. });
  353. // We use a NotConstant result from eval to communicate back an impl
  354. // lookup failure. See `EvalConstantInst()` for `LookupImplWitness`.
  355. if (!witness_const_id.is_constant()) {
  356. return SemIR::InstId::None;
  357. }
  358. return context.constant_values().GetInstId(witness_const_id);
  359. }
  360. auto LookupImplWitness(Context& context, SemIR::LocId loc_id,
  361. SemIR::ConstantId query_self_const_id,
  362. SemIR::ConstantId query_facet_type_const_id)
  363. -> SemIR::InstBlockIdOrError {
  364. if (query_self_const_id == SemIR::ErrorInst::ConstantId ||
  365. query_facet_type_const_id == SemIR::ErrorInst::ConstantId) {
  366. return SemIR::InstBlockIdOrError::MakeError();
  367. }
  368. {
  369. // The query self value is a type value or a facet value.
  370. auto query_self_type_id =
  371. context.insts()
  372. .Get(context.constant_values().GetInstId(query_self_const_id))
  373. .type_id();
  374. CARBON_CHECK(context.types().Is<SemIR::TypeType>(query_self_type_id) ||
  375. context.types().Is<SemIR::FacetType>(query_self_type_id));
  376. // The query facet type value is indeed a facet type.
  377. CARBON_CHECK(context.insts().Is<SemIR::FacetType>(
  378. context.constant_values().GetInstId(query_facet_type_const_id)));
  379. }
  380. auto import_irs = FindAssociatedImportIRs(context, query_self_const_id,
  381. query_facet_type_const_id);
  382. for (auto import_ir : import_irs) {
  383. // TODO: Instead of importing all impls, only import ones that are in some
  384. // way connected to this query.
  385. for (auto impl_index : llvm::seq(
  386. context.import_irs().Get(import_ir).sem_ir->impls().size())) {
  387. // TODO: Track the relevant impls and only consider those ones and any
  388. // local impls, rather than looping over all impls below.
  389. ImportImpl(context, import_ir, SemIR::ImplId(impl_index));
  390. }
  391. }
  392. if (FindAndDiagnoseImplLookupCycle(context, context.impl_lookup_stack(),
  393. loc_id, query_self_const_id,
  394. query_facet_type_const_id)) {
  395. return SemIR::InstBlockIdOrError::MakeError();
  396. }
  397. bool has_other_requirements = false;
  398. auto interfaces = GetInterfacesFromConstantId(
  399. context, query_facet_type_const_id, has_other_requirements);
  400. if (has_other_requirements) {
  401. // TODO: Remove this when other requirements go away.
  402. return SemIR::InstBlockId::None;
  403. }
  404. if (interfaces.empty()) {
  405. return SemIR::InstBlockId::Empty;
  406. }
  407. auto& stack = context.impl_lookup_stack();
  408. stack.push_back({
  409. .query_self_const_id = query_self_const_id,
  410. .query_facet_type_const_id = query_facet_type_const_id,
  411. });
  412. // We need to find a witness for each interface in `interfaces`. Every
  413. // consumer of a facet type needs to agree on the order of interfaces used for
  414. // its witnesses.
  415. llvm::SmallVector<SemIR::InstId> result_witness_ids;
  416. for (const auto& interface : interfaces) {
  417. // TODO: Since both `interfaces` and `query_self_const_id` are sorted lists,
  418. // do an O(N+M) merge instead of O(N*M) nested loops.
  419. auto result_witness_id = GetOrAddLookupImplWitness(
  420. context, loc_id, query_self_const_id, interface);
  421. if (result_witness_id.has_value()) {
  422. result_witness_ids.push_back(result_witness_id);
  423. } else {
  424. // At least one queried interface in the facet type has no witness for the
  425. // given type, we can stop looking for more.
  426. break;
  427. }
  428. }
  429. stack.pop_back();
  430. // All interfaces in the query facet type must have been found to be available
  431. // through some impl, or directly on the value's facet type if
  432. // `query_self_const_id` is a facet value.
  433. if (result_witness_ids.size() != interfaces.size()) {
  434. return SemIR::InstBlockId::None;
  435. }
  436. // TODO: Validate that the witness satisfies the other requirements in
  437. // `interface_const_id`.
  438. return context.inst_blocks().AddCanonical(result_witness_ids);
  439. }
  440. // Returns whether the query is concrete, it is false if the self type or
  441. // interface specifics have a symbolic dependency.
  442. static auto QueryIsConcrete(Context& context, SemIR::ConstantId self_const_id,
  443. const SemIR::SpecificInterface& specific_interface)
  444. -> bool {
  445. if (!self_const_id.is_concrete()) {
  446. return false;
  447. }
  448. if (!specific_interface.specific_id.has_value()) {
  449. return true;
  450. }
  451. auto args_id =
  452. context.specifics().Get(specific_interface.specific_id).args_id;
  453. for (auto inst_id : context.inst_blocks().Get(args_id)) {
  454. if (!context.constant_values().Get(inst_id).is_concrete()) {
  455. return false;
  456. }
  457. }
  458. return true;
  459. }
  460. struct CandidateImpl {
  461. SemIR::ImplId impl_id;
  462. SemIR::InstId loc_inst_id;
  463. // Used for sorting the candidates to find the most-specialized match.
  464. TypeStructure type_structure;
  465. };
  466. // Returns the list of candidates impls for lookup to select from.
  467. static auto CollectCandidateImplsForQuery(
  468. Context& context, bool final_only,
  469. const TypeStructure& query_type_structure,
  470. SemIR::SpecificInterface& query_specific_interface)
  471. -> llvm::SmallVector<CandidateImpl> {
  472. llvm::SmallVector<CandidateImpl> candidate_impls;
  473. for (auto [id, impl] : context.impls().enumerate()) {
  474. if (final_only && !IsImplEffectivelyFinal(context, impl)) {
  475. continue;
  476. }
  477. // If the impl's interface_id differs from the query, then this impl can
  478. // not possibly provide the queried interface.
  479. if (impl.interface.interface_id != query_specific_interface.interface_id) {
  480. continue;
  481. }
  482. // When the impl's interface_id matches, but the interface is generic, the
  483. // impl may or may not match based on restrictions in the generic
  484. // parameters of the impl.
  485. //
  486. // As a shortcut, if the impl's constraint is not symbolic (does not
  487. // depend on any generic parameters), then we can determine whether we match
  488. // by looking if the specific ids match exactly.
  489. auto impl_interface_const_id =
  490. context.constant_values().Get(impl.constraint_id);
  491. if (!impl_interface_const_id.is_symbolic() &&
  492. impl.interface.specific_id != query_specific_interface.specific_id) {
  493. continue;
  494. }
  495. // This check comes first to avoid deduction with an invalid impl. We use
  496. // an error value to indicate an error during creation of the impl, such
  497. // as a recursive impl which will cause deduction to recurse infinitely.
  498. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  499. continue;
  500. }
  501. CARBON_CHECK(impl.witness_id.has_value());
  502. // Build the type structure used for choosing the best the candidate.
  503. auto type_structure =
  504. BuildTypeStructure(context, impl.self_id, impl.interface);
  505. // TODO: We can skip the comparison here if the `impl_interface_const_id` is
  506. // not symbolic, since when the interface and specific ids match, and they
  507. // aren't symbolic, the structure will be identical.
  508. if (!query_type_structure.IsCompatibleWith(type_structure)) {
  509. continue;
  510. }
  511. candidate_impls.push_back(
  512. {id, impl.definition_id, std::move(type_structure)});
  513. }
  514. auto compare = [](auto& lhs, auto& rhs) -> bool {
  515. return lhs.type_structure < rhs.type_structure;
  516. };
  517. // Stable sort is used so that impls that are seen first are preferred when
  518. // they have an equal priority ordering.
  519. // TODO: Allow Carbon code to provide a priority ordering explicitly. For
  520. // now they have all the same priority, so the priority is the order in
  521. // which they are found in code.
  522. llvm::stable_sort(candidate_impls, compare);
  523. return candidate_impls;
  524. }
  525. auto EvalLookupSingleImplWitness(Context& context, SemIR::LocId loc_id,
  526. SemIR::LookupImplWitness eval_query,
  527. SemIR::InstId non_canonical_query_self_inst_id,
  528. bool poison_concrete_results)
  529. -> EvalImplLookupResult {
  530. // NOTE: Do not retain this reference to the SpecificInterface obtained from a
  531. // value store by SpecificInterfaceId. Doing impl lookup does deduce which can
  532. // do more impl lookups, and impl lookup can add a new SpecificInterface to
  533. // the store which can reallocate and invalidate any references held here into
  534. // the store.
  535. auto query_specific_interface =
  536. context.specific_interfaces().Get(eval_query.query_specific_interface_id);
  537. auto facet_lookup_result = LookupImplWitnessInSelfFacetValue(
  538. context, non_canonical_query_self_inst_id, query_specific_interface);
  539. if (facet_lookup_result.has_concrete_value()) {
  540. return facet_lookup_result;
  541. }
  542. // If the self type is a facet that provides a witness, then we are in an
  543. // `interface` or an `impl`. In both cases, we don't want to do any impl
  544. // lookups. The query will eventually resolve to a concrete witness when it
  545. // can get it from the self facet value, when it has a specific applied in the
  546. // future.
  547. //
  548. // In particular, this avoids a LookupImplWitness instruction in the eval
  549. // block of an impl declaration from doing impl lookup. Specifically the
  550. // lookup of the implicit .Self in `impl ... where .X`. If it does impl lookup
  551. // when the eval block is run, it finds the same `impl`, tries to build a
  552. // specific from it, which runs the eval block, creating a recursive loop that
  553. // crashes.
  554. bool self_facet_provides_witness = facet_lookup_result.has_value();
  555. if (self_facet_provides_witness) {
  556. if (auto bind = context.insts().TryGetAs<SemIR::BindSymbolicName>(
  557. eval_query.query_self_inst_id)) {
  558. const auto& entity = context.entity_names().Get(bind->entity_name_id);
  559. if (entity.name_id == SemIR::NameId::PeriodSelf ||
  560. entity.name_id == SemIR::NameId::SelfType) {
  561. return EvalImplLookupResult::MakeNonFinal();
  562. }
  563. }
  564. }
  565. SemIR::ConstantId query_self_const_id =
  566. context.constant_values().Get(eval_query.query_self_inst_id);
  567. auto query_type_structure = BuildTypeStructure(
  568. context, context.constant_values().GetInstId(query_self_const_id),
  569. query_specific_interface);
  570. bool query_is_concrete =
  571. QueryIsConcrete(context, query_self_const_id, query_specific_interface);
  572. // If we have a symbolic witness in the self query, then the query can not be
  573. // concrete: the query includes a symbolic self value.
  574. CARBON_CHECK(!self_facet_provides_witness || !query_is_concrete);
  575. // If the self value is a (symbolic) facet value that has a symbolic witness,
  576. // then we don't need to do impl lookup, except that we want to find any final
  577. // impls to return a concrete witness if possible. So we limit the query to
  578. // final impls only in that case. Note as in the CHECK above, the query can
  579. // not be concrete in this case, so only final impls can produce a concrete
  580. // witness for this query.
  581. auto candidate_impls = CollectCandidateImplsForQuery(
  582. context, self_facet_provides_witness, query_type_structure,
  583. query_specific_interface);
  584. for (const auto& candidate : candidate_impls) {
  585. // In deferred lookup for a symbolic impl witness, while building a
  586. // specific, there may be no stack yet as this may be the first lookup. If
  587. // further lookups are started as a result in deduce, they will build the
  588. // stack.
  589. //
  590. // NOTE: Don't retain a reference into the stack, it may be invalidated if
  591. // we do further impl lookups when GetWitnessIdForImpl() does deduction.
  592. if (!context.impl_lookup_stack().empty()) {
  593. context.impl_lookup_stack().back().impl_loc = candidate.loc_inst_id;
  594. }
  595. // NOTE: GetWitnessIdForImpl() does deduction, which can cause new impls
  596. // to be imported, invalidating any pointer into `context.impls()`.
  597. auto result = GetWitnessIdForImpl(
  598. context, loc_id, query_is_concrete, query_self_const_id,
  599. query_specific_interface, candidate.impl_id);
  600. if (result.has_value()) {
  601. // Record the query which found a concrete impl witness. It's illegal to
  602. // write a final impl afterward that would match the same query.
  603. //
  604. // If the impl was effectively final, then we don't need to poison here. A
  605. // change of query result will already be diagnosed at the point where the
  606. // new impl decl was written that changes the result.
  607. if (poison_concrete_results && result.has_concrete_value() &&
  608. !IsImplEffectivelyFinal(context,
  609. context.impls().Get(candidate.impl_id))) {
  610. context.poisoned_concrete_impl_lookup_queries().push_back(
  611. {.loc_id = loc_id,
  612. .query = eval_query,
  613. .non_canonical_query_self_inst_id =
  614. non_canonical_query_self_inst_id,
  615. .impl_witness = result.concrete_witness()});
  616. }
  617. return result;
  618. }
  619. }
  620. if (self_facet_provides_witness) {
  621. // If we did not find a final impl, but the self value is a facet that
  622. // provides a symbolic witness, when we record that an impl will exist for
  623. // the specific, but is yet unknown.
  624. return EvalImplLookupResult::MakeNonFinal();
  625. }
  626. return EvalImplLookupResult::MakeNone();
  627. }
  628. auto LookupMatchesImpl(Context& context, SemIR::LocId loc_id,
  629. SemIR::ConstantId query_self_const_id,
  630. SemIR::SpecificInterface query_specific_interface,
  631. SemIR::ImplId target_impl) -> bool {
  632. if (query_self_const_id == SemIR::ErrorInst::ConstantId) {
  633. return false;
  634. }
  635. auto result = GetWitnessIdForImpl(
  636. context, loc_id, /*query_is_concrete=*/false, query_self_const_id,
  637. query_specific_interface, target_impl);
  638. return result.has_value();
  639. }
  640. } // namespace Carbon::Check