1 //! This module is concerned with finding methods that a given type provides.
2 //! For details about how this works in rustc, see the method lookup page in the
3 //! [rustc guide](https://rust-lang.github.io/rustc-guide/method-lookup.html)
4 //! and the corresponding code mostly in librustc_typeck/check/method/probe.rs.
5 use std::{iter, sync::Arc};
7 use arrayvec::ArrayVec;
9 use chalk_ir::{cast::Cast, Mutability, UniverseIndex};
11 lang_item::LangItemTarget, nameres::DefMap, AssocContainerId, AssocItemId, FunctionId,
12 GenericDefId, HasModule, ImplId, Lookup, ModuleId, TraitId,
14 use hir_expand::name::Name;
15 use rustc_hash::{FxHashMap, FxHashSet};
22 primitive::{self, FloatTy, IntTy, UintTy},
24 utils::all_super_traits,
25 AdtId, Canonical, CanonicalVarKinds, DebruijnIndex, ForeignDefId, HirDisplay, InEnvironment,
26 Interner, 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(|trait_| TyFingerprint::Dyn(trait_))?,
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(|trait_| TyFingerprint::Dyn(trait_))?,
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 collect_def_map(db, &crate_def_map, &mut impls);
145 return Arc::new(impls);
147 fn collect_def_map(db: &dyn HirDatabase, def_map: &DefMap, impls: &mut TraitImpls) {
148 for (_module_id, module_data) in def_map.modules() {
149 for impl_id in module_data.scope.impls() {
150 let target_trait = match db.impl_trait(impl_id) {
151 Some(tr) => tr.skip_binders().hir_trait_id(),
154 let self_ty = db.impl_self_ty(impl_id);
155 let self_ty_fp = TyFingerprint::for_trait_impl(self_ty.skip_binders());
165 // To better support custom derives, collect impls in all unnamed const items.
166 // const _: () = { ... };
167 for konst in module_data.scope.unnamed_consts() {
168 let body = db.body(konst.into());
169 for (_, block_def_map) in body.blocks(db.upcast()) {
170 collect_def_map(db, &block_def_map, impls);
177 pub(crate) fn trait_impls_in_deps_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
178 let _p = profile::span("trait_impls_in_deps_query");
179 let crate_graph = db.crate_graph();
180 let mut res = Self { map: FxHashMap::default() };
182 for krate in crate_graph.transitive_deps(krate) {
183 res.merge(&db.trait_impls_in_crate(krate));
189 fn merge(&mut self, other: &Self) {
190 for (trait_, other_map) in &other.map {
191 let map = self.map.entry(*trait_).or_default();
192 for (fp, impls) in other_map {
193 let vec = map.entry(*fp).or_default();
199 /// Queries all trait impls for the given type.
200 pub fn for_self_ty_without_blanket_impls(
203 ) -> impl Iterator<Item = ImplId> + '_ {
206 .flat_map(move |impls| impls.get(&Some(fp)).into_iter())
207 .flat_map(|it| it.iter().copied())
210 /// Queries all impls of the given trait.
211 pub fn for_trait(&self, trait_: TraitId) -> impl Iterator<Item = ImplId> + '_ {
215 .flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
218 /// Queries all impls of `trait_` that may apply to `self_ty`.
219 pub fn for_trait_and_self_ty(
222 self_ty: TyFingerprint,
223 ) -> impl Iterator<Item = ImplId> + '_ {
227 .flat_map(move |map| map.get(&None).into_iter().chain(map.get(&Some(self_ty))))
228 .flat_map(|v| v.iter().copied())
231 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
232 self.map.values().flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
236 /// Inherent impls defined in some crate.
238 /// Inherent impls can only be defined in the crate that also defines the self type of the impl
239 /// (note that some primitives are considered to be defined by both libcore and liballoc).
241 /// This makes inherent impl lookup easier than trait impl lookup since we only have to consider a
243 #[derive(Debug, Eq, PartialEq)]
244 pub struct InherentImpls {
245 map: FxHashMap<TyFingerprint, Vec<ImplId>>,
249 pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
250 let mut map: FxHashMap<_, Vec<_>> = FxHashMap::default();
252 let crate_def_map = db.crate_def_map(krate);
253 for (_module_id, module_data) in crate_def_map.modules() {
254 for impl_id in module_data.scope.impls() {
255 let data = db.impl_data(impl_id);
256 if data.target_trait.is_some() {
260 let self_ty = db.impl_self_ty(impl_id);
261 let fp = TyFingerprint::for_inherent_impl(self_ty.skip_binders());
262 always!(fp.is_some(), "no fingerprint for {}", self_ty.skip_binders().display(db));
263 if let Some(fp) = fp {
264 map.entry(fp).or_default().push(impl_id);
269 // NOTE: We're not collecting inherent impls from unnamed consts here, we intentionally only
270 // support trait impls there.
272 Arc::new(Self { map })
275 pub fn for_self_ty(&self, self_ty: &Ty) -> &[ImplId] {
276 match TyFingerprint::for_inherent_impl(self_ty) {
277 Some(fp) => self.map.get(&fp).map(|vec| vec.as_ref()).unwrap_or(&[]),
282 pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
283 self.map.values().flat_map(|v| v.iter().copied())
288 db: &dyn HirDatabase,
291 ) -> Option<ArrayVec<CrateId, 2>> {
292 // Types like slice can have inherent impls in several crates, (core and alloc).
293 // The corresponding impls are marked with lang items, so we can use them to find the required crates.
294 macro_rules! lang_item_crate {
295 ($($name:expr),+ $(,)?) => {{
296 let mut v = ArrayVec::<LangItemTarget, 2>::new();
298 v.extend(db.lang_item(cur_crate, $name.into()));
304 let mod_to_crate_ids = |module: ModuleId| Some(std::iter::once(module.krate()).collect());
306 let lang_item_targets = match ty.kind(&Interner) {
307 TyKind::Adt(AdtId(def_id), _) => {
308 return mod_to_crate_ids(def_id.module(db.upcast()));
310 TyKind::Foreign(id) => {
311 return mod_to_crate_ids(
312 from_foreign_def_id(*id).lookup(db.upcast()).module(db.upcast()),
315 TyKind::Scalar(Scalar::Bool) => lang_item_crate!("bool"),
316 TyKind::Scalar(Scalar::Char) => lang_item_crate!("char"),
317 TyKind::Scalar(Scalar::Float(f)) => match f {
318 // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime)
319 FloatTy::F32 => lang_item_crate!("f32", "f32_runtime"),
320 FloatTy::F64 => lang_item_crate!("f64", "f64_runtime"),
322 &TyKind::Scalar(Scalar::Int(t)) => {
323 lang_item_crate!(primitive::int_ty_to_string(t))
325 &TyKind::Scalar(Scalar::Uint(t)) => {
326 lang_item_crate!(primitive::uint_ty_to_string(t))
328 TyKind::Str => lang_item_crate!("str_alloc", "str"),
329 TyKind::Slice(_) => lang_item_crate!("slice_alloc", "slice"),
330 TyKind::Raw(Mutability::Not, _) => lang_item_crate!("const_ptr"),
331 TyKind::Raw(Mutability::Mut, _) => lang_item_crate!("mut_ptr"),
333 return ty.dyn_trait().and_then(|trait_| {
334 mod_to_crate_ids(GenericDefId::TraitId(trait_).module(db.upcast()))
339 let res = lang_item_targets
341 .filter_map(|it| match it {
342 LangItemTarget::ImplDefId(it) => Some(it),
345 .map(|it| it.lookup(db.upcast()).container.krate())
350 /// Look up the method with the given name, returning the actual autoderefed
351 /// receiver type (but without autoref applied yet).
352 pub(crate) fn lookup_method(
354 db: &dyn HirDatabase,
355 env: Arc<TraitEnvironment>,
357 traits_in_scope: &FxHashSet<TraitId>,
358 visible_from_module: Option<ModuleId>,
360 ) -> Option<(Ty, FunctionId)> {
361 iterate_method_candidates(
369 LookupMode::MethodCall,
371 AssocItemId::FunctionId(f) => Some((ty.clone(), f)),
377 /// Whether we're looking up a dotted method call (like `v.len()`) or a path
378 /// (like `Vec::new`).
379 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
380 pub enum LookupMode {
381 /// Looking up a method call like `v.len()`: We only consider candidates
382 /// that have a `self` parameter, and do autoderef.
384 /// Looking up a path like `Vec::new` or `Vec::default`: We consider all
385 /// candidates including associated constants, but don't do autoderef.
389 // This would be nicer if it just returned an iterator, but that runs into
390 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
391 // FIXME add a context type here?
392 pub fn iterate_method_candidates<T>(
394 db: &dyn HirDatabase,
395 env: Arc<TraitEnvironment>,
397 traits_in_scope: &FxHashSet<TraitId>,
398 visible_from_module: Option<ModuleId>,
401 mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>,
404 iterate_method_candidates_impl(
414 assert!(slot.is_none());
415 slot = callback(ty, item);
422 fn iterate_method_candidates_impl(
424 db: &dyn HirDatabase,
425 env: Arc<TraitEnvironment>,
427 traits_in_scope: &FxHashSet<TraitId>,
428 visible_from_module: Option<ModuleId>,
431 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
434 LookupMode::MethodCall => {
435 // For method calls, rust first does any number of autoderef, and then one
436 // autoref (i.e. when the method takes &self or &mut self). We just ignore
437 // the autoref currently -- when we find a method matching the given name,
438 // we assume it fits.
440 // Also note that when we've got a receiver like &S, even if the method we
441 // find in the end takes &self, we still do the autoderef step (just as
442 // rustc does an autoderef and then autoref again).
443 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
445 // We have to be careful about the order we're looking at candidates
446 // in here. Consider the case where we're resolving `x.clone()`
447 // where `x: &Vec<_>`. This resolves to the clone method with self
448 // type `Vec<_>`, *not* `&_`. I.e. we need to consider methods where
449 // the receiver type exactly matches before cases where we have to
450 // do autoref. But in the autoderef steps, the `&_` self type comes
451 // up *before* the `Vec<_>` self type.
453 // On the other hand, we don't want to just pick any by-value method
454 // before any by-autoref method; it's just that we need to consider
455 // the methods by autoderef order of *receiver types*, not *self
458 let deref_chain = autoderef_method_receiver(db, krate, ty);
459 for i in 0..deref_chain.len() {
460 if iterate_method_candidates_with_autoref(
475 LookupMode::Path => {
476 // No autoderef for path lookups
477 iterate_method_candidates_for_self_ty(
491 fn iterate_method_candidates_with_autoref(
492 deref_chain: &[Canonical<Ty>],
493 db: &dyn HirDatabase,
494 env: Arc<TraitEnvironment>,
496 traits_in_scope: &FxHashSet<TraitId>,
497 visible_from_module: Option<ModuleId>,
499 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
501 if iterate_method_candidates_by_receiver(
514 let refed = Canonical {
515 binders: deref_chain[0].binders.clone(),
516 value: TyKind::Ref(Mutability::Not, static_lifetime(), deref_chain[0].value.clone())
519 if iterate_method_candidates_by_receiver(
532 let ref_muted = Canonical {
533 binders: deref_chain[0].binders.clone(),
534 value: TyKind::Ref(Mutability::Mut, static_lifetime(), deref_chain[0].value.clone())
537 if iterate_method_candidates_by_receiver(
553 fn iterate_method_candidates_by_receiver(
554 receiver_ty: &Canonical<Ty>,
555 rest_of_deref_chain: &[Canonical<Ty>],
556 db: &dyn HirDatabase,
557 env: Arc<TraitEnvironment>,
559 traits_in_scope: &FxHashSet<TraitId>,
560 visible_from_module: Option<ModuleId>,
562 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
564 // We're looking for methods with *receiver* type receiver_ty. These could
565 // be found in any of the derefs of receiver_ty, so we have to go through
567 for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
568 if iterate_inherent_methods(
580 for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
581 if iterate_trait_method_candidates(
597 fn iterate_method_candidates_for_self_ty(
598 self_ty: &Canonical<Ty>,
599 db: &dyn HirDatabase,
600 env: Arc<TraitEnvironment>,
602 traits_in_scope: &FxHashSet<TraitId>,
603 visible_from_module: Option<ModuleId>,
605 mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
607 if iterate_inherent_methods(self_ty, db, name, None, krate, visible_from_module, &mut callback)
611 iterate_trait_method_candidates(self_ty, db, env, krate, traits_in_scope, name, None, callback)
614 fn iterate_trait_method_candidates(
615 self_ty: &Canonical<Ty>,
616 db: &dyn HirDatabase,
617 env: Arc<TraitEnvironment>,
619 traits_in_scope: &FxHashSet<TraitId>,
621 receiver_ty: Option<&Canonical<Ty>>,
622 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
624 // if ty is `dyn Trait`, the trait doesn't need to be in scope
626 self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t));
627 let env_traits = if let TyKind::Placeholder(_) = self_ty.value.kind(&Interner) {
628 // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
629 env.traits_in_scope_from_clauses(&self_ty.value)
630 .flat_map(|t| all_super_traits(db.upcast(), t))
636 inherent_trait.chain(env_traits.into_iter()).chain(traits_in_scope.iter().copied());
637 'traits: for t in traits {
638 let data = db.trait_data(t);
640 // we'll be lazy about checking whether the type implements the
641 // trait, but if we find out it doesn't, we'll skip the rest of the
643 let mut known_implemented = false;
644 for (_name, item) in data.items.iter() {
645 // Don't pass a `visible_from_module` down to `is_valid_candidate`,
646 // since only inherent methods should be included into visibility checking.
647 if !is_valid_candidate(db, name, receiver_ty, *item, self_ty, None) {
650 if !known_implemented {
651 let goal = generic_implements_goal(db, env.clone(), t, self_ty.clone());
652 if db.trait_solve(krate, goal).is_none() {
656 known_implemented = true;
657 // FIXME: we shouldn't be ignoring the binders here
658 if callback(&self_ty.value, *item) {
666 fn iterate_inherent_methods(
667 self_ty: &Canonical<Ty>,
668 db: &dyn HirDatabase,
670 receiver_ty: Option<&Canonical<Ty>>,
672 visible_from_module: Option<ModuleId>,
673 callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
675 let def_crates = match def_crates(db, &self_ty.value, krate) {
677 None => return false,
679 for krate in def_crates {
680 let impls = db.inherent_impls_in_crate(krate);
682 for &impl_def in impls.for_self_ty(&self_ty.value) {
683 for &item in db.impl_data(impl_def).items.iter() {
684 if !is_valid_candidate(db, name, receiver_ty, item, self_ty, visible_from_module) {
687 // we have to check whether the self type unifies with the type
688 // that the impl is for. If we have a receiver type, this
689 // already happens in `is_valid_candidate` above; if not, we
691 if receiver_ty.is_none() && inherent_impl_substs(db, impl_def, self_ty).is_none() {
692 cov_mark::hit!(impl_self_type_match_without_receiver);
695 if callback(&self_ty.value, item) {
704 /// Returns the self type for the index trait call.
705 pub fn resolve_indexing_op(
706 db: &dyn HirDatabase,
708 env: Arc<TraitEnvironment>,
710 index_trait: TraitId,
711 ) -> Option<Canonical<Ty>> {
712 let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
713 let deref_chain = autoderef_method_receiver(db, krate, ty);
714 for ty in deref_chain {
715 let goal = generic_implements_goal(db, env.clone(), index_trait, ty.clone());
716 if db.trait_solve(krate, goal).is_some() {
723 fn is_valid_candidate(
724 db: &dyn HirDatabase,
726 receiver_ty: Option<&Canonical<Ty>>,
728 self_ty: &Canonical<Ty>,
729 visible_from_module: Option<ModuleId>,
732 AssocItemId::FunctionId(m) => {
733 let data = db.function_data(m);
734 if let Some(name) = name {
735 if &data.name != name {
739 if let Some(receiver_ty) = receiver_ty {
740 if !data.has_self_param() {
743 let transformed_receiver_ty = match transform_receiver_ty(db, m, self_ty) {
745 None => return false,
747 if transformed_receiver_ty != receiver_ty.value {
751 if let Some(from_module) = visible_from_module {
752 if !db.function_visibility(m).is_visible_from(db.upcast(), from_module) {
753 cov_mark::hit!(autoderef_candidate_not_visible);
760 AssocItemId::ConstId(c) => {
761 let data = db.const_data(c);
762 name.map_or(true, |name| data.name.as_ref() == Some(name)) && receiver_ty.is_none()
768 pub(crate) fn inherent_impl_substs(
769 db: &dyn HirDatabase,
771 self_ty: &Canonical<Ty>,
772 ) -> Option<Substitution> {
773 // we create a var for each type parameter of the impl; we need to keep in
774 // mind here that `self_ty` might have vars of its own
775 let self_ty_vars = self_ty.binders.len(&Interner);
776 let vars = TyBuilder::subst_for_def(db, impl_id)
777 .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty_vars)
779 let self_ty_with_vars = db.impl_self_ty(impl_id).substitute(&Interner, &vars);
780 let mut kinds = self_ty.binders.interned().to_vec();
782 iter::repeat(chalk_ir::WithKind::new(
783 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
786 .take(vars.len(&Interner)),
788 let tys = Canonical {
789 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
790 value: (self_ty_with_vars, self_ty.value.clone()),
792 let substs = super::infer::unify(&tys)?;
793 // We only want the substs for the vars we added, not the ones from self_ty.
794 // Also, if any of the vars we added are still in there, we replace them by
795 // Unknown. I think this can only really happen if self_ty contained
796 // Unknown, and in that case we want the result to contain Unknown in those
799 Substitution::from_iter(&Interner, substs.iter(&Interner).cloned().skip(self_ty_vars));
800 Some(fallback_bound_vars(suffix, self_ty_vars))
803 /// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
804 /// num_vars_to_keep) by `TyKind::Unknown`.
805 fn fallback_bound_vars(s: Substitution, num_vars_to_keep: usize) -> Substitution {
806 crate::fold_free_vars(s, |bound, binders| {
807 if bound.index >= num_vars_to_keep && bound.debruijn == DebruijnIndex::INNERMOST {
808 TyKind::Error.intern(&Interner)
810 bound.shifted_in_from(binders).to_ty(&Interner)
815 fn transform_receiver_ty(
816 db: &dyn HirDatabase,
817 function_id: FunctionId,
818 self_ty: &Canonical<Ty>,
820 let substs = match function_id.lookup(db.upcast()).container {
821 AssocContainerId::TraitId(_) => TyBuilder::subst_for_def(db, function_id)
822 .push(self_ty.value.clone())
825 AssocContainerId::ImplId(impl_id) => {
826 let impl_substs = inherent_impl_substs(db, impl_id, &self_ty)?;
827 TyBuilder::subst_for_def(db, function_id)
828 .use_parent_substs(&impl_substs)
832 AssocContainerId::ModuleId(_) => unreachable!(),
834 let sig = db.callable_item_signature(function_id.into());
835 Some(sig.map(|s| s.params()[0].clone()).substitute(&Interner, &substs))
838 pub fn implements_trait(
840 db: &dyn HirDatabase,
841 env: Arc<TraitEnvironment>,
845 let goal = generic_implements_goal(db, env, trait_, ty.clone());
846 let solution = db.trait_solve(krate, goal);
851 pub fn implements_trait_unique(
853 db: &dyn HirDatabase,
854 env: Arc<TraitEnvironment>,
858 let goal = generic_implements_goal(db, env, trait_, ty.clone());
859 let solution = db.trait_solve(krate, goal);
861 matches!(solution, Some(crate::Solution::Unique(_)))
864 /// This creates Substs for a trait with the given Self type and type variables
865 /// for all other parameters, to query Chalk with it.
866 fn generic_implements_goal(
867 db: &dyn HirDatabase,
868 env: Arc<TraitEnvironment>,
870 self_ty: Canonical<Ty>,
871 ) -> Canonical<InEnvironment<super::DomainGoal>> {
872 let mut kinds = self_ty.binders.interned().to_vec();
873 let trait_ref = TyBuilder::trait_ref(db, trait_)
875 .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
878 iter::repeat(chalk_ir::WithKind::new(
879 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
882 .take(trait_ref.substitution.len(&Interner) - 1),
884 let obligation = trait_ref.cast(&Interner);
886 binders: CanonicalVarKinds::from_iter(&Interner, kinds),
887 value: InEnvironment::new(&env.env, obligation),
891 fn autoderef_method_receiver(
892 db: &dyn HirDatabase,
894 ty: InEnvironment<Canonical<Ty>>,
895 ) -> Vec<Canonical<Ty>> {
896 let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
897 // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
898 if let Some(TyKind::Array(parameters, _)) =
899 deref_chain.last().map(|ty| ty.value.kind(&Interner))
901 let kinds = deref_chain.last().unwrap().binders.clone();
902 let unsized_ty = TyKind::Slice(parameters.clone()).intern(&Interner);
903 deref_chain.push(Canonical { value: unsized_ty, binders: kinds })