impl_lookup.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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/cpp/impl_lookup.h"
  11. #include "toolchain/check/custom_witness.h"
  12. #include "toolchain/check/deduce.h"
  13. #include "toolchain/check/diagnostic_helpers.h"
  14. #include "toolchain/check/eval.h"
  15. #include "toolchain/check/facet_type.h"
  16. #include "toolchain/check/generic.h"
  17. #include "toolchain/check/impl.h"
  18. #include "toolchain/check/import_ref.h"
  19. #include "toolchain/check/inst.h"
  20. #include "toolchain/check/subst.h"
  21. #include "toolchain/check/type.h"
  22. #include "toolchain/check/type_completion.h"
  23. #include "toolchain/check/type_structure.h"
  24. #include "toolchain/sem_ir/facet_type_info.h"
  25. #include "toolchain/sem_ir/ids.h"
  26. #include "toolchain/sem_ir/impl.h"
  27. #include "toolchain/sem_ir/inst.h"
  28. #include "toolchain/sem_ir/typed_insts.h"
  29. namespace Carbon::Check {
  30. // Returns IRs which are allowed to define an `impl` involving the arguments.
  31. // This is limited by the orphan rule.
  32. static auto FindAssociatedImportIRs(
  33. Context& context, SemIR::ConstantId query_self_const_id,
  34. SemIR::SpecificInterface query_specific_interface)
  35. -> llvm::SmallVector<SemIR::ImportIRId> {
  36. llvm::SmallVector<SemIR::ImportIRId> result;
  37. // Add an entity to our result.
  38. auto add_entity = [&](const SemIR::EntityWithParamsBase& entity) {
  39. // We will look for impls in the import IR associated with the first owning
  40. // declaration.
  41. auto decl_id = entity.first_owning_decl_id;
  42. if (!decl_id.has_value()) {
  43. return;
  44. }
  45. auto import_ir_inst = GetCanonicalImportIRInst(context, decl_id);
  46. const auto* sem_ir = &context.sem_ir();
  47. if (import_ir_inst.ir_id().has_value()) {
  48. sem_ir = context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  49. }
  50. // For an instruction imported from C++, `GetCanonicalImportIRInst` returns
  51. // the final Carbon import instruction, so go one extra step to check for a
  52. // C++ import.
  53. if (auto import_ir_inst_id =
  54. sem_ir->insts().GetImportSource(import_ir_inst.inst_id());
  55. import_ir_inst_id.has_value()) {
  56. result.push_back(
  57. sem_ir->import_ir_insts().Get(import_ir_inst_id).ir_id());
  58. } else if (import_ir_inst.ir_id().has_value()) {
  59. result.push_back(import_ir_inst.ir_id());
  60. }
  61. };
  62. llvm::SmallVector<SemIR::InstId> worklist;
  63. // Push the contents of an instruction block onto our worklist.
  64. auto push_block = [&](SemIR::InstBlockId block_id) {
  65. if (block_id.has_value()) {
  66. llvm::append_range(worklist, context.inst_blocks().Get(block_id));
  67. }
  68. };
  69. // Add the arguments of a specific to the worklist.
  70. auto push_args = [&](SemIR::SpecificId specific_id) {
  71. if (specific_id.has_value()) {
  72. push_block(context.specifics().Get(specific_id).args_id);
  73. }
  74. };
  75. worklist.push_back(context.constant_values().GetInstId(query_self_const_id));
  76. add_entity(context.interfaces().Get(query_specific_interface.interface_id));
  77. push_args(query_specific_interface.specific_id);
  78. while (!worklist.empty()) {
  79. auto inst_id = worklist.pop_back_val();
  80. // Visit the operands of the constant.
  81. auto inst = context.insts().Get(inst_id);
  82. for (auto arg : {inst.arg0_and_kind(), inst.arg1_and_kind()}) {
  83. CARBON_KIND_SWITCH(arg) {
  84. case CARBON_KIND(SemIR::InstId inst_id): {
  85. if (inst_id.has_value()) {
  86. worklist.push_back(inst_id);
  87. }
  88. break;
  89. }
  90. case CARBON_KIND(SemIR::TypeInstId inst_id): {
  91. if (inst_id.has_value()) {
  92. worklist.push_back(inst_id);
  93. }
  94. break;
  95. }
  96. case CARBON_KIND(SemIR::InstBlockId inst_block_id): {
  97. push_block(inst_block_id);
  98. break;
  99. }
  100. case CARBON_KIND(SemIR::ClassId class_id): {
  101. add_entity(context.classes().Get(class_id));
  102. break;
  103. }
  104. case CARBON_KIND(SemIR::InterfaceId interface_id): {
  105. add_entity(context.interfaces().Get(interface_id));
  106. break;
  107. }
  108. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  109. const auto& facet_type_info =
  110. context.facet_types().Get(facet_type_id);
  111. for (const auto& impl : facet_type_info.extend_constraints) {
  112. add_entity(context.interfaces().Get(impl.interface_id));
  113. push_args(impl.specific_id);
  114. }
  115. for (const auto& impl : facet_type_info.self_impls_constraints) {
  116. add_entity(context.interfaces().Get(impl.interface_id));
  117. push_args(impl.specific_id);
  118. }
  119. break;
  120. }
  121. case CARBON_KIND(SemIR::FunctionId function_id): {
  122. add_entity(context.functions().Get(function_id));
  123. break;
  124. }
  125. case CARBON_KIND(SemIR::SpecificId specific_id): {
  126. push_args(specific_id);
  127. break;
  128. }
  129. default: {
  130. break;
  131. }
  132. }
  133. }
  134. }
  135. // Deduplicate.
  136. llvm::sort(result, [](SemIR::ImportIRId a, SemIR::ImportIRId b) {
  137. return a.index < b.index;
  138. });
  139. result.erase(llvm::unique(result), result.end());
  140. return result;
  141. }
  142. // Returns true if a cycle was found and diagnosed.
  143. static auto FindAndDiagnoseImplLookupCycle(
  144. Context& context,
  145. const llvm::SmallVector<Context::ImplLookupStackEntry>& stack,
  146. SemIR::LocId loc_id, SemIR::ConstantId query_self_const_id,
  147. SemIR::ConstantId query_facet_type_const_id) -> bool {
  148. // Deduction of the interface parameters can do further impl lookups, and we
  149. // need to ensure we terminate.
  150. //
  151. // https://docs.carbon-lang.dev/docs/design/generics/details.html#acyclic-rule
  152. // - We look for violations of the acyclic rule by seeing if a previous lookup
  153. // had all the same type inputs.
  154. // - The `query_facet_type_const_id` encodes the entire facet type being
  155. // looked up, including any specific parameters for a generic interface.
  156. //
  157. // TODO: Implement the termination rule, which requires looking at the
  158. // complexity of the types on the top of (or throughout?) the stack:
  159. // https://docs.carbon-lang.dev/docs/design/generics/details.html#termination-rule
  160. for (auto [i, entry] : llvm::enumerate(stack)) {
  161. if (entry.query_self_const_id == query_self_const_id &&
  162. entry.query_facet_type_const_id == query_facet_type_const_id) {
  163. auto facet_type_type_id =
  164. context.types().GetTypeIdForTypeConstantId(query_facet_type_const_id);
  165. CARBON_DIAGNOSTIC(ImplLookupCycle, Error,
  166. "cycle found in search for impl of {0} for type {1}",
  167. SemIR::TypeId, SemIR::TypeId);
  168. auto builder = context.emitter().Build(
  169. loc_id, ImplLookupCycle, facet_type_type_id,
  170. context.types().GetTypeIdForTypeConstantId(query_self_const_id));
  171. for (const auto& active_entry : llvm::drop_begin(stack, i)) {
  172. if (active_entry.impl_loc.has_value()) {
  173. CARBON_DIAGNOSTIC(ImplLookupCycleNote, Note,
  174. "determining if this impl clause matches", );
  175. builder.Note(active_entry.impl_loc, ImplLookupCycleNote);
  176. }
  177. }
  178. builder.Emit();
  179. return true;
  180. }
  181. }
  182. return false;
  183. }
  184. struct RequiredImplsFromConstraint {
  185. llvm::ArrayRef<SemIR::IdentifiedFacetType::RequiredImpl> req_impls;
  186. bool other_requirements;
  187. };
  188. // Gets the set of `SpecificInterface`s that are required by a facet type
  189. // (as a constant value), and any special requirements.
  190. static auto GetRequiredImplsFromConstraint(
  191. Context& context, SemIR::LocId loc_id,
  192. SemIR::ConstantId query_self_const_id,
  193. SemIR::ConstantId query_facet_type_const_id)
  194. -> std::optional<RequiredImplsFromConstraint> {
  195. auto facet_type_inst_id =
  196. context.constant_values().GetInstId(query_facet_type_const_id);
  197. auto facet_type_inst =
  198. context.insts().GetAs<SemIR::FacetType>(facet_type_inst_id);
  199. const auto& facet_type_info =
  200. context.facet_types().Get(facet_type_inst.facet_type_id);
  201. auto identified_id = RequireIdentifiedFacetType(
  202. context, loc_id, query_self_const_id, facet_type_inst, [&] {
  203. CARBON_DIAGNOSTIC(ImplLookupInUnidentifiedFacetType, Error,
  204. "facet type {0} can not be identified", InstIdAsType);
  205. return context.emitter().Build(
  206. loc_id, ImplLookupInUnidentifiedFacetType, facet_type_inst_id);
  207. });
  208. if (!identified_id.has_value()) {
  209. return std::nullopt;
  210. }
  211. return {
  212. {.req_impls =
  213. context.identified_facet_types().Get(identified_id).required_impls(),
  214. .other_requirements = facet_type_info.other_requirements}};
  215. }
  216. static auto GetWitnessIdForImpl(Context& context, SemIR::LocId loc_id,
  217. bool query_is_concrete,
  218. SemIR::ConstantId query_self_const_id,
  219. const SemIR::SpecificInterface& interface,
  220. const SemIR::Impl& impl)
  221. -> EvalImplLookupResult {
  222. // The impl may have generic arguments, in which case we need to deduce them
  223. // to find what they are given the specific type and interface query. We use
  224. // that specific to map values in the impl to the deduced values.
  225. auto specific_id = SemIR::SpecificId::None;
  226. if (impl.generic_id.has_value()) {
  227. specific_id = DeduceImplArguments(
  228. context, loc_id, impl, query_self_const_id, interface.specific_id);
  229. if (!specific_id.has_value()) {
  230. return EvalImplLookupResult::MakeNone();
  231. }
  232. }
  233. // The self type of the impl must match the type in the query, or this is an
  234. // `impl T as ...` for some other type `T` and should not be considered.
  235. auto noncanonical_deduced_self_const_id = SemIR::GetConstantValueInSpecific(
  236. context.sem_ir(), specific_id, impl.self_id);
  237. // In a generic `impl forall` the self type can be a FacetAccessType, which
  238. // will not be the same constant value as a query facet value. We move through
  239. // to the facet value here, and if the query was a FacetAccessType we did the
  240. // same there so they still match.
  241. auto deduced_self_const_id =
  242. GetCanonicalFacetOrTypeValue(context, noncanonical_deduced_self_const_id);
  243. if (query_self_const_id != deduced_self_const_id) {
  244. return EvalImplLookupResult::MakeNone();
  245. }
  246. // The impl's constraint is a facet type which it is implementing for the self
  247. // type: the `I` in `impl ... as I`. The deduction step may be unable to be
  248. // fully applied to the types in the constraint and result in an error here,
  249. // in which case it does not match the query.
  250. auto deduced_constraint_id =
  251. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  252. context.sem_ir(), specific_id, impl.constraint_id));
  253. if (deduced_constraint_id == SemIR::ErrorInst::InstId) {
  254. return EvalImplLookupResult::MakeNone();
  255. }
  256. auto deduced_constraint_facet_type_id =
  257. context.insts()
  258. .GetAs<SemIR::FacetType>(deduced_constraint_id)
  259. .facet_type_id;
  260. const auto& deduced_constraint_facet_type_info =
  261. context.facet_types().Get(deduced_constraint_facet_type_id);
  262. CARBON_CHECK(deduced_constraint_facet_type_info.extend_constraints.size() ==
  263. 1);
  264. if (deduced_constraint_facet_type_info.other_requirements) {
  265. return EvalImplLookupResult::MakeNone();
  266. }
  267. // The specifics in the queried interface must match the deduced specifics in
  268. // the impl's constraint facet type.
  269. auto impl_interface_specific_id =
  270. deduced_constraint_facet_type_info.extend_constraints[0].specific_id;
  271. auto query_interface_specific_id = interface.specific_id;
  272. if (impl_interface_specific_id != query_interface_specific_id) {
  273. return EvalImplLookupResult::MakeNone();
  274. }
  275. LoadImportRef(context, impl.witness_id);
  276. if (specific_id.has_value()) {
  277. // If the impl definition can be resolved, eval will do it immediately;
  278. // otherwise, it can be resolved by further specialization. This is used to
  279. // resolve dependency chains when `MakeFinal` is returned without a concrete
  280. // definition; particularly final impls with symbolic constants.
  281. AddInstInNoBlock(
  282. context, loc_id,
  283. SemIR::RequireSpecificDefinition{
  284. .type_id = GetSingletonType(
  285. context, SemIR::RequireSpecificDefinitionType::TypeInstId),
  286. .specific_id = specific_id});
  287. }
  288. if (query_is_concrete || impl.is_final) {
  289. // TODO: These final results should be cached somehow. Positive (non-None)
  290. // results could be cached globally, as they can not change. But
  291. // negative results can change after a final impl is written, so
  292. // they can only be cached in a limited way, or the cache needs to
  293. // be invalidated by writing a final impl that would match.
  294. return EvalImplLookupResult::MakeFinal(
  295. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  296. context.sem_ir(), specific_id, impl.witness_id)));
  297. } else {
  298. return EvalImplLookupResult::MakeNonFinal();
  299. }
  300. }
  301. // Finds a lookup result from `query_self_inst_id` if it is a facet value that
  302. // names the query interface in its facet type. Note that `query_self_inst_id`
  303. // is allowed to be a non-canonical facet value in order to find a concrete
  304. // witness, so it's not referenced as a constant value.
  305. static auto LookupImplWitnessInSelfFacetValue(
  306. Context& context, SemIR::LocId loc_id,
  307. SemIR::InstId self_facet_value_inst_id,
  308. SemIR::SpecificInterface query_specific_interface) -> EvalImplLookupResult {
  309. auto facet_type = context.types().TryGetAs<SemIR::FacetType>(
  310. context.insts().Get(self_facet_value_inst_id).type_id());
  311. if (!facet_type) {
  312. return EvalImplLookupResult::MakeNone();
  313. }
  314. auto self_facet_value_const_id =
  315. context.constant_values().Get(self_facet_value_inst_id);
  316. // The position of the interface in `required_impls()` is also the
  317. // position of the witness for that interface in `FacetValue`. The
  318. // `FacetValue` witnesses are the output of an impl lookup, which finds and
  319. // returns witnesses in the same order.
  320. auto identified_id = RequireIdentifiedFacetType(
  321. context, loc_id, self_facet_value_const_id, *facet_type, nullptr);
  322. // This should not be possible as FacetValue is constructed by a conversion
  323. // to a facet type, which performs impl lookup for that facet type, and
  324. // lookup only succeeds for identified facet types.
  325. CARBON_CHECK(identified_id.has_value(),
  326. "FacetValue was constructed with an unidentified facet type");
  327. auto facet_type_req_impls = llvm::enumerate(
  328. context.identified_facet_types().Get(identified_id).required_impls());
  329. auto it = llvm::find_if(facet_type_req_impls, [&](auto e) {
  330. auto [req_self, req_specific_interface] = e.value();
  331. // The `self_facet_value_inst_id` in eval is a canonicalized facet value, so
  332. // we need to do the same to `req_self` that comes from the
  333. // IdentifiedFacetType in order to compare them.
  334. auto canonical_req_self = GetCanonicalFacetOrTypeValue(context, req_self);
  335. return canonical_req_self == self_facet_value_const_id &&
  336. req_specific_interface == query_specific_interface;
  337. });
  338. if (it == facet_type_req_impls.end()) {
  339. return EvalImplLookupResult::MakeNone();
  340. }
  341. auto index = (*it).index();
  342. if (auto facet_value = context.insts().TryGetAs<SemIR::FacetValue>(
  343. self_facet_value_inst_id)) {
  344. auto witness_id =
  345. context.inst_blocks().Get(facet_value->witnesses_block_id)[index];
  346. if (context.insts().Is<SemIR::ImplWitness>(witness_id)) {
  347. return EvalImplLookupResult::MakeFinal(witness_id);
  348. }
  349. }
  350. return EvalImplLookupResult::MakeNonFinal();
  351. }
  352. // Substitutes witnesess in place of `LookupImplWitness` queries into `.Self`,
  353. // when the witness is for the same interface as the one `.Self` is referring
  354. // to.
  355. //
  356. // This allows access to the `FacetType` and its constraints from the witness,
  357. // and allows `ImplWitnessAccess` instructions to be immediately resolved to a
  358. // more specific value when possible.
  359. class SubstWitnessesCallbacks : public SubstInstCallbacks {
  360. public:
  361. // `context` must not be null.
  362. explicit SubstWitnessesCallbacks(
  363. Context* context, SemIR::LocId loc_id,
  364. SemIR::ConstantId query_self_const_id,
  365. llvm::ArrayRef<SemIR::IdentifiedFacetType::RequiredImpl> req_impls,
  366. llvm::ArrayRef<SemIR::InstId> witness_inst_ids)
  367. : SubstInstCallbacks(context),
  368. loc_id_(loc_id),
  369. query_self_const_id_(query_self_const_id),
  370. req_impls_(req_impls),
  371. witness_inst_ids_(witness_inst_ids) {}
  372. auto Subst(SemIR::InstId& inst_id) -> SubstResult override {
  373. // `FacetType` can be concrete even when it has rewrite constraints that
  374. // have a symbolic dependency on `.Self`. See use of
  375. // `GetConstantValueIgnoringPeriodSelf` in eval. So in order to recurse into
  376. // `FacetType` we must check for it before the `is_concrete` early return.
  377. if (context().insts().Is<SemIR::FacetType>(inst_id)) {
  378. ++facet_type_depth_;
  379. return SubstOperands;
  380. }
  381. if (context().constant_values().Get(inst_id).is_concrete()) {
  382. return FullySubstituted;
  383. }
  384. auto access = context().insts().TryGetAs<SemIR::ImplWitnessAccess>(inst_id);
  385. if (!access) {
  386. return SubstOperands;
  387. }
  388. auto lookup =
  389. context().insts().GetAs<SemIR::LookupImplWitness>(access->witness_id);
  390. auto bind_name = context().insts().TryGetAs<SemIR::SymbolicBinding>(
  391. lookup.query_self_inst_id);
  392. if (!bind_name) {
  393. return SubstOperands;
  394. }
  395. const auto& self_entity_name =
  396. context().entity_names().Get(bind_name->entity_name_id);
  397. if (self_entity_name.name_id != SemIR::NameId::PeriodSelf) {
  398. return SubstOperands;
  399. }
  400. // TODO: Once we are numbering `EntityName`, (see the third model in
  401. // https://docs.google.com/document/d/1Yt-i5AmF76LSvD4TrWRIAE_92kii6j5yFiW-S7ahzlg/edit?tab=t.0#heading=h.7urbxcq23olv)
  402. // then verify that the index here is equal to the `facet_type_depth_`,
  403. // which would mean that it is a reference to the top-level `Self`, which is
  404. // being replaced with the impl lookup query self facet value (and then we
  405. // use the witness derived from it).
  406. //
  407. // For now, we only substitute if depth == 0, which is incorrect inside
  408. // nested facet types, as it can miss references in specifics up to the top
  409. // level facet value.
  410. if (facet_type_depth_ > 0) {
  411. return SubstOperands;
  412. }
  413. auto witness_id =
  414. FindWitnessForInterface(lookup.query_specific_interface_id);
  415. if (!witness_id.has_value()) {
  416. return SubstOperands;
  417. }
  418. inst_id = RebuildNewInst(
  419. context().insts().GetLocIdForDesugaring(loc_id_),
  420. SemIR::ImplWitnessAccess{.type_id = GetSingletonType(
  421. context(), SemIR::WitnessType::TypeInstId),
  422. .witness_id = witness_id,
  423. .index = access->index});
  424. // Once we replace a witness, we either have a concrete value or some
  425. // reference to an associated constant that came from the witness's facet
  426. // type. We don't want to substitute into the witness's facet type, so we
  427. // don't recurse on whatever came from the witness.
  428. return FullySubstituted;
  429. }
  430. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst)
  431. -> SemIR::InstId override {
  432. if (context().insts().Is<SemIR::FacetType>(orig_inst_id)) {
  433. --facet_type_depth_;
  434. }
  435. return RebuildNewInst(loc_id_, new_inst);
  436. }
  437. auto ReuseUnchanged(SemIR::InstId orig_inst_id) -> SemIR::InstId override {
  438. if (context().insts().Is<SemIR::FacetType>(orig_inst_id)) {
  439. --facet_type_depth_;
  440. }
  441. return orig_inst_id;
  442. }
  443. private:
  444. auto FindWitnessForInterface(SemIR::SpecificInterfaceId specific_interface_id)
  445. -> SemIR::InstId {
  446. auto lookup_query_interface =
  447. context().specific_interfaces().Get(specific_interface_id);
  448. for (auto [req_impl, witness_inst_id] :
  449. llvm::zip_equal(req_impls_, witness_inst_ids_)) {
  450. auto [req_self, req_interface] = req_impl;
  451. // The `LookupImplWitness` is for `.Self`, so if the witness is for some
  452. // type other than the query self, we can't use it for `.Self`.
  453. if (req_self != query_self_const_id_) {
  454. continue;
  455. }
  456. // If the `LookupImplWitness` for `.Self` is not looking for the same
  457. // interface as we have a witness for, this is not the right witness to
  458. // use to replace the lookup for `.Self`.
  459. if (req_interface.interface_id != lookup_query_interface.interface_id) {
  460. continue;
  461. }
  462. return witness_inst_id;
  463. }
  464. return SemIR::InstId::None;
  465. }
  466. SemIR::LocId loc_id_;
  467. SemIR::ConstantId query_self_const_id_;
  468. llvm::ArrayRef<SemIR::IdentifiedFacetType::RequiredImpl> req_impls_;
  469. llvm::ArrayRef<SemIR::InstId> witness_inst_ids_;
  470. int facet_type_depth_ = 0;
  471. };
  472. static auto VerifyQueryFacetTypeConstraints(
  473. Context& context, SemIR::LocId loc_id,
  474. SemIR::ConstantId query_self_const_id,
  475. SemIR::ConstantId query_facet_type_const_id,
  476. llvm::ArrayRef<SemIR::IdentifiedFacetType::RequiredImpl> req_impls,
  477. llvm::ArrayRef<SemIR::InstId> witness_inst_ids) -> bool {
  478. SemIR::InstId query_facet_type_inst_id =
  479. context.constant_values().GetInstId(query_facet_type_const_id);
  480. CARBON_CHECK(context.insts().Is<SemIR::FacetType>(query_facet_type_inst_id));
  481. const auto& facet_type_info = context.facet_types().Get(
  482. context.insts()
  483. .GetAs<SemIR::FacetType>(query_facet_type_inst_id)
  484. .facet_type_id);
  485. if (!facet_type_info.rewrite_constraints.empty()) {
  486. auto callbacks = SubstWitnessesCallbacks(
  487. &context, loc_id, query_self_const_id, req_impls, witness_inst_ids);
  488. for (const auto& rewrite : facet_type_info.rewrite_constraints) {
  489. auto lhs_id = SubstInst(context, rewrite.lhs_id, callbacks);
  490. auto rhs_id = SubstInst(context, rewrite.rhs_id, callbacks);
  491. if (lhs_id != rhs_id) {
  492. // TODO: Provide a diagnostic note and location for which rewrite
  493. // constraint was not satisfied, if a diagnostic is going to be
  494. // displayed for the LookupImplWitessFailure. This will require plumbing
  495. // through a callback that lets us add a Note to another diagnostic.
  496. return false;
  497. }
  498. }
  499. }
  500. // TODO: Validate that the witnesses satisfy the other requirements in the
  501. // `facet_type_info`.
  502. return true;
  503. }
  504. // Begin a search for an impl declaration matching the query. We do this by
  505. // creating an LookupImplWitness instruction and evaluating. If it's able to
  506. // find a final concrete impl, then it will evaluate to that `ImplWitness` but
  507. // if not, it will evaluate to itself as a symbolic witness to be further
  508. // evaluated with a more specific query when building a specific for the generic
  509. // context the query came from.
  510. static auto GetOrAddLookupImplWitness(Context& context, SemIR::LocId loc_id,
  511. SemIR::ConstantId query_self_const_id,
  512. SemIR::SpecificInterface interface)
  513. -> SemIR::InstId {
  514. auto witness_const_id = EvalOrAddInst(
  515. context, context.insts().GetLocIdForDesugaring(loc_id),
  516. SemIR::LookupImplWitness{
  517. .type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  518. .query_self_inst_id =
  519. context.constant_values().GetInstId(query_self_const_id),
  520. .query_specific_interface_id =
  521. context.specific_interfaces().Add(interface),
  522. });
  523. // We use a NotConstant result from eval to communicate back an impl
  524. // lookup failure. See `EvalConstantInst()` for `LookupImplWitness`.
  525. if (!witness_const_id.is_constant()) {
  526. return SemIR::InstId::None;
  527. }
  528. return context.constant_values().GetInstId(witness_const_id);
  529. }
  530. auto LookupImplWitness(Context& context, SemIR::LocId loc_id,
  531. SemIR::ConstantId query_self_const_id,
  532. SemIR::ConstantId query_facet_type_const_id)
  533. -> SemIR::InstBlockIdOrError {
  534. if (query_self_const_id == SemIR::ErrorInst::ConstantId ||
  535. query_facet_type_const_id == SemIR::ErrorInst::ConstantId) {
  536. return SemIR::InstBlockIdOrError::MakeError();
  537. }
  538. {
  539. // The query self value is a type value or a facet value.
  540. auto query_self_type_id =
  541. context.insts()
  542. .Get(context.constant_values().GetInstId(query_self_const_id))
  543. .type_id();
  544. CARBON_CHECK((context.types().IsOneOf<SemIR::TypeType, SemIR::FacetType>(
  545. query_self_type_id)));
  546. // The query facet type value is indeed a facet type.
  547. CARBON_CHECK(context.insts().Is<SemIR::FacetType>(
  548. context.constant_values().GetInstId(query_facet_type_const_id)));
  549. }
  550. auto req_impls_from_constraint = GetRequiredImplsFromConstraint(
  551. context, loc_id, query_self_const_id, query_facet_type_const_id);
  552. if (!req_impls_from_constraint) {
  553. return SemIR::InstBlockIdOrError::MakeError();
  554. }
  555. auto [req_impls, other_requirements] = *req_impls_from_constraint;
  556. if (other_requirements) {
  557. // TODO: Remove this when other requirements go away.
  558. return SemIR::InstBlockId::None;
  559. }
  560. if (req_impls.empty()) {
  561. return SemIR::InstBlockId::Empty;
  562. }
  563. if (FindAndDiagnoseImplLookupCycle(context, context.impl_lookup_stack(),
  564. loc_id, query_self_const_id,
  565. query_facet_type_const_id)) {
  566. return SemIR::InstBlockIdOrError::MakeError();
  567. }
  568. auto& stack = context.impl_lookup_stack();
  569. stack.push_back({
  570. .query_self_const_id = query_self_const_id,
  571. .query_facet_type_const_id = query_facet_type_const_id,
  572. });
  573. // We need to find a witness for each self+interface pair in `req_impls`.
  574. //
  575. // Every consumer of a facet type needs to agree on the order of interfaces
  576. // used for its witnesses, which is done by following the order in the
  577. // IdentifiedFacetType.
  578. llvm::SmallVector<SemIR::InstId> result_witness_ids;
  579. for (const auto& req_impl : req_impls) {
  580. // TODO: Since both `interfaces` and `query_self_const_id` are sorted lists,
  581. // do an O(N+M) merge instead of O(N*M) nested loops.
  582. auto result_witness_id =
  583. GetOrAddLookupImplWitness(context, loc_id, req_impl.self_facet_value,
  584. req_impl.specific_interface);
  585. if (result_witness_id.has_value()) {
  586. result_witness_ids.push_back(result_witness_id);
  587. } else {
  588. // At least one queried interface in the facet type has no witness for the
  589. // given type, we can stop looking for more.
  590. break;
  591. }
  592. }
  593. stack.pop_back();
  594. // All interfaces in the query facet type must have been found to be available
  595. // through some impl, or directly on the value's facet type if
  596. // `query_self_const_id` is a facet value.
  597. if (result_witness_ids.size() != req_impls.size()) {
  598. return SemIR::InstBlockId::None;
  599. }
  600. // Verify rewrite constraints in the query constraint are satisfied after
  601. // applying the rewrites from the found witnesses.
  602. if (!VerifyQueryFacetTypeConstraints(context, loc_id, query_self_const_id,
  603. query_facet_type_const_id, req_impls,
  604. result_witness_ids)) {
  605. return SemIR::InstBlockId::None;
  606. }
  607. return context.inst_blocks().AddCanonical(result_witness_ids);
  608. }
  609. // Returns whether the query is concrete, it is false if the self type or
  610. // interface specifics have a symbolic dependency.
  611. static auto QueryIsConcrete(Context& context, SemIR::ConstantId self_const_id,
  612. const SemIR::SpecificInterface& specific_interface)
  613. -> bool {
  614. if (!self_const_id.is_concrete()) {
  615. return false;
  616. }
  617. if (!specific_interface.specific_id.has_value()) {
  618. return true;
  619. }
  620. auto args_id =
  621. context.specifics().Get(specific_interface.specific_id).args_id;
  622. for (auto inst_id : context.inst_blocks().Get(args_id)) {
  623. if (!context.constant_values().Get(inst_id).is_concrete()) {
  624. return false;
  625. }
  626. }
  627. return true;
  628. }
  629. namespace {
  630. // A class to filter imported impls based on whether they could possibly match a
  631. // query, prior to importing them. For now we only consider impls that are for
  632. // an interface that's being queried.
  633. //
  634. // TODO: There's a lot more we could do to filter out impls that can't possibly
  635. // match.
  636. class ImportImplFilter {
  637. public:
  638. explicit ImportImplFilter(Context& context, SemIR::ImportIRId import_ir_id,
  639. SemIR::SpecificInterface interface)
  640. : context_(&context),
  641. interface_id_(interface.interface_id),
  642. import_ir_id_(import_ir_id),
  643. import_ir_(context_->import_irs().Get(import_ir_id).sem_ir),
  644. cached_import_interface_id_(SemIR::InterfaceId::None) {}
  645. // Returns whether the given impl is potentially relevant for the current
  646. // query.
  647. auto IsRelevantImpl(SemIR::ImplId import_impl_id) -> bool {
  648. auto impl_interface_id =
  649. import_ir_->impls().Get(import_impl_id).interface.interface_id;
  650. if (!impl_interface_id.has_value()) {
  651. // This indicates that an error occurred when type-checking the impl.
  652. // TODO: Use an explicit error value for this rather than None.
  653. return false;
  654. }
  655. return IsRelevantInterface(impl_interface_id);
  656. }
  657. private:
  658. // Returns whether an impl for the given interface might be relevant to the
  659. // current query.
  660. auto IsRelevantInterface(SemIR::InterfaceId import_interface_id) -> bool {
  661. if (!cached_import_interface_id_.has_value()) {
  662. if (IsSameInterface(import_interface_id, interface_id_)) {
  663. cached_import_interface_id_ = import_interface_id;
  664. return true;
  665. }
  666. } else if (cached_import_interface_id_ == import_interface_id) {
  667. return true;
  668. }
  669. return false;
  670. }
  671. // Returns whether the given interfaces from two different IRs are the same.
  672. auto IsSameInterface(SemIR::InterfaceId import_interface_id,
  673. SemIR::InterfaceId local_interface_id) -> bool {
  674. // The names must be the same.
  675. if (import_ir_->names().GetAsStringIfIdentifier(
  676. import_ir_->interfaces().Get(import_interface_id).name_id) !=
  677. context_->names().GetAsStringIfIdentifier(
  678. context_->interfaces().Get(local_interface_id).name_id)) {
  679. return false;
  680. }
  681. // Compare the interfaces themselves.
  682. // TODO: Should we check the scope of the interface before doing this?
  683. auto local_version_of_import_interface_id =
  684. ImportInterface(*context_, import_ir_id_, import_interface_id);
  685. return local_version_of_import_interface_id == local_interface_id;
  686. }
  687. Context* context_;
  688. // The interface being looked up.
  689. SemIR::InterfaceId interface_id_;
  690. // The IR that we are currently importing impls from.
  691. SemIR::ImportIRId import_ir_id_;
  692. const SemIR::File* import_ir_;
  693. // The interface ID of `interface_id_` in `import_ir_`, if known.
  694. SemIR::InterfaceId cached_import_interface_id_;
  695. };
  696. } // namespace
  697. struct CandidateImpl {
  698. const SemIR::Impl* impl;
  699. // Used for sorting the candidates to find the most-specialized match.
  700. TypeStructure type_structure;
  701. };
  702. struct CandidateImpls {
  703. llvm::SmallVector<CandidateImpl> impls;
  704. bool consider_cpp_candidates = false;
  705. };
  706. // Returns the list of candidates impls for lookup to select from.
  707. static auto CollectCandidateImplsForQuery(
  708. Context& context, bool final_only, SemIR::ConstantId query_self_const_id,
  709. const TypeStructure& query_type_structure,
  710. SemIR::SpecificInterface& query_specific_interface) -> CandidateImpls {
  711. CandidateImpls candidates;
  712. auto import_irs = FindAssociatedImportIRs(context, query_self_const_id,
  713. query_specific_interface);
  714. for (auto import_ir_id : import_irs) {
  715. // If `Cpp` is an associated package, then we'll instead look for C++
  716. // operator overloads for certain well-known interfaces.
  717. if (import_ir_id == SemIR::ImportIRId::Cpp) {
  718. candidates.consider_cpp_candidates = true;
  719. continue;
  720. }
  721. // Instead of importing all impls, only import ones that are in some way
  722. // connected to this query.
  723. ImportImplFilter filter(context, import_ir_id, query_specific_interface);
  724. for (auto [import_impl_id, _] :
  725. context.import_irs().Get(import_ir_id).sem_ir->impls().enumerate()) {
  726. if (filter.IsRelevantImpl(import_impl_id)) {
  727. // TODO: Track the relevant impls and only consider those ones and any
  728. // local impls, rather than looping over all impls below.
  729. ImportImpl(context, import_ir_id, import_impl_id);
  730. }
  731. }
  732. }
  733. for (auto [id, impl] : context.impls().enumerate()) {
  734. CARBON_CHECK(impl.witness_id.has_value());
  735. if (final_only && !IsImplEffectivelyFinal(context, impl)) {
  736. continue;
  737. }
  738. // If the impl's interface_id differs from the query, then this impl can
  739. // not possibly provide the queried interface.
  740. if (impl.interface.interface_id != query_specific_interface.interface_id) {
  741. continue;
  742. }
  743. // When the impl's interface_id matches, but the interface is generic, the
  744. // impl may or may not match based on restrictions in the generic
  745. // parameters of the impl.
  746. //
  747. // As a shortcut, if the impl's constraint is not symbolic (does not
  748. // depend on any generic parameters), then we can determine whether we match
  749. // by looking if the specific ids match exactly.
  750. auto impl_interface_const_id =
  751. context.constant_values().Get(impl.constraint_id);
  752. if (!impl_interface_const_id.is_symbolic() &&
  753. impl.interface.specific_id != query_specific_interface.specific_id) {
  754. continue;
  755. }
  756. // Build the type structure used for choosing the best the candidate.
  757. auto type_structure =
  758. BuildTypeStructure(context, impl.self_id, impl.interface);
  759. if (!type_structure) {
  760. continue;
  761. }
  762. // TODO: We can skip the comparison here if the `impl_interface_const_id` is
  763. // not symbolic, since when the interface and specific ids match, and they
  764. // aren't symbolic, the structure will be identical.
  765. if (!query_type_structure.CompareStructure(
  766. TypeStructure::CompareTest::IsEqualToOrMoreSpecificThan,
  767. *type_structure)) {
  768. continue;
  769. }
  770. candidates.impls.push_back({&impl, std::move(*type_structure)});
  771. }
  772. auto compare = [](auto& lhs, auto& rhs) -> bool {
  773. return lhs.type_structure < rhs.type_structure;
  774. };
  775. // Stable sort is used so that impls that are seen first are preferred when
  776. // they have an equal priority ordering.
  777. // TODO: Allow Carbon code to provide a priority ordering explicitly. For
  778. // now they have all the same priority, so the priority is the order in
  779. // which they are found in code.
  780. llvm::stable_sort(candidates.impls, compare);
  781. return candidates;
  782. }
  783. // Record the query which found a final impl witness. It's illegal to
  784. // write a final impl afterward that would match the same query.
  785. static auto PoisonImplLookupQuery(Context& context, SemIR::LocId loc_id,
  786. EvalImplLookupMode mode,
  787. SemIR::LookupImplWitness eval_query,
  788. const EvalImplLookupResult& result,
  789. const SemIR::Impl& impl) -> void {
  790. if (mode == EvalImplLookupMode::RecheckPoisonedLookup) {
  791. return;
  792. }
  793. if (!result.has_final_value()) {
  794. return;
  795. }
  796. // If the impl was effectively final, then we don't need to poison here. A
  797. // change of query result will already be diagnosed at the point where the
  798. // new impl decl was written that changes the result.
  799. if (IsImplEffectivelyFinal(context, impl)) {
  800. return;
  801. }
  802. context.poisoned_concrete_impl_lookup_queries().push_back(
  803. {.loc_id = loc_id,
  804. .query = eval_query,
  805. .impl_witness = result.final_witness()});
  806. }
  807. auto EvalLookupSingleImplWitness(Context& context, SemIR::LocId loc_id,
  808. SemIR::LookupImplWitness eval_query,
  809. SemIR::InstId self_facet_value_inst_id,
  810. EvalImplLookupMode mode)
  811. -> EvalImplLookupResult {
  812. auto query_specific_interface =
  813. context.specific_interfaces().Get(eval_query.query_specific_interface_id);
  814. // Ensure specifics don't substitute in weird things for the query self.
  815. CARBON_CHECK(context.types().IsFacetType(
  816. context.insts().Get(eval_query.query_self_inst_id).type_id()));
  817. SemIR::ConstantId query_self_const_id =
  818. context.constant_values().Get(eval_query.query_self_inst_id);
  819. auto facet_lookup_result = LookupImplWitnessInSelfFacetValue(
  820. context, loc_id, self_facet_value_inst_id, query_specific_interface);
  821. if (facet_lookup_result.has_final_value()) {
  822. return facet_lookup_result;
  823. }
  824. // If the self type is a facet that provides a witness, then we are in an
  825. // `interface` or an `impl`. In both cases, we don't want to do any impl
  826. // lookups. The query will eventually resolve to a concrete witness when it
  827. // can get it from the self facet value, when it has a specific applied in the
  828. // future.
  829. //
  830. // In particular, this avoids a LookupImplWitness instruction in the eval
  831. // block of an impl declaration from doing impl lookup. Specifically the
  832. // lookup of the implicit .Self in `impl ... where .X`. If it does impl lookup
  833. // when the eval block is run, it finds the same `impl`, tries to build a
  834. // specific from it, which runs the eval block, creating a recursive loop that
  835. // crashes.
  836. if (facet_lookup_result.has_value()) {
  837. if (auto bind = context.insts().TryGetAs<SemIR::SymbolicBinding>(
  838. eval_query.query_self_inst_id)) {
  839. const auto& entity = context.entity_names().Get(bind->entity_name_id);
  840. if (entity.name_id == SemIR::NameId::PeriodSelf ||
  841. entity.name_id == SemIR::NameId::SelfType) {
  842. return facet_lookup_result;
  843. }
  844. }
  845. }
  846. auto query_type_structure = BuildTypeStructure(
  847. context, context.constant_values().GetInstId(query_self_const_id),
  848. query_specific_interface);
  849. if (!query_type_structure) {
  850. return EvalImplLookupResult::MakeNone();
  851. }
  852. // Check to see if this result is in the cache. But skip the cache if we're
  853. // re-checking a poisoned result and need to redo the lookup.
  854. auto impl_lookup_cache_key = Context::ImplLookupCacheKey{
  855. query_self_const_id, eval_query.query_specific_interface_id};
  856. if (mode != EvalImplLookupMode::RecheckPoisonedLookup) {
  857. if (auto result =
  858. context.impl_lookup_cache().Lookup(impl_lookup_cache_key)) {
  859. return EvalImplLookupResult::MakeFinal(result.value());
  860. }
  861. }
  862. // If the self value is a (symbolic) facet value that has a symbolic witness,
  863. // then we don't need to do impl lookup, except that we want to find any final
  864. // impls to return a concrete witness if possible. So we limit the query to
  865. // final impls only in that case. Note as in the CHECK above, the query can
  866. // not be concrete in this case, so only final impls can produce a concrete
  867. // witness for this query.
  868. auto candidates = CollectCandidateImplsForQuery(
  869. context, facet_lookup_result.has_value(), query_self_const_id,
  870. *query_type_structure, query_specific_interface);
  871. bool query_is_concrete =
  872. QueryIsConcrete(context, query_self_const_id, query_specific_interface);
  873. CARBON_CHECK(!query_is_concrete || !facet_lookup_result.has_value(),
  874. "Non-concrete facet lookup value for concrete query");
  875. // Perform a lookup for an `impl` that matches the query. If we don't find a
  876. // final impl, the self value may still have been a facet that provides a
  877. // symbolic witness in the `facet_lookup_result`, which we want to fall back
  878. // to. It records that an `impl` will exist for the query, but is yet unknown.
  879. struct LookupResult {
  880. EvalImplLookupResult result;
  881. const TypeStructure* impl_type_structure = nullptr;
  882. SemIR::LocId impl_loc_id = SemIR::LocId::None;
  883. };
  884. LookupResult lookup_result = {.result = facet_lookup_result};
  885. auto core_interface =
  886. GetCoreInterface(context, query_specific_interface.interface_id);
  887. // Consider a custom witness for core interfaces.
  888. // TODO: This needs to expand to more interfaces, and we might want to have
  889. // that dispatch in custom_witness.cpp instead of here.
  890. bool used_custom_witness = false;
  891. if (auto witness_id = LookupCustomWitness(
  892. context, loc_id, core_interface, query_self_const_id,
  893. eval_query.query_specific_interface_id);
  894. witness_id.has_value()) {
  895. lookup_result = {.result = EvalImplLookupResult::MakeFinal(witness_id)};
  896. used_custom_witness = true;
  897. }
  898. // Only consider candidates when a custom witness didn't apply.
  899. if (!used_custom_witness) {
  900. for (const auto& candidate : candidates.impls) {
  901. const auto& impl = *candidate.impl;
  902. // In deferred lookup for a symbolic impl witness, while building a
  903. // specific, there may be no stack yet as this may be the first lookup. If
  904. // further lookups are started as a result in deduce, they will build the
  905. // stack.
  906. if (!context.impl_lookup_stack().empty()) {
  907. context.impl_lookup_stack().back().impl_loc = impl.definition_id;
  908. }
  909. auto result = GetWitnessIdForImpl(context, loc_id, query_is_concrete,
  910. query_self_const_id,
  911. query_specific_interface, impl);
  912. if (result.has_value()) {
  913. PoisonImplLookupQuery(context, loc_id, mode, eval_query, result, impl);
  914. lookup_result = {.result = result,
  915. .impl_type_structure = &candidate.type_structure,
  916. .impl_loc_id = SemIR::LocId(impl.definition_id)};
  917. break;
  918. }
  919. }
  920. }
  921. if (query_is_concrete && candidates.consider_cpp_candidates &&
  922. core_interface != CoreInterface::Unknown) {
  923. // Also check for a C++ candidate that is a better match than whatever
  924. // `impl` we may have found in Carbon.
  925. auto cpp_witness_id = LookupCppImpl(
  926. context, loc_id, core_interface, query_self_const_id,
  927. eval_query.query_specific_interface_id,
  928. lookup_result.impl_type_structure, lookup_result.impl_loc_id);
  929. if (cpp_witness_id.has_value()) {
  930. lookup_result = {.result =
  931. EvalImplLookupResult::MakeFinal(cpp_witness_id)};
  932. }
  933. }
  934. if (mode != EvalImplLookupMode::RecheckPoisonedLookup &&
  935. lookup_result.result.has_final_value()) {
  936. context.impl_lookup_cache().Insert(impl_lookup_cache_key,
  937. lookup_result.result.final_witness());
  938. }
  939. return lookup_result.result;
  940. }
  941. auto LookupMatchesImpl(Context& context, SemIR::LocId loc_id,
  942. SemIR::ConstantId query_self_const_id,
  943. SemIR::SpecificInterface query_specific_interface,
  944. SemIR::ImplId target_impl) -> bool {
  945. if (query_self_const_id == SemIR::ErrorInst::ConstantId) {
  946. return false;
  947. }
  948. auto result = GetWitnessIdForImpl(
  949. context, loc_id, /*query_is_concrete=*/false, query_self_const_id,
  950. query_specific_interface, context.impls().Get(target_impl));
  951. return result.has_value();
  952. }
  953. } // namespace Carbon::Check