1 //! This module is concerned with finding methods that a given type provides.
2 //! For details about how this works in rustc, see the method lookup page in the
3 //! [rustc guide](https://rust-lang.github.io/rustc-guide/method-lookup.html)
4 //! and the corresponding code mostly in librustc_typeck/check/method/probe.rs.
5 use std::{iter, sync::Arc};
7 use arrayvec::ArrayVec;
8 use base_db::{CrateId, Edition};
9 use chalk_ir::{cast::Cast, Mutability, UniverseIndex};
11 lang_item::LangItemTarget, nameres::DefMap, AssocContainerId, AssocItemId, BlockId, FunctionId,
12 GenericDefId, HasModule, ImplId, Lookup, ModuleId, TraitId,
14 use hir_expand::name::Name;
15 use rustc_hash::{FxHashMap, FxHashSet};
21 primitive::{self, FloatTy, IntTy, UintTy},
23 utils::all_super_traits,
24 AdtId, Canonical, CanonicalVarKinds, DebruijnIndex, ForeignDefId, InEnvironment, Interner,
25 Scalar, Substitution, TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyExt, TyKind,
28 /// This is used as a key for indexing impls.
29 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
30 pub enum TyFingerprint {
31 // These are lang item impls:
38 // These can have user-defined impls:
41 ForeignType(ForeignDefId),
42 // These only exist for trait impls
49 /// Creates a TyFingerprint for looking up an inherent impl. Only certain
50 /// types can have inherent impls: if we have some `struct S`, we can have
51 /// an `impl S`, but not `impl &S`. Hence, this will return `None` for
52 /// reference types and such.
53 pub fn for_inherent_impl(ty: &Ty) -> Option<TyFingerprint> {
54 let fp = match ty.kind(&Interner) {
55 TyKind::Str => TyFingerprint::Str,
56 TyKind::Never => TyFingerprint::Never,
57 TyKind::Slice(..) => TyFingerprint::Slice,
58 TyKind::Array(..) => TyFingerprint::Array,
59 TyKind::Scalar(scalar) => TyFingerprint::Scalar(*scalar),
60 TyKind::Adt(AdtId(adt), _) => TyFingerprint::Adt(*adt),
61 TyKind::Raw(mutability, ..) => TyFingerprint::RawPtr(*mutability),
62 TyKind::Foreign(alias_id, ..) => TyFingerprint::ForeignType(*alias_id),
63 TyKind::Dyn(_) => ty.dyn_trait().map(TyFingerprint::Dyn)?,
69 /// Creates a TyFingerprint for looking up a trait impl.
70 pub fn for_trait_impl(ty: &Ty) -> Option<TyFingerprint> {
71 let fp = match ty.kind(&Interner) {
72 TyKind::Str => TyFingerprint::Str,
73 TyKind::Never => TyFingerprint::Never,
74 TyKind::Slice(..) => TyFingerprint::Slice,
75 TyKind::Array(..) => TyFingerprint::Array,
76 TyKind::Scalar(scalar) => TyFingerprint::Scalar(*scalar),
77 TyKind::Adt(AdtId(adt), _) => TyFingerprint::Adt(*adt),
78 TyKind::Raw(mutability, ..) => TyFingerprint::RawPtr(*mutability),
79 TyKind::Foreign(alias_id, ..) => TyFingerprint::ForeignType(*alias_id),
80 TyKind::Dyn(_) => ty.dyn_trait().map(TyFingerprint::Dyn)?,
81 TyKind::Ref(_, _, ty) => return TyFingerprint::for_trait_impl(ty),
82 TyKind::Tuple(_, subst) => {
83 let first_ty = subst.interned().get(0).map(|arg| arg.assert_ty_ref(&Interner));
84 if let Some(ty) = first_ty {
85 return TyFingerprint::for_trait_impl(ty);
90 TyKind::AssociatedType(_, _)
91 | TyKind::OpaqueType(_, _)
93 | TyKind::Closure(_, _)
94 | TyKind::Generator(..)
95 | TyKind::GeneratorWitness(..) => TyFingerprint::Unnameable,
96 TyKind::Function(fn_ptr) => {
97 TyFingerprint::Function(fn_ptr.substitution.0.len(&Interner) as u32)
100 | TyKind::Placeholder(_)
101 | TyKind::BoundVar(_)
102 | TyKind::InferenceVar(_, _)
103 | TyKind::Error => return None,
109 pub(crate) const ALL_INT_FPS: [TyFingerprint; 12] = [
110 TyFingerprint::Scalar(Scalar::Int(IntTy::I8)),
111 TyFingerprint::Scalar(Scalar::Int(IntTy::I16)),
112 TyFingerprint::Scalar(Scalar::Int(IntTy::I32)),
113 TyFingerprint::Scalar(Scalar::Int(IntTy::I64)),
114 TyFingerprint::Scalar(Scalar::Int(IntTy::I128)),
115 TyFingerprint::Scalar(Scalar::Int(IntTy::Isize)),
116 TyFingerprint::Scalar(Scalar::Uint(UintTy::U8)),
117 TyFingerprint::Scalar(Scalar::Uint(UintTy::U16)),
118 TyFingerprint::Scalar(Scalar::Uint(UintTy::U32)),
119 TyFingerprint::Scalar(Scalar::Uint(UintTy::U64)),
120 TyFingerprint::Scalar(Scalar::Uint(UintTy::U128)),
121 TyFingerprint::Scalar(Scalar::Uint(UintTy::Usize)),
124 pub(crate) const ALL_FLOAT_FPS: [TyFingerprint; 2] = [
125 TyFingerprint::Scalar(Scalar::Float(FloatTy::F32)),
126 TyFingerprint::Scalar(Scalar::Float(FloatTy::F64)),
129 /// Trait impls defined or available in some crate.
130 #[derive(Debug, Eq, PartialEq)]
131 pub struct TraitImpls {
132 // If the `Option<TyFingerprint>` is `None`, the impl may apply to any self type.
133 map: FxHashMap<TraitId, FxHashMap<Option<TyFingerprint>, Vec<ImplId>>>,
137 pub(crate) fn trait_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
138 let _p = profile::span("trait_impls_in_crate_query");
139 let mut impls = Self { map: FxHashMap::default() };
141 let crate_def_map = db.crate_def_map(krate);
142 impls.collect_def_map(db, &crate_def_map);
147 pub(crate) fn trait_impls_in_block_query(
148 db: &dyn HirDatabase,
150 ) -> Option<Arc<Self>> {
151 let _p = profile::span("trait_impls_in_block_query");
152 let mut impls = Self { map: FxHashMap::default() };
154 let block_def_map = db.block_def_map(block)?;
155 impls.collect_def_map(db, &block_def_map);
157 Some(Arc::new(impls))
160 fn collect_def_map(&mut self, db: &dyn HirDatabase, def_map: &DefMap) {
161 for (_module_id, module_data) in def_map.modules() {
162 for impl_id in module_data.scope.impls() {
163 let target_trait = match db.impl_trait(impl_id) {
164 Some(tr) => tr.skip_binders().hir_trait_id(),
167 let self_ty = db.impl_self_ty(impl_id);
168 let self_ty_fp = TyFingerprint::for_trait_impl(self_ty.skip_binders());
177 // To better support custom derives, collect impls in all unnamed const items.
178 // const _: () = { ... };
179 for konst in module_data.scope.unnamed_consts() {
180 let body = db.body(konst.into());
181 for (_, block_def_map) in body.blocks(db.upcast()) {
182 self.collect_def_map(db, &block_def_map);
188 pub(crate) fn trait_impls_in_deps_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
189 let _p = profile::span("trait_impls_in_deps_query");
190 let crate_graph = db.crate_graph();
191 let mut res = Self { map: FxHashMap::default() };
193 for krate in crate_graph.transitive_deps(krate) {
194 res.merge(&db.trait_impls_in_crate(krate));
200 fn merge(&mut self, other: &Self) {
201 for (trait_, other_map) in &other.map {
202 let map = self.map.entry(*trait_).or_default();
203 for (fp, impls) in other_map {
204 let vec = map.entry(*fp).or_default();
210 /// Queries all trait impls for the given type.
211 pub fn for_self_ty_without_blanket_impls(
214 ) -> impl Iterator<Item = ImplId> + '_ {
217 .flat_map(move |impls| impls.get(&Some(fp)).into_iter())
218 .flat_map(|it| it.iter().copied())
221 /// Queries all impls of the given trait.
222 pub fn for_trait(&self, trait_: TraitId) -> impl Iterator<Item = ImplId> + '_ {
226 .flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
229 /// Queries all impls of `trait_` that may apply to `self_ty`.
230 pub fn for_trait_and_self_ty(
233 self_ty: TyFingerprint,
234 ) -> impl Iterator<Item = ImplId> + '_ {
238 .flat_map(move |map| map.get(&None).into_iter().chain(map.get(&Some(self_ty))))
239 .flat_map(|v| v.iter().copied())
242 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
243 self.map.values().flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
247 /// Inherent impls defined in some crate.
249 /// Inherent impls can only be defined in the crate that also defines the self type of the impl
250 /// (note that some primitives are considered to be defined by both libcore and liballoc).
252 /// This makes inherent impl lookup easier than trait impl lookup since we only have to consider a
254 #[derive(Debug, Eq, PartialEq)]
255 pub struct InherentImpls {
256 map: FxHashMap<TyFingerprint, Vec<ImplId>>,
260 pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
261 let mut impls = Self { map: FxHashMap::default() };
263 let crate_def_map = db.crate_def_map(krate);
264 collect_def_map(db, &crate_def_map, &mut impls);
266 return Arc::new(impls);
268 fn collect_def_map(db: &dyn HirDatabase, def_map: &DefMap, impls: &mut InherentImpls) {
269 for (_module_id, module_data) in def_map.modules() {
270 for impl_id in module_data.scope.impls() {
271 let data = db.impl_data(impl_id);
272 if data.target_trait.is_some() {
276 let self_ty = db.impl_self_ty(impl_id);
277 let fp = TyFingerprint::for_inherent_impl(self_ty.skip_binders());
278 if let Some(fp) = fp {
279 impls.map.entry(fp).or_default().push(impl_id);
281 // `fp` should only be `None` in error cases (either erroneous code or incomplete name resolution)
284 // To better support custom derives, collect impls in all unnamed const items.
285 // const _: () = { ... };
286 for konst in module_data.scope.unnamed_consts() {
287 let body = db.body(konst.into());
288 for (_, block_def_map) in body.blocks(db.upcast()) {
289 collect_def_map(db, &block_def_map, impls);
296 pub fn for_self_ty(&self, self_ty: &Ty) -> &[ImplId] {
297 match TyFingerprint::for_inherent_impl(self_ty) {
298 Some(fp) => self.map.get(&fp).map(|vec| vec.as_ref()).unwrap_or(&[]),
303 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
304 self.map.values().flat_map(|v| v.iter().copied())
309 db: &dyn HirDatabase,
312 ) -> Option<ArrayVec<CrateId, 2>> {
313 // Types like slice can have inherent impls in several crates, (core and alloc).
314 // The corresponding impls are marked with lang items, so we can use them to find the required crates.
315 macro_rules! lang_item_crate {
316 ($($name:expr),+ $(,)?) => {{
317 let mut v = ArrayVec::<LangItemTarget, 2>::new();
319 v.extend(db.lang_item(cur_crate, $name.into()));
325 let mod_to_crate_ids = |module: ModuleId| Some(std::iter::once(module.krate()).collect());
327 let lang_item_targets = match ty.kind(&Interner) {
328 TyKind::Adt(AdtId(def_id), _) => {
329 return mod_to_crate_ids(def_id.module(db.upcast()));
331 TyKind::Foreign(id) => {
332 return mod_to_crate_ids(
333 from_foreign_def_id(*id).lookup(db.upcast()).module(db.upcast()),
336 TyKind::Scalar(Scalar::Bool) => lang_item_crate!("bool"),
337 TyKind::Scalar(Scalar::Char) => lang_item_crate!("char"),
338 TyKind::Scalar(Scalar::Float(f)) => match f {
339 // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime)
340 FloatTy::F32 => lang_item_crate!("f32", "f32_runtime"),
341 FloatTy::F64 => lang_item_crate!("f64", "f64_runtime"),
343 &TyKind::Scalar(Scalar::Int(t)) => {
344 lang_item_crate!(primitive::int_ty_to_string(t))
346 &TyKind::Scalar(Scalar::Uint(t)) => {
347 lang_item_crate!(primitive::uint_ty_to_string(t))
349 TyKind::Str => lang_item_crate!("str_alloc", "str"),
350 TyKind::Slice(_) => lang_item_crate!("slice_alloc", "slice"),
351 TyKind::Array(..) => lang_item_crate!("array"),
352 TyKind::Raw(Mutability::Not, _) => lang_item_crate!("const_ptr"),
353 TyKind::Raw(Mutability::Mut, _) => lang_item_crate!("mut_ptr"),
355 return ty.dyn_trait().and_then(|trait_| {
356 mod_to_crate_ids(GenericDefId::TraitId(trait_).module(db.upcast()))
361 let res = lang_item_targets
363 .filter_map(|it| match it {
364 LangItemTarget::ImplDefId(it) => Some(it),
367 .map(|it| it.lookup(db.upcast()).container.krate())
372 /// Look up the method with the given name, returning the actual autoderefed
373 /// receiver type (but without autoref applied yet).
374 pub(crate) fn lookup_method(
376 db: &dyn HirDatabase,
377 env: Arc<TraitEnvironment>,
379 traits_in_scope: &FxHashSet<TraitId>,
380 visible_from_module: Option<ModuleId>,
382 ) -> Option<(Ty, FunctionId)> {
383 iterate_method_candidates(
391 LookupMode::MethodCall,
393 AssocItemId::FunctionId(f) => Some((ty.clone(), f)),
399 /// Whether we're looking up a dotted method call (like `v.len()`) or a path
400 /// (like `Vec::new`).
401 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
402 pub enum LookupMode {
403 /// Looking up a method call like `v.len()`: We only consider candidates
404 /// that have a `self` parameter, and do autoderef.
406 /// Looking up a path like `Vec::new` or `Vec::default`: We consider all
407 /// candidates including associated constants, but don't do autoderef.
411 // This would be nicer if it just returned an iterator, but that runs into
412 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
413 // FIXME add a context type here?
414 pub fn iterate_method_candidates<T>(
416 db: &dyn HirDatabase,
417 env: Arc<TraitEnvironment>,
419 traits_in_scope: &FxHashSet<TraitId>,
420 visible_from_module: Option<ModuleId>,
423 mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>,
426 iterate_method_candidates_dyn(
436 assert!(slot.is_none());
437 slot = callback(ty, item);
444 pub fn iterate_method_candidates_dyn(
446 db: &dyn HirDatabase,
447 env: Arc<TraitEnvironment>,
449 traits_in_scope: &FxHashSet<TraitId>,
450 visible_from_module: Option<ModuleId>,
453 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
456 LookupMode::MethodCall => {
457 // For method calls, rust first does any number of autoderef, and then one
458 // autoref (i.e. when the method takes &self or &mut self). We just ignore
459 // the autoref currently -- when we find a method matching the given name,
460 // we assume it fits.
462 // Also note that when we've got a receiver like &S, even if the method we
463 // find in the end takes &self, we still do the autoderef step (just as
464 // rustc does an autoderef and then autoref again).
465 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
467 // We have to be careful about the order we're looking at candidates
468 // in here. Consider the case where we're resolving `x.clone()`
469 // where `x: &Vec<_>`. This resolves to the clone method with self
470 // type `Vec<_>`, *not* `&_`. I.e. we need to consider methods where
471 // the receiver type exactly matches before cases where we have to
472 // do autoref. But in the autoderef steps, the `&_` self type comes
473 // up *before* the `Vec<_>` self type.
475 // On the other hand, we don't want to just pick any by-value method
476 // before any by-autoref method; it's just that we need to consider
477 // the methods by autoderef order of *receiver types*, not *self
480 let deref_chain = autoderef_method_receiver(db, krate, ty);
481 for i in 0..deref_chain.len() {
482 if iterate_method_candidates_with_autoref(
497 LookupMode::Path => {
498 // No autoderef for path lookups
499 iterate_method_candidates_for_self_ty(
513 fn iterate_method_candidates_with_autoref(
514 deref_chain: &[Canonical<Ty>],
515 db: &dyn HirDatabase,
516 env: Arc<TraitEnvironment>,
518 traits_in_scope: &FxHashSet<TraitId>,
519 visible_from_module: Option<ModuleId>,
521 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
523 if iterate_method_candidates_by_receiver(
536 let refed = Canonical {
537 binders: deref_chain[0].binders.clone(),
538 value: TyKind::Ref(Mutability::Not, static_lifetime(), deref_chain[0].value.clone())
541 if iterate_method_candidates_by_receiver(
554 let ref_muted = Canonical {
555 binders: deref_chain[0].binders.clone(),
556 value: TyKind::Ref(Mutability::Mut, static_lifetime(), deref_chain[0].value.clone())
559 if iterate_method_candidates_by_receiver(
575 fn iterate_method_candidates_by_receiver(
576 receiver_ty: &Canonical<Ty>,
577 rest_of_deref_chain: &[Canonical<Ty>],
578 db: &dyn HirDatabase,
579 env: Arc<TraitEnvironment>,
581 traits_in_scope: &FxHashSet<TraitId>,
582 visible_from_module: Option<ModuleId>,
584 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
586 // We're looking for methods with *receiver* type receiver_ty. These could
587 // be found in any of the derefs of receiver_ty, so we have to go through
589 for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
590 if iterate_inherent_methods(
603 for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
604 if iterate_trait_method_candidates(
620 fn iterate_method_candidates_for_self_ty(
621 self_ty: &Canonical<Ty>,
622 db: &dyn HirDatabase,
623 env: Arc<TraitEnvironment>,
625 traits_in_scope: &FxHashSet<TraitId>,
626 visible_from_module: Option<ModuleId>,
628 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
630 if iterate_inherent_methods(
642 iterate_trait_method_candidates(self_ty, db, env, krate, traits_in_scope, name, None, callback)
645 fn iterate_trait_method_candidates(
646 self_ty: &Canonical<Ty>,
647 db: &dyn HirDatabase,
648 env: Arc<TraitEnvironment>,
650 traits_in_scope: &FxHashSet<TraitId>,
652 receiver_ty: Option<&Canonical<Ty>>,
653 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
655 let receiver_is_array = matches!(self_ty.value.kind(&Interner), chalk_ir::TyKind::Array(..));
656 // if ty is `dyn Trait`, the trait doesn't need to be in scope
658 self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t));
659 let env_traits = if let TyKind::Placeholder(_) = self_ty.value.kind(&Interner) {
660 // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
661 env.traits_in_scope_from_clauses(&self_ty.value)
662 .flat_map(|t| all_super_traits(db.upcast(), t))
668 inherent_trait.chain(env_traits.into_iter()).chain(traits_in_scope.iter().copied());
669 'traits: for t in traits {
670 let data = db.trait_data(t);
672 // Traits annotated with `#[rustc_skip_array_during_method_dispatch]` are skipped during
673 // method resolution, if the receiver is an array, and we're compiling for editions before
675 // This is to make `[a].into_iter()` not break code with the new `IntoIterator` impl for
677 if data.skip_array_during_method_dispatch && receiver_is_array {
678 // FIXME: this should really be using the edition of the method name's span, in case it
679 // comes from a macro
680 if db.crate_graph()[krate].edition < Edition::Edition2021 {
685 // we'll be lazy about checking whether the type implements the
686 // trait, but if we find out it doesn't, we'll skip the rest of the
688 let mut known_implemented = false;
689 for (_name, item) in data.items.iter() {
690 // Don't pass a `visible_from_module` down to `is_valid_candidate`,
691 // since only inherent methods should be included into visibility checking.
692 if !is_valid_candidate(db, env.clone(), name, receiver_ty, *item, self_ty, None) {
695 if !known_implemented {
696 let goal = generic_implements_goal(db, env.clone(), t, self_ty.clone());
697 if db.trait_solve(krate, goal.cast(&Interner)).is_none() {
701 known_implemented = true;
702 // FIXME: we shouldn't be ignoring the binders here
703 if callback(&self_ty.value, *item) {
711 fn iterate_inherent_methods(
712 self_ty: &Canonical<Ty>,
713 db: &dyn HirDatabase,
714 env: Arc<TraitEnvironment>,
716 receiver_ty: Option<&Canonical<Ty>>,
718 visible_from_module: Option<ModuleId>,
719 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
721 let def_crates = match def_crates(db, &self_ty.value, krate) {
723 None => return false,
725 for krate in def_crates {
726 let impls = db.inherent_impls_in_crate(krate);
728 for &impl_def in impls.for_self_ty(&self_ty.value) {
729 for &item in db.impl_data(impl_def).items.iter() {
730 if !is_valid_candidate(
741 // we have to check whether the self type unifies with the type
742 // that the impl is for. If we have a receiver type, this
743 // already happens in `is_valid_candidate` above; if not, we
745 if receiver_ty.is_none()
746 && inherent_impl_substs(db, env.clone(), impl_def, self_ty).is_none()
748 cov_mark::hit!(impl_self_type_match_without_receiver);
751 let receiver_ty = receiver_ty.map(|x| &x.value).unwrap_or(&self_ty.value);
752 if callback(receiver_ty, item) {
761 /// Returns the self type for the index trait call.
762 pub fn resolve_indexing_op(
763 db: &dyn HirDatabase,
765 env: Arc<TraitEnvironment>,
767 index_trait: TraitId,
768 ) -> Option<Canonical<Ty>> {
769 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
770 let deref_chain = autoderef_method_receiver(db, krate, ty);
771 for ty in deref_chain {
772 let goal = generic_implements_goal(db, env.clone(), index_trait, ty.clone());
773 if db.trait_solve(krate, goal.cast(&Interner)).is_some() {
780 fn is_valid_candidate(
781 db: &dyn HirDatabase,
782 env: Arc<TraitEnvironment>,
784 receiver_ty: Option<&Canonical<Ty>>,
786 self_ty: &Canonical<Ty>,
787 visible_from_module: Option<ModuleId>,
790 AssocItemId::FunctionId(m) => {
791 let data = db.function_data(m);
792 if let Some(name) = name {
793 if &data.name != name {
797 if let Some(receiver_ty) = receiver_ty {
798 if !data.has_self_param() {
801 let transformed_receiver_ty = match transform_receiver_ty(db, env, m, self_ty) {
803 None => return false,
805 if transformed_receiver_ty != receiver_ty.value {
809 if let Some(from_module) = visible_from_module {
810 if !db.function_visibility(m).is_visible_from(db.upcast(), from_module) {
811 cov_mark::hit!(autoderef_candidate_not_visible);
818 AssocItemId::ConstId(c) => {
819 let data = db.const_data(c);
820 name.map_or(true, |name| data.name.as_ref() == Some(name)) && receiver_ty.is_none()
826 pub(crate) fn inherent_impl_substs(
827 db: &dyn HirDatabase,
828 env: Arc<TraitEnvironment>,
830 self_ty: &Canonical<Ty>,
831 ) -> Option<Substitution> {
832 // we create a var for each type parameter of the impl; we need to keep in
833 // mind here that `self_ty` might have vars of its own
834 let self_ty_vars = self_ty.binders.len(&Interner);
835 let vars = TyBuilder::subst_for_def(db, impl_id)
836 .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty_vars)
838 let self_ty_with_vars = db.impl_self_ty(impl_id).substitute(&Interner, &vars);
839 let mut kinds = self_ty.binders.interned().to_vec();
841 iter::repeat(chalk_ir::WithKind::new(
842 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
845 .take(vars.len(&Interner)),
847 let tys = Canonical {
848 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
849 value: (self_ty_with_vars, self_ty.value.clone()),
851 let substs = super::infer::unify(db, env, &tys)?;
852 // We only want the substs for the vars we added, not the ones from self_ty.
853 // Also, if any of the vars we added are still in there, we replace them by
854 // Unknown. I think this can only really happen if self_ty contained
855 // Unknown, and in that case we want the result to contain Unknown in those
858 Substitution::from_iter(&Interner, substs.iter(&Interner).cloned().skip(self_ty_vars));
859 Some(fallback_bound_vars(suffix, self_ty_vars))
862 /// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
863 /// num_vars_to_keep) by `TyKind::Unknown`.
864 fn fallback_bound_vars(s: Substitution, num_vars_to_keep: usize) -> Substitution {
865 crate::fold_free_vars(s, |bound, binders| {
866 if bound.index >= num_vars_to_keep && bound.debruijn == DebruijnIndex::INNERMOST {
867 TyKind::Error.intern(&Interner)
869 bound.shifted_in_from(binders).to_ty(&Interner)
874 fn transform_receiver_ty(
875 db: &dyn HirDatabase,
876 env: Arc<TraitEnvironment>,
877 function_id: FunctionId,
878 self_ty: &Canonical<Ty>,
880 let substs = match function_id.lookup(db.upcast()).container {
881 AssocContainerId::TraitId(_) => TyBuilder::subst_for_def(db, function_id)
882 .push(self_ty.value.clone())
885 AssocContainerId::ImplId(impl_id) => {
886 let impl_substs = inherent_impl_substs(db, env, impl_id, self_ty)?;
887 TyBuilder::subst_for_def(db, function_id)
888 .use_parent_substs(&impl_substs)
892 AssocContainerId::ModuleId(_) => unreachable!(),
894 let sig = db.callable_item_signature(function_id.into());
895 Some(sig.map(|s| s.params()[0].clone()).substitute(&Interner, &substs))
898 pub fn implements_trait(
900 db: &dyn HirDatabase,
901 env: Arc<TraitEnvironment>,
905 let goal = generic_implements_goal(db, env, trait_, ty.clone());
906 let solution = db.trait_solve(krate, goal.cast(&Interner));
911 pub fn implements_trait_unique(
913 db: &dyn HirDatabase,
914 env: Arc<TraitEnvironment>,
918 let goal = generic_implements_goal(db, env, trait_, ty.clone());
919 let solution = db.trait_solve(krate, goal.cast(&Interner));
921 matches!(solution, Some(crate::Solution::Unique(_)))
924 /// This creates Substs for a trait with the given Self type and type variables
925 /// for all other parameters, to query Chalk with it.
926 fn generic_implements_goal(
927 db: &dyn HirDatabase,
928 env: Arc<TraitEnvironment>,
930 self_ty: Canonical<Ty>,
931 ) -> Canonical<InEnvironment<super::DomainGoal>> {
932 let mut kinds = self_ty.binders.interned().to_vec();
933 let trait_ref = TyBuilder::trait_ref(db, trait_)
935 .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
938 iter::repeat(chalk_ir::WithKind::new(
939 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
942 .take(trait_ref.substitution.len(&Interner) - 1),
944 let obligation = trait_ref.cast(&Interner);
946 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
947 value: InEnvironment::new(&env.env, obligation),
951 fn autoderef_method_receiver(
952 db: &dyn HirDatabase,
954 ty: InEnvironment<Canonical<Ty>>,
955 ) -> Vec<Canonical<Ty>> {
956 let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
957 // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
958 if let Some(TyKind::Array(parameters, _)) =
959 deref_chain.last().map(|ty| ty.value.kind(&Interner))
961 let kinds = deref_chain.last().unwrap().binders.clone();
962 let unsized_ty = TyKind::Slice(parameters.clone()).intern(&Interner);
963 deref_chain.push(Canonical { value: unsized_ty, binders: kinds })