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;
10 builtin_type::{IntBitness, Signedness},
11 lang_item::LangItemTarget,
13 AssocContainerId, AssocItemId, FunctionId, HasModule, ImplId, Lookup, TraitId,
15 use hir_expand::name::Name;
16 use rustc_hash::{FxHashMap, FxHashSet};
22 primitive::{FloatBitness, FloatTy, IntTy},
23 utils::all_super_traits,
24 ApplicationTy, Canonical, DebruijnIndex, InEnvironment, TraitEnvironment, TraitRef, Ty, TyKind,
28 /// This is used as a key for indexing impls.
29 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
30 pub enum TyFingerprint {
35 /// Creates a TyFingerprint for looking up an impl. Only certain types can
36 /// have impls: if we have some `struct S`, we can have an `impl S`, but not
37 /// `impl &S`. Hence, this will return `None` for reference types and such.
38 pub(crate) fn for_impl(ty: &Ty) -> Option<TyFingerprint> {
40 Ty::Apply(a_ty) => Some(TyFingerprint::Apply(a_ty.ctor)),
46 pub(crate) const ALL_INT_FPS: [TyFingerprint; 12] = [
47 TyFingerprint::Apply(TypeCtor::Int(IntTy {
48 signedness: Signedness::Unsigned,
49 bitness: IntBitness::X8,
51 TyFingerprint::Apply(TypeCtor::Int(IntTy {
52 signedness: Signedness::Unsigned,
53 bitness: IntBitness::X16,
55 TyFingerprint::Apply(TypeCtor::Int(IntTy {
56 signedness: Signedness::Unsigned,
57 bitness: IntBitness::X32,
59 TyFingerprint::Apply(TypeCtor::Int(IntTy {
60 signedness: Signedness::Unsigned,
61 bitness: IntBitness::X64,
63 TyFingerprint::Apply(TypeCtor::Int(IntTy {
64 signedness: Signedness::Unsigned,
65 bitness: IntBitness::X128,
67 TyFingerprint::Apply(TypeCtor::Int(IntTy {
68 signedness: Signedness::Unsigned,
69 bitness: IntBitness::Xsize,
71 TyFingerprint::Apply(TypeCtor::Int(IntTy {
72 signedness: Signedness::Signed,
73 bitness: IntBitness::X8,
75 TyFingerprint::Apply(TypeCtor::Int(IntTy {
76 signedness: Signedness::Signed,
77 bitness: IntBitness::X16,
79 TyFingerprint::Apply(TypeCtor::Int(IntTy {
80 signedness: Signedness::Signed,
81 bitness: IntBitness::X32,
83 TyFingerprint::Apply(TypeCtor::Int(IntTy {
84 signedness: Signedness::Signed,
85 bitness: IntBitness::X64,
87 TyFingerprint::Apply(TypeCtor::Int(IntTy {
88 signedness: Signedness::Signed,
89 bitness: IntBitness::X128,
91 TyFingerprint::Apply(TypeCtor::Int(IntTy {
92 signedness: Signedness::Signed,
93 bitness: IntBitness::Xsize,
97 pub(crate) const ALL_FLOAT_FPS: [TyFingerprint; 2] = [
98 TyFingerprint::Apply(TypeCtor::Float(FloatTy { bitness: FloatBitness::X32 })),
99 TyFingerprint::Apply(TypeCtor::Float(FloatTy { bitness: FloatBitness::X64 })),
102 /// Trait impls defined or available in some crate.
103 #[derive(Debug, Eq, PartialEq)]
104 pub struct TraitImpls {
105 // If the `Option<TyFingerprint>` is `None`, the impl may apply to any self type.
106 map: FxHashMap<TraitId, FxHashMap<Option<TyFingerprint>, Vec<ImplId>>>,
110 pub(crate) fn trait_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
111 let _p = profile::span("trait_impls_in_crate_query");
112 let mut impls = Self { map: FxHashMap::default() };
114 let crate_def_map = db.crate_def_map(krate);
115 for (_module_id, module_data) in crate_def_map.modules.iter() {
116 for impl_id in module_data.scope.impls() {
117 let target_trait = match db.impl_trait(impl_id) {
118 Some(tr) => tr.value.trait_,
121 let self_ty = db.impl_self_ty(impl_id);
122 let self_ty_fp = TyFingerprint::for_impl(&self_ty.value);
136 pub(crate) fn trait_impls_in_deps_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
137 let _p = profile::span("trait_impls_in_deps_query");
138 let crate_graph = db.crate_graph();
139 let mut res = Self { map: FxHashMap::default() };
141 for krate in crate_graph.transitive_deps(krate) {
142 res.merge(&db.trait_impls_in_crate(krate));
148 fn merge(&mut self, other: &Self) {
149 for (trait_, other_map) in &other.map {
150 let map = self.map.entry(*trait_).or_default();
151 for (fp, impls) in other_map {
152 let vec = map.entry(*fp).or_default();
158 /// Queries all impls of the given trait.
159 pub fn for_trait(&self, trait_: TraitId) -> impl Iterator<Item = ImplId> + '_ {
163 .flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
166 /// Queries all impls of `trait_` that may apply to `self_ty`.
167 pub fn for_trait_and_self_ty(
170 self_ty: TyFingerprint,
171 ) -> impl Iterator<Item = ImplId> + '_ {
175 .flat_map(move |map| map.get(&None).into_iter().chain(map.get(&Some(self_ty))))
176 .flat_map(|v| v.iter().copied())
179 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
180 self.map.values().flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
184 /// Inherent impls defined in some crate.
186 /// Inherent impls can only be defined in the crate that also defines the self type of the impl
187 /// (note that some primitives are considered to be defined by both libcore and liballoc).
189 /// This makes inherent impl lookup easier than trait impl lookup since we only have to consider a
191 #[derive(Debug, Eq, PartialEq)]
192 pub struct InherentImpls {
193 map: FxHashMap<TyFingerprint, Vec<ImplId>>,
197 pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
198 let mut map: FxHashMap<_, Vec<_>> = FxHashMap::default();
200 let crate_def_map = db.crate_def_map(krate);
201 for (_module_id, module_data) in crate_def_map.modules.iter() {
202 for impl_id in module_data.scope.impls() {
203 let data = db.impl_data(impl_id);
204 if data.target_trait.is_some() {
208 let self_ty = db.impl_self_ty(impl_id);
209 if let Some(fp) = TyFingerprint::for_impl(&self_ty.value) {
210 map.entry(fp).or_default().push(impl_id);
215 Arc::new(Self { map })
218 pub fn for_self_ty(&self, self_ty: &Ty) -> &[ImplId] {
219 match TyFingerprint::for_impl(self_ty) {
220 Some(fp) => self.map.get(&fp).map(|vec| vec.as_ref()).unwrap_or(&[]),
225 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
226 self.map.values().flat_map(|v| v.iter().copied())
233 db: &dyn HirDatabase,
235 ) -> Option<ArrayVec<[CrateId; 2]>> {
236 // Types like slice can have inherent impls in several crates, (core and alloc).
237 // The corresponding impls are marked with lang items, so we can use them to find the required crates.
238 macro_rules! lang_item_crate {
239 ($($name:expr),+ $(,)?) => {{
240 let mut v = ArrayVec::<[LangItemTarget; 2]>::new();
242 v.extend(db.lang_item(cur_crate, $name.into()));
248 let lang_item_targets = match self {
249 Ty::Apply(a_ty) => match a_ty.ctor {
250 TypeCtor::Adt(def_id) => {
251 return Some(std::iter::once(def_id.module(db.upcast()).krate).collect())
253 TypeCtor::ForeignType(type_alias_id) => {
256 type_alias_id.lookup(db.upcast()).module(db.upcast()).krate,
261 TypeCtor::Bool => lang_item_crate!("bool"),
262 TypeCtor::Char => lang_item_crate!("char"),
263 TypeCtor::Float(f) => match f.bitness {
264 // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime)
265 FloatBitness::X32 => lang_item_crate!("f32", "f32_runtime"),
266 FloatBitness::X64 => lang_item_crate!("f64", "f64_runtime"),
268 TypeCtor::Int(i) => lang_item_crate!(i.ty_to_string()),
269 TypeCtor::Str => lang_item_crate!("str_alloc", "str"),
270 TypeCtor::Slice => lang_item_crate!("slice_alloc", "slice"),
271 TypeCtor::RawPtr(Mutability::Shared) => lang_item_crate!("const_ptr"),
272 TypeCtor::RawPtr(Mutability::Mut) => lang_item_crate!("mut_ptr"),
277 let res = lang_item_targets
279 .filter_map(|it| match it {
280 LangItemTarget::ImplDefId(it) => Some(it),
283 .map(|it| it.lookup(db.upcast()).container.module(db.upcast()).krate)
288 /// Look up the method with the given name, returning the actual autoderefed
289 /// receiver type (but without autoref applied yet).
290 pub(crate) fn lookup_method(
292 db: &dyn HirDatabase,
293 env: Arc<TraitEnvironment>,
295 traits_in_scope: &FxHashSet<TraitId>,
297 ) -> Option<(Ty, FunctionId)> {
298 iterate_method_candidates(
305 LookupMode::MethodCall,
307 AssocItemId::FunctionId(f) => Some((ty.clone(), f)),
313 /// Whether we're looking up a dotted method call (like `v.len()`) or a path
314 /// (like `Vec::new`).
315 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
316 pub enum LookupMode {
317 /// Looking up a method call like `v.len()`: We only consider candidates
318 /// that have a `self` parameter, and do autoderef.
320 /// Looking up a path like `Vec::new` or `Vec::default`: We consider all
321 /// candidates including associated constants, but don't do autoderef.
325 // This would be nicer if it just returned an iterator, but that runs into
326 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
327 // FIXME add a context type here?
328 pub fn iterate_method_candidates<T>(
330 db: &dyn HirDatabase,
331 env: Arc<TraitEnvironment>,
333 traits_in_scope: &FxHashSet<TraitId>,
336 mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>,
339 iterate_method_candidates_impl(
348 assert!(slot.is_none());
349 slot = callback(ty, item);
356 fn iterate_method_candidates_impl(
358 db: &dyn HirDatabase,
359 env: Arc<TraitEnvironment>,
361 traits_in_scope: &FxHashSet<TraitId>,
364 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
367 LookupMode::MethodCall => {
368 // For method calls, rust first does any number of autoderef, and then one
369 // autoref (i.e. when the method takes &self or &mut self). We just ignore
370 // the autoref currently -- when we find a method matching the given name,
371 // we assume it fits.
373 // Also note that when we've got a receiver like &S, even if the method we
374 // find in the end takes &self, we still do the autoderef step (just as
375 // rustc does an autoderef and then autoref again).
376 let ty = InEnvironment { value: ty.clone(), environment: env.clone() };
378 // We have to be careful about the order we're looking at candidates
379 // in here. Consider the case where we're resolving `x.clone()`
380 // where `x: &Vec<_>`. This resolves to the clone method with self
381 // type `Vec<_>`, *not* `&_`. I.e. we need to consider methods where
382 // the receiver type exactly matches before cases where we have to
383 // do autoref. But in the autoderef steps, the `&_` self type comes
384 // up *before* the `Vec<_>` self type.
386 // On the other hand, we don't want to just pick any by-value method
387 // before any by-autoref method; it's just that we need to consider
388 // the methods by autoderef order of *receiver types*, not *self
391 let deref_chain = autoderef_method_receiver(db, krate, ty);
392 for i in 0..deref_chain.len() {
393 if iterate_method_candidates_with_autoref(
407 LookupMode::Path => {
408 // No autoderef for path lookups
409 iterate_method_candidates_for_self_ty(
422 fn iterate_method_candidates_with_autoref(
423 deref_chain: &[Canonical<Ty>],
424 db: &dyn HirDatabase,
425 env: Arc<TraitEnvironment>,
427 traits_in_scope: &FxHashSet<TraitId>,
429 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
431 if iterate_method_candidates_by_receiver(
443 let refed = Canonical {
444 kinds: deref_chain[0].kinds.clone(),
445 value: Ty::apply_one(TypeCtor::Ref(Mutability::Shared), deref_chain[0].value.clone()),
447 if iterate_method_candidates_by_receiver(
459 let ref_muted = Canonical {
460 kinds: deref_chain[0].kinds.clone(),
461 value: Ty::apply_one(TypeCtor::Ref(Mutability::Mut), deref_chain[0].value.clone()),
463 if iterate_method_candidates_by_receiver(
478 fn iterate_method_candidates_by_receiver(
479 receiver_ty: &Canonical<Ty>,
480 rest_of_deref_chain: &[Canonical<Ty>],
481 db: &dyn HirDatabase,
482 env: Arc<TraitEnvironment>,
484 traits_in_scope: &FxHashSet<TraitId>,
486 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
488 // We're looking for methods with *receiver* type receiver_ty. These could
489 // be found in any of the derefs of receiver_ty, so we have to go through
491 for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
492 if iterate_inherent_methods(self_ty, db, name, Some(receiver_ty), krate, &mut callback) {
496 for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
497 if iterate_trait_method_candidates(
513 fn iterate_method_candidates_for_self_ty(
514 self_ty: &Canonical<Ty>,
515 db: &dyn HirDatabase,
516 env: Arc<TraitEnvironment>,
518 traits_in_scope: &FxHashSet<TraitId>,
520 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
522 if iterate_inherent_methods(self_ty, db, name, None, krate, &mut callback) {
525 iterate_trait_method_candidates(self_ty, db, env, krate, traits_in_scope, name, None, callback)
528 fn iterate_trait_method_candidates(
529 self_ty: &Canonical<Ty>,
530 db: &dyn HirDatabase,
531 env: Arc<TraitEnvironment>,
533 traits_in_scope: &FxHashSet<TraitId>,
535 receiver_ty: Option<&Canonical<Ty>>,
536 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
538 // if ty is `dyn Trait`, the trait doesn't need to be in scope
540 self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t));
541 let env_traits = if let Ty::Placeholder(_) = self_ty.value {
542 // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
543 env.trait_predicates_for_self_ty(&self_ty.value)
545 .flat_map(|t| all_super_traits(db.upcast(), t))
551 inherent_trait.chain(env_traits.into_iter()).chain(traits_in_scope.iter().copied());
552 'traits: for t in traits {
553 let data = db.trait_data(t);
555 // we'll be lazy about checking whether the type implements the
556 // trait, but if we find out it doesn't, we'll skip the rest of the
558 let mut known_implemented = false;
559 for (_name, item) in data.items.iter() {
560 if !is_valid_candidate(db, name, receiver_ty, *item, self_ty) {
563 if !known_implemented {
564 let goal = generic_implements_goal(db, env.clone(), t, self_ty.clone());
565 if db.trait_solve(krate, goal).is_none() {
569 known_implemented = true;
570 if callback(&self_ty.value, *item) {
578 fn iterate_inherent_methods(
579 self_ty: &Canonical<Ty>,
580 db: &dyn HirDatabase,
582 receiver_ty: Option<&Canonical<Ty>>,
584 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
586 let def_crates = match self_ty.value.def_crates(db, krate) {
588 None => return false,
590 for krate in def_crates {
591 let impls = db.inherent_impls_in_crate(krate);
593 for &impl_def in impls.for_self_ty(&self_ty.value) {
594 for &item in db.impl_data(impl_def).items.iter() {
595 if !is_valid_candidate(db, name, receiver_ty, item, self_ty) {
598 // we have to check whether the self type unifies with the type
599 // that the impl is for. If we have a receiver type, this
600 // already happens in `is_valid_candidate` above; if not, we
602 if receiver_ty.is_none() && inherent_impl_substs(db, impl_def, self_ty).is_none() {
603 test_utils::mark::hit!(impl_self_type_match_without_receiver);
606 if callback(&self_ty.value, item) {
615 /// Returns the self type for the index trait call.
616 pub fn resolve_indexing_op(
617 db: &dyn HirDatabase,
619 env: Arc<TraitEnvironment>,
621 index_trait: TraitId,
622 ) -> Option<Canonical<Ty>> {
623 let ty = InEnvironment { value: ty.clone(), environment: env.clone() };
624 let deref_chain = autoderef_method_receiver(db, krate, ty);
625 for ty in deref_chain {
626 let goal = generic_implements_goal(db, env.clone(), index_trait, ty.clone());
627 if db.trait_solve(krate, goal).is_some() {
634 fn is_valid_candidate(
635 db: &dyn HirDatabase,
637 receiver_ty: Option<&Canonical<Ty>>,
639 self_ty: &Canonical<Ty>,
642 AssocItemId::FunctionId(m) => {
643 let data = db.function_data(m);
644 if let Some(name) = name {
645 if &data.name != name {
649 if let Some(receiver_ty) = receiver_ty {
650 if !data.has_self_param {
653 let transformed_receiver_ty = match transform_receiver_ty(db, m, self_ty) {
655 None => return false,
657 if transformed_receiver_ty != receiver_ty.value {
663 AssocItemId::ConstId(c) => {
664 let data = db.const_data(c);
665 name.map_or(true, |name| data.name.as_ref() == Some(name)) && receiver_ty.is_none()
671 pub(crate) fn inherent_impl_substs(
672 db: &dyn HirDatabase,
674 self_ty: &Canonical<Ty>,
675 ) -> Option<Substs> {
676 // we create a var for each type parameter of the impl; we need to keep in
677 // mind here that `self_ty` might have vars of its own
678 let vars = Substs::build_for_def(db, impl_id)
679 .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty.kinds.len())
681 let self_ty_with_vars = db.impl_self_ty(impl_id).subst(&vars);
682 let mut kinds = self_ty.kinds.to_vec();
683 kinds.extend(iter::repeat(TyKind::General).take(vars.len()));
684 let tys = Canonical { kinds: kinds.into(), value: (self_ty_with_vars, self_ty.value.clone()) };
685 let substs = super::infer::unify(&tys);
686 // We only want the substs for the vars we added, not the ones from self_ty.
687 // Also, if any of the vars we added are still in there, we replace them by
688 // Unknown. I think this can only really happen if self_ty contained
689 // Unknown, and in that case we want the result to contain Unknown in those
691 substs.map(|s| fallback_bound_vars(s.suffix(vars.len()), self_ty.kinds.len()))
694 /// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
695 /// num_vars_to_keep) by `Ty::Unknown`.
696 fn fallback_bound_vars(s: Substs, num_vars_to_keep: usize) -> Substs {
699 if let Ty::Bound(bound) = &ty {
700 if bound.index >= num_vars_to_keep && bound.debruijn >= binders {
709 DebruijnIndex::INNERMOST,
713 fn transform_receiver_ty(
714 db: &dyn HirDatabase,
715 function_id: FunctionId,
716 self_ty: &Canonical<Ty>,
718 let substs = match function_id.lookup(db.upcast()).container {
719 AssocContainerId::TraitId(_) => Substs::build_for_def(db, function_id)
720 .push(self_ty.value.clone())
723 AssocContainerId::ImplId(impl_id) => {
724 let impl_substs = inherent_impl_substs(db, impl_id, &self_ty)?;
725 Substs::build_for_def(db, function_id)
726 .use_parent_substs(&impl_substs)
730 AssocContainerId::ContainerId(_) => unreachable!(),
732 let sig = db.callable_item_signature(function_id.into());
733 Some(sig.value.params()[0].clone().subst_bound_vars(&substs))
736 pub fn implements_trait(
738 db: &dyn HirDatabase,
739 env: Arc<TraitEnvironment>,
743 let goal = generic_implements_goal(db, env, trait_, ty.clone());
744 let solution = db.trait_solve(krate, goal);
749 pub fn implements_trait_unique(
751 db: &dyn HirDatabase,
752 env: Arc<TraitEnvironment>,
756 let goal = generic_implements_goal(db, env, trait_, ty.clone());
757 let solution = db.trait_solve(krate, goal);
759 matches!(solution, Some(crate::traits::Solution::Unique(_)))
762 /// This creates Substs for a trait with the given Self type and type variables
763 /// for all other parameters, to query Chalk with it.
764 fn generic_implements_goal(
765 db: &dyn HirDatabase,
766 env: Arc<TraitEnvironment>,
768 self_ty: Canonical<Ty>,
769 ) -> Canonical<InEnvironment<super::Obligation>> {
770 let mut kinds = self_ty.kinds.to_vec();
771 let substs = super::Substs::build_for_def(db, trait_)
773 .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
775 kinds.extend(iter::repeat(TyKind::General).take(substs.len() - 1));
776 let trait_ref = TraitRef { trait_, substs };
777 let obligation = super::Obligation::Trait(trait_ref);
778 Canonical { kinds: kinds.into(), value: InEnvironment::new(env, obligation) }
781 fn autoderef_method_receiver(
782 db: &dyn HirDatabase,
784 ty: InEnvironment<Canonical<Ty>>,
785 ) -> Vec<Canonical<Ty>> {
786 let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
787 // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
788 if let Some(Ty::Apply(ApplicationTy { ctor: TypeCtor::Array, parameters })) =
789 deref_chain.last().map(|ty| &ty.value)
791 let kinds = deref_chain.last().unwrap().kinds.clone();
792 let unsized_ty = Ty::apply(TypeCtor::Slice, parameters.clone());
793 deref_chain.push(Canonical { value: unsized_ty, kinds })