impl_lookup.cpp 43 KB

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