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);
145 impls.shrink_to_fit();
150 pub(crate) fn trait_impls_in_block_query(
151 db: &dyn HirDatabase,
153 ) -> Option<Arc<Self>> {
154 let _p = profile::span("trait_impls_in_block_query");
155 let mut impls = Self { map: FxHashMap::default() };
157 let block_def_map = db.block_def_map(block)?;
158 impls.collect_def_map(db, &block_def_map);
159 impls.shrink_to_fit();
161 Some(Arc::new(impls))
164 pub(crate) fn trait_impls_in_deps_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
165 let _p = profile::span("trait_impls_in_deps_query");
166 let crate_graph = db.crate_graph();
167 let mut res = Self { map: FxHashMap::default() };
169 for krate in crate_graph.transitive_deps(krate) {
170 res.merge(&db.trait_impls_in_crate(krate));
177 fn shrink_to_fit(&mut self) {
178 self.map.shrink_to_fit();
179 self.map.values_mut().for_each(|map| {
181 map.values_mut().for_each(Vec::shrink_to_fit);
185 fn collect_def_map(&mut self, db: &dyn HirDatabase, def_map: &DefMap) {
186 for (_module_id, module_data) in def_map.modules() {
187 for impl_id in module_data.scope.impls() {
188 let target_trait = match db.impl_trait(impl_id) {
189 Some(tr) => tr.skip_binders().hir_trait_id(),
192 let self_ty = db.impl_self_ty(impl_id);
193 let self_ty_fp = TyFingerprint::for_trait_impl(self_ty.skip_binders());
202 // To better support custom derives, collect impls in all unnamed const items.
203 // const _: () = { ... };
204 for konst in collect_unnamed_consts(db, &module_data.scope) {
205 let body = db.body(konst.into());
206 for (_, block_def_map) in body.blocks(db.upcast()) {
207 self.collect_def_map(db, &block_def_map);
213 fn merge(&mut self, other: &Self) {
214 for (trait_, other_map) in &other.map {
215 let map = self.map.entry(*trait_).or_default();
216 for (fp, impls) in other_map {
217 let vec = map.entry(*fp).or_default();
223 /// Queries all trait impls for the given type.
224 pub fn for_self_ty_without_blanket_impls(
227 ) -> impl Iterator<Item = ImplId> + '_ {
230 .flat_map(move |impls| impls.get(&Some(fp)).into_iter())
231 .flat_map(|it| it.iter().copied())
234 /// Queries all impls of the given trait.
235 pub fn for_trait(&self, trait_: TraitId) -> impl Iterator<Item = ImplId> + '_ {
239 .flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
242 /// Queries all impls of `trait_` that may apply to `self_ty`.
243 pub fn for_trait_and_self_ty(
246 self_ty: TyFingerprint,
247 ) -> impl Iterator<Item = ImplId> + '_ {
251 .flat_map(move |map| map.get(&None).into_iter().chain(map.get(&Some(self_ty))))
252 .flat_map(|v| v.iter().copied())
255 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
256 self.map.values().flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
260 /// Inherent impls defined in some crate.
262 /// Inherent impls can only be defined in the crate that also defines the self type of the impl
263 /// (note that some primitives are considered to be defined by both libcore and liballoc).
265 /// This makes inherent impl lookup easier than trait impl lookup since we only have to consider a
267 #[derive(Debug, Eq, PartialEq)]
268 pub struct InherentImpls {
269 map: FxHashMap<TyFingerprint, Vec<ImplId>>,
273 pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
274 let mut impls = Self { map: FxHashMap::default() };
276 let crate_def_map = db.crate_def_map(krate);
277 impls.collect_def_map(db, &crate_def_map);
278 impls.shrink_to_fit();
280 return Arc::new(impls);
283 pub(crate) fn inherent_impls_in_block_query(
284 db: &dyn HirDatabase,
286 ) -> Option<Arc<Self>> {
287 let mut impls = Self { map: FxHashMap::default() };
288 if let Some(block_def_map) = db.block_def_map(block) {
289 impls.collect_def_map(db, &block_def_map);
290 impls.shrink_to_fit();
291 return Some(Arc::new(impls));
296 fn shrink_to_fit(&mut self) {
297 self.map.values_mut().for_each(Vec::shrink_to_fit);
298 self.map.shrink_to_fit();
301 fn collect_def_map(&mut self, db: &dyn HirDatabase, def_map: &DefMap) {
302 for (_module_id, module_data) in def_map.modules() {
303 for impl_id in module_data.scope.impls() {
304 let data = db.impl_data(impl_id);
305 if data.target_trait.is_some() {
309 let self_ty = db.impl_self_ty(impl_id);
310 let fp = TyFingerprint::for_inherent_impl(self_ty.skip_binders());
311 if let Some(fp) = fp {
312 self.map.entry(fp).or_default().push(impl_id);
314 // `fp` should only be `None` in error cases (either erroneous code or incomplete name resolution)
317 // To better support custom derives, collect impls in all unnamed const items.
318 // const _: () = { ... };
319 for konst in collect_unnamed_consts(db, &module_data.scope) {
320 let body = db.body(konst.into());
321 for (_, block_def_map) in body.blocks(db.upcast()) {
322 self.collect_def_map(db, &block_def_map);
328 pub fn for_self_ty(&self, self_ty: &Ty) -> &[ImplId] {
329 match TyFingerprint::for_inherent_impl(self_ty) {
330 Some(fp) => self.map.get(&fp).map(|vec| vec.as_ref()).unwrap_or(&[]),
335 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
336 self.map.values().flat_map(|v| v.iter().copied())
340 fn collect_unnamed_consts<'a>(
341 db: &'a dyn HirDatabase,
342 scope: &'a ItemScope,
343 ) -> impl Iterator<Item = ConstId> + 'a {
344 let unnamed_consts = scope.unnamed_consts();
346 // FIXME: Also treat consts named `_DERIVE_*` as unnamed, since synstructure generates those.
347 // Should be removed once synstructure stops doing that.
348 let synstructure_hack_consts = scope.values().filter_map(|(item, _)| match item {
349 ModuleDefId::ConstId(id) => {
350 let loc = id.lookup(db.upcast());
351 let item_tree = loc.id.item_tree(db.upcast());
352 if item_tree[loc.id.value]
355 .map_or(false, |n| n.to_smol_str().starts_with("_DERIVE_"))
365 unnamed_consts.chain(synstructure_hack_consts)
369 db: &dyn HirDatabase,
372 ) -> Option<ArrayVec<CrateId, 2>> {
373 // Types like slice can have inherent impls in several crates, (core and alloc).
374 // The corresponding impls are marked with lang items, so we can use them to find the required crates.
375 macro_rules! lang_item_crate {
376 ($($name:expr),+ $(,)?) => {{
377 let mut v = ArrayVec::<LangItemTarget, 2>::new();
379 v.extend(db.lang_item(cur_crate, $name.into()));
385 let mod_to_crate_ids = |module: ModuleId| Some(iter::once(module.krate()).collect());
387 let lang_item_targets = match ty.kind(&Interner) {
388 TyKind::Adt(AdtId(def_id), _) => {
389 return mod_to_crate_ids(def_id.module(db.upcast()));
391 TyKind::Foreign(id) => {
392 return mod_to_crate_ids(
393 from_foreign_def_id(*id).lookup(db.upcast()).module(db.upcast()),
396 TyKind::Scalar(Scalar::Bool) => lang_item_crate!("bool"),
397 TyKind::Scalar(Scalar::Char) => lang_item_crate!("char"),
398 TyKind::Scalar(Scalar::Float(f)) => match f {
399 // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime)
400 FloatTy::F32 => lang_item_crate!("f32", "f32_runtime"),
401 FloatTy::F64 => lang_item_crate!("f64", "f64_runtime"),
403 &TyKind::Scalar(Scalar::Int(t)) => {
404 lang_item_crate!(primitive::int_ty_to_string(t))
406 &TyKind::Scalar(Scalar::Uint(t)) => {
407 lang_item_crate!(primitive::uint_ty_to_string(t))
409 TyKind::Str => lang_item_crate!("str_alloc", "str"),
410 TyKind::Slice(_) => lang_item_crate!("slice_alloc", "slice"),
411 TyKind::Array(..) => lang_item_crate!("array"),
412 TyKind::Raw(Mutability::Not, _) => lang_item_crate!("const_ptr"),
413 TyKind::Raw(Mutability::Mut, _) => lang_item_crate!("mut_ptr"),
415 return ty.dyn_trait().and_then(|trait_| {
416 mod_to_crate_ids(GenericDefId::TraitId(trait_).module(db.upcast()))
421 let res = lang_item_targets
423 .filter_map(|it| match it {
424 LangItemTarget::ImplDefId(it) => Some(it),
427 .map(|it| it.lookup(db.upcast()).container.krate())
432 /// Look up the method with the given name, returning the actual autoderefed
433 /// receiver type (but without autoref applied yet).
434 pub(crate) fn lookup_method(
436 db: &dyn HirDatabase,
437 env: Arc<TraitEnvironment>,
439 traits_in_scope: &FxHashSet<TraitId>,
440 visible_from_module: Option<ModuleId>,
442 ) -> Option<(Canonical<Ty>, FunctionId)> {
443 iterate_method_candidates(
451 LookupMode::MethodCall,
453 AssocItemId::FunctionId(f) => Some((ty.clone(), f)),
459 /// Whether we're looking up a dotted method call (like `v.len()`) or a path
460 /// (like `Vec::new`).
461 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
462 pub enum LookupMode {
463 /// Looking up a method call like `v.len()`: We only consider candidates
464 /// that have a `self` parameter, and do autoderef.
466 /// Looking up a path like `Vec::new` or `Vec::default`: We consider all
467 /// candidates including associated constants, but don't do autoderef.
471 // This would be nicer if it just returned an iterator, but that runs into
472 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
473 // FIXME add a context type here?
474 pub fn iterate_method_candidates<T>(
476 db: &dyn HirDatabase,
477 env: Arc<TraitEnvironment>,
479 traits_in_scope: &FxHashSet<TraitId>,
480 visible_from_module: Option<ModuleId>,
483 mut callback: impl FnMut(&Canonical<Ty>, AssocItemId) -> Option<T>,
486 iterate_method_candidates_dyn(
496 assert!(slot.is_none());
497 if let Some(it) = callback(ty, item) {
499 return ControlFlow::Break(());
501 ControlFlow::Continue(())
507 pub fn iterate_method_candidates_dyn(
509 db: &dyn HirDatabase,
510 env: Arc<TraitEnvironment>,
512 traits_in_scope: &FxHashSet<TraitId>,
513 visible_from_module: Option<ModuleId>,
516 callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
517 ) -> ControlFlow<()> {
519 LookupMode::MethodCall => {
520 // For method calls, rust first does any number of autoderef, and then one
521 // autoref (i.e. when the method takes &self or &mut self). We just ignore
522 // the autoref currently -- when we find a method matching the given name,
523 // we assume it fits.
525 // Also note that when we've got a receiver like &S, even if the method we
526 // find in the end takes &self, we still do the autoderef step (just as
527 // rustc does an autoderef and then autoref again).
528 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
530 // We have to be careful about the order we're looking at candidates
531 // in here. Consider the case where we're resolving `x.clone()`
532 // where `x: &Vec<_>`. This resolves to the clone method with self
533 // type `Vec<_>`, *not* `&_`. I.e. we need to consider methods where
534 // the receiver type exactly matches before cases where we have to
535 // do autoref. But in the autoderef steps, the `&_` self type comes
536 // up *before* the `Vec<_>` self type.
538 // On the other hand, we don't want to just pick any by-value method
539 // before any by-autoref method; it's just that we need to consider
540 // the methods by autoderef order of *receiver types*, not *self
543 let deref_chain = autoderef_method_receiver(db, krate, ty);
544 for i in 0..deref_chain.len() {
545 iterate_method_candidates_with_autoref(
556 ControlFlow::Continue(())
558 LookupMode::Path => {
559 // No autoderef for path lookups
560 iterate_method_candidates_for_self_ty(
574 fn iterate_method_candidates_with_autoref(
575 deref_chain: &[Canonical<Ty>],
576 db: &dyn HirDatabase,
577 env: Arc<TraitEnvironment>,
579 traits_in_scope: &FxHashSet<TraitId>,
580 visible_from_module: Option<ModuleId>,
582 mut callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
583 ) -> ControlFlow<()> {
584 let (receiver_ty, rest) = match deref_chain.split_first() {
585 Some((rec, rest)) => (rec.clone(), rest),
587 never!("received empty deref-chain");
588 return ControlFlow::Break(());
591 iterate_method_candidates_by_receiver(
603 let refed = Canonical {
604 binders: receiver_ty.binders.clone(),
605 value: TyKind::Ref(Mutability::Not, static_lifetime(), receiver_ty.value.clone())
609 iterate_method_candidates_by_receiver(
621 let ref_muted = Canonical {
622 binders: receiver_ty.binders,
623 value: TyKind::Ref(Mutability::Mut, static_lifetime(), receiver_ty.value).intern(&Interner),
626 iterate_method_candidates_by_receiver(
639 fn iterate_method_candidates_by_receiver(
640 receiver_ty: &Canonical<Ty>,
641 rest_of_deref_chain: &[Canonical<Ty>],
642 db: &dyn HirDatabase,
643 env: Arc<TraitEnvironment>,
645 traits_in_scope: &FxHashSet<TraitId>,
646 visible_from_module: Option<ModuleId>,
648 mut callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
649 ) -> ControlFlow<()> {
650 // We're looking for methods with *receiver* type receiver_ty. These could
651 // be found in any of the derefs of receiver_ty, so we have to go through
653 for self_ty in iter::once(receiver_ty).chain(rest_of_deref_chain) {
654 iterate_inherent_methods(
666 for self_ty in iter::once(receiver_ty).chain(rest_of_deref_chain) {
667 iterate_trait_method_candidates(
679 ControlFlow::Continue(())
682 fn iterate_method_candidates_for_self_ty(
683 self_ty: &Canonical<Ty>,
684 db: &dyn HirDatabase,
685 env: Arc<TraitEnvironment>,
687 traits_in_scope: &FxHashSet<TraitId>,
688 visible_from_module: Option<ModuleId>,
690 mut callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
691 ) -> ControlFlow<()> {
692 iterate_inherent_methods(
702 iterate_trait_method_candidates(self_ty, db, env, krate, traits_in_scope, name, None, callback)
705 fn iterate_trait_method_candidates(
706 self_ty: &Canonical<Ty>,
707 db: &dyn HirDatabase,
708 env: Arc<TraitEnvironment>,
710 traits_in_scope: &FxHashSet<TraitId>,
712 receiver_ty: Option<&Canonical<Ty>>,
713 callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
714 ) -> ControlFlow<()> {
715 let receiver_is_array = matches!(self_ty.value.kind(&Interner), chalk_ir::TyKind::Array(..));
716 // if ty is `dyn Trait`, the trait doesn't need to be in scope
718 self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t));
719 let env_traits = match self_ty.value.kind(&Interner) {
720 TyKind::Placeholder(_) => {
721 // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
722 env.traits_in_scope_from_clauses(&self_ty.value)
723 .flat_map(|t| all_super_traits(db.upcast(), t))
728 let traits = inherent_trait.chain(env_traits).chain(traits_in_scope.iter().copied());
730 'traits: for t in traits {
731 let data = db.trait_data(t);
733 // Traits annotated with `#[rustc_skip_array_during_method_dispatch]` are skipped during
734 // method resolution, if the receiver is an array, and we're compiling for editions before
736 // This is to make `[a].into_iter()` not break code with the new `IntoIterator` impl for
738 if data.skip_array_during_method_dispatch && receiver_is_array {
739 // FIXME: this should really be using the edition of the method name's span, in case it
740 // comes from a macro
741 if db.crate_graph()[krate].edition < Edition::Edition2021 {
746 // we'll be lazy about checking whether the type implements the
747 // trait, but if we find out it doesn't, we'll skip the rest of the
749 let mut known_implemented = false;
750 for (_name, item) in data.items.iter() {
751 // Don't pass a `visible_from_module` down to `is_valid_candidate`,
752 // since only inherent methods should be included into visibility checking.
753 if !is_valid_candidate(db, env.clone(), name, receiver_ty, *item, self_ty, None) {
756 if !known_implemented {
757 let goal = generic_implements_goal(db, env.clone(), t, self_ty.clone());
758 if db.trait_solve(krate, goal.cast(&Interner)).is_none() {
762 known_implemented = true;
763 // FIXME: we shouldn't be ignoring the binders here
764 callback(self_ty, *item)?
767 ControlFlow::Continue(())
770 fn filter_inherent_impls_for_self_ty<'i>(
771 impls: &'i InherentImpls,
773 ) -> impl Iterator<Item = &'i ImplId> {
774 // inherent methods on arrays are fingerprinted as [T; {unknown}], so we must also consider them when
775 // resolving a method call on an array with a known len
777 if let TyKind::Array(parameters, array_len) = self_ty.kind(&Interner) {
778 if !array_len.is_unknown() {
779 let unknown_array_len_ty =
780 TyKind::Array(parameters.clone(), consteval::usize_const(None))
783 Some(impls.for_self_ty(&unknown_array_len_ty))
794 impls.for_self_ty(self_ty).iter().chain(array_impls)
797 fn iterate_inherent_methods(
798 self_ty: &Canonical<Ty>,
799 db: &dyn HirDatabase,
800 env: Arc<TraitEnvironment>,
802 receiver_ty: Option<&Canonical<Ty>>,
804 visible_from_module: Option<ModuleId>,
805 callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
806 ) -> ControlFlow<()> {
807 let def_crates = match def_crates(db, &self_ty.value, krate) {
809 None => return ControlFlow::Continue(()),
812 if let Some(module_id) = visible_from_module {
813 if let Some(block_id) = module_id.containing_block() {
814 if let Some(impls) = db.inherent_impls_in_block(block_id) {
829 for krate in def_crates {
830 let impls = db.inherent_impls_in_crate(krate);
842 return ControlFlow::Continue(());
844 fn impls_for_self_ty(
845 impls: &InherentImpls,
846 self_ty: &Canonical<Ty>,
847 db: &dyn HirDatabase,
848 env: Arc<TraitEnvironment>,
850 receiver_ty: Option<&Canonical<Ty>>,
851 visible_from_module: Option<ModuleId>,
852 callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
853 ) -> ControlFlow<()> {
854 let impls_for_self_ty = filter_inherent_impls_for_self_ty(impls, &self_ty.value);
855 for &impl_def in impls_for_self_ty {
856 for &item in &db.impl_data(impl_def).items {
857 if !is_valid_candidate(
868 // we have to check whether the self type unifies with the type
869 // that the impl is for. If we have a receiver type, this
870 // already happens in `is_valid_candidate` above; if not, we
872 if receiver_ty.is_none()
873 && inherent_impl_substs(db, env.clone(), impl_def, self_ty).is_none()
875 cov_mark::hit!(impl_self_type_match_without_receiver);
878 let receiver_ty = receiver_ty.unwrap_or(self_ty);
879 callback(receiver_ty, item)?;
882 ControlFlow::Continue(())
886 /// Returns the self type for the index trait call.
887 pub fn resolve_indexing_op(
888 db: &dyn HirDatabase,
890 env: Arc<TraitEnvironment>,
892 index_trait: TraitId,
893 ) -> Option<Canonical<Ty>> {
894 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
895 let deref_chain = autoderef_method_receiver(db, krate, ty);
896 for ty in deref_chain {
897 let goal = generic_implements_goal(db, env.clone(), index_trait, ty.clone());
898 if db.trait_solve(krate, goal.cast(&Interner)).is_some() {
905 fn is_transformed_receiver_ty_equal(transformed_receiver_ty: &Ty, receiver_ty: &Ty) -> bool {
906 if transformed_receiver_ty == receiver_ty {
910 // a transformed receiver may be considered equal (and a valid method call candidate) if it is an array
911 // with an unknown (i.e. generic) length, and the receiver is an array with the same item type but a known len,
912 // this allows inherent methods on arrays to be considered valid resolution candidates
913 match (transformed_receiver_ty.kind(&Interner), receiver_ty.kind(&Interner)) {
915 TyKind::Array(transformed_array_ty, transformed_array_len),
916 TyKind::Array(receiver_array_ty, receiver_array_len),
917 ) if transformed_array_ty == receiver_array_ty
918 && transformed_array_len.is_unknown()
919 && !receiver_array_len.is_unknown() =>
927 fn is_valid_candidate(
928 db: &dyn HirDatabase,
929 env: Arc<TraitEnvironment>,
931 receiver_ty: Option<&Canonical<Ty>>,
933 self_ty: &Canonical<Ty>,
934 visible_from_module: Option<ModuleId>,
937 AssocItemId::FunctionId(m) => {
938 let data = db.function_data(m);
939 if let Some(name) = name {
940 if &data.name != name {
944 if let Some(receiver_ty) = receiver_ty {
945 if !data.has_self_param() {
948 let transformed_receiver_ty = match transform_receiver_ty(db, env, m, self_ty) {
950 None => return false,
953 if !is_transformed_receiver_ty_equal(&transformed_receiver_ty, &receiver_ty.value) {
957 if let Some(from_module) = visible_from_module {
958 if !db.function_visibility(m).is_visible_from(db.upcast(), from_module) {
959 cov_mark::hit!(autoderef_candidate_not_visible);
966 AssocItemId::ConstId(c) => {
967 let data = db.const_data(c);
968 name.map_or(true, |name| data.name.as_ref() == Some(name)) && receiver_ty.is_none()
974 pub(crate) fn inherent_impl_substs(
975 db: &dyn HirDatabase,
976 env: Arc<TraitEnvironment>,
978 self_ty: &Canonical<Ty>,
979 ) -> Option<Substitution> {
980 // we create a var for each type parameter of the impl; we need to keep in
981 // mind here that `self_ty` might have vars of its own
982 let self_ty_vars = self_ty.binders.len(&Interner);
983 let vars = TyBuilder::subst_for_def(db, impl_id)
984 .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty_vars)
986 let self_ty_with_vars = db.impl_self_ty(impl_id).substitute(&Interner, &vars);
987 let mut kinds = self_ty.binders.interned().to_vec();
989 iter::repeat(chalk_ir::WithKind::new(
990 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
993 .take(vars.len(&Interner)),
995 let tys = Canonical {
996 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
997 value: (self_ty_with_vars, self_ty.value.clone()),
999 let substs = super::infer::unify(db, env, &tys)?;
1000 // We only want the substs for the vars we added, not the ones from self_ty.
1001 // Also, if any of the vars we added are still in there, we replace them by
1002 // Unknown. I think this can only really happen if self_ty contained
1003 // Unknown, and in that case we want the result to contain Unknown in those
1006 Substitution::from_iter(&Interner, substs.iter(&Interner).cloned().skip(self_ty_vars));
1007 Some(fallback_bound_vars(suffix, self_ty_vars))
1010 /// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
1011 /// num_vars_to_keep) by `TyKind::Unknown`.
1012 fn fallback_bound_vars(s: Substitution, num_vars_to_keep: usize) -> Substitution {
1013 crate::fold_free_vars(s, |bound, binders| {
1014 if bound.index >= num_vars_to_keep && bound.debruijn == DebruijnIndex::INNERMOST {
1015 TyKind::Error.intern(&Interner)
1017 bound.shifted_in_from(binders).to_ty(&Interner)
1022 fn transform_receiver_ty(
1023 db: &dyn HirDatabase,
1024 env: Arc<TraitEnvironment>,
1025 function_id: FunctionId,
1026 self_ty: &Canonical<Ty>,
1028 let substs = match function_id.lookup(db.upcast()).container {
1029 ItemContainerId::TraitId(_) => TyBuilder::subst_for_def(db, function_id)
1030 .push(self_ty.value.clone())
1031 .fill_with_unknown()
1033 ItemContainerId::ImplId(impl_id) => {
1034 let impl_substs = inherent_impl_substs(db, env, impl_id, self_ty)?;
1035 TyBuilder::subst_for_def(db, function_id)
1036 .use_parent_substs(&impl_substs)
1037 .fill_with_unknown()
1041 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => unreachable!(),
1043 let sig = db.callable_item_signature(function_id.into());
1044 Some(sig.map(|s| s.params()[0].clone()).substitute(&Interner, &substs))
1047 pub fn implements_trait(
1049 db: &dyn HirDatabase,
1050 env: Arc<TraitEnvironment>,
1054 let goal = generic_implements_goal(db, env, trait_, ty.clone());
1055 let solution = db.trait_solve(krate, goal.cast(&Interner));
1060 pub fn implements_trait_unique(
1062 db: &dyn HirDatabase,
1063 env: Arc<TraitEnvironment>,
1067 let goal = generic_implements_goal(db, env, trait_, ty.clone());
1068 let solution = db.trait_solve(krate, goal.cast(&Interner));
1070 matches!(solution, Some(crate::Solution::Unique(_)))
1073 /// This creates Substs for a trait with the given Self type and type variables
1074 /// for all other parameters, to query Chalk with it.
1075 fn generic_implements_goal(
1076 db: &dyn HirDatabase,
1077 env: Arc<TraitEnvironment>,
1079 self_ty: Canonical<Ty>,
1080 ) -> Canonical<InEnvironment<super::DomainGoal>> {
1081 let mut kinds = self_ty.binders.interned().to_vec();
1082 let trait_ref = TyBuilder::trait_ref(db, trait_)
1083 .push(self_ty.value)
1084 .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
1087 iter::repeat(chalk_ir::WithKind::new(
1088 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
1089 UniverseIndex::ROOT,
1091 .take(trait_ref.substitution.len(&Interner) - 1),
1093 let obligation = trait_ref.cast(&Interner);
1095 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
1096 value: InEnvironment::new(&env.env, obligation),
1100 fn autoderef_method_receiver(
1101 db: &dyn HirDatabase,
1103 ty: InEnvironment<Canonical<Ty>>,
1104 ) -> Vec<Canonical<Ty>> {
1105 let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
1106 // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
1107 if let Some(TyKind::Array(parameters, _)) =
1108 deref_chain.last().map(|ty| ty.value.kind(&Interner))
1110 let kinds = deref_chain.last().unwrap().binders.clone();
1111 let unsized_ty = TyKind::Slice(parameters.clone()).intern(&Interner);
1112 deref_chain.push(Canonical { value: unsized_ty, binders: kinds })