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;
9 use chalk_ir::{cast::Cast, Mutability, UniverseIndex};
11 lang_item::LangItemTarget, AssocContainerId, AssocItemId, FunctionId, GenericDefId, HasModule,
12 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, FnPointer, FnSig, ForeignDefId,
25 InEnvironment, Interner, Scalar, Substitution, TraitEnvironment, Ty, TyBuilder, TyKind,
29 /// This is used as a key for indexing impls.
30 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
31 pub enum TyFingerprint {
41 ForeignType(ForeignDefId),
46 /// Creates a TyFingerprint for looking up an impl. Only certain types can
47 /// have impls: if we have some `struct S`, we can have an `impl S`, but not
48 /// `impl &S`. Hence, this will return `None` for reference types and such.
49 pub fn for_impl(ty: &Ty) -> Option<TyFingerprint> {
50 let fp = match ty.kind(&Interner) {
51 TyKind::Str => TyFingerprint::Str,
52 TyKind::Never => TyFingerprint::Never,
53 TyKind::Slice(..) => TyFingerprint::Slice,
54 TyKind::Array(..) => TyFingerprint::Array,
55 TyKind::Scalar(scalar) => TyFingerprint::Scalar(*scalar),
56 TyKind::Adt(AdtId(adt), _) => TyFingerprint::Adt(*adt),
57 TyKind::Tuple(cardinality, _) => TyFingerprint::Tuple(*cardinality),
58 TyKind::Raw(mutability, ..) => TyFingerprint::RawPtr(*mutability),
59 TyKind::Foreign(alias_id, ..) => TyFingerprint::ForeignType(*alias_id),
60 TyKind::Function(FnPointer { sig, substitution: substs, .. }) => {
61 TyFingerprint::FnPtr(substs.0.len(&Interner) - 1, *sig)
63 TyKind::Dyn(_) => ty.dyn_trait().map(|trait_| TyFingerprint::Dyn(trait_))?,
70 pub(crate) const ALL_INT_FPS: [TyFingerprint; 12] = [
71 TyFingerprint::Scalar(Scalar::Int(IntTy::I8)),
72 TyFingerprint::Scalar(Scalar::Int(IntTy::I16)),
73 TyFingerprint::Scalar(Scalar::Int(IntTy::I32)),
74 TyFingerprint::Scalar(Scalar::Int(IntTy::I64)),
75 TyFingerprint::Scalar(Scalar::Int(IntTy::I128)),
76 TyFingerprint::Scalar(Scalar::Int(IntTy::Isize)),
77 TyFingerprint::Scalar(Scalar::Uint(UintTy::U8)),
78 TyFingerprint::Scalar(Scalar::Uint(UintTy::U16)),
79 TyFingerprint::Scalar(Scalar::Uint(UintTy::U32)),
80 TyFingerprint::Scalar(Scalar::Uint(UintTy::U64)),
81 TyFingerprint::Scalar(Scalar::Uint(UintTy::U128)),
82 TyFingerprint::Scalar(Scalar::Uint(UintTy::Usize)),
85 pub(crate) const ALL_FLOAT_FPS: [TyFingerprint; 2] = [
86 TyFingerprint::Scalar(Scalar::Float(FloatTy::F32)),
87 TyFingerprint::Scalar(Scalar::Float(FloatTy::F64)),
90 /// Trait impls defined or available in some crate.
91 #[derive(Debug, Eq, PartialEq)]
92 pub struct TraitImpls {
93 // If the `Option<TyFingerprint>` is `None`, the impl may apply to any self type.
94 map: FxHashMap<TraitId, FxHashMap<Option<TyFingerprint>, Vec<ImplId>>>,
98 pub(crate) fn trait_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
99 let _p = profile::span("trait_impls_in_crate_query");
100 let mut impls = Self { map: FxHashMap::default() };
102 let crate_def_map = db.crate_def_map(krate);
103 for (_module_id, module_data) in crate_def_map.modules() {
104 for impl_id in module_data.scope.impls() {
105 let target_trait = match db.impl_trait(impl_id) {
106 Some(tr) => tr.skip_binders().hir_trait_id(),
109 let self_ty = db.impl_self_ty(impl_id);
110 let self_ty_fp = TyFingerprint::for_impl(self_ty.skip_binders());
124 pub(crate) fn trait_impls_in_deps_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
125 let _p = profile::span("trait_impls_in_deps_query");
126 let crate_graph = db.crate_graph();
127 let mut res = Self { map: FxHashMap::default() };
129 for krate in crate_graph.transitive_deps(krate) {
130 res.merge(&db.trait_impls_in_crate(krate));
136 fn merge(&mut self, other: &Self) {
137 for (trait_, other_map) in &other.map {
138 let map = self.map.entry(*trait_).or_default();
139 for (fp, impls) in other_map {
140 let vec = map.entry(*fp).or_default();
146 /// Queries all trait impls for the given type.
147 pub fn for_self_ty(&self, fp: TyFingerprint) -> impl Iterator<Item = ImplId> + '_ {
150 .flat_map(move |impls| impls.get(&None).into_iter().chain(impls.get(&Some(fp))))
151 .flat_map(|it| it.iter().copied())
154 /// Queries all impls of the given trait.
155 pub fn for_trait(&self, trait_: TraitId) -> impl Iterator<Item = ImplId> + '_ {
159 .flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
162 /// Queries all impls of `trait_` that may apply to `self_ty`.
163 pub fn for_trait_and_self_ty(
166 self_ty: TyFingerprint,
167 ) -> impl Iterator<Item = ImplId> + '_ {
171 .flat_map(move |map| map.get(&None).into_iter().chain(map.get(&Some(self_ty))))
172 .flat_map(|v| v.iter().copied())
175 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
176 self.map.values().flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
180 /// Inherent impls defined in some crate.
182 /// Inherent impls can only be defined in the crate that also defines the self type of the impl
183 /// (note that some primitives are considered to be defined by both libcore and liballoc).
185 /// This makes inherent impl lookup easier than trait impl lookup since we only have to consider a
187 #[derive(Debug, Eq, PartialEq)]
188 pub struct InherentImpls {
189 map: FxHashMap<TyFingerprint, Vec<ImplId>>,
193 pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
194 let mut map: FxHashMap<_, Vec<_>> = FxHashMap::default();
196 let crate_def_map = db.crate_def_map(krate);
197 for (_module_id, module_data) in crate_def_map.modules() {
198 for impl_id in module_data.scope.impls() {
199 let data = db.impl_data(impl_id);
200 if data.target_trait.is_some() {
204 let self_ty = db.impl_self_ty(impl_id);
205 if let Some(fp) = TyFingerprint::for_impl(self_ty.skip_binders()) {
206 map.entry(fp).or_default().push(impl_id);
211 Arc::new(Self { map })
214 pub fn for_self_ty(&self, self_ty: &Ty) -> &[ImplId] {
215 match TyFingerprint::for_impl(self_ty) {
216 Some(fp) => self.map.get(&fp).map(|vec| vec.as_ref()).unwrap_or(&[]),
221 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
222 self.map.values().flat_map(|v| v.iter().copied())
229 db: &dyn HirDatabase,
231 ) -> Option<ArrayVec<CrateId, 2>> {
232 // Types like slice can have inherent impls in several crates, (core and alloc).
233 // The corresponding impls are marked with lang items, so we can use them to find the required crates.
234 macro_rules! lang_item_crate {
235 ($($name:expr),+ $(,)?) => {{
236 let mut v = ArrayVec::<LangItemTarget, 2>::new();
238 v.extend(db.lang_item(cur_crate, $name.into()));
244 let mod_to_crate_ids = |module: ModuleId| Some(std::iter::once(module.krate()).collect());
246 let lang_item_targets = match self.kind(&Interner) {
247 TyKind::Adt(AdtId(def_id), _) => {
248 return mod_to_crate_ids(def_id.module(db.upcast()));
250 TyKind::Foreign(id) => {
251 return mod_to_crate_ids(
252 from_foreign_def_id(*id).lookup(db.upcast()).module(db.upcast()),
255 TyKind::Scalar(Scalar::Bool) => lang_item_crate!("bool"),
256 TyKind::Scalar(Scalar::Char) => lang_item_crate!("char"),
257 TyKind::Scalar(Scalar::Float(f)) => match f {
258 // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime)
259 FloatTy::F32 => lang_item_crate!("f32", "f32_runtime"),
260 FloatTy::F64 => lang_item_crate!("f64", "f64_runtime"),
262 &TyKind::Scalar(Scalar::Int(t)) => {
263 lang_item_crate!(primitive::int_ty_to_string(t))
265 &TyKind::Scalar(Scalar::Uint(t)) => {
266 lang_item_crate!(primitive::uint_ty_to_string(t))
268 TyKind::Str => lang_item_crate!("str_alloc", "str"),
269 TyKind::Slice(_) => lang_item_crate!("slice_alloc", "slice"),
270 TyKind::Raw(Mutability::Not, _) => lang_item_crate!("const_ptr"),
271 TyKind::Raw(Mutability::Mut, _) => lang_item_crate!("mut_ptr"),
273 return self.dyn_trait().and_then(|trait_| {
274 mod_to_crate_ids(GenericDefId::TraitId(trait_).module(db.upcast()))
279 let res = lang_item_targets
281 .filter_map(|it| match it {
282 LangItemTarget::ImplDefId(it) => Some(it),
285 .map(|it| it.lookup(db.upcast()).container.krate())
291 /// Look up the method with the given name, returning the actual autoderefed
292 /// receiver type (but without autoref applied yet).
293 pub(crate) fn lookup_method(
295 db: &dyn HirDatabase,
296 env: Arc<TraitEnvironment>,
298 traits_in_scope: &FxHashSet<TraitId>,
299 visible_from_module: Option<ModuleId>,
301 ) -> Option<(Ty, FunctionId)> {
302 iterate_method_candidates(
310 LookupMode::MethodCall,
312 AssocItemId::FunctionId(f) => Some((ty.clone(), f)),
318 /// Whether we're looking up a dotted method call (like `v.len()`) or a path
319 /// (like `Vec::new`).
320 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
321 pub enum LookupMode {
322 /// Looking up a method call like `v.len()`: We only consider candidates
323 /// that have a `self` parameter, and do autoderef.
325 /// Looking up a path like `Vec::new` or `Vec::default`: We consider all
326 /// candidates including associated constants, but don't do autoderef.
330 // This would be nicer if it just returned an iterator, but that runs into
331 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
332 // FIXME add a context type here?
333 pub fn iterate_method_candidates<T>(
335 db: &dyn HirDatabase,
336 env: Arc<TraitEnvironment>,
338 traits_in_scope: &FxHashSet<TraitId>,
339 visible_from_module: Option<ModuleId>,
342 mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>,
345 iterate_method_candidates_impl(
355 assert!(slot.is_none());
356 slot = callback(ty, item);
363 fn iterate_method_candidates_impl(
365 db: &dyn HirDatabase,
366 env: Arc<TraitEnvironment>,
368 traits_in_scope: &FxHashSet<TraitId>,
369 visible_from_module: Option<ModuleId>,
372 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
375 LookupMode::MethodCall => {
376 // For method calls, rust first does any number of autoderef, and then one
377 // autoref (i.e. when the method takes &self or &mut self). We just ignore
378 // the autoref currently -- when we find a method matching the given name,
379 // we assume it fits.
381 // Also note that when we've got a receiver like &S, even if the method we
382 // find in the end takes &self, we still do the autoderef step (just as
383 // rustc does an autoderef and then autoref again).
384 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
386 // We have to be careful about the order we're looking at candidates
387 // in here. Consider the case where we're resolving `x.clone()`
388 // where `x: &Vec<_>`. This resolves to the clone method with self
389 // type `Vec<_>`, *not* `&_`. I.e. we need to consider methods where
390 // the receiver type exactly matches before cases where we have to
391 // do autoref. But in the autoderef steps, the `&_` self type comes
392 // up *before* the `Vec<_>` self type.
394 // On the other hand, we don't want to just pick any by-value method
395 // before any by-autoref method; it's just that we need to consider
396 // the methods by autoderef order of *receiver types*, not *self
399 let deref_chain = autoderef_method_receiver(db, krate, ty);
400 for i in 0..deref_chain.len() {
401 if iterate_method_candidates_with_autoref(
416 LookupMode::Path => {
417 // No autoderef for path lookups
418 iterate_method_candidates_for_self_ty(
432 fn iterate_method_candidates_with_autoref(
433 deref_chain: &[Canonical<Ty>],
434 db: &dyn HirDatabase,
435 env: Arc<TraitEnvironment>,
437 traits_in_scope: &FxHashSet<TraitId>,
438 visible_from_module: Option<ModuleId>,
440 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
442 if iterate_method_candidates_by_receiver(
455 let refed = Canonical {
456 binders: deref_chain[0].binders.clone(),
457 value: TyKind::Ref(Mutability::Not, static_lifetime(), deref_chain[0].value.clone())
460 if iterate_method_candidates_by_receiver(
473 let ref_muted = Canonical {
474 binders: deref_chain[0].binders.clone(),
475 value: TyKind::Ref(Mutability::Mut, static_lifetime(), deref_chain[0].value.clone())
478 if iterate_method_candidates_by_receiver(
494 fn iterate_method_candidates_by_receiver(
495 receiver_ty: &Canonical<Ty>,
496 rest_of_deref_chain: &[Canonical<Ty>],
497 db: &dyn HirDatabase,
498 env: Arc<TraitEnvironment>,
500 traits_in_scope: &FxHashSet<TraitId>,
501 visible_from_module: Option<ModuleId>,
503 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
505 // We're looking for methods with *receiver* type receiver_ty. These could
506 // be found in any of the derefs of receiver_ty, so we have to go through
508 for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
509 if iterate_inherent_methods(
521 for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
522 if iterate_trait_method_candidates(
538 fn iterate_method_candidates_for_self_ty(
539 self_ty: &Canonical<Ty>,
540 db: &dyn HirDatabase,
541 env: Arc<TraitEnvironment>,
543 traits_in_scope: &FxHashSet<TraitId>,
544 visible_from_module: Option<ModuleId>,
546 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
548 if iterate_inherent_methods(self_ty, db, name, None, krate, visible_from_module, &mut callback)
552 iterate_trait_method_candidates(self_ty, db, env, krate, traits_in_scope, name, None, callback)
555 fn iterate_trait_method_candidates(
556 self_ty: &Canonical<Ty>,
557 db: &dyn HirDatabase,
558 env: Arc<TraitEnvironment>,
560 traits_in_scope: &FxHashSet<TraitId>,
562 receiver_ty: Option<&Canonical<Ty>>,
563 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
565 // if ty is `dyn Trait`, the trait doesn't need to be in scope
567 self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t));
568 let env_traits = if let TyKind::Placeholder(_) = self_ty.value.kind(&Interner) {
569 // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
570 env.traits_in_scope_from_clauses(&self_ty.value)
571 .flat_map(|t| all_super_traits(db.upcast(), t))
577 inherent_trait.chain(env_traits.into_iter()).chain(traits_in_scope.iter().copied());
578 'traits: for t in traits {
579 let data = db.trait_data(t);
581 // we'll be lazy about checking whether the type implements the
582 // trait, but if we find out it doesn't, we'll skip the rest of the
584 let mut known_implemented = false;
585 for (_name, item) in data.items.iter() {
586 // Don't pass a `visible_from_module` down to `is_valid_candidate`,
587 // since only inherent methods should be included into visibility checking.
588 if !is_valid_candidate(db, name, receiver_ty, *item, self_ty, None) {
591 if !known_implemented {
592 let goal = generic_implements_goal(db, env.clone(), t, self_ty.clone());
593 if db.trait_solve(krate, goal).is_none() {
597 known_implemented = true;
598 if callback(&self_ty.value, *item) {
606 fn iterate_inherent_methods(
607 self_ty: &Canonical<Ty>,
608 db: &dyn HirDatabase,
610 receiver_ty: Option<&Canonical<Ty>>,
612 visible_from_module: Option<ModuleId>,
613 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
615 let def_crates = match self_ty.value.def_crates(db, krate) {
617 None => return false,
619 for krate in def_crates {
620 let impls = db.inherent_impls_in_crate(krate);
622 for &impl_def in impls.for_self_ty(&self_ty.value) {
623 for &item in db.impl_data(impl_def).items.iter() {
624 if !is_valid_candidate(db, name, receiver_ty, item, self_ty, visible_from_module) {
627 // we have to check whether the self type unifies with the type
628 // that the impl is for. If we have a receiver type, this
629 // already happens in `is_valid_candidate` above; if not, we
631 if receiver_ty.is_none() && inherent_impl_substs(db, impl_def, self_ty).is_none() {
632 cov_mark::hit!(impl_self_type_match_without_receiver);
635 if callback(&self_ty.value, item) {
644 /// Returns the self type for the index trait call.
645 pub fn resolve_indexing_op(
646 db: &dyn HirDatabase,
648 env: Arc<TraitEnvironment>,
650 index_trait: TraitId,
651 ) -> Option<Canonical<Ty>> {
652 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
653 let deref_chain = autoderef_method_receiver(db, krate, ty);
654 for ty in deref_chain {
655 let goal = generic_implements_goal(db, env.clone(), index_trait, ty.clone());
656 if db.trait_solve(krate, goal).is_some() {
663 fn is_valid_candidate(
664 db: &dyn HirDatabase,
666 receiver_ty: Option<&Canonical<Ty>>,
668 self_ty: &Canonical<Ty>,
669 visible_from_module: Option<ModuleId>,
672 AssocItemId::FunctionId(m) => {
673 let data = db.function_data(m);
674 if let Some(name) = name {
675 if &data.name != name {
679 if let Some(receiver_ty) = receiver_ty {
680 if !data.has_self_param() {
683 let transformed_receiver_ty = match transform_receiver_ty(db, m, self_ty) {
685 None => return false,
687 if transformed_receiver_ty != receiver_ty.value {
691 if let Some(from_module) = visible_from_module {
692 if !db.function_visibility(m).is_visible_from(db.upcast(), from_module) {
693 cov_mark::hit!(autoderef_candidate_not_visible);
700 AssocItemId::ConstId(c) => {
701 let data = db.const_data(c);
702 name.map_or(true, |name| data.name.as_ref() == Some(name)) && receiver_ty.is_none()
708 pub(crate) fn inherent_impl_substs(
709 db: &dyn HirDatabase,
711 self_ty: &Canonical<Ty>,
712 ) -> Option<Substitution> {
713 // we create a var for each type parameter of the impl; we need to keep in
714 // mind here that `self_ty` might have vars of its own
715 let self_ty_vars = self_ty.binders.len(&Interner);
716 let vars = TyBuilder::subst_for_def(db, impl_id)
717 .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty_vars)
719 let self_ty_with_vars = db.impl_self_ty(impl_id).substitute(&Interner, &vars);
720 let mut kinds = self_ty.binders.interned().to_vec();
722 iter::repeat(chalk_ir::WithKind::new(
723 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
726 .take(vars.len(&Interner)),
728 let tys = Canonical {
729 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
730 value: (self_ty_with_vars, self_ty.value.clone()),
732 let substs = super::infer::unify(&tys)?;
733 // We only want the substs for the vars we added, not the ones from self_ty.
734 // Also, if any of the vars we added are still in there, we replace them by
735 // Unknown. I think this can only really happen if self_ty contained
736 // Unknown, and in that case we want the result to contain Unknown in those
739 Substitution::from_iter(&Interner, substs.iter(&Interner).cloned().skip(self_ty_vars));
740 Some(fallback_bound_vars(suffix, self_ty_vars))
743 /// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
744 /// num_vars_to_keep) by `TyKind::Unknown`.
745 fn fallback_bound_vars(s: Substitution, num_vars_to_keep: usize) -> Substitution {
748 if let TyKind::BoundVar(bound) = ty.kind(&Interner) {
749 if bound.index >= num_vars_to_keep && bound.debruijn >= binders {
750 TyKind::Error.intern(&Interner)
758 DebruijnIndex::INNERMOST,
762 fn transform_receiver_ty(
763 db: &dyn HirDatabase,
764 function_id: FunctionId,
765 self_ty: &Canonical<Ty>,
767 let substs = match function_id.lookup(db.upcast()).container {
768 AssocContainerId::TraitId(_) => TyBuilder::subst_for_def(db, function_id)
769 .push(self_ty.value.clone())
772 AssocContainerId::ImplId(impl_id) => {
773 let impl_substs = inherent_impl_substs(db, impl_id, &self_ty)?;
774 TyBuilder::subst_for_def(db, function_id)
775 .use_parent_substs(&impl_substs)
779 AssocContainerId::ModuleId(_) => unreachable!(),
781 let sig = db.callable_item_signature(function_id.into());
782 Some(sig.map(|s| s.params()[0].clone()).substitute(&Interner, &substs))
785 pub fn implements_trait(
787 db: &dyn HirDatabase,
788 env: Arc<TraitEnvironment>,
792 let goal = generic_implements_goal(db, env, trait_, ty.clone());
793 let solution = db.trait_solve(krate, goal);
798 pub fn implements_trait_unique(
800 db: &dyn HirDatabase,
801 env: Arc<TraitEnvironment>,
805 let goal = generic_implements_goal(db, env, trait_, ty.clone());
806 let solution = db.trait_solve(krate, goal);
808 matches!(solution, Some(crate::Solution::Unique(_)))
811 /// This creates Substs for a trait with the given Self type and type variables
812 /// for all other parameters, to query Chalk with it.
813 fn generic_implements_goal(
814 db: &dyn HirDatabase,
815 env: Arc<TraitEnvironment>,
817 self_ty: Canonical<Ty>,
818 ) -> Canonical<InEnvironment<super::DomainGoal>> {
819 let mut kinds = self_ty.binders.interned().to_vec();
820 let trait_ref = TyBuilder::trait_ref(db, trait_)
822 .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
825 iter::repeat(chalk_ir::WithKind::new(
826 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
829 .take(trait_ref.substitution.len(&Interner) - 1),
831 let obligation = trait_ref.cast(&Interner);
833 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
834 value: InEnvironment::new(env.env.clone(), obligation),
838 fn autoderef_method_receiver(
839 db: &dyn HirDatabase,
841 ty: InEnvironment<Canonical<Ty>>,
842 ) -> Vec<Canonical<Ty>> {
843 let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
844 // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
845 if let Some(TyKind::Array(parameters, _)) =
846 deref_chain.last().map(|ty| ty.value.kind(&Interner))
848 let kinds = deref_chain.last().unwrap().binders.clone();
849 let unsized_ty = TyKind::Slice(parameters.clone()).intern(&Interner);
850 deref_chain.push(Canonical { value: unsized_ty, binders: kinds })