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;
12 Fallible, Mutability, UniverseIndex,
15 lang_item::LangItemTarget, nameres::DefMap, AssocContainerId, AssocItemId, FunctionId,
16 GenericDefId, HasModule, ImplId, Lookup, ModuleId, TraitId,
18 use hir_expand::name::Name;
19 use rustc_hash::{FxHashMap, FxHashSet};
25 primitive::{self, FloatTy, IntTy, UintTy},
27 utils::all_super_traits,
28 AdtId, BoundVar, Canonical, CanonicalVarKinds, DebruijnIndex, FnPointer, FnSig, ForeignDefId,
29 InEnvironment, Interner, Scalar, Substitution, TraitEnvironment, TraitRefExt, Ty, TyBuilder,
30 TyExt, TyKind, TypeWalk,
33 /// This is used as a key for indexing impls.
34 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
35 pub enum TyFingerprint {
45 ForeignType(ForeignDefId),
50 /// Creates a TyFingerprint for looking up an impl. Only certain types can
51 /// have impls: if we have some `struct S`, we can have an `impl S`, but not
52 /// `impl &S`. Hence, this will return `None` for reference types and such.
53 pub fn for_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::Tuple(cardinality, _) => TyFingerprint::Tuple(*cardinality),
62 TyKind::Raw(mutability, ..) => TyFingerprint::RawPtr(*mutability),
63 TyKind::Foreign(alias_id, ..) => TyFingerprint::ForeignType(*alias_id),
64 TyKind::Function(FnPointer { sig, substitution: substs, .. }) => {
65 TyFingerprint::FnPtr(substs.0.len(&Interner) - 1, *sig)
67 TyKind::Dyn(_) => ty.dyn_trait().map(|trait_| TyFingerprint::Dyn(trait_))?,
74 pub(crate) const ALL_INT_FPS: [TyFingerprint; 12] = [
75 TyFingerprint::Scalar(Scalar::Int(IntTy::I8)),
76 TyFingerprint::Scalar(Scalar::Int(IntTy::I16)),
77 TyFingerprint::Scalar(Scalar::Int(IntTy::I32)),
78 TyFingerprint::Scalar(Scalar::Int(IntTy::I64)),
79 TyFingerprint::Scalar(Scalar::Int(IntTy::I128)),
80 TyFingerprint::Scalar(Scalar::Int(IntTy::Isize)),
81 TyFingerprint::Scalar(Scalar::Uint(UintTy::U8)),
82 TyFingerprint::Scalar(Scalar::Uint(UintTy::U16)),
83 TyFingerprint::Scalar(Scalar::Uint(UintTy::U32)),
84 TyFingerprint::Scalar(Scalar::Uint(UintTy::U64)),
85 TyFingerprint::Scalar(Scalar::Uint(UintTy::U128)),
86 TyFingerprint::Scalar(Scalar::Uint(UintTy::Usize)),
89 pub(crate) const ALL_FLOAT_FPS: [TyFingerprint; 2] = [
90 TyFingerprint::Scalar(Scalar::Float(FloatTy::F32)),
91 TyFingerprint::Scalar(Scalar::Float(FloatTy::F64)),
94 /// Trait impls defined or available in some crate.
95 #[derive(Debug, Eq, PartialEq)]
96 pub struct TraitImpls {
97 // If the `Option<TyFingerprint>` is `None`, the impl may apply to any self type.
98 map: FxHashMap<TraitId, FxHashMap<Option<TyFingerprint>, Vec<ImplId>>>,
102 pub(crate) fn trait_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
103 let _p = profile::span("trait_impls_in_crate_query");
104 let mut impls = Self { map: FxHashMap::default() };
106 let crate_def_map = db.crate_def_map(krate);
107 collect_def_map(db, &crate_def_map, &mut impls);
109 return Arc::new(impls);
111 fn collect_def_map(db: &dyn HirDatabase, def_map: &DefMap, impls: &mut TraitImpls) {
112 for (_module_id, module_data) in def_map.modules() {
113 for impl_id in module_data.scope.impls() {
114 let target_trait = match db.impl_trait(impl_id) {
115 Some(tr) => tr.skip_binders().hir_trait_id(),
118 let self_ty = db.impl_self_ty(impl_id);
119 let self_ty_fp = TyFingerprint::for_impl(self_ty.skip_binders());
129 // To better support custom derives, collect impls in all unnamed const items.
130 // const _: () = { ... };
131 for konst in module_data.scope.unnamed_consts() {
132 let body = db.body(konst.into());
133 for (_, block_def_map) in body.blocks(db.upcast()) {
134 collect_def_map(db, &block_def_map, impls);
141 pub(crate) fn trait_impls_in_deps_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
142 let _p = profile::span("trait_impls_in_deps_query");
143 let crate_graph = db.crate_graph();
144 let mut res = Self { map: FxHashMap::default() };
146 for krate in crate_graph.transitive_deps(krate) {
147 res.merge(&db.trait_impls_in_crate(krate));
153 fn merge(&mut self, other: &Self) {
154 for (trait_, other_map) in &other.map {
155 let map = self.map.entry(*trait_).or_default();
156 for (fp, impls) in other_map {
157 let vec = map.entry(*fp).or_default();
163 /// Queries all trait impls for the given type.
164 pub fn for_self_ty(&self, fp: TyFingerprint) -> impl Iterator<Item = ImplId> + '_ {
167 .flat_map(move |impls| impls.get(&None).into_iter().chain(impls.get(&Some(fp))))
168 .flat_map(|it| it.iter().copied())
171 /// Queries all impls of the given trait.
172 pub fn for_trait(&self, trait_: TraitId) -> impl Iterator<Item = ImplId> + '_ {
176 .flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
179 /// Queries all impls of `trait_` that may apply to `self_ty`.
180 pub fn for_trait_and_self_ty(
183 self_ty: TyFingerprint,
184 ) -> impl Iterator<Item = ImplId> + '_ {
188 .flat_map(move |map| map.get(&None).into_iter().chain(map.get(&Some(self_ty))))
189 .flat_map(|v| v.iter().copied())
192 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
193 self.map.values().flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
197 /// Inherent impls defined in some crate.
199 /// Inherent impls can only be defined in the crate that also defines the self type of the impl
200 /// (note that some primitives are considered to be defined by both libcore and liballoc).
202 /// This makes inherent impl lookup easier than trait impl lookup since we only have to consider a
204 #[derive(Debug, Eq, PartialEq)]
205 pub struct InherentImpls {
206 map: FxHashMap<TyFingerprint, Vec<ImplId>>,
210 pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
211 let mut map: FxHashMap<_, Vec<_>> = FxHashMap::default();
213 let crate_def_map = db.crate_def_map(krate);
214 for (_module_id, module_data) in crate_def_map.modules() {
215 for impl_id in module_data.scope.impls() {
216 let data = db.impl_data(impl_id);
217 if data.target_trait.is_some() {
221 let self_ty = db.impl_self_ty(impl_id);
222 if let Some(fp) = TyFingerprint::for_impl(self_ty.skip_binders()) {
223 map.entry(fp).or_default().push(impl_id);
228 // NOTE: We're not collecting inherent impls from unnamed consts here, we intentionally only
229 // support trait impls there.
231 Arc::new(Self { map })
234 pub fn for_self_ty(&self, self_ty: &Ty) -> &[ImplId] {
235 match TyFingerprint::for_impl(self_ty) {
236 Some(fp) => self.map.get(&fp).map(|vec| vec.as_ref()).unwrap_or(&[]),
241 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
242 self.map.values().flat_map(|v| v.iter().copied())
247 db: &dyn HirDatabase,
250 ) -> Option<ArrayVec<CrateId, 2>> {
251 // Types like slice can have inherent impls in several crates, (core and alloc).
252 // The corresponding impls are marked with lang items, so we can use them to find the required crates.
253 macro_rules! lang_item_crate {
254 ($($name:expr),+ $(,)?) => {{
255 let mut v = ArrayVec::<LangItemTarget, 2>::new();
257 v.extend(db.lang_item(cur_crate, $name.into()));
263 let mod_to_crate_ids = |module: ModuleId| Some(std::iter::once(module.krate()).collect());
265 let lang_item_targets = match ty.kind(&Interner) {
266 TyKind::Adt(AdtId(def_id), _) => {
267 return mod_to_crate_ids(def_id.module(db.upcast()));
269 TyKind::Foreign(id) => {
270 return mod_to_crate_ids(
271 from_foreign_def_id(*id).lookup(db.upcast()).module(db.upcast()),
274 TyKind::Scalar(Scalar::Bool) => lang_item_crate!("bool"),
275 TyKind::Scalar(Scalar::Char) => lang_item_crate!("char"),
276 TyKind::Scalar(Scalar::Float(f)) => match f {
277 // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime)
278 FloatTy::F32 => lang_item_crate!("f32", "f32_runtime"),
279 FloatTy::F64 => lang_item_crate!("f64", "f64_runtime"),
281 &TyKind::Scalar(Scalar::Int(t)) => {
282 lang_item_crate!(primitive::int_ty_to_string(t))
284 &TyKind::Scalar(Scalar::Uint(t)) => {
285 lang_item_crate!(primitive::uint_ty_to_string(t))
287 TyKind::Str => lang_item_crate!("str_alloc", "str"),
288 TyKind::Slice(_) => lang_item_crate!("slice_alloc", "slice"),
289 TyKind::Raw(Mutability::Not, _) => lang_item_crate!("const_ptr"),
290 TyKind::Raw(Mutability::Mut, _) => lang_item_crate!("mut_ptr"),
292 return ty.dyn_trait().and_then(|trait_| {
293 mod_to_crate_ids(GenericDefId::TraitId(trait_).module(db.upcast()))
298 let res = lang_item_targets
300 .filter_map(|it| match it {
301 LangItemTarget::ImplDefId(it) => Some(it),
304 .map(|it| it.lookup(db.upcast()).container.krate())
309 /// Look up the method with the given name, returning the actual autoderefed
310 /// receiver type (but without autoref applied yet).
311 pub(crate) fn lookup_method(
313 db: &dyn HirDatabase,
314 env: Arc<TraitEnvironment>,
316 traits_in_scope: &FxHashSet<TraitId>,
317 visible_from_module: Option<ModuleId>,
319 ) -> Option<(Ty, FunctionId)> {
320 iterate_method_candidates(
328 LookupMode::MethodCall,
330 AssocItemId::FunctionId(f) => Some((ty.clone(), f)),
336 /// Whether we're looking up a dotted method call (like `v.len()`) or a path
337 /// (like `Vec::new`).
338 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
339 pub enum LookupMode {
340 /// Looking up a method call like `v.len()`: We only consider candidates
341 /// that have a `self` parameter, and do autoderef.
343 /// Looking up a path like `Vec::new` or `Vec::default`: We consider all
344 /// candidates including associated constants, but don't do autoderef.
348 // This would be nicer if it just returned an iterator, but that runs into
349 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
350 // FIXME add a context type here?
351 pub fn iterate_method_candidates<T>(
353 db: &dyn HirDatabase,
354 env: Arc<TraitEnvironment>,
356 traits_in_scope: &FxHashSet<TraitId>,
357 visible_from_module: Option<ModuleId>,
360 mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>,
363 iterate_method_candidates_impl(
373 assert!(slot.is_none());
374 slot = callback(ty, item);
381 fn iterate_method_candidates_impl(
383 db: &dyn HirDatabase,
384 env: Arc<TraitEnvironment>,
386 traits_in_scope: &FxHashSet<TraitId>,
387 visible_from_module: Option<ModuleId>,
390 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
393 LookupMode::MethodCall => {
394 // For method calls, rust first does any number of autoderef, and then one
395 // autoref (i.e. when the method takes &self or &mut self). We just ignore
396 // the autoref currently -- when we find a method matching the given name,
397 // we assume it fits.
399 // Also note that when we've got a receiver like &S, even if the method we
400 // find in the end takes &self, we still do the autoderef step (just as
401 // rustc does an autoderef and then autoref again).
402 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
404 // We have to be careful about the order we're looking at candidates
405 // in here. Consider the case where we're resolving `x.clone()`
406 // where `x: &Vec<_>`. This resolves to the clone method with self
407 // type `Vec<_>`, *not* `&_`. I.e. we need to consider methods where
408 // the receiver type exactly matches before cases where we have to
409 // do autoref. But in the autoderef steps, the `&_` self type comes
410 // up *before* the `Vec<_>` self type.
412 // On the other hand, we don't want to just pick any by-value method
413 // before any by-autoref method; it's just that we need to consider
414 // the methods by autoderef order of *receiver types*, not *self
417 let deref_chain = autoderef_method_receiver(db, krate, ty);
418 for i in 0..deref_chain.len() {
419 if iterate_method_candidates_with_autoref(
434 LookupMode::Path => {
435 // No autoderef for path lookups
436 iterate_method_candidates_for_self_ty(
450 fn iterate_method_candidates_with_autoref(
451 deref_chain: &[Canonical<Ty>],
452 db: &dyn HirDatabase,
453 env: Arc<TraitEnvironment>,
455 traits_in_scope: &FxHashSet<TraitId>,
456 visible_from_module: Option<ModuleId>,
458 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
460 if iterate_method_candidates_by_receiver(
473 let refed = Canonical {
474 binders: deref_chain[0].binders.clone(),
475 value: TyKind::Ref(Mutability::Not, static_lifetime(), deref_chain[0].value.clone())
478 if iterate_method_candidates_by_receiver(
491 let ref_muted = Canonical {
492 binders: deref_chain[0].binders.clone(),
493 value: TyKind::Ref(Mutability::Mut, static_lifetime(), deref_chain[0].value.clone())
496 if iterate_method_candidates_by_receiver(
512 fn iterate_method_candidates_by_receiver(
513 receiver_ty: &Canonical<Ty>,
514 rest_of_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 // We're looking for methods with *receiver* type receiver_ty. These could
524 // be found in any of the derefs of receiver_ty, so we have to go through
526 for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
527 if iterate_inherent_methods(
539 for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
540 if iterate_trait_method_candidates(
556 fn iterate_method_candidates_for_self_ty(
557 self_ty: &Canonical<Ty>,
558 db: &dyn HirDatabase,
559 env: Arc<TraitEnvironment>,
561 traits_in_scope: &FxHashSet<TraitId>,
562 visible_from_module: Option<ModuleId>,
564 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
566 if iterate_inherent_methods(self_ty, db, name, None, krate, visible_from_module, &mut callback)
570 iterate_trait_method_candidates(self_ty, db, env, krate, traits_in_scope, name, None, callback)
573 fn iterate_trait_method_candidates(
574 self_ty: &Canonical<Ty>,
575 db: &dyn HirDatabase,
576 env: Arc<TraitEnvironment>,
578 traits_in_scope: &FxHashSet<TraitId>,
580 receiver_ty: Option<&Canonical<Ty>>,
581 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
583 // if ty is `dyn Trait`, the trait doesn't need to be in scope
585 self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t));
586 let env_traits = if let TyKind::Placeholder(_) = self_ty.value.kind(&Interner) {
587 // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
588 env.traits_in_scope_from_clauses(&self_ty.value)
589 .flat_map(|t| all_super_traits(db.upcast(), t))
595 inherent_trait.chain(env_traits.into_iter()).chain(traits_in_scope.iter().copied());
596 'traits: for t in traits {
597 let data = db.trait_data(t);
599 // we'll be lazy about checking whether the type implements the
600 // trait, but if we find out it doesn't, we'll skip the rest of the
602 let mut known_implemented = false;
603 for (_name, item) in data.items.iter() {
604 // Don't pass a `visible_from_module` down to `is_valid_candidate`,
605 // since only inherent methods should be included into visibility checking.
606 if !is_valid_candidate(db, name, receiver_ty, *item, self_ty, None) {
609 if !known_implemented {
610 let goal = generic_implements_goal(db, env.clone(), t, self_ty.clone());
611 if db.trait_solve(krate, goal).is_none() {
615 known_implemented = true;
616 if callback(&self_ty.value, *item) {
624 fn iterate_inherent_methods(
625 self_ty: &Canonical<Ty>,
626 db: &dyn HirDatabase,
628 receiver_ty: Option<&Canonical<Ty>>,
630 visible_from_module: Option<ModuleId>,
631 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
633 let def_crates = match def_crates(db, &self_ty.value, krate) {
635 None => return false,
637 for krate in def_crates {
638 let impls = db.inherent_impls_in_crate(krate);
640 for &impl_def in impls.for_self_ty(&self_ty.value) {
641 for &item in db.impl_data(impl_def).items.iter() {
642 if !is_valid_candidate(db, name, receiver_ty, item, self_ty, visible_from_module) {
645 // we have to check whether the self type unifies with the type
646 // that the impl is for. If we have a receiver type, this
647 // already happens in `is_valid_candidate` above; if not, we
649 if receiver_ty.is_none() && inherent_impl_substs(db, impl_def, self_ty).is_none() {
650 cov_mark::hit!(impl_self_type_match_without_receiver);
653 if callback(&self_ty.value, item) {
662 /// Returns the self type for the index trait call.
663 pub fn resolve_indexing_op(
664 db: &dyn HirDatabase,
666 env: Arc<TraitEnvironment>,
668 index_trait: TraitId,
669 ) -> Option<Canonical<Ty>> {
670 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
671 let deref_chain = autoderef_method_receiver(db, krate, ty);
672 for ty in deref_chain {
673 let goal = generic_implements_goal(db, env.clone(), index_trait, ty.clone());
674 if db.trait_solve(krate, goal).is_some() {
681 fn is_valid_candidate(
682 db: &dyn HirDatabase,
684 receiver_ty: Option<&Canonical<Ty>>,
686 self_ty: &Canonical<Ty>,
687 visible_from_module: Option<ModuleId>,
690 AssocItemId::FunctionId(m) => {
691 let data = db.function_data(m);
692 if let Some(name) = name {
693 if &data.name != name {
697 if let Some(receiver_ty) = receiver_ty {
698 if !data.has_self_param() {
701 let transformed_receiver_ty = match transform_receiver_ty(db, m, self_ty) {
703 None => return false,
705 if transformed_receiver_ty != receiver_ty.value {
709 if let Some(from_module) = visible_from_module {
710 if !db.function_visibility(m).is_visible_from(db.upcast(), from_module) {
711 cov_mark::hit!(autoderef_candidate_not_visible);
718 AssocItemId::ConstId(c) => {
719 let data = db.const_data(c);
720 name.map_or(true, |name| data.name.as_ref() == Some(name)) && receiver_ty.is_none()
726 pub(crate) fn inherent_impl_substs(
727 db: &dyn HirDatabase,
729 self_ty: &Canonical<Ty>,
730 ) -> Option<Substitution> {
731 // we create a var for each type parameter of the impl; we need to keep in
732 // mind here that `self_ty` might have vars of its own
733 let self_ty_vars = self_ty.binders.len(&Interner);
734 let vars = TyBuilder::subst_for_def(db, impl_id)
735 .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty_vars)
737 let self_ty_with_vars = db.impl_self_ty(impl_id).substitute(&Interner, &vars);
738 let mut kinds = self_ty.binders.interned().to_vec();
740 iter::repeat(chalk_ir::WithKind::new(
741 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
744 .take(vars.len(&Interner)),
746 let tys = Canonical {
747 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
748 value: (self_ty_with_vars, self_ty.value.clone()),
750 let substs = super::infer::unify(&tys)?;
751 // We only want the substs for the vars we added, not the ones from self_ty.
752 // Also, if any of the vars we added are still in there, we replace them by
753 // Unknown. I think this can only really happen if self_ty contained
754 // Unknown, and in that case we want the result to contain Unknown in those
757 Substitution::from_iter(&Interner, substs.iter(&Interner).cloned().skip(self_ty_vars));
758 Some(fallback_bound_vars(suffix, self_ty_vars))
761 /// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
762 /// num_vars_to_keep) by `TyKind::Unknown`.
763 fn fallback_bound_vars(s: Substitution, num_vars_to_keep: usize) -> Substitution {
764 crate::fold_free_vars(s, |bound, binders| {
765 if bound.index >= num_vars_to_keep && bound.debruijn == DebruijnIndex::INNERMOST {
766 TyKind::Error.intern(&Interner)
768 bound.shifted_in_from(binders).to_ty(&Interner)
773 fn transform_receiver_ty(
774 db: &dyn HirDatabase,
775 function_id: FunctionId,
776 self_ty: &Canonical<Ty>,
778 let substs = match function_id.lookup(db.upcast()).container {
779 AssocContainerId::TraitId(_) => TyBuilder::subst_for_def(db, function_id)
780 .push(self_ty.value.clone())
783 AssocContainerId::ImplId(impl_id) => {
784 let impl_substs = inherent_impl_substs(db, impl_id, &self_ty)?;
785 TyBuilder::subst_for_def(db, function_id)
786 .use_parent_substs(&impl_substs)
790 AssocContainerId::ModuleId(_) => unreachable!(),
792 let sig = db.callable_item_signature(function_id.into());
793 Some(sig.map(|s| s.params()[0].clone()).substitute(&Interner, &substs))
796 pub fn implements_trait(
798 db: &dyn HirDatabase,
799 env: Arc<TraitEnvironment>,
803 let goal = generic_implements_goal(db, env, trait_, ty.clone());
804 let solution = db.trait_solve(krate, goal);
809 pub fn implements_trait_unique(
811 db: &dyn HirDatabase,
812 env: Arc<TraitEnvironment>,
816 let goal = generic_implements_goal(db, env, trait_, ty.clone());
817 let solution = db.trait_solve(krate, goal);
819 matches!(solution, Some(crate::Solution::Unique(_)))
822 /// This creates Substs for a trait with the given Self type and type variables
823 /// for all other parameters, to query Chalk with it.
824 fn generic_implements_goal(
825 db: &dyn HirDatabase,
826 env: Arc<TraitEnvironment>,
828 self_ty: Canonical<Ty>,
829 ) -> Canonical<InEnvironment<super::DomainGoal>> {
830 let mut kinds = self_ty.binders.interned().to_vec();
831 let trait_ref = TyBuilder::trait_ref(db, trait_)
833 .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
836 iter::repeat(chalk_ir::WithKind::new(
837 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
840 .take(trait_ref.substitution.len(&Interner) - 1),
842 let obligation = trait_ref.cast(&Interner);
844 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
845 value: InEnvironment::new(&env.env, obligation),
849 fn autoderef_method_receiver(
850 db: &dyn HirDatabase,
852 ty: InEnvironment<Canonical<Ty>>,
853 ) -> Vec<Canonical<Ty>> {
854 let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
855 // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
856 if let Some(TyKind::Array(parameters, _)) =
857 deref_chain.last().map(|ty| ty.value.kind(&Interner))
859 let kinds = deref_chain.last().unwrap().binders.clone();
860 let unsized_ty = TyKind::Slice(parameters.clone()).intern(&Interner);
861 deref_chain.push(Canonical { value: unsized_ty, binders: kinds })