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, ops::ControlFlow, 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};
19 consteval::{self, ConstExt},
22 primitive::{self, FloatTy, IntTy, UintTy},
24 utils::all_super_traits,
25 AdtId, Canonical, CanonicalVarKinds, DebruijnIndex, ForeignDefId, InEnvironment, Interner,
26 Scalar, Substitution, TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyExt, TyKind,
29 /// This is used as a key for indexing impls.
30 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
31 pub enum TyFingerprint {
32 // These are lang item impls:
39 // These can have user-defined impls:
42 ForeignType(ForeignDefId),
43 // These only exist for trait impls
50 /// Creates a TyFingerprint for looking up an inherent impl. Only certain
51 /// types can have inherent impls: if we have some `struct S`, we can have
52 /// an `impl S`, but not `impl &S`. Hence, this will return `None` for
53 /// reference types and such.
54 pub fn for_inherent_impl(ty: &Ty) -> Option<TyFingerprint> {
55 let fp = match ty.kind(&Interner) {
56 TyKind::Str => TyFingerprint::Str,
57 TyKind::Never => TyFingerprint::Never,
58 TyKind::Slice(..) => TyFingerprint::Slice,
59 TyKind::Array(..) => TyFingerprint::Array,
60 TyKind::Scalar(scalar) => TyFingerprint::Scalar(*scalar),
61 TyKind::Adt(AdtId(adt), _) => TyFingerprint::Adt(*adt),
62 TyKind::Raw(mutability, ..) => TyFingerprint::RawPtr(*mutability),
63 TyKind::Foreign(alias_id, ..) => TyFingerprint::ForeignType(*alias_id),
64 TyKind::Dyn(_) => ty.dyn_trait().map(TyFingerprint::Dyn)?,
70 /// Creates a TyFingerprint for looking up a trait impl.
71 pub fn for_trait_impl(ty: &Ty) -> Option<TyFingerprint> {
72 let fp = match ty.kind(&Interner) {
73 TyKind::Str => TyFingerprint::Str,
74 TyKind::Never => TyFingerprint::Never,
75 TyKind::Slice(..) => TyFingerprint::Slice,
76 TyKind::Array(..) => TyFingerprint::Array,
77 TyKind::Scalar(scalar) => TyFingerprint::Scalar(*scalar),
78 TyKind::Adt(AdtId(adt), _) => TyFingerprint::Adt(*adt),
79 TyKind::Raw(mutability, ..) => TyFingerprint::RawPtr(*mutability),
80 TyKind::Foreign(alias_id, ..) => TyFingerprint::ForeignType(*alias_id),
81 TyKind::Dyn(_) => ty.dyn_trait().map(TyFingerprint::Dyn)?,
82 TyKind::Ref(_, _, ty) => return TyFingerprint::for_trait_impl(ty),
83 TyKind::Tuple(_, subst) => {
84 let first_ty = subst.interned().get(0).map(|arg| arg.assert_ty_ref(&Interner));
85 if let Some(ty) = first_ty {
86 return TyFingerprint::for_trait_impl(ty);
91 TyKind::AssociatedType(_, _)
92 | TyKind::OpaqueType(_, _)
94 | TyKind::Closure(_, _)
95 | TyKind::Generator(..)
96 | TyKind::GeneratorWitness(..) => TyFingerprint::Unnameable,
97 TyKind::Function(fn_ptr) => {
98 TyFingerprint::Function(fn_ptr.substitution.0.len(&Interner) as u32)
101 | TyKind::Placeholder(_)
102 | TyKind::BoundVar(_)
103 | TyKind::InferenceVar(_, _)
104 | TyKind::Error => return None,
110 pub(crate) const ALL_INT_FPS: [TyFingerprint; 12] = [
111 TyFingerprint::Scalar(Scalar::Int(IntTy::I8)),
112 TyFingerprint::Scalar(Scalar::Int(IntTy::I16)),
113 TyFingerprint::Scalar(Scalar::Int(IntTy::I32)),
114 TyFingerprint::Scalar(Scalar::Int(IntTy::I64)),
115 TyFingerprint::Scalar(Scalar::Int(IntTy::I128)),
116 TyFingerprint::Scalar(Scalar::Int(IntTy::Isize)),
117 TyFingerprint::Scalar(Scalar::Uint(UintTy::U8)),
118 TyFingerprint::Scalar(Scalar::Uint(UintTy::U16)),
119 TyFingerprint::Scalar(Scalar::Uint(UintTy::U32)),
120 TyFingerprint::Scalar(Scalar::Uint(UintTy::U64)),
121 TyFingerprint::Scalar(Scalar::Uint(UintTy::U128)),
122 TyFingerprint::Scalar(Scalar::Uint(UintTy::Usize)),
125 pub(crate) const ALL_FLOAT_FPS: [TyFingerprint; 2] = [
126 TyFingerprint::Scalar(Scalar::Float(FloatTy::F32)),
127 TyFingerprint::Scalar(Scalar::Float(FloatTy::F64)),
130 /// Trait impls defined or available in some crate.
131 #[derive(Debug, Eq, PartialEq)]
132 pub struct TraitImpls {
133 // If the `Option<TyFingerprint>` is `None`, the impl may apply to any self type.
134 map: FxHashMap<TraitId, FxHashMap<Option<TyFingerprint>, Vec<ImplId>>>,
138 pub(crate) fn trait_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
139 let _p = profile::span("trait_impls_in_crate_query");
140 let mut impls = Self { map: FxHashMap::default() };
142 let crate_def_map = db.crate_def_map(krate);
143 impls.collect_def_map(db, &crate_def_map);
148 pub(crate) fn trait_impls_in_block_query(
149 db: &dyn HirDatabase,
151 ) -> Option<Arc<Self>> {
152 let _p = profile::span("trait_impls_in_block_query");
153 let mut impls = Self { map: FxHashMap::default() };
155 let block_def_map = db.block_def_map(block)?;
156 impls.collect_def_map(db, &block_def_map);
158 Some(Arc::new(impls))
161 fn collect_def_map(&mut self, db: &dyn HirDatabase, def_map: &DefMap) {
162 for (_module_id, module_data) in def_map.modules() {
163 for impl_id in module_data.scope.impls() {
164 let target_trait = match db.impl_trait(impl_id) {
165 Some(tr) => tr.skip_binders().hir_trait_id(),
168 let self_ty = db.impl_self_ty(impl_id);
169 let self_ty_fp = TyFingerprint::for_trait_impl(self_ty.skip_binders());
178 // To better support custom derives, collect impls in all unnamed const items.
179 // const _: () = { ... };
180 for konst in module_data.scope.unnamed_consts() {
181 let body = db.body(konst.into());
182 for (_, block_def_map) in body.blocks(db.upcast()) {
183 self.collect_def_map(db, &block_def_map);
189 pub(crate) fn trait_impls_in_deps_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
190 let _p = profile::span("trait_impls_in_deps_query");
191 let crate_graph = db.crate_graph();
192 let mut res = Self { map: FxHashMap::default() };
194 for krate in crate_graph.transitive_deps(krate) {
195 res.merge(&db.trait_impls_in_crate(krate));
201 fn merge(&mut self, other: &Self) {
202 for (trait_, other_map) in &other.map {
203 let map = self.map.entry(*trait_).or_default();
204 for (fp, impls) in other_map {
205 let vec = map.entry(*fp).or_default();
211 /// Queries all trait impls for the given type.
212 pub fn for_self_ty_without_blanket_impls(
215 ) -> impl Iterator<Item = ImplId> + '_ {
218 .flat_map(move |impls| impls.get(&Some(fp)).into_iter())
219 .flat_map(|it| it.iter().copied())
222 /// Queries all impls of the given trait.
223 pub fn for_trait(&self, trait_: TraitId) -> impl Iterator<Item = ImplId> + '_ {
227 .flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
230 /// Queries all impls of `trait_` that may apply to `self_ty`.
231 pub fn for_trait_and_self_ty(
234 self_ty: TyFingerprint,
235 ) -> impl Iterator<Item = ImplId> + '_ {
239 .flat_map(move |map| map.get(&None).into_iter().chain(map.get(&Some(self_ty))))
240 .flat_map(|v| v.iter().copied())
243 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
244 self.map.values().flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
248 /// Inherent impls defined in some crate.
250 /// Inherent impls can only be defined in the crate that also defines the self type of the impl
251 /// (note that some primitives are considered to be defined by both libcore and liballoc).
253 /// This makes inherent impl lookup easier than trait impl lookup since we only have to consider a
255 #[derive(Debug, Eq, PartialEq)]
256 pub struct InherentImpls {
257 map: FxHashMap<TyFingerprint, Vec<ImplId>>,
261 pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
262 let mut impls = Self { map: FxHashMap::default() };
264 let crate_def_map = db.crate_def_map(krate);
265 collect_def_map(db, &crate_def_map, &mut impls);
267 return Arc::new(impls);
269 fn collect_def_map(db: &dyn HirDatabase, def_map: &DefMap, impls: &mut InherentImpls) {
270 for (_module_id, module_data) in def_map.modules() {
271 for impl_id in module_data.scope.impls() {
272 let data = db.impl_data(impl_id);
273 if data.target_trait.is_some() {
277 let self_ty = db.impl_self_ty(impl_id);
278 let fp = TyFingerprint::for_inherent_impl(self_ty.skip_binders());
279 if let Some(fp) = fp {
280 impls.map.entry(fp).or_default().push(impl_id);
282 // `fp` should only be `None` in error cases (either erroneous code or incomplete name resolution)
285 // To better support custom derives, collect impls in all unnamed const items.
286 // const _: () = { ... };
287 for konst in module_data.scope.unnamed_consts() {
288 let body = db.body(konst.into());
289 for (_, block_def_map) in body.blocks(db.upcast()) {
290 collect_def_map(db, &block_def_map, impls);
297 pub fn for_self_ty(&self, self_ty: &Ty) -> &[ImplId] {
298 match TyFingerprint::for_inherent_impl(self_ty) {
299 Some(fp) => self.map.get(&fp).map(|vec| vec.as_ref()).unwrap_or(&[]),
304 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
305 self.map.values().flat_map(|v| v.iter().copied())
310 db: &dyn HirDatabase,
313 ) -> Option<ArrayVec<CrateId, 2>> {
314 // Types like slice can have inherent impls in several crates, (core and alloc).
315 // The corresponding impls are marked with lang items, so we can use them to find the required crates.
316 macro_rules! lang_item_crate {
317 ($($name:expr),+ $(,)?) => {{
318 let mut v = ArrayVec::<LangItemTarget, 2>::new();
320 v.extend(db.lang_item(cur_crate, $name.into()));
326 let mod_to_crate_ids = |module: ModuleId| Some(std::iter::once(module.krate()).collect());
328 let lang_item_targets = match ty.kind(&Interner) {
329 TyKind::Adt(AdtId(def_id), _) => {
330 return mod_to_crate_ids(def_id.module(db.upcast()));
332 TyKind::Foreign(id) => {
333 return mod_to_crate_ids(
334 from_foreign_def_id(*id).lookup(db.upcast()).module(db.upcast()),
337 TyKind::Scalar(Scalar::Bool) => lang_item_crate!("bool"),
338 TyKind::Scalar(Scalar::Char) => lang_item_crate!("char"),
339 TyKind::Scalar(Scalar::Float(f)) => match f {
340 // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime)
341 FloatTy::F32 => lang_item_crate!("f32", "f32_runtime"),
342 FloatTy::F64 => lang_item_crate!("f64", "f64_runtime"),
344 &TyKind::Scalar(Scalar::Int(t)) => {
345 lang_item_crate!(primitive::int_ty_to_string(t))
347 &TyKind::Scalar(Scalar::Uint(t)) => {
348 lang_item_crate!(primitive::uint_ty_to_string(t))
350 TyKind::Str => lang_item_crate!("str_alloc", "str"),
351 TyKind::Slice(_) => lang_item_crate!("slice_alloc", "slice"),
352 TyKind::Array(..) => lang_item_crate!("array"),
353 TyKind::Raw(Mutability::Not, _) => lang_item_crate!("const_ptr"),
354 TyKind::Raw(Mutability::Mut, _) => lang_item_crate!("mut_ptr"),
356 return ty.dyn_trait().and_then(|trait_| {
357 mod_to_crate_ids(GenericDefId::TraitId(trait_).module(db.upcast()))
362 let res = lang_item_targets
364 .filter_map(|it| match it {
365 LangItemTarget::ImplDefId(it) => Some(it),
368 .map(|it| it.lookup(db.upcast()).container.krate())
373 /// Look up the method with the given name, returning the actual autoderefed
374 /// receiver type (but without autoref applied yet).
375 pub(crate) fn lookup_method(
377 db: &dyn HirDatabase,
378 env: Arc<TraitEnvironment>,
380 traits_in_scope: &FxHashSet<TraitId>,
381 visible_from_module: Option<ModuleId>,
383 ) -> Option<(Canonical<Ty>, FunctionId)> {
384 iterate_method_candidates(
392 LookupMode::MethodCall,
394 AssocItemId::FunctionId(f) => Some((ty.clone(), f)),
400 /// Whether we're looking up a dotted method call (like `v.len()`) or a path
401 /// (like `Vec::new`).
402 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
403 pub enum LookupMode {
404 /// Looking up a method call like `v.len()`: We only consider candidates
405 /// that have a `self` parameter, and do autoderef.
407 /// Looking up a path like `Vec::new` or `Vec::default`: We consider all
408 /// candidates including associated constants, but don't do autoderef.
412 // This would be nicer if it just returned an iterator, but that runs into
413 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
414 // FIXME add a context type here?
415 pub fn iterate_method_candidates<T>(
417 db: &dyn HirDatabase,
418 env: Arc<TraitEnvironment>,
420 traits_in_scope: &FxHashSet<TraitId>,
421 visible_from_module: Option<ModuleId>,
424 mut callback: impl FnMut(&Canonical<Ty>, AssocItemId) -> Option<T>,
427 iterate_method_candidates_dyn(
437 assert!(slot.is_none());
438 if let Some(it) = callback(ty, item) {
440 return ControlFlow::Break(());
442 ControlFlow::Continue(())
448 pub fn iterate_method_candidates_dyn(
450 db: &dyn HirDatabase,
451 env: Arc<TraitEnvironment>,
453 traits_in_scope: &FxHashSet<TraitId>,
454 visible_from_module: Option<ModuleId>,
457 callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
458 ) -> ControlFlow<()> {
460 LookupMode::MethodCall => {
461 // For method calls, rust first does any number of autoderef, and then one
462 // autoref (i.e. when the method takes &self or &mut self). We just ignore
463 // the autoref currently -- when we find a method matching the given name,
464 // we assume it fits.
466 // Also note that when we've got a receiver like &S, even if the method we
467 // find in the end takes &self, we still do the autoderef step (just as
468 // rustc does an autoderef and then autoref again).
469 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
471 // We have to be careful about the order we're looking at candidates
472 // in here. Consider the case where we're resolving `x.clone()`
473 // where `x: &Vec<_>`. This resolves to the clone method with self
474 // type `Vec<_>`, *not* `&_`. I.e. we need to consider methods where
475 // the receiver type exactly matches before cases where we have to
476 // do autoref. But in the autoderef steps, the `&_` self type comes
477 // up *before* the `Vec<_>` self type.
479 // On the other hand, we don't want to just pick any by-value method
480 // before any by-autoref method; it's just that we need to consider
481 // the methods by autoderef order of *receiver types*, not *self
484 let deref_chain = autoderef_method_receiver(db, krate, ty);
485 for i in 0..deref_chain.len() {
486 iterate_method_candidates_with_autoref(
497 ControlFlow::Continue(())
499 LookupMode::Path => {
500 // No autoderef for path lookups
501 iterate_method_candidates_for_self_ty(
515 fn iterate_method_candidates_with_autoref(
516 deref_chain: &[Canonical<Ty>],
517 db: &dyn HirDatabase,
518 env: Arc<TraitEnvironment>,
520 traits_in_scope: &FxHashSet<TraitId>,
521 visible_from_module: Option<ModuleId>,
523 mut callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
524 ) -> ControlFlow<()> {
525 iterate_method_candidates_by_receiver(
537 let refed = Canonical {
538 binders: deref_chain[0].binders.clone(),
539 value: TyKind::Ref(Mutability::Not, static_lifetime(), deref_chain[0].value.clone())
543 iterate_method_candidates_by_receiver(
555 let ref_muted = Canonical {
556 binders: deref_chain[0].binders.clone(),
557 value: TyKind::Ref(Mutability::Mut, static_lifetime(), deref_chain[0].value.clone())
561 iterate_method_candidates_by_receiver(
574 fn iterate_method_candidates_by_receiver(
575 receiver_ty: &Canonical<Ty>,
576 rest_of_deref_chain: &[Canonical<Ty>],
577 db: &dyn HirDatabase,
578 env: Arc<TraitEnvironment>,
580 traits_in_scope: &FxHashSet<TraitId>,
581 visible_from_module: Option<ModuleId>,
583 mut callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
584 ) -> ControlFlow<()> {
585 // We're looking for methods with *receiver* type receiver_ty. These could
586 // be found in any of the derefs of receiver_ty, so we have to go through
588 for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
589 iterate_inherent_methods(
601 for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
602 iterate_trait_method_candidates(
614 ControlFlow::Continue(())
617 fn iterate_method_candidates_for_self_ty(
618 self_ty: &Canonical<Ty>,
619 db: &dyn HirDatabase,
620 env: Arc<TraitEnvironment>,
622 traits_in_scope: &FxHashSet<TraitId>,
623 visible_from_module: Option<ModuleId>,
625 mut callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
626 ) -> ControlFlow<()> {
627 iterate_inherent_methods(
637 iterate_trait_method_candidates(self_ty, db, env, krate, traits_in_scope, name, None, callback)
640 fn iterate_trait_method_candidates(
641 self_ty: &Canonical<Ty>,
642 db: &dyn HirDatabase,
643 env: Arc<TraitEnvironment>,
645 traits_in_scope: &FxHashSet<TraitId>,
647 receiver_ty: Option<&Canonical<Ty>>,
648 callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
649 ) -> ControlFlow<()> {
650 let receiver_is_array = matches!(self_ty.value.kind(&Interner), chalk_ir::TyKind::Array(..));
651 // if ty is `dyn Trait`, the trait doesn't need to be in scope
653 self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t));
654 let env_traits = match self_ty.value.kind(&Interner) {
655 TyKind::Placeholder(_) => {
656 // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
657 env.traits_in_scope_from_clauses(&self_ty.value)
658 .flat_map(|t| all_super_traits(db.upcast(), t))
664 inherent_trait.chain(env_traits.into_iter()).chain(traits_in_scope.iter().copied());
666 'traits: for t in traits {
667 let data = db.trait_data(t);
669 // Traits annotated with `#[rustc_skip_array_during_method_dispatch]` are skipped during
670 // method resolution, if the receiver is an array, and we're compiling for editions before
672 // This is to make `[a].into_iter()` not break code with the new `IntoIterator` impl for
674 if data.skip_array_during_method_dispatch && receiver_is_array {
675 // FIXME: this should really be using the edition of the method name's span, in case it
676 // comes from a macro
677 if db.crate_graph()[krate].edition < Edition::Edition2021 {
682 // we'll be lazy about checking whether the type implements the
683 // trait, but if we find out it doesn't, we'll skip the rest of the
685 let mut known_implemented = false;
686 for (_name, item) in data.items.iter() {
687 // Don't pass a `visible_from_module` down to `is_valid_candidate`,
688 // since only inherent methods should be included into visibility checking.
689 if !is_valid_candidate(db, env.clone(), name, receiver_ty, *item, self_ty, None) {
692 if !known_implemented {
693 let goal = generic_implements_goal(db, env.clone(), t, self_ty.clone());
694 if db.trait_solve(krate, goal.cast(&Interner)).is_none() {
698 known_implemented = true;
699 // FIXME: we shouldn't be ignoring the binders here
700 callback(self_ty, *item)?
703 ControlFlow::Continue(())
706 fn filter_inherent_impls_for_self_ty<'i>(
707 impls: &'i InherentImpls,
709 ) -> impl Iterator<Item = &'i ImplId> {
710 // inherent methods on arrays are fingerprinted as [T; {unknown}], so we must also consider them when
711 // resolving a method call on an array with a known len
713 if let TyKind::Array(parameters, array_len) = self_ty.kind(&Interner) {
714 if !array_len.is_unknown() {
715 let unknown_array_len_ty =
716 TyKind::Array(parameters.clone(), consteval::usize_const(None))
719 Some(impls.for_self_ty(&unknown_array_len_ty))
730 impls.for_self_ty(self_ty).iter().chain(array_impls)
733 fn iterate_inherent_methods(
734 self_ty: &Canonical<Ty>,
735 db: &dyn HirDatabase,
736 env: Arc<TraitEnvironment>,
738 receiver_ty: Option<&Canonical<Ty>>,
740 visible_from_module: Option<ModuleId>,
741 callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
742 ) -> ControlFlow<()> {
743 let def_crates = match def_crates(db, &self_ty.value, krate) {
745 None => return ControlFlow::Continue(()),
748 for krate in def_crates {
749 let impls = db.inherent_impls_in_crate(krate);
751 let impls_for_self_ty = filter_inherent_impls_for_self_ty(&impls, &self_ty.value);
753 for &impl_def in impls_for_self_ty {
754 for &item in db.impl_data(impl_def).items.iter() {
755 if !is_valid_candidate(
766 // we have to check whether the self type unifies with the type
767 // that the impl is for. If we have a receiver type, this
768 // already happens in `is_valid_candidate` above; if not, we
770 if receiver_ty.is_none()
771 && inherent_impl_substs(db, env.clone(), impl_def, self_ty).is_none()
773 cov_mark::hit!(impl_self_type_match_without_receiver);
776 let receiver_ty = receiver_ty.unwrap_or(self_ty);
777 callback(receiver_ty, item)?;
781 ControlFlow::Continue(())
784 /// Returns the self type for the index trait call.
785 pub fn resolve_indexing_op(
786 db: &dyn HirDatabase,
788 env: Arc<TraitEnvironment>,
790 index_trait: TraitId,
791 ) -> Option<Canonical<Ty>> {
792 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
793 let deref_chain = autoderef_method_receiver(db, krate, ty);
794 for ty in deref_chain {
795 let goal = generic_implements_goal(db, env.clone(), index_trait, ty.clone());
796 if db.trait_solve(krate, goal.cast(&Interner)).is_some() {
803 fn is_transformed_receiver_ty_equal(transformed_receiver_ty: &Ty, receiver_ty: &Ty) -> bool {
804 if transformed_receiver_ty == receiver_ty {
808 // a transformed receiver may be considered equal (and a valid method call candidate) if it is an array
809 // with an unknown (i.e. generic) length, and the receiver is an array with the same item type but a known len,
810 // this allows inherent methods on arrays to be considered valid resolution candidates
811 match (transformed_receiver_ty.kind(&Interner), receiver_ty.kind(&Interner)) {
813 TyKind::Array(transformed_array_ty, transformed_array_len),
814 TyKind::Array(receiver_array_ty, receiver_array_len),
815 ) if transformed_array_ty == receiver_array_ty
816 && transformed_array_len.is_unknown()
817 && !receiver_array_len.is_unknown() =>
825 fn is_valid_candidate(
826 db: &dyn HirDatabase,
827 env: Arc<TraitEnvironment>,
829 receiver_ty: Option<&Canonical<Ty>>,
831 self_ty: &Canonical<Ty>,
832 visible_from_module: Option<ModuleId>,
835 AssocItemId::FunctionId(m) => {
836 let data = db.function_data(m);
837 if let Some(name) = name {
838 if &data.name != name {
842 if let Some(receiver_ty) = receiver_ty {
843 if !data.has_self_param() {
846 let transformed_receiver_ty = match transform_receiver_ty(db, env, m, self_ty) {
848 None => return false,
851 if !is_transformed_receiver_ty_equal(&transformed_receiver_ty, &receiver_ty.value) {
855 if let Some(from_module) = visible_from_module {
856 if !db.function_visibility(m).is_visible_from(db.upcast(), from_module) {
857 cov_mark::hit!(autoderef_candidate_not_visible);
864 AssocItemId::ConstId(c) => {
865 let data = db.const_data(c);
866 name.map_or(true, |name| data.name.as_ref() == Some(name)) && receiver_ty.is_none()
872 pub(crate) fn inherent_impl_substs(
873 db: &dyn HirDatabase,
874 env: Arc<TraitEnvironment>,
876 self_ty: &Canonical<Ty>,
877 ) -> Option<Substitution> {
878 // we create a var for each type parameter of the impl; we need to keep in
879 // mind here that `self_ty` might have vars of its own
880 let self_ty_vars = self_ty.binders.len(&Interner);
881 let vars = TyBuilder::subst_for_def(db, impl_id)
882 .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty_vars)
884 let self_ty_with_vars = db.impl_self_ty(impl_id).substitute(&Interner, &vars);
885 let mut kinds = self_ty.binders.interned().to_vec();
887 iter::repeat(chalk_ir::WithKind::new(
888 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
891 .take(vars.len(&Interner)),
893 let tys = Canonical {
894 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
895 value: (self_ty_with_vars, self_ty.value.clone()),
897 let substs = super::infer::unify(db, env, &tys)?;
898 // We only want the substs for the vars we added, not the ones from self_ty.
899 // Also, if any of the vars we added are still in there, we replace them by
900 // Unknown. I think this can only really happen if self_ty contained
901 // Unknown, and in that case we want the result to contain Unknown in those
904 Substitution::from_iter(&Interner, substs.iter(&Interner).cloned().skip(self_ty_vars));
905 Some(fallback_bound_vars(suffix, self_ty_vars))
908 /// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
909 /// num_vars_to_keep) by `TyKind::Unknown`.
910 fn fallback_bound_vars(s: Substitution, num_vars_to_keep: usize) -> Substitution {
911 crate::fold_free_vars(s, |bound, binders| {
912 if bound.index >= num_vars_to_keep && bound.debruijn == DebruijnIndex::INNERMOST {
913 TyKind::Error.intern(&Interner)
915 bound.shifted_in_from(binders).to_ty(&Interner)
920 fn transform_receiver_ty(
921 db: &dyn HirDatabase,
922 env: Arc<TraitEnvironment>,
923 function_id: FunctionId,
924 self_ty: &Canonical<Ty>,
926 let substs = match function_id.lookup(db.upcast()).container {
927 AssocContainerId::TraitId(_) => TyBuilder::subst_for_def(db, function_id)
928 .push(self_ty.value.clone())
931 AssocContainerId::ImplId(impl_id) => {
932 let impl_substs = inherent_impl_substs(db, env, impl_id, self_ty)?;
933 TyBuilder::subst_for_def(db, function_id)
934 .use_parent_substs(&impl_substs)
938 AssocContainerId::ModuleId(_) => unreachable!(),
940 let sig = db.callable_item_signature(function_id.into());
941 Some(sig.map(|s| s.params()[0].clone()).substitute(&Interner, &substs))
944 pub fn implements_trait(
946 db: &dyn HirDatabase,
947 env: Arc<TraitEnvironment>,
951 let goal = generic_implements_goal(db, env, trait_, ty.clone());
952 let solution = db.trait_solve(krate, goal.cast(&Interner));
957 pub fn implements_trait_unique(
959 db: &dyn HirDatabase,
960 env: Arc<TraitEnvironment>,
964 let goal = generic_implements_goal(db, env, trait_, ty.clone());
965 let solution = db.trait_solve(krate, goal.cast(&Interner));
967 matches!(solution, Some(crate::Solution::Unique(_)))
970 /// This creates Substs for a trait with the given Self type and type variables
971 /// for all other parameters, to query Chalk with it.
972 fn generic_implements_goal(
973 db: &dyn HirDatabase,
974 env: Arc<TraitEnvironment>,
976 self_ty: Canonical<Ty>,
977 ) -> Canonical<InEnvironment<super::DomainGoal>> {
978 let mut kinds = self_ty.binders.interned().to_vec();
979 let trait_ref = TyBuilder::trait_ref(db, trait_)
981 .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
984 iter::repeat(chalk_ir::WithKind::new(
985 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
988 .take(trait_ref.substitution.len(&Interner) - 1),
990 let obligation = trait_ref.cast(&Interner);
992 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
993 value: InEnvironment::new(&env.env, obligation),
997 fn autoderef_method_receiver(
998 db: &dyn HirDatabase,
1000 ty: InEnvironment<Canonical<Ty>>,
1001 ) -> Vec<Canonical<Ty>> {
1002 let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
1003 // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
1004 if let Some(TyKind::Array(parameters, _)) =
1005 deref_chain.last().map(|ty| ty.value.kind(&Interner))
1007 let kinds = deref_chain.last().unwrap().binders.clone();
1008 let unsized_ty = TyKind::Slice(parameters.clone()).intern(&Interner);
1009 deref_chain.push(Canonical { value: unsized_ty, binders: kinds })