impl_lookup.cpp 28 KB

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