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, nameres::DefMap, AssocContainerId, AssocItemId, 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, FnPointer, FnSig, ForeignDefId,
25 InEnvironment, Interner, Scalar, Substitution, TraitEnvironment, TraitRefExt, Ty, TyBuilder,
26 TyExt, TyKind, TypeWalk,
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 collect_def_map(db, &crate_def_map, &mut impls);
105 return Arc::new(impls);
107 fn collect_def_map(db: &dyn HirDatabase, def_map: &DefMap, impls: &mut TraitImpls) {
108 for (_module_id, module_data) in def_map.modules() {
109 for impl_id in module_data.scope.impls() {
110 let target_trait = match db.impl_trait(impl_id) {
111 Some(tr) => tr.skip_binders().hir_trait_id(),
114 let self_ty = db.impl_self_ty(impl_id);
115 let self_ty_fp = TyFingerprint::for_impl(self_ty.skip_binders());
125 // To better support custom derives, collect impls in all unnamed const items.
126 // const _: () = { ... };
127 for konst in module_data.scope.unnamed_consts() {
128 let body = db.body(konst.into());
129 for (_, block_def_map) in body.blocks(db.upcast()) {
130 collect_def_map(db, &block_def_map, impls);
137 pub(crate) fn trait_impls_in_deps_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
138 let _p = profile::span("trait_impls_in_deps_query");
139 let crate_graph = db.crate_graph();
140 let mut res = Self { map: FxHashMap::default() };
142 for krate in crate_graph.transitive_deps(krate) {
143 res.merge(&db.trait_impls_in_crate(krate));
149 fn merge(&mut self, other: &Self) {
150 for (trait_, other_map) in &other.map {
151 let map = self.map.entry(*trait_).or_default();
152 for (fp, impls) in other_map {
153 let vec = map.entry(*fp).or_default();
159 /// Queries all trait impls for the given type.
160 pub fn for_self_ty(&self, fp: TyFingerprint) -> impl Iterator<Item = ImplId> + '_ {
163 .flat_map(move |impls| impls.get(&None).into_iter().chain(impls.get(&Some(fp))))
164 .flat_map(|it| it.iter().copied())
167 /// Queries all impls of the given trait.
168 pub fn for_trait(&self, trait_: TraitId) -> impl Iterator<Item = ImplId> + '_ {
172 .flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
175 /// Queries all impls of `trait_` that may apply to `self_ty`.
176 pub fn for_trait_and_self_ty(
179 self_ty: TyFingerprint,
180 ) -> impl Iterator<Item = ImplId> + '_ {
184 .flat_map(move |map| map.get(&None).into_iter().chain(map.get(&Some(self_ty))))
185 .flat_map(|v| v.iter().copied())
188 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
189 self.map.values().flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
193 /// Inherent impls defined in some crate.
195 /// Inherent impls can only be defined in the crate that also defines the self type of the impl
196 /// (note that some primitives are considered to be defined by both libcore and liballoc).
198 /// This makes inherent impl lookup easier than trait impl lookup since we only have to consider a
200 #[derive(Debug, Eq, PartialEq)]
201 pub struct InherentImpls {
202 map: FxHashMap<TyFingerprint, Vec<ImplId>>,
206 pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
207 let mut map: FxHashMap<_, Vec<_>> = FxHashMap::default();
209 let crate_def_map = db.crate_def_map(krate);
210 for (_module_id, module_data) in crate_def_map.modules() {
211 for impl_id in module_data.scope.impls() {
212 let data = db.impl_data(impl_id);
213 if data.target_trait.is_some() {
217 let self_ty = db.impl_self_ty(impl_id);
218 if let Some(fp) = TyFingerprint::for_impl(self_ty.skip_binders()) {
219 map.entry(fp).or_default().push(impl_id);
224 // NOTE: We're not collecting inherent impls from unnamed consts here, we intentionally only
225 // support trait impls there.
227 Arc::new(Self { map })
230 pub fn for_self_ty(&self, self_ty: &Ty) -> &[ImplId] {
231 match TyFingerprint::for_impl(self_ty) {
232 Some(fp) => self.map.get(&fp).map(|vec| vec.as_ref()).unwrap_or(&[]),
237 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
238 self.map.values().flat_map(|v| v.iter().copied())
243 db: &dyn HirDatabase,
246 ) -> Option<ArrayVec<CrateId, 2>> {
247 // Types like slice can have inherent impls in several crates, (core and alloc).
248 // The corresponding impls are marked with lang items, so we can use them to find the required crates.
249 macro_rules! lang_item_crate {
250 ($($name:expr),+ $(,)?) => {{
251 let mut v = ArrayVec::<LangItemTarget, 2>::new();
253 v.extend(db.lang_item(cur_crate, $name.into()));
259 let mod_to_crate_ids = |module: ModuleId| Some(std::iter::once(module.krate()).collect());
261 let lang_item_targets = match ty.kind(&Interner) {
262 TyKind::Adt(AdtId(def_id), _) => {
263 return mod_to_crate_ids(def_id.module(db.upcast()));
265 TyKind::Foreign(id) => {
266 return mod_to_crate_ids(
267 from_foreign_def_id(*id).lookup(db.upcast()).module(db.upcast()),
270 TyKind::Scalar(Scalar::Bool) => lang_item_crate!("bool"),
271 TyKind::Scalar(Scalar::Char) => lang_item_crate!("char"),
272 TyKind::Scalar(Scalar::Float(f)) => match f {
273 // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime)
274 FloatTy::F32 => lang_item_crate!("f32", "f32_runtime"),
275 FloatTy::F64 => lang_item_crate!("f64", "f64_runtime"),
277 &TyKind::Scalar(Scalar::Int(t)) => {
278 lang_item_crate!(primitive::int_ty_to_string(t))
280 &TyKind::Scalar(Scalar::Uint(t)) => {
281 lang_item_crate!(primitive::uint_ty_to_string(t))
283 TyKind::Str => lang_item_crate!("str_alloc", "str"),
284 TyKind::Slice(_) => lang_item_crate!("slice_alloc", "slice"),
285 TyKind::Raw(Mutability::Not, _) => lang_item_crate!("const_ptr"),
286 TyKind::Raw(Mutability::Mut, _) => lang_item_crate!("mut_ptr"),
288 return ty.dyn_trait().and_then(|trait_| {
289 mod_to_crate_ids(GenericDefId::TraitId(trait_).module(db.upcast()))
294 let res = lang_item_targets
296 .filter_map(|it| match it {
297 LangItemTarget::ImplDefId(it) => Some(it),
300 .map(|it| it.lookup(db.upcast()).container.krate())
305 /// Look up the method with the given name, returning the actual autoderefed
306 /// receiver type (but without autoref applied yet).
307 pub(crate) fn lookup_method(
309 db: &dyn HirDatabase,
310 env: Arc<TraitEnvironment>,
312 traits_in_scope: &FxHashSet<TraitId>,
313 visible_from_module: Option<ModuleId>,
315 ) -> Option<(Ty, FunctionId)> {
316 iterate_method_candidates(
324 LookupMode::MethodCall,
326 AssocItemId::FunctionId(f) => Some((ty.clone(), f)),
332 /// Whether we're looking up a dotted method call (like `v.len()`) or a path
333 /// (like `Vec::new`).
334 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
335 pub enum LookupMode {
336 /// Looking up a method call like `v.len()`: We only consider candidates
337 /// that have a `self` parameter, and do autoderef.
339 /// Looking up a path like `Vec::new` or `Vec::default`: We consider all
340 /// candidates including associated constants, but don't do autoderef.
344 // This would be nicer if it just returned an iterator, but that runs into
345 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
346 // FIXME add a context type here?
347 pub fn iterate_method_candidates<T>(
349 db: &dyn HirDatabase,
350 env: Arc<TraitEnvironment>,
352 traits_in_scope: &FxHashSet<TraitId>,
353 visible_from_module: Option<ModuleId>,
356 mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>,
359 iterate_method_candidates_impl(
369 assert!(slot.is_none());
370 slot = callback(ty, item);
377 fn iterate_method_candidates_impl(
379 db: &dyn HirDatabase,
380 env: Arc<TraitEnvironment>,
382 traits_in_scope: &FxHashSet<TraitId>,
383 visible_from_module: Option<ModuleId>,
386 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
389 LookupMode::MethodCall => {
390 // For method calls, rust first does any number of autoderef, and then one
391 // autoref (i.e. when the method takes &self or &mut self). We just ignore
392 // the autoref currently -- when we find a method matching the given name,
393 // we assume it fits.
395 // Also note that when we've got a receiver like &S, even if the method we
396 // find in the end takes &self, we still do the autoderef step (just as
397 // rustc does an autoderef and then autoref again).
398 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
400 // We have to be careful about the order we're looking at candidates
401 // in here. Consider the case where we're resolving `x.clone()`
402 // where `x: &Vec<_>`. This resolves to the clone method with self
403 // type `Vec<_>`, *not* `&_`. I.e. we need to consider methods where
404 // the receiver type exactly matches before cases where we have to
405 // do autoref. But in the autoderef steps, the `&_` self type comes
406 // up *before* the `Vec<_>` self type.
408 // On the other hand, we don't want to just pick any by-value method
409 // before any by-autoref method; it's just that we need to consider
410 // the methods by autoderef order of *receiver types*, not *self
413 let deref_chain = autoderef_method_receiver(db, krate, ty);
414 for i in 0..deref_chain.len() {
415 if iterate_method_candidates_with_autoref(
430 LookupMode::Path => {
431 // No autoderef for path lookups
432 iterate_method_candidates_for_self_ty(
446 fn iterate_method_candidates_with_autoref(
447 deref_chain: &[Canonical<Ty>],
448 db: &dyn HirDatabase,
449 env: Arc<TraitEnvironment>,
451 traits_in_scope: &FxHashSet<TraitId>,
452 visible_from_module: Option<ModuleId>,
454 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
456 if iterate_method_candidates_by_receiver(
469 let refed = Canonical {
470 binders: deref_chain[0].binders.clone(),
471 value: TyKind::Ref(Mutability::Not, static_lifetime(), deref_chain[0].value.clone())
474 if iterate_method_candidates_by_receiver(
487 let ref_muted = Canonical {
488 binders: deref_chain[0].binders.clone(),
489 value: TyKind::Ref(Mutability::Mut, static_lifetime(), deref_chain[0].value.clone())
492 if iterate_method_candidates_by_receiver(
508 fn iterate_method_candidates_by_receiver(
509 receiver_ty: &Canonical<Ty>,
510 rest_of_deref_chain: &[Canonical<Ty>],
511 db: &dyn HirDatabase,
512 env: Arc<TraitEnvironment>,
514 traits_in_scope: &FxHashSet<TraitId>,
515 visible_from_module: Option<ModuleId>,
517 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
519 // We're looking for methods with *receiver* type receiver_ty. These could
520 // be found in any of the derefs of receiver_ty, so we have to go through
522 for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
523 if iterate_inherent_methods(
535 for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
536 if iterate_trait_method_candidates(
552 fn iterate_method_candidates_for_self_ty(
553 self_ty: &Canonical<Ty>,
554 db: &dyn HirDatabase,
555 env: Arc<TraitEnvironment>,
557 traits_in_scope: &FxHashSet<TraitId>,
558 visible_from_module: Option<ModuleId>,
560 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
562 if iterate_inherent_methods(self_ty, db, name, None, krate, visible_from_module, &mut callback)
566 iterate_trait_method_candidates(self_ty, db, env, krate, traits_in_scope, name, None, callback)
569 fn iterate_trait_method_candidates(
570 self_ty: &Canonical<Ty>,
571 db: &dyn HirDatabase,
572 env: Arc<TraitEnvironment>,
574 traits_in_scope: &FxHashSet<TraitId>,
576 receiver_ty: Option<&Canonical<Ty>>,
577 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
579 // if ty is `dyn Trait`, the trait doesn't need to be in scope
581 self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t));
582 let env_traits = if let TyKind::Placeholder(_) = self_ty.value.kind(&Interner) {
583 // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
584 env.traits_in_scope_from_clauses(&self_ty.value)
585 .flat_map(|t| all_super_traits(db.upcast(), t))
591 inherent_trait.chain(env_traits.into_iter()).chain(traits_in_scope.iter().copied());
592 'traits: for t in traits {
593 let data = db.trait_data(t);
595 // we'll be lazy about checking whether the type implements the
596 // trait, but if we find out it doesn't, we'll skip the rest of the
598 let mut known_implemented = false;
599 for (_name, item) in data.items.iter() {
600 // Don't pass a `visible_from_module` down to `is_valid_candidate`,
601 // since only inherent methods should be included into visibility checking.
602 if !is_valid_candidate(db, name, receiver_ty, *item, self_ty, None) {
605 if !known_implemented {
606 let goal = generic_implements_goal(db, env.clone(), t, self_ty.clone());
607 if db.trait_solve(krate, goal).is_none() {
611 known_implemented = true;
612 if callback(&self_ty.value, *item) {
620 fn iterate_inherent_methods(
621 self_ty: &Canonical<Ty>,
622 db: &dyn HirDatabase,
624 receiver_ty: Option<&Canonical<Ty>>,
626 visible_from_module: Option<ModuleId>,
627 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
629 let def_crates = match def_crates(db, &self_ty.value, krate) {
631 None => return false,
633 for krate in def_crates {
634 let impls = db.inherent_impls_in_crate(krate);
636 for &impl_def in impls.for_self_ty(&self_ty.value) {
637 for &item in db.impl_data(impl_def).items.iter() {
638 if !is_valid_candidate(db, name, receiver_ty, item, self_ty, visible_from_module) {
641 // we have to check whether the self type unifies with the type
642 // that the impl is for. If we have a receiver type, this
643 // already happens in `is_valid_candidate` above; if not, we
645 if receiver_ty.is_none() && inherent_impl_substs(db, impl_def, self_ty).is_none() {
646 cov_mark::hit!(impl_self_type_match_without_receiver);
649 if callback(&self_ty.value, item) {
658 /// Returns the self type for the index trait call.
659 pub fn resolve_indexing_op(
660 db: &dyn HirDatabase,
662 env: Arc<TraitEnvironment>,
664 index_trait: TraitId,
665 ) -> Option<Canonical<Ty>> {
666 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
667 let deref_chain = autoderef_method_receiver(db, krate, ty);
668 for ty in deref_chain {
669 let goal = generic_implements_goal(db, env.clone(), index_trait, ty.clone());
670 if db.trait_solve(krate, goal).is_some() {
677 fn is_valid_candidate(
678 db: &dyn HirDatabase,
680 receiver_ty: Option<&Canonical<Ty>>,
682 self_ty: &Canonical<Ty>,
683 visible_from_module: Option<ModuleId>,
686 AssocItemId::FunctionId(m) => {
687 let data = db.function_data(m);
688 if let Some(name) = name {
689 if &data.name != name {
693 if let Some(receiver_ty) = receiver_ty {
694 if !data.has_self_param() {
697 let transformed_receiver_ty = match transform_receiver_ty(db, m, self_ty) {
699 None => return false,
701 if transformed_receiver_ty != receiver_ty.value {
705 if let Some(from_module) = visible_from_module {
706 if !db.function_visibility(m).is_visible_from(db.upcast(), from_module) {
707 cov_mark::hit!(autoderef_candidate_not_visible);
714 AssocItemId::ConstId(c) => {
715 let data = db.const_data(c);
716 name.map_or(true, |name| data.name.as_ref() == Some(name)) && receiver_ty.is_none()
722 pub(crate) fn inherent_impl_substs(
723 db: &dyn HirDatabase,
725 self_ty: &Canonical<Ty>,
726 ) -> Option<Substitution> {
727 // we create a var for each type parameter of the impl; we need to keep in
728 // mind here that `self_ty` might have vars of its own
729 let self_ty_vars = self_ty.binders.len(&Interner);
730 let vars = TyBuilder::subst_for_def(db, impl_id)
731 .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty_vars)
733 let self_ty_with_vars = db.impl_self_ty(impl_id).substitute(&Interner, &vars);
734 let mut kinds = self_ty.binders.interned().to_vec();
736 iter::repeat(chalk_ir::WithKind::new(
737 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
740 .take(vars.len(&Interner)),
742 let tys = Canonical {
743 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
744 value: (self_ty_with_vars, self_ty.value.clone()),
746 let substs = super::infer::unify(&tys)?;
747 // We only want the substs for the vars we added, not the ones from self_ty.
748 // Also, if any of the vars we added are still in there, we replace them by
749 // Unknown. I think this can only really happen if self_ty contained
750 // Unknown, and in that case we want the result to contain Unknown in those
753 Substitution::from_iter(&Interner, substs.iter(&Interner).cloned().skip(self_ty_vars));
754 Some(fallback_bound_vars(suffix, self_ty_vars))
757 /// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
758 /// num_vars_to_keep) by `TyKind::Unknown`.
759 fn fallback_bound_vars(s: Substitution, num_vars_to_keep: usize) -> Substitution {
762 if let TyKind::BoundVar(bound) = ty.kind(&Interner) {
763 if bound.index >= num_vars_to_keep && bound.debruijn >= binders {
764 TyKind::Error.intern(&Interner)
772 DebruijnIndex::INNERMOST,
776 fn transform_receiver_ty(
777 db: &dyn HirDatabase,
778 function_id: FunctionId,
779 self_ty: &Canonical<Ty>,
781 let substs = match function_id.lookup(db.upcast()).container {
782 AssocContainerId::TraitId(_) => TyBuilder::subst_for_def(db, function_id)
783 .push(self_ty.value.clone())
786 AssocContainerId::ImplId(impl_id) => {
787 let impl_substs = inherent_impl_substs(db, impl_id, &self_ty)?;
788 TyBuilder::subst_for_def(db, function_id)
789 .use_parent_substs(&impl_substs)
793 AssocContainerId::ModuleId(_) => unreachable!(),
795 let sig = db.callable_item_signature(function_id.into());
796 Some(sig.map(|s| s.params()[0].clone()).substitute(&Interner, &substs))
799 pub fn implements_trait(
801 db: &dyn HirDatabase,
802 env: Arc<TraitEnvironment>,
806 let goal = generic_implements_goal(db, env, trait_, ty.clone());
807 let solution = db.trait_solve(krate, goal);
812 pub fn implements_trait_unique(
814 db: &dyn HirDatabase,
815 env: Arc<TraitEnvironment>,
819 let goal = generic_implements_goal(db, env, trait_, ty.clone());
820 let solution = db.trait_solve(krate, goal);
822 matches!(solution, Some(crate::Solution::Unique(_)))
825 /// This creates Substs for a trait with the given Self type and type variables
826 /// for all other parameters, to query Chalk with it.
827 fn generic_implements_goal(
828 db: &dyn HirDatabase,
829 env: Arc<TraitEnvironment>,
831 self_ty: Canonical<Ty>,
832 ) -> Canonical<InEnvironment<super::DomainGoal>> {
833 let mut kinds = self_ty.binders.interned().to_vec();
834 let trait_ref = TyBuilder::trait_ref(db, trait_)
836 .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
839 iter::repeat(chalk_ir::WithKind::new(
840 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
843 .take(trait_ref.substitution.len(&Interner) - 1),
845 let obligation = trait_ref.cast(&Interner);
847 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
848 value: InEnvironment::new(&env.env, obligation),
852 fn autoderef_method_receiver(
853 db: &dyn HirDatabase,
855 ty: InEnvironment<Canonical<Ty>>,
856 ) -> Vec<Canonical<Ty>> {
857 let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
858 // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
859 if let Some(TyKind::Array(parameters, _)) =
860 deref_chain.last().map(|ty| ty.value.kind(&Interner))
862 let kinds = deref_chain.last().unwrap().binders.clone();
863 let unsized_ty = TyKind::Slice(parameters.clone()).intern(&Interner);
864 deref_chain.push(Canonical { value: unsized_ty, binders: kinds })