impl_lookup.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  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/facet_type.h"
  14. #include "toolchain/check/generic.h"
  15. #include "toolchain/check/impl.h"
  16. #include "toolchain/check/import_ref.h"
  17. #include "toolchain/check/inst.h"
  18. #include "toolchain/check/subst.h"
  19. #include "toolchain/check/type.h"
  20. #include "toolchain/check/type_completion.h"
  21. #include "toolchain/check/type_structure.h"
  22. #include "toolchain/sem_ir/facet_type_info.h"
  23. #include "toolchain/sem_ir/ids.h"
  24. #include "toolchain/sem_ir/impl.h"
  25. #include "toolchain/sem_ir/inst.h"
  26. #include "toolchain/sem_ir/typed_insts.h"
  27. namespace Carbon::Check {
  28. // Returns IRs which are allowed to define an `impl` involving the arguments.
  29. // This is limited by the orphan rule.
  30. static auto FindAssociatedImportIRs(
  31. Context& context, SemIR::ConstantId query_self_const_id,
  32. SemIR::SpecificInterface query_specific_interface)
  33. -> llvm::SmallVector<SemIR::ImportIRId> {
  34. llvm::SmallVector<SemIR::ImportIRId> result;
  35. // Add an entity to our result.
  36. auto add_entity = [&](const SemIR::EntityWithParamsBase& entity) {
  37. // We will look for impls in the import IR associated with the first owning
  38. // declaration.
  39. auto decl_id = entity.first_owning_decl_id;
  40. if (!decl_id.has_value()) {
  41. return;
  42. }
  43. if (auto ir_id = GetCanonicalImportIRInst(context, decl_id).ir_id();
  44. ir_id.has_value()) {
  45. result.push_back(ir_id);
  46. }
  47. };
  48. llvm::SmallVector<SemIR::InstId> worklist;
  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. worklist.push_back(context.constant_values().GetInstId(query_self_const_id));
  62. add_entity(context.interfaces().Get(query_specific_interface.interface_id));
  63. push_args(query_specific_interface.specific_id);
  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. struct InterfacesFromConstantId {
  171. llvm::SmallVector<SemIR::SpecificInterface> interfaces;
  172. SemIR::BuiltinConstraintMask builtin_constraint_mask;
  173. bool other_requirements;
  174. };
  175. // Gets the set of `SpecificInterface`s that are required by a facet type
  176. // (as a constant value), and any special requirements.
  177. static auto GetInterfacesFromConstantId(
  178. Context& context, SemIR::ConstantId query_facet_type_const_id)
  179. -> InterfacesFromConstantId {
  180. auto facet_type_inst_id =
  181. context.constant_values().GetInstId(query_facet_type_const_id);
  182. auto facet_type_inst =
  183. context.insts().GetAs<SemIR::FacetType>(facet_type_inst_id);
  184. const auto& facet_type_info =
  185. context.facet_types().Get(facet_type_inst.facet_type_id);
  186. auto identified_id = RequireIdentifiedFacetType(context, facet_type_inst);
  187. auto interfaces_array_ref =
  188. context.identified_facet_types().Get(identified_id).required_interfaces();
  189. // Returns a copy to avoid use-after-free when the identified_facet_types
  190. // store resizes.
  191. return {
  192. .interfaces = {interfaces_array_ref.begin(), interfaces_array_ref.end()},
  193. .builtin_constraint_mask = facet_type_info.builtin_constraint_mask,
  194. .other_requirements = facet_type_info.other_requirements};
  195. }
  196. static auto GetWitnessIdForImpl(Context& context, SemIR::LocId loc_id,
  197. bool query_is_concrete,
  198. SemIR::ConstantId query_self_const_id,
  199. const SemIR::SpecificInterface& interface,
  200. SemIR::ImplId impl_id) -> EvalImplLookupResult {
  201. const SemIR::Impl& impl = context.impls().Get(impl_id);
  202. // The impl may have generic arguments, in which case we need to deduce them
  203. // to find what they are given the specific type and interface query. We use
  204. // that specific to map values in the impl to the deduced values.
  205. auto specific_id = SemIR::SpecificId::None;
  206. if (impl.generic_id.has_value()) {
  207. specific_id = DeduceImplArguments(
  208. context, loc_id, impl, query_self_const_id, interface.specific_id);
  209. if (!specific_id.has_value()) {
  210. return EvalImplLookupResult::MakeNone();
  211. }
  212. }
  213. // The self type of the impl must match the type in the query, or this is an
  214. // `impl T as ...` for some other type `T` and should not be considered.
  215. auto deduced_self_const_id = SemIR::GetConstantValueInSpecific(
  216. context.sem_ir(), specific_id, impl.self_id);
  217. // In a generic `impl forall` the self type can be a FacetAccessType, which
  218. // will not be the same constant value as a query facet value. We move through
  219. // to the facet value here, and if the query was a FacetAccessType we did the
  220. // same there so they still match.
  221. deduced_self_const_id =
  222. GetCanonicalizedFacetOrTypeValue(context, deduced_self_const_id);
  223. if (query_self_const_id != deduced_self_const_id) {
  224. return EvalImplLookupResult::MakeNone();
  225. }
  226. // The impl's constraint is a facet type which it is implementing for the self
  227. // type: the `I` in `impl ... as I`. The deduction step may be unable to be
  228. // fully applied to the types in the constraint and result in an error here,
  229. // in which case it does not match the query.
  230. auto deduced_constraint_id =
  231. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  232. context.sem_ir(), specific_id, impl.constraint_id));
  233. if (deduced_constraint_id == SemIR::ErrorInst::InstId) {
  234. return EvalImplLookupResult::MakeNone();
  235. }
  236. auto deduced_constraint_facet_type_id =
  237. context.insts()
  238. .GetAs<SemIR::FacetType>(deduced_constraint_id)
  239. .facet_type_id;
  240. const auto& deduced_constraint_facet_type_info =
  241. context.facet_types().Get(deduced_constraint_facet_type_id);
  242. CARBON_CHECK(deduced_constraint_facet_type_info.extend_constraints.size() ==
  243. 1);
  244. if (deduced_constraint_facet_type_info.other_requirements ||
  245. !deduced_constraint_facet_type_info.builtin_constraint_mask.empty()) {
  246. return EvalImplLookupResult::MakeNone();
  247. }
  248. // The specifics in the queried interface must match the deduced specifics in
  249. // the impl's constraint facet type.
  250. auto impl_interface_specific_id =
  251. deduced_constraint_facet_type_info.extend_constraints[0].specific_id;
  252. auto query_interface_specific_id = interface.specific_id;
  253. if (impl_interface_specific_id != query_interface_specific_id) {
  254. return EvalImplLookupResult::MakeNone();
  255. }
  256. LoadImportRef(context, impl.witness_id);
  257. if (specific_id.has_value()) {
  258. // We need a definition of the specific `impl` so we can access its
  259. // witness.
  260. ResolveSpecificDefinition(context, loc_id, specific_id);
  261. }
  262. if (query_is_concrete || impl.is_final) {
  263. // TODO: These final results should be cached somehow. Positive (non-None)
  264. // results could be cached globally, as they can not change. But
  265. // negative results can change after a final impl is written, so
  266. // they can only be cached in a limited way, or the cache needs to
  267. // be invalidated by writing a final impl that would match.
  268. return EvalImplLookupResult::MakeFinal(
  269. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  270. context.sem_ir(), specific_id, impl.witness_id)));
  271. } else {
  272. return EvalImplLookupResult::MakeNonFinal();
  273. }
  274. }
  275. // Unwraps a FacetAccessType to move from a value of type `TypeType` to a facet
  276. // value of type `FacetType` if possible.
  277. //
  278. // Generally `GetCanonicalizedFacetOrTypeValue()` is what you want to call
  279. // instead, as this only does part of that operation, potentially returning a
  280. // non-canonical facet value.
  281. static auto UnwrapFacetAccessType(Context& context, SemIR::InstId inst_id)
  282. -> SemIR::InstId {
  283. if (auto access = context.insts().TryGetAs<SemIR::FacetAccessType>(inst_id)) {
  284. return access->facet_value_inst_id;
  285. }
  286. return inst_id;
  287. }
  288. // Finds a lookup result from `query_self_inst_id` if it is a facet value that
  289. // names the query interface in its facet type. Note that `query_self_inst_id`
  290. // is allowed to be a non-canonical facet value in order to find a concrete
  291. // witness, so it's not referenced as a constant value.
  292. static auto LookupImplWitnessInSelfFacetValue(
  293. Context& context, SemIR::InstId query_self_inst_id,
  294. SemIR::SpecificInterface query_specific_interface) -> EvalImplLookupResult {
  295. // Unwrap FacetAccessType without getting the canonical facet value from the
  296. // self value, as we want to preserve the non-canonical `FacetValue`
  297. // instruction which can contain the concrete witness.
  298. query_self_inst_id = UnwrapFacetAccessType(context, query_self_inst_id);
  299. auto facet_type = context.types().TryGetAs<SemIR::FacetType>(
  300. context.insts().Get(query_self_inst_id).type_id());
  301. if (!facet_type) {
  302. return EvalImplLookupResult::MakeNone();
  303. }
  304. // The position of the interface in `required_interfaces()` is also the
  305. // position of the witness for that interface in `FacetValue`.
  306. auto identified_id = RequireIdentifiedFacetType(context, *facet_type);
  307. auto facet_type_required_interfaces =
  308. llvm::enumerate(context.identified_facet_types()
  309. .Get(identified_id)
  310. .required_interfaces());
  311. auto it = llvm::find_if(facet_type_required_interfaces, [=](auto e) {
  312. return e.value() == query_specific_interface;
  313. });
  314. if (it == facet_type_required_interfaces.end()) {
  315. return EvalImplLookupResult::MakeNone();
  316. }
  317. auto index = (*it).index();
  318. if (auto facet_value =
  319. context.insts().TryGetAs<SemIR::FacetValue>(query_self_inst_id)) {
  320. auto witness_id =
  321. context.inst_blocks().Get(facet_value->witnesses_block_id)[index];
  322. if (context.insts().Is<SemIR::ImplWitness>(witness_id)) {
  323. return EvalImplLookupResult::MakeFinal(witness_id);
  324. }
  325. }
  326. return EvalImplLookupResult::MakeNonFinal();
  327. }
  328. // Substitutes witnesess in place of `LookupImplWitness` queries into `.Self`,
  329. // when the witness is for the same interface as the one `.Self` is referring
  330. // to.
  331. //
  332. // This allows access to the `FacetType` and its constraints from the witness,
  333. // and allows `ImplWitnessAccess` instructions to be immediately resolved to a
  334. // more specific value when possible.
  335. class SubstWitnessesCallbacks : public SubstInstCallbacks {
  336. public:
  337. // `context` must not be null.
  338. explicit SubstWitnessesCallbacks(
  339. Context* context, SemIR::LocId loc_id,
  340. llvm::ArrayRef<SemIR::SpecificInterface> interfaces,
  341. llvm::ArrayRef<SemIR::InstId> witness_inst_ids)
  342. : SubstInstCallbacks(context),
  343. loc_id_(loc_id),
  344. interfaces_(interfaces),
  345. witness_inst_ids_(witness_inst_ids) {}
  346. auto Subst(SemIR::InstId& inst_id) -> SubstResult override {
  347. // `FacetType` can be concrete even when it has rewrite constraints that
  348. // have a symbolic dependency on `.Self`. See use of
  349. // `GetConstantValueIgnoringPeriodSelf` in eval. So in order to recurse into
  350. // `FacetType` we must check for it before the `is_concrete` early return.
  351. if (context().insts().Is<SemIR::FacetType>(inst_id)) {
  352. ++facet_type_depth_;
  353. return SubstOperands;
  354. }
  355. if (context().constant_values().Get(inst_id).is_concrete()) {
  356. return FullySubstituted;
  357. }
  358. auto access = context().insts().TryGetAs<SemIR::ImplWitnessAccess>(inst_id);
  359. if (!access) {
  360. return SubstOperands;
  361. }
  362. auto lookup =
  363. context().insts().GetAs<SemIR::LookupImplWitness>(access->witness_id);
  364. auto bind_name = context().insts().TryGetAs<SemIR::BindSymbolicName>(
  365. lookup.query_self_inst_id);
  366. if (!bind_name) {
  367. return SubstOperands;
  368. }
  369. const auto& self_entity_name =
  370. context().entity_names().Get(bind_name->entity_name_id);
  371. if (self_entity_name.name_id != SemIR::NameId::PeriodSelf) {
  372. return SubstOperands;
  373. }
  374. // TODO: Once we are numbering `EntityName`, (see the third model in
  375. // https://docs.google.com/document/d/1Yt-i5AmF76LSvD4TrWRIAE_92kii6j5yFiW-S7ahzlg/edit?tab=t.0#heading=h.7urbxcq23olv)
  376. // then verify that the index here is equal to the `facet_type_depth_`,
  377. // which would mean that it is a reference to the top-level `Self`, which is
  378. // being replaced with the impl lookup query self facet value (and then we
  379. // use the witness derived from it).
  380. //
  381. // For now, we only substitute if depth == 0, which is incorrect inside
  382. // nested facet types, as it can miss references in specifics up to the top
  383. // level facet value.
  384. if (facet_type_depth_ > 0) {
  385. return SubstOperands;
  386. }
  387. auto witness_id =
  388. FindWitnessForInterface(lookup.query_specific_interface_id);
  389. if (!witness_id.has_value()) {
  390. return SubstOperands;
  391. }
  392. inst_id = RebuildNewInst(
  393. context().insts().GetLocIdForDesugaring(loc_id_),
  394. SemIR::ImplWitnessAccess{.type_id = GetSingletonType(
  395. context(), SemIR::WitnessType::TypeInstId),
  396. .witness_id = witness_id,
  397. .index = access->index});
  398. // Once we replace a witness, we either have a concrete value or some
  399. // reference to an associated constant that came from the witness's facet
  400. // type. We don't want to substitute into the witness's facet type, so we
  401. // don't recurse on whatever came from the witness.
  402. return FullySubstituted;
  403. }
  404. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst)
  405. -> SemIR::InstId override {
  406. if (context().insts().Is<SemIR::FacetType>(orig_inst_id)) {
  407. --facet_type_depth_;
  408. }
  409. return RebuildNewInst(loc_id_, new_inst);
  410. }
  411. auto ReuseUnchanged(SemIR::InstId orig_inst_id) -> SemIR::InstId override {
  412. if (context().insts().Is<SemIR::FacetType>(orig_inst_id)) {
  413. --facet_type_depth_;
  414. }
  415. return orig_inst_id;
  416. }
  417. private:
  418. auto FindWitnessForInterface(SemIR::SpecificInterfaceId specific_interface_id)
  419. -> SemIR::InstId {
  420. auto lookup_query_interface =
  421. context().specific_interfaces().Get(specific_interface_id);
  422. for (auto [interface, witness_inst_id] :
  423. llvm::zip(interfaces_, witness_inst_ids_)) {
  424. // If the `LookupImplWitness` for `.Self` is not looking for the same
  425. // interface as we have a witness for, this is not the right witness to
  426. // use to replace the lookup for `.Self`.
  427. if (interface.interface_id == lookup_query_interface.interface_id) {
  428. return witness_inst_id;
  429. }
  430. }
  431. return SemIR::InstId::None;
  432. }
  433. SemIR::LocId loc_id_;
  434. llvm::ArrayRef<SemIR::SpecificInterface> interfaces_;
  435. llvm::ArrayRef<SemIR::InstId> witness_inst_ids_;
  436. int facet_type_depth_ = 0;
  437. };
  438. static auto VerifyQueryFacetTypeConstraints(
  439. Context& context, SemIR::LocId loc_id,
  440. SemIR::InstId query_facet_type_inst_id,
  441. llvm::ArrayRef<SemIR::SpecificInterface> interfaces,
  442. llvm::ArrayRef<SemIR::InstId> witness_inst_ids) -> bool {
  443. CARBON_CHECK(context.insts().Is<SemIR::FacetType>(query_facet_type_inst_id));
  444. const auto& facet_type_info = context.facet_types().Get(
  445. context.insts()
  446. .GetAs<SemIR::FacetType>(query_facet_type_inst_id)
  447. .facet_type_id);
  448. if (!facet_type_info.rewrite_constraints.empty()) {
  449. auto callbacks =
  450. SubstWitnessesCallbacks(&context, loc_id, interfaces, witness_inst_ids);
  451. for (const auto& rewrite : facet_type_info.rewrite_constraints) {
  452. auto lhs_id = SubstInst(context, rewrite.lhs_id, callbacks);
  453. auto rhs_id = SubstInst(context, rewrite.rhs_id, callbacks);
  454. if (lhs_id != rhs_id) {
  455. // TODO: Provide a diagnostic note and location for which rewrite
  456. // constraint was not satisfied, if a diagnostic is going to be
  457. // displayed for the LookupImplWitessFailure. This will require plumbing
  458. // through a callback that lets us add a Note to another diagnostic.
  459. return false;
  460. }
  461. }
  462. }
  463. // TODO: Validate that the witnesses satisfy the other requirements in the
  464. // `facet_type_info`.
  465. return true;
  466. }
  467. // Begin a search for an impl declaration matching the query. We do this by
  468. // creating an LookupImplWitness instruction and evaluating. If it's able to
  469. // find a final concrete impl, then it will evaluate to that `ImplWitness` but
  470. // if not, it will evaluate to itself as a symbolic witness to be further
  471. // evaluated with a more specific query when building a specific for the generic
  472. // context the query came from.
  473. static auto GetOrAddLookupImplWitness(Context& context, SemIR::LocId loc_id,
  474. SemIR::ConstantId query_self_const_id,
  475. SemIR::SpecificInterface interface)
  476. -> SemIR::InstId {
  477. auto witness_const_id = EvalOrAddInst(
  478. context, context.insts().GetLocIdForDesugaring(loc_id),
  479. SemIR::LookupImplWitness{
  480. .type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  481. .query_self_inst_id =
  482. context.constant_values().GetInstId(query_self_const_id),
  483. .query_specific_interface_id =
  484. context.specific_interfaces().Add(interface),
  485. });
  486. // We use a NotConstant result from eval to communicate back an impl
  487. // lookup failure. See `EvalConstantInst()` for `LookupImplWitness`.
  488. if (!witness_const_id.is_constant()) {
  489. return SemIR::InstId::None;
  490. }
  491. return context.constant_values().GetInstId(witness_const_id);
  492. }
  493. // Returns true if the `Self` should impl `Destroy`.
  494. static auto TypeCanDestroy(Context& context,
  495. SemIR::ConstantId query_self_const_id) -> bool {
  496. auto inst = context.insts().Get(
  497. context.constant_values().GetInstId(query_self_const_id));
  498. CARBON_KIND_SWITCH(inst) {
  499. case CARBON_KIND(SemIR::ClassType class_type): {
  500. auto class_info = context.classes().Get(class_type.class_id);
  501. // Incomplete and abstract classes can't be destroyed.
  502. // TODO: Return false if the object repr doesn't impl `Destroy`.
  503. // TODO: Return false for C++ types that lack a destructor.
  504. return class_info.is_complete() &&
  505. class_info.inheritance_kind !=
  506. SemIR::Class::InheritanceKind::Abstract;
  507. }
  508. case SemIR::ArrayType::Kind:
  509. case SemIR::ConstType::Kind:
  510. case SemIR::MaybeUnformedType::Kind:
  511. case SemIR::PartialType::Kind:
  512. case SemIR::StructType::Kind:
  513. case SemIR::TupleType::Kind:
  514. // TODO: Return false for types that indirectly reference a type that
  515. // doesn't impl `Destroy`.
  516. return true;
  517. case SemIR::BoolType::Kind:
  518. case SemIR::PointerType::Kind:
  519. // Trivially destructible.
  520. return true;
  521. default:
  522. return false;
  523. }
  524. }
  525. auto LookupImplWitness(Context& context, SemIR::LocId loc_id,
  526. SemIR::ConstantId query_self_const_id,
  527. SemIR::ConstantId query_facet_type_const_id)
  528. -> SemIR::InstBlockIdOrError {
  529. if (query_self_const_id == SemIR::ErrorInst::ConstantId ||
  530. query_facet_type_const_id == SemIR::ErrorInst::ConstantId) {
  531. return SemIR::InstBlockIdOrError::MakeError();
  532. }
  533. {
  534. // The query self value is a type value or a facet value.
  535. auto query_self_type_id =
  536. context.insts()
  537. .Get(context.constant_values().GetInstId(query_self_const_id))
  538. .type_id();
  539. CARBON_CHECK(context.types().Is<SemIR::TypeType>(query_self_type_id) ||
  540. context.types().Is<SemIR::FacetType>(query_self_type_id));
  541. // The query facet type value is indeed a facet type.
  542. CARBON_CHECK(context.insts().Is<SemIR::FacetType>(
  543. context.constant_values().GetInstId(query_facet_type_const_id)));
  544. }
  545. auto [interfaces, builtin_constraint_mask, other_requirements] =
  546. GetInterfacesFromConstantId(context, query_facet_type_const_id);
  547. if (other_requirements) {
  548. // TODO: Remove this when other requirements go away.
  549. return SemIR::InstBlockId::None;
  550. }
  551. if (builtin_constraint_mask.HasAnyOf(
  552. SemIR::BuiltinConstraintMask::TypeCanDestroy) &&
  553. !TypeCanDestroy(context, query_self_const_id)) {
  554. return SemIR::InstBlockId::None;
  555. }
  556. if (interfaces.empty()) {
  557. return SemIR::InstBlockId::Empty;
  558. }
  559. if (FindAndDiagnoseImplLookupCycle(context, context.impl_lookup_stack(),
  560. loc_id, query_self_const_id,
  561. query_facet_type_const_id)) {
  562. return SemIR::InstBlockIdOrError::MakeError();
  563. }
  564. auto& stack = context.impl_lookup_stack();
  565. stack.push_back({
  566. .query_self_const_id = query_self_const_id,
  567. .query_facet_type_const_id = query_facet_type_const_id,
  568. });
  569. // We need to find a witness for each interface in `interfaces`. Every
  570. // consumer of a facet type needs to agree on the order of interfaces used for
  571. // its witnesses.
  572. llvm::SmallVector<SemIR::InstId> result_witness_ids;
  573. for (const auto& interface : interfaces) {
  574. // TODO: Since both `interfaces` and `query_self_const_id` are sorted lists,
  575. // do an O(N+M) merge instead of O(N*M) nested loops.
  576. auto result_witness_id = GetOrAddLookupImplWitness(
  577. context, loc_id, query_self_const_id, interface);
  578. if (result_witness_id.has_value()) {
  579. result_witness_ids.push_back(result_witness_id);
  580. } else {
  581. // At least one queried interface in the facet type has no witness for the
  582. // given type, we can stop looking for more.
  583. break;
  584. }
  585. }
  586. stack.pop_back();
  587. // All interfaces in the query facet type must have been found to be available
  588. // through some impl, or directly on the value's facet type if
  589. // `query_self_const_id` is a facet value.
  590. if (result_witness_ids.size() != interfaces.size()) {
  591. return SemIR::InstBlockId::None;
  592. }
  593. // Verify rewrite constraints in the query constraint are satisfied after
  594. // applying the rewrites from the found witnesses.
  595. if (!VerifyQueryFacetTypeConstraints(
  596. context, loc_id,
  597. context.constant_values().GetInstId(query_facet_type_const_id),
  598. interfaces, result_witness_ids)) {
  599. return SemIR::InstBlockId::None;
  600. }
  601. return context.inst_blocks().AddCanonical(result_witness_ids);
  602. }
  603. // Returns whether the query is concrete, it is false if the self type or
  604. // interface specifics have a symbolic dependency.
  605. static auto QueryIsConcrete(Context& context, SemIR::ConstantId self_const_id,
  606. const SemIR::SpecificInterface& specific_interface)
  607. -> bool {
  608. if (!self_const_id.is_concrete()) {
  609. return false;
  610. }
  611. if (!specific_interface.specific_id.has_value()) {
  612. return true;
  613. }
  614. auto args_id =
  615. context.specifics().Get(specific_interface.specific_id).args_id;
  616. for (auto inst_id : context.inst_blocks().Get(args_id)) {
  617. if (!context.constant_values().Get(inst_id).is_concrete()) {
  618. return false;
  619. }
  620. }
  621. return true;
  622. }
  623. namespace {
  624. // A class to filter imported impls based on whether they could possibly match a
  625. // query, prior to importing them. For now we only consider impls that are for
  626. // an interface that's being queried.
  627. //
  628. // TODO: There's a lot more we could do to filter out impls that can't possibly
  629. // match.
  630. class ImportImplFilter {
  631. public:
  632. explicit ImportImplFilter(Context& context, SemIR::ImportIRId import_ir_id,
  633. SemIR::SpecificInterface interface)
  634. : context_(&context),
  635. interface_id_(interface.interface_id),
  636. import_ir_id_(import_ir_id),
  637. import_ir_(context_->import_irs().Get(import_ir_id).sem_ir),
  638. cached_import_interface_id_(SemIR::InterfaceId::None) {}
  639. // Returns whether the given impl is potentially relevant for the current
  640. // query.
  641. auto IsRelevantImpl(SemIR::ImplId import_impl_id) -> bool {
  642. auto impl_interface_id =
  643. import_ir_->impls().Get(import_impl_id).interface.interface_id;
  644. if (!impl_interface_id.has_value()) {
  645. // This indicates that an error occurred when type-checking the impl.
  646. // TODO: Use an explicit error value for this rather than None.
  647. return false;
  648. }
  649. return IsRelevantInterface(impl_interface_id);
  650. }
  651. private:
  652. // Returns whether an impl for the given interface might be relevant to the
  653. // current query.
  654. auto IsRelevantInterface(SemIR::InterfaceId import_interface_id) -> bool {
  655. if (!cached_import_interface_id_.has_value()) {
  656. if (IsSameInterface(import_interface_id, interface_id_)) {
  657. cached_import_interface_id_ = import_interface_id;
  658. return true;
  659. }
  660. } else if (cached_import_interface_id_ == import_interface_id) {
  661. return true;
  662. }
  663. return false;
  664. }
  665. // Returns whether the given interfaces from two different IRs are the same.
  666. auto IsSameInterface(SemIR::InterfaceId import_interface_id,
  667. SemIR::InterfaceId local_interface_id) -> bool {
  668. // The names must be the same.
  669. if (import_ir_->names().GetAsStringIfIdentifier(
  670. import_ir_->interfaces().Get(import_interface_id).name_id) !=
  671. context_->names().GetAsStringIfIdentifier(
  672. context_->interfaces().Get(local_interface_id).name_id)) {
  673. return false;
  674. }
  675. // Compare the interfaces themselves.
  676. // TODO: Should we check the scope of the interface before doing this?
  677. auto local_version_of_import_interface_id =
  678. ImportInterface(*context_, import_ir_id_, import_interface_id);
  679. return local_version_of_import_interface_id == local_interface_id;
  680. }
  681. Context* context_;
  682. // The interface being looked up.
  683. SemIR::InterfaceId interface_id_;
  684. // The IR that we are currently importing impls from.
  685. SemIR::ImportIRId import_ir_id_;
  686. const SemIR::File* import_ir_;
  687. // The interface ID of `interface_id_` in `import_ir_`, if known.
  688. SemIR::InterfaceId cached_import_interface_id_;
  689. };
  690. } // namespace
  691. struct CandidateImpl {
  692. SemIR::ImplId impl_id;
  693. SemIR::InstId loc_inst_id;
  694. // Used for sorting the candidates to find the most-specialized match.
  695. TypeStructure type_structure;
  696. };
  697. // Returns the list of candidates impls for lookup to select from.
  698. static auto CollectCandidateImplsForQuery(
  699. Context& context, bool final_only, SemIR::ConstantId query_self_const_id,
  700. const TypeStructure& query_type_structure,
  701. SemIR::SpecificInterface& query_specific_interface)
  702. -> llvm::SmallVector<CandidateImpl> {
  703. auto import_irs = FindAssociatedImportIRs(context, query_self_const_id,
  704. query_specific_interface);
  705. for (auto import_ir_id : import_irs) {
  706. // Instead of importing all impls, only import ones that are in some way
  707. // connected to this query.
  708. ImportImplFilter filter(context, import_ir_id, query_specific_interface);
  709. for (auto [import_impl_id, _] :
  710. context.import_irs().Get(import_ir_id).sem_ir->impls().enumerate()) {
  711. if (filter.IsRelevantImpl(import_impl_id)) {
  712. // TODO: Track the relevant impls and only consider those ones and any
  713. // local impls, rather than looping over all impls below.
  714. ImportImpl(context, import_ir_id, import_impl_id);
  715. }
  716. }
  717. }
  718. llvm::SmallVector<CandidateImpl> candidate_impls;
  719. for (auto [id, impl] : context.impls().enumerate()) {
  720. if (final_only && !IsImplEffectivelyFinal(context, impl)) {
  721. continue;
  722. }
  723. // If the impl's interface_id differs from the query, then this impl can
  724. // not possibly provide the queried interface.
  725. if (impl.interface.interface_id != query_specific_interface.interface_id) {
  726. continue;
  727. }
  728. // When the impl's interface_id matches, but the interface is generic, the
  729. // impl may or may not match based on restrictions in the generic
  730. // parameters of the impl.
  731. //
  732. // As a shortcut, if the impl's constraint is not symbolic (does not
  733. // depend on any generic parameters), then we can determine whether we match
  734. // by looking if the specific ids match exactly.
  735. auto impl_interface_const_id =
  736. context.constant_values().Get(impl.constraint_id);
  737. if (!impl_interface_const_id.is_symbolic() &&
  738. impl.interface.specific_id != query_specific_interface.specific_id) {
  739. continue;
  740. }
  741. // This check comes first to avoid deduction with an invalid impl. We use
  742. // an error value to indicate an error during creation of the impl, such
  743. // as a recursive impl which will cause deduction to recurse infinitely.
  744. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  745. continue;
  746. }
  747. CARBON_CHECK(impl.witness_id.has_value());
  748. // Build the type structure used for choosing the best the candidate.
  749. auto type_structure =
  750. BuildTypeStructure(context, impl.self_id, impl.interface);
  751. if (!type_structure) {
  752. continue;
  753. }
  754. // TODO: We can skip the comparison here if the `impl_interface_const_id` is
  755. // not symbolic, since when the interface and specific ids match, and they
  756. // aren't symbolic, the structure will be identical.
  757. if (!query_type_structure.CompareStructure(
  758. TypeStructure::CompareTest::IsEqualToOrMoreSpecificThan,
  759. *type_structure)) {
  760. continue;
  761. }
  762. candidate_impls.push_back(
  763. {id, impl.definition_id, std::move(*type_structure)});
  764. }
  765. auto compare = [](auto& lhs, auto& rhs) -> bool {
  766. return lhs.type_structure < rhs.type_structure;
  767. };
  768. // Stable sort is used so that impls that are seen first are preferred when
  769. // they have an equal priority ordering.
  770. // TODO: Allow Carbon code to provide a priority ordering explicitly. For
  771. // now they have all the same priority, so the priority is the order in
  772. // which they are found in code.
  773. llvm::stable_sort(candidate_impls, compare);
  774. return candidate_impls;
  775. }
  776. auto EvalLookupSingleImplWitness(Context& context, SemIR::LocId loc_id,
  777. SemIR::LookupImplWitness eval_query,
  778. SemIR::InstId non_canonical_query_self_inst_id,
  779. bool poison_concrete_results)
  780. -> EvalImplLookupResult {
  781. auto query_specific_interface =
  782. context.specific_interfaces().Get(eval_query.query_specific_interface_id);
  783. auto facet_lookup_result = LookupImplWitnessInSelfFacetValue(
  784. context, non_canonical_query_self_inst_id, query_specific_interface);
  785. if (facet_lookup_result.has_concrete_value()) {
  786. return facet_lookup_result;
  787. }
  788. // If the self type is a facet that provides a witness, then we are in an
  789. // `interface` or an `impl`. In both cases, we don't want to do any impl
  790. // lookups. The query will eventually resolve to a concrete witness when it
  791. // can get it from the self facet value, when it has a specific applied in the
  792. // future.
  793. //
  794. // In particular, this avoids a LookupImplWitness instruction in the eval
  795. // block of an impl declaration from doing impl lookup. Specifically the
  796. // lookup of the implicit .Self in `impl ... where .X`. If it does impl lookup
  797. // when the eval block is run, it finds the same `impl`, tries to build a
  798. // specific from it, which runs the eval block, creating a recursive loop that
  799. // crashes.
  800. bool self_facet_provides_witness = facet_lookup_result.has_value();
  801. if (self_facet_provides_witness) {
  802. if (auto bind = context.insts().TryGetAs<SemIR::BindSymbolicName>(
  803. eval_query.query_self_inst_id)) {
  804. const auto& entity = context.entity_names().Get(bind->entity_name_id);
  805. if (entity.name_id == SemIR::NameId::PeriodSelf ||
  806. entity.name_id == SemIR::NameId::SelfType) {
  807. return EvalImplLookupResult::MakeNonFinal();
  808. }
  809. }
  810. }
  811. SemIR::ConstantId query_self_const_id =
  812. context.constant_values().Get(eval_query.query_self_inst_id);
  813. auto query_type_structure = BuildTypeStructure(
  814. context, context.constant_values().GetInstId(query_self_const_id),
  815. query_specific_interface);
  816. if (!query_type_structure) {
  817. return EvalImplLookupResult::MakeNone();
  818. }
  819. bool query_is_concrete =
  820. QueryIsConcrete(context, query_self_const_id, query_specific_interface);
  821. // If we have a symbolic witness in the self query, then the query can not be
  822. // concrete: the query includes a symbolic self value.
  823. CARBON_CHECK(!self_facet_provides_witness || !query_is_concrete);
  824. // If the self value is a (symbolic) facet value that has a symbolic witness,
  825. // then we don't need to do impl lookup, except that we want to find any final
  826. // impls to return a concrete witness if possible. So we limit the query to
  827. // final impls only in that case. Note as in the CHECK above, the query can
  828. // not be concrete in this case, so only final impls can produce a concrete
  829. // witness for this query.
  830. auto candidate_impls = CollectCandidateImplsForQuery(
  831. context, self_facet_provides_witness, query_self_const_id,
  832. *query_type_structure, query_specific_interface);
  833. for (const auto& candidate : candidate_impls) {
  834. // In deferred lookup for a symbolic impl witness, while building a
  835. // specific, there may be no stack yet as this may be the first lookup. If
  836. // further lookups are started as a result in deduce, they will build the
  837. // stack.
  838. //
  839. // NOTE: Don't retain a reference into the stack, it may be invalidated if
  840. // we do further impl lookups when GetWitnessIdForImpl() does deduction.
  841. if (!context.impl_lookup_stack().empty()) {
  842. context.impl_lookup_stack().back().impl_loc = candidate.loc_inst_id;
  843. }
  844. auto result = GetWitnessIdForImpl(
  845. context, loc_id, query_is_concrete, query_self_const_id,
  846. query_specific_interface, candidate.impl_id);
  847. if (result.has_value()) {
  848. // Record the query which found a concrete impl witness. It's illegal to
  849. // write a final impl afterward that would match the same query.
  850. //
  851. // If the impl was effectively final, then we don't need to poison here. A
  852. // change of query result will already be diagnosed at the point where the
  853. // new impl decl was written that changes the result.
  854. if (poison_concrete_results && result.has_concrete_value() &&
  855. !IsImplEffectivelyFinal(context,
  856. context.impls().Get(candidate.impl_id))) {
  857. context.poisoned_concrete_impl_lookup_queries().push_back(
  858. {.loc_id = loc_id,
  859. .query = eval_query,
  860. .non_canonical_query_self_inst_id =
  861. non_canonical_query_self_inst_id,
  862. .impl_witness = result.concrete_witness()});
  863. }
  864. return result;
  865. }
  866. }
  867. if (self_facet_provides_witness) {
  868. // If we did not find a final impl, but the self value is a facet that
  869. // provides a symbolic witness, when we record that an impl will exist for
  870. // the specific, but is yet unknown.
  871. return EvalImplLookupResult::MakeNonFinal();
  872. }
  873. return EvalImplLookupResult::MakeNone();
  874. }
  875. auto LookupMatchesImpl(Context& context, SemIR::LocId loc_id,
  876. SemIR::ConstantId query_self_const_id,
  877. SemIR::SpecificInterface query_specific_interface,
  878. SemIR::ImplId target_impl) -> bool {
  879. if (query_self_const_id == SemIR::ErrorInst::ConstantId) {
  880. return false;
  881. }
  882. auto result = GetWitnessIdForImpl(
  883. context, loc_id, /*query_is_concrete=*/false, query_self_const_id,
  884. query_specific_interface, target_impl);
  885. return result.has_value();
  886. }
  887. } // namespace Carbon::Check