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 item_scope::ItemScope, lang_item::LangItemTarget, nameres::DefMap, AssocItemId, BlockId,
12 ConstId, FunctionId, GenericDefId, HasModule, ImplId, ItemContainerId, Lookup, ModuleDefId,
15 use hir_expand::name::Name;
16 use rustc_hash::{FxHashMap, FxHashSet};
21 consteval::{self, ConstExt},
24 primitive::{self, FloatTy, IntTy, UintTy},
26 utils::all_super_traits,
27 AdtId, Canonical, CanonicalVarKinds, DebruijnIndex, ForeignDefId, InEnvironment, Interner,
28 Scalar, Substitution, TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyExt, TyKind,
31 /// This is used as a key for indexing impls.
32 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
33 pub enum TyFingerprint {
34 // These are lang item impls:
41 // These can have user-defined impls:
44 ForeignType(ForeignDefId),
45 // These only exist for trait impls
52 /// Creates a TyFingerprint for looking up an inherent impl. Only certain
53 /// types can have inherent impls: if we have some `struct S`, we can have
54 /// an `impl S`, but not `impl &S`. Hence, this will return `None` for
55 /// reference types and such.
56 pub fn for_inherent_impl(ty: &Ty) -> Option<TyFingerprint> {
57 let fp = match ty.kind(&Interner) {
58 TyKind::Str => TyFingerprint::Str,
59 TyKind::Never => TyFingerprint::Never,
60 TyKind::Slice(..) => TyFingerprint::Slice,
61 TyKind::Array(..) => TyFingerprint::Array,
62 TyKind::Scalar(scalar) => TyFingerprint::Scalar(*scalar),
63 TyKind::Adt(AdtId(adt), _) => TyFingerprint::Adt(*adt),
64 TyKind::Raw(mutability, ..) => TyFingerprint::RawPtr(*mutability),
65 TyKind::Foreign(alias_id, ..) => TyFingerprint::ForeignType(*alias_id),
66 TyKind::Dyn(_) => ty.dyn_trait().map(TyFingerprint::Dyn)?,
72 /// Creates a TyFingerprint for looking up a trait impl.
73 pub fn for_trait_impl(ty: &Ty) -> Option<TyFingerprint> {
74 let fp = match ty.kind(&Interner) {
75 TyKind::Str => TyFingerprint::Str,
76 TyKind::Never => TyFingerprint::Never,
77 TyKind::Slice(..) => TyFingerprint::Slice,
78 TyKind::Array(..) => TyFingerprint::Array,
79 TyKind::Scalar(scalar) => TyFingerprint::Scalar(*scalar),
80 TyKind::Adt(AdtId(adt), _) => TyFingerprint::Adt(*adt),
81 TyKind::Raw(mutability, ..) => TyFingerprint::RawPtr(*mutability),
82 TyKind::Foreign(alias_id, ..) => TyFingerprint::ForeignType(*alias_id),
83 TyKind::Dyn(_) => ty.dyn_trait().map(TyFingerprint::Dyn)?,
84 TyKind::Ref(_, _, ty) => return TyFingerprint::for_trait_impl(ty),
85 TyKind::Tuple(_, subst) => {
86 let first_ty = subst.interned().get(0).map(|arg| arg.assert_ty_ref(&Interner));
88 Some(ty) => return TyFingerprint::for_trait_impl(ty),
89 None => TyFingerprint::Unit,
92 TyKind::AssociatedType(_, _)
93 | TyKind::OpaqueType(_, _)
95 | TyKind::Closure(_, _)
96 | TyKind::Generator(..)
97 | TyKind::GeneratorWitness(..) => TyFingerprint::Unnameable,
98 TyKind::Function(fn_ptr) => {
99 TyFingerprint::Function(fn_ptr.substitution.0.len(&Interner) as u32)
102 | TyKind::Placeholder(_)
103 | TyKind::BoundVar(_)
104 | TyKind::InferenceVar(_, _)
105 | TyKind::Error => return None,
111 pub(crate) const ALL_INT_FPS: [TyFingerprint; 12] = [
112 TyFingerprint::Scalar(Scalar::Int(IntTy::I8)),
113 TyFingerprint::Scalar(Scalar::Int(IntTy::I16)),
114 TyFingerprint::Scalar(Scalar::Int(IntTy::I32)),
115 TyFingerprint::Scalar(Scalar::Int(IntTy::I64)),
116 TyFingerprint::Scalar(Scalar::Int(IntTy::I128)),
117 TyFingerprint::Scalar(Scalar::Int(IntTy::Isize)),
118 TyFingerprint::Scalar(Scalar::Uint(UintTy::U8)),
119 TyFingerprint::Scalar(Scalar::Uint(UintTy::U16)),
120 TyFingerprint::Scalar(Scalar::Uint(UintTy::U32)),
121 TyFingerprint::Scalar(Scalar::Uint(UintTy::U64)),
122 TyFingerprint::Scalar(Scalar::Uint(UintTy::U128)),
123 TyFingerprint::Scalar(Scalar::Uint(UintTy::Usize)),
126 pub(crate) const ALL_FLOAT_FPS: [TyFingerprint; 2] = [
127 TyFingerprint::Scalar(Scalar::Float(FloatTy::F32)),
128 TyFingerprint::Scalar(Scalar::Float(FloatTy::F64)),
131 /// Trait impls defined or available in some crate.
132 #[derive(Debug, Eq, PartialEq)]
133 pub struct TraitImpls {
134 // If the `Option<TyFingerprint>` is `None`, the impl may apply to any self type.
135 map: FxHashMap<TraitId, FxHashMap<Option<TyFingerprint>, Vec<ImplId>>>,
139 pub(crate) fn trait_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
140 let _p = profile::span("trait_impls_in_crate_query");
141 let mut impls = Self { map: FxHashMap::default() };
143 let crate_def_map = db.crate_def_map(krate);
144 impls.collect_def_map(db, &crate_def_map);
149 pub(crate) fn trait_impls_in_block_query(
150 db: &dyn HirDatabase,
152 ) -> Option<Arc<Self>> {
153 let _p = profile::span("trait_impls_in_block_query");
154 let mut impls = Self { map: FxHashMap::default() };
156 let block_def_map = db.block_def_map(block)?;
157 impls.collect_def_map(db, &block_def_map);
159 Some(Arc::new(impls))
162 fn collect_def_map(&mut self, db: &dyn HirDatabase, def_map: &DefMap) {
163 for (_module_id, module_data) in def_map.modules() {
164 for impl_id in module_data.scope.impls() {
165 let target_trait = match db.impl_trait(impl_id) {
166 Some(tr) => tr.skip_binders().hir_trait_id(),
169 let self_ty = db.impl_self_ty(impl_id);
170 let self_ty_fp = TyFingerprint::for_trait_impl(self_ty.skip_binders());
179 // To better support custom derives, collect impls in all unnamed const items.
180 // const _: () = { ... };
181 for konst in collect_unnamed_consts(db, &module_data.scope) {
182 let body = db.body(konst.into());
183 for (_, block_def_map) in body.blocks(db.upcast()) {
184 self.collect_def_map(db, &block_def_map);
190 pub(crate) fn trait_impls_in_deps_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
191 let _p = profile::span("trait_impls_in_deps_query");
192 let crate_graph = db.crate_graph();
193 let mut res = Self { map: FxHashMap::default() };
195 for krate in crate_graph.transitive_deps(krate) {
196 res.merge(&db.trait_impls_in_crate(krate));
202 fn merge(&mut self, other: &Self) {
203 for (trait_, other_map) in &other.map {
204 let map = self.map.entry(*trait_).or_default();
205 for (fp, impls) in other_map {
206 let vec = map.entry(*fp).or_default();
212 /// Queries all trait impls for the given type.
213 pub fn for_self_ty_without_blanket_impls(
216 ) -> impl Iterator<Item = ImplId> + '_ {
219 .flat_map(move |impls| impls.get(&Some(fp)).into_iter())
220 .flat_map(|it| it.iter().copied())
223 /// Queries all impls of the given trait.
224 pub fn for_trait(&self, trait_: TraitId) -> impl Iterator<Item = ImplId> + '_ {
228 .flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
231 /// Queries all impls of `trait_` that may apply to `self_ty`.
232 pub fn for_trait_and_self_ty(
235 self_ty: TyFingerprint,
236 ) -> impl Iterator<Item = ImplId> + '_ {
240 .flat_map(move |map| map.get(&None).into_iter().chain(map.get(&Some(self_ty))))
241 .flat_map(|v| v.iter().copied())
244 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
245 self.map.values().flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
249 /// Inherent impls defined in some crate.
251 /// Inherent impls can only be defined in the crate that also defines the self type of the impl
252 /// (note that some primitives are considered to be defined by both libcore and liballoc).
254 /// This makes inherent impl lookup easier than trait impl lookup since we only have to consider a
256 #[derive(Debug, Eq, PartialEq)]
257 pub struct InherentImpls {
258 map: FxHashMap<TyFingerprint, Vec<ImplId>>,
262 pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
263 let mut impls = Self { map: FxHashMap::default() };
265 let crate_def_map = db.crate_def_map(krate);
266 impls.collect_def_map(db, &crate_def_map);
268 return Arc::new(impls);
271 pub(crate) fn inherent_impls_in_block_query(
272 db: &dyn HirDatabase,
274 ) -> Option<Arc<Self>> {
275 let mut impls = Self { map: FxHashMap::default() };
276 if let Some(block_def_map) = db.block_def_map(block) {
277 impls.collect_def_map(db, &block_def_map);
278 return Some(Arc::new(impls));
283 fn collect_def_map(&mut self, db: &dyn HirDatabase, def_map: &DefMap) {
284 for (_module_id, module_data) in def_map.modules() {
285 for impl_id in module_data.scope.impls() {
286 let data = db.impl_data(impl_id);
287 if data.target_trait.is_some() {
291 let self_ty = db.impl_self_ty(impl_id);
292 let fp = TyFingerprint::for_inherent_impl(self_ty.skip_binders());
293 if let Some(fp) = fp {
294 self.map.entry(fp).or_default().push(impl_id);
296 // `fp` should only be `None` in error cases (either erroneous code or incomplete name resolution)
299 // To better support custom derives, collect impls in all unnamed const items.
300 // const _: () = { ... };
301 for konst in collect_unnamed_consts(db, &module_data.scope) {
302 let body = db.body(konst.into());
303 for (_, block_def_map) in body.blocks(db.upcast()) {
304 self.collect_def_map(db, &block_def_map);
310 pub fn for_self_ty(&self, self_ty: &Ty) -> &[ImplId] {
311 match TyFingerprint::for_inherent_impl(self_ty) {
312 Some(fp) => self.map.get(&fp).map(|vec| vec.as_ref()).unwrap_or(&[]),
317 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
318 self.map.values().flat_map(|v| v.iter().copied())
322 fn collect_unnamed_consts<'a>(
323 db: &'a dyn HirDatabase,
324 scope: &'a ItemScope,
325 ) -> impl Iterator<Item = ConstId> + 'a {
326 let unnamed_consts = scope.unnamed_consts();
328 // FIXME: Also treat consts named `_DERIVE_*` as unnamed, since synstructure generates those.
329 // Should be removed once synstructure stops doing that.
330 let synstructure_hack_consts = scope.values().filter_map(|(item, _)| match item {
331 ModuleDefId::ConstId(id) => {
332 let loc = id.lookup(db.upcast());
333 let item_tree = loc.id.item_tree(db.upcast());
334 if item_tree[loc.id.value]
337 .map_or(false, |n| n.to_smol_str().starts_with("_DERIVE_"))
347 unnamed_consts.chain(synstructure_hack_consts)
351 db: &dyn HirDatabase,
354 ) -> Option<ArrayVec<CrateId, 2>> {
355 // Types like slice can have inherent impls in several crates, (core and alloc).
356 // The corresponding impls are marked with lang items, so we can use them to find the required crates.
357 macro_rules! lang_item_crate {
358 ($($name:expr),+ $(,)?) => {{
359 let mut v = ArrayVec::<LangItemTarget, 2>::new();
361 v.extend(db.lang_item(cur_crate, $name.into()));
367 let mod_to_crate_ids = |module: ModuleId| Some(iter::once(module.krate()).collect());
369 let lang_item_targets = match ty.kind(&Interner) {
370 TyKind::Adt(AdtId(def_id), _) => {
371 return mod_to_crate_ids(def_id.module(db.upcast()));
373 TyKind::Foreign(id) => {
374 return mod_to_crate_ids(
375 from_foreign_def_id(*id).lookup(db.upcast()).module(db.upcast()),
378 TyKind::Scalar(Scalar::Bool) => lang_item_crate!("bool"),
379 TyKind::Scalar(Scalar::Char) => lang_item_crate!("char"),
380 TyKind::Scalar(Scalar::Float(f)) => match f {
381 // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime)
382 FloatTy::F32 => lang_item_crate!("f32", "f32_runtime"),
383 FloatTy::F64 => lang_item_crate!("f64", "f64_runtime"),
385 &TyKind::Scalar(Scalar::Int(t)) => {
386 lang_item_crate!(primitive::int_ty_to_string(t))
388 &TyKind::Scalar(Scalar::Uint(t)) => {
389 lang_item_crate!(primitive::uint_ty_to_string(t))
391 TyKind::Str => lang_item_crate!("str_alloc", "str"),
392 TyKind::Slice(_) => lang_item_crate!("slice_alloc", "slice"),
393 TyKind::Array(..) => lang_item_crate!("array"),
394 TyKind::Raw(Mutability::Not, _) => lang_item_crate!("const_ptr"),
395 TyKind::Raw(Mutability::Mut, _) => lang_item_crate!("mut_ptr"),
397 return ty.dyn_trait().and_then(|trait_| {
398 mod_to_crate_ids(GenericDefId::TraitId(trait_).module(db.upcast()))
403 let res = lang_item_targets
405 .filter_map(|it| match it {
406 LangItemTarget::ImplDefId(it) => Some(it),
409 .map(|it| it.lookup(db.upcast()).container.krate())
414 /// Look up the method with the given name, returning the actual autoderefed
415 /// receiver type (but without autoref applied yet).
416 pub(crate) fn lookup_method(
418 db: &dyn HirDatabase,
419 env: Arc<TraitEnvironment>,
421 traits_in_scope: &FxHashSet<TraitId>,
422 visible_from_module: Option<ModuleId>,
424 ) -> Option<(Canonical<Ty>, FunctionId)> {
425 iterate_method_candidates(
433 LookupMode::MethodCall,
435 AssocItemId::FunctionId(f) => Some((ty.clone(), f)),
441 /// Whether we're looking up a dotted method call (like `v.len()`) or a path
442 /// (like `Vec::new`).
443 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
444 pub enum LookupMode {
445 /// Looking up a method call like `v.len()`: We only consider candidates
446 /// that have a `self` parameter, and do autoderef.
448 /// Looking up a path like `Vec::new` or `Vec::default`: We consider all
449 /// candidates including associated constants, but don't do autoderef.
453 // This would be nicer if it just returned an iterator, but that runs into
454 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
455 // FIXME add a context type here?
456 pub fn iterate_method_candidates<T>(
458 db: &dyn HirDatabase,
459 env: Arc<TraitEnvironment>,
461 traits_in_scope: &FxHashSet<TraitId>,
462 visible_from_module: Option<ModuleId>,
465 mut callback: impl FnMut(&Canonical<Ty>, AssocItemId) -> Option<T>,
468 iterate_method_candidates_dyn(
478 assert!(slot.is_none());
479 if let Some(it) = callback(ty, item) {
481 return ControlFlow::Break(());
483 ControlFlow::Continue(())
489 pub fn iterate_method_candidates_dyn(
491 db: &dyn HirDatabase,
492 env: Arc<TraitEnvironment>,
494 traits_in_scope: &FxHashSet<TraitId>,
495 visible_from_module: Option<ModuleId>,
498 callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
499 ) -> ControlFlow<()> {
501 LookupMode::MethodCall => {
502 // For method calls, rust first does any number of autoderef, and then one
503 // autoref (i.e. when the method takes &self or &mut self). We just ignore
504 // the autoref currently -- when we find a method matching the given name,
505 // we assume it fits.
507 // Also note that when we've got a receiver like &S, even if the method we
508 // find in the end takes &self, we still do the autoderef step (just as
509 // rustc does an autoderef and then autoref again).
510 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
512 // We have to be careful about the order we're looking at candidates
513 // in here. Consider the case where we're resolving `x.clone()`
514 // where `x: &Vec<_>`. This resolves to the clone method with self
515 // type `Vec<_>`, *not* `&_`. I.e. we need to consider methods where
516 // the receiver type exactly matches before cases where we have to
517 // do autoref. But in the autoderef steps, the `&_` self type comes
518 // up *before* the `Vec<_>` self type.
520 // On the other hand, we don't want to just pick any by-value method
521 // before any by-autoref method; it's just that we need to consider
522 // the methods by autoderef order of *receiver types*, not *self
525 let deref_chain = autoderef_method_receiver(db, krate, ty);
526 for i in 0..deref_chain.len() {
527 iterate_method_candidates_with_autoref(
538 ControlFlow::Continue(())
540 LookupMode::Path => {
541 // No autoderef for path lookups
542 iterate_method_candidates_for_self_ty(
556 fn iterate_method_candidates_with_autoref(
557 deref_chain: &[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(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
565 ) -> ControlFlow<()> {
566 let (receiver_ty, rest) = match deref_chain.split_first() {
567 Some((rec, rest)) => (rec.clone(), rest),
569 never!("received empty deref-chain");
570 return ControlFlow::Break(());
573 iterate_method_candidates_by_receiver(
585 let refed = Canonical {
586 binders: receiver_ty.binders.clone(),
587 value: TyKind::Ref(Mutability::Not, static_lifetime(), receiver_ty.value.clone())
591 iterate_method_candidates_by_receiver(
603 let ref_muted = Canonical {
604 binders: receiver_ty.binders,
605 value: TyKind::Ref(Mutability::Mut, static_lifetime(), receiver_ty.value).intern(&Interner),
608 iterate_method_candidates_by_receiver(
621 fn iterate_method_candidates_by_receiver(
622 receiver_ty: &Canonical<Ty>,
623 rest_of_deref_chain: &[Canonical<Ty>],
624 db: &dyn HirDatabase,
625 env: Arc<TraitEnvironment>,
627 traits_in_scope: &FxHashSet<TraitId>,
628 visible_from_module: Option<ModuleId>,
630 mut callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
631 ) -> ControlFlow<()> {
632 // We're looking for methods with *receiver* type receiver_ty. These could
633 // be found in any of the derefs of receiver_ty, so we have to go through
635 for self_ty in iter::once(receiver_ty).chain(rest_of_deref_chain) {
636 iterate_inherent_methods(
648 for self_ty in iter::once(receiver_ty).chain(rest_of_deref_chain) {
649 iterate_trait_method_candidates(
661 ControlFlow::Continue(())
664 fn iterate_method_candidates_for_self_ty(
665 self_ty: &Canonical<Ty>,
666 db: &dyn HirDatabase,
667 env: Arc<TraitEnvironment>,
669 traits_in_scope: &FxHashSet<TraitId>,
670 visible_from_module: Option<ModuleId>,
672 mut callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
673 ) -> ControlFlow<()> {
674 iterate_inherent_methods(
684 iterate_trait_method_candidates(self_ty, db, env, krate, traits_in_scope, name, None, callback)
687 fn iterate_trait_method_candidates(
688 self_ty: &Canonical<Ty>,
689 db: &dyn HirDatabase,
690 env: Arc<TraitEnvironment>,
692 traits_in_scope: &FxHashSet<TraitId>,
694 receiver_ty: Option<&Canonical<Ty>>,
695 callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
696 ) -> ControlFlow<()> {
697 let receiver_is_array = matches!(self_ty.value.kind(&Interner), chalk_ir::TyKind::Array(..));
698 // if ty is `dyn Trait`, the trait doesn't need to be in scope
700 self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t));
701 let env_traits = match self_ty.value.kind(&Interner) {
702 TyKind::Placeholder(_) => {
703 // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
704 env.traits_in_scope_from_clauses(&self_ty.value)
705 .flat_map(|t| all_super_traits(db.upcast(), t))
710 let traits = inherent_trait.chain(env_traits).chain(traits_in_scope.iter().copied());
712 'traits: for t in traits {
713 let data = db.trait_data(t);
715 // Traits annotated with `#[rustc_skip_array_during_method_dispatch]` are skipped during
716 // method resolution, if the receiver is an array, and we're compiling for editions before
718 // This is to make `[a].into_iter()` not break code with the new `IntoIterator` impl for
720 if data.skip_array_during_method_dispatch && receiver_is_array {
721 // FIXME: this should really be using the edition of the method name's span, in case it
722 // comes from a macro
723 if db.crate_graph()[krate].edition < Edition::Edition2021 {
728 // we'll be lazy about checking whether the type implements the
729 // trait, but if we find out it doesn't, we'll skip the rest of the
731 let mut known_implemented = false;
732 for (_name, item) in data.items.iter() {
733 // Don't pass a `visible_from_module` down to `is_valid_candidate`,
734 // since only inherent methods should be included into visibility checking.
735 if !is_valid_candidate(db, env.clone(), name, receiver_ty, *item, self_ty, None) {
738 if !known_implemented {
739 let goal = generic_implements_goal(db, env.clone(), t, self_ty.clone());
740 if db.trait_solve(krate, goal.cast(&Interner)).is_none() {
744 known_implemented = true;
745 // FIXME: we shouldn't be ignoring the binders here
746 callback(self_ty, *item)?
749 ControlFlow::Continue(())
752 fn filter_inherent_impls_for_self_ty<'i>(
753 impls: &'i InherentImpls,
755 ) -> impl Iterator<Item = &'i ImplId> {
756 // inherent methods on arrays are fingerprinted as [T; {unknown}], so we must also consider them when
757 // resolving a method call on an array with a known len
759 if let TyKind::Array(parameters, array_len) = self_ty.kind(&Interner) {
760 if !array_len.is_unknown() {
761 let unknown_array_len_ty =
762 TyKind::Array(parameters.clone(), consteval::usize_const(None))
765 Some(impls.for_self_ty(&unknown_array_len_ty))
776 impls.for_self_ty(self_ty).iter().chain(array_impls)
779 fn iterate_inherent_methods(
780 self_ty: &Canonical<Ty>,
781 db: &dyn HirDatabase,
782 env: Arc<TraitEnvironment>,
784 receiver_ty: Option<&Canonical<Ty>>,
786 visible_from_module: Option<ModuleId>,
787 callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
788 ) -> ControlFlow<()> {
789 let def_crates = match def_crates(db, &self_ty.value, krate) {
791 None => return ControlFlow::Continue(()),
794 if let Some(module_id) = visible_from_module {
795 if let Some(block_id) = module_id.containing_block() {
796 if let Some(impls) = db.inherent_impls_in_block(block_id) {
811 for krate in def_crates {
812 let impls = db.inherent_impls_in_crate(krate);
824 return ControlFlow::Continue(());
826 fn impls_for_self_ty(
827 impls: &InherentImpls,
828 self_ty: &Canonical<Ty>,
829 db: &dyn HirDatabase,
830 env: Arc<TraitEnvironment>,
832 receiver_ty: Option<&Canonical<Ty>>,
833 visible_from_module: Option<ModuleId>,
834 callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
835 ) -> ControlFlow<()> {
836 let impls_for_self_ty = filter_inherent_impls_for_self_ty(impls, &self_ty.value);
837 for &impl_def in impls_for_self_ty {
838 for &item in &db.impl_data(impl_def).items {
839 if !is_valid_candidate(
850 // we have to check whether the self type unifies with the type
851 // that the impl is for. If we have a receiver type, this
852 // already happens in `is_valid_candidate` above; if not, we
854 if receiver_ty.is_none()
855 && inherent_impl_substs(db, env.clone(), impl_def, self_ty).is_none()
857 cov_mark::hit!(impl_self_type_match_without_receiver);
860 let receiver_ty = receiver_ty.unwrap_or(self_ty);
861 callback(receiver_ty, item)?;
864 ControlFlow::Continue(())
868 /// Returns the self type for the index trait call.
869 pub fn resolve_indexing_op(
870 db: &dyn HirDatabase,
872 env: Arc<TraitEnvironment>,
874 index_trait: TraitId,
875 ) -> Option<Canonical<Ty>> {
876 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
877 let deref_chain = autoderef_method_receiver(db, krate, ty);
878 for ty in deref_chain {
879 let goal = generic_implements_goal(db, env.clone(), index_trait, ty.clone());
880 if db.trait_solve(krate, goal.cast(&Interner)).is_some() {
887 fn is_transformed_receiver_ty_equal(transformed_receiver_ty: &Ty, receiver_ty: &Ty) -> bool {
888 if transformed_receiver_ty == receiver_ty {
892 // a transformed receiver may be considered equal (and a valid method call candidate) if it is an array
893 // with an unknown (i.e. generic) length, and the receiver is an array with the same item type but a known len,
894 // this allows inherent methods on arrays to be considered valid resolution candidates
895 match (transformed_receiver_ty.kind(&Interner), receiver_ty.kind(&Interner)) {
897 TyKind::Array(transformed_array_ty, transformed_array_len),
898 TyKind::Array(receiver_array_ty, receiver_array_len),
899 ) if transformed_array_ty == receiver_array_ty
900 && transformed_array_len.is_unknown()
901 && !receiver_array_len.is_unknown() =>
909 fn is_valid_candidate(
910 db: &dyn HirDatabase,
911 env: Arc<TraitEnvironment>,
913 receiver_ty: Option<&Canonical<Ty>>,
915 self_ty: &Canonical<Ty>,
916 visible_from_module: Option<ModuleId>,
919 AssocItemId::FunctionId(m) => {
920 let data = db.function_data(m);
921 if let Some(name) = name {
922 if &data.name != name {
926 if let Some(receiver_ty) = receiver_ty {
927 if !data.has_self_param() {
930 let transformed_receiver_ty = match transform_receiver_ty(db, env, m, self_ty) {
932 None => return false,
935 if !is_transformed_receiver_ty_equal(&transformed_receiver_ty, &receiver_ty.value) {
939 if let Some(from_module) = visible_from_module {
940 if !db.function_visibility(m).is_visible_from(db.upcast(), from_module) {
941 cov_mark::hit!(autoderef_candidate_not_visible);
948 AssocItemId::ConstId(c) => {
949 let data = db.const_data(c);
950 name.map_or(true, |name| data.name.as_ref() == Some(name)) && receiver_ty.is_none()
956 pub(crate) fn inherent_impl_substs(
957 db: &dyn HirDatabase,
958 env: Arc<TraitEnvironment>,
960 self_ty: &Canonical<Ty>,
961 ) -> Option<Substitution> {
962 // we create a var for each type parameter of the impl; we need to keep in
963 // mind here that `self_ty` might have vars of its own
964 let self_ty_vars = self_ty.binders.len(&Interner);
965 let vars = TyBuilder::subst_for_def(db, impl_id)
966 .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty_vars)
968 let self_ty_with_vars = db.impl_self_ty(impl_id).substitute(&Interner, &vars);
969 let mut kinds = self_ty.binders.interned().to_vec();
971 iter::repeat(chalk_ir::WithKind::new(
972 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
975 .take(vars.len(&Interner)),
977 let tys = Canonical {
978 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
979 value: (self_ty_with_vars, self_ty.value.clone()),
981 let substs = super::infer::unify(db, env, &tys)?;
982 // We only want the substs for the vars we added, not the ones from self_ty.
983 // Also, if any of the vars we added are still in there, we replace them by
984 // Unknown. I think this can only really happen if self_ty contained
985 // Unknown, and in that case we want the result to contain Unknown in those
988 Substitution::from_iter(&Interner, substs.iter(&Interner).cloned().skip(self_ty_vars));
989 Some(fallback_bound_vars(suffix, self_ty_vars))
992 /// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
993 /// num_vars_to_keep) by `TyKind::Unknown`.
994 fn fallback_bound_vars(s: Substitution, num_vars_to_keep: usize) -> Substitution {
995 crate::fold_free_vars(s, |bound, binders| {
996 if bound.index >= num_vars_to_keep && bound.debruijn == DebruijnIndex::INNERMOST {
997 TyKind::Error.intern(&Interner)
999 bound.shifted_in_from(binders).to_ty(&Interner)
1004 fn transform_receiver_ty(
1005 db: &dyn HirDatabase,
1006 env: Arc<TraitEnvironment>,
1007 function_id: FunctionId,
1008 self_ty: &Canonical<Ty>,
1010 let substs = match function_id.lookup(db.upcast()).container {
1011 ItemContainerId::TraitId(_) => TyBuilder::subst_for_def(db, function_id)
1012 .push(self_ty.value.clone())
1013 .fill_with_unknown()
1015 ItemContainerId::ImplId(impl_id) => {
1016 let impl_substs = inherent_impl_substs(db, env, impl_id, self_ty)?;
1017 TyBuilder::subst_for_def(db, function_id)
1018 .use_parent_substs(&impl_substs)
1019 .fill_with_unknown()
1023 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => unreachable!(),
1025 let sig = db.callable_item_signature(function_id.into());
1026 Some(sig.map(|s| s.params()[0].clone()).substitute(&Interner, &substs))
1029 pub fn implements_trait(
1031 db: &dyn HirDatabase,
1032 env: Arc<TraitEnvironment>,
1036 let goal = generic_implements_goal(db, env, trait_, ty.clone());
1037 let solution = db.trait_solve(krate, goal.cast(&Interner));
1042 pub fn implements_trait_unique(
1044 db: &dyn HirDatabase,
1045 env: Arc<TraitEnvironment>,
1049 let goal = generic_implements_goal(db, env, trait_, ty.clone());
1050 let solution = db.trait_solve(krate, goal.cast(&Interner));
1052 matches!(solution, Some(crate::Solution::Unique(_)))
1055 /// This creates Substs for a trait with the given Self type and type variables
1056 /// for all other parameters, to query Chalk with it.
1057 fn generic_implements_goal(
1058 db: &dyn HirDatabase,
1059 env: Arc<TraitEnvironment>,
1061 self_ty: Canonical<Ty>,
1062 ) -> Canonical<InEnvironment<super::DomainGoal>> {
1063 let mut kinds = self_ty.binders.interned().to_vec();
1064 let trait_ref = TyBuilder::trait_ref(db, trait_)
1065 .push(self_ty.value)
1066 .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
1069 iter::repeat(chalk_ir::WithKind::new(
1070 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
1071 UniverseIndex::ROOT,
1073 .take(trait_ref.substitution.len(&Interner) - 1),
1075 let obligation = trait_ref.cast(&Interner);
1077 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
1078 value: InEnvironment::new(&env.env, obligation),
1082 fn autoderef_method_receiver(
1083 db: &dyn HirDatabase,
1085 ty: InEnvironment<Canonical<Ty>>,
1086 ) -> Vec<Canonical<Ty>> {
1087 let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
1088 // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
1089 if let Some(TyKind::Array(parameters, _)) =
1090 deref_chain.last().map(|ty| ty.value.kind(&Interner))
1092 let kinds = deref_chain.last().unwrap().binders.clone();
1093 let unsized_ty = TyKind::Slice(parameters.clone()).intern(&Interner);
1094 deref_chain.push(Canonical { value: unsized_ty, binders: kinds })