]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/method_resolution.rs
Merge #8394
[rust.git] / crates / hir_ty / src / method_resolution.rs
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};
6
7 use arrayvec::ArrayVec;
8 use base_db::CrateId;
9 use chalk_ir::{cast::Cast, Mutability, UniverseIndex};
10 use hir_def::{
11     lang_item::LangItemTarget, nameres::DefMap, AssocContainerId, AssocItemId, FunctionId,
12     GenericDefId, HasModule, ImplId, Lookup, ModuleId, TraitId,
13 };
14 use hir_expand::name::Name;
15 use rustc_hash::{FxHashMap, FxHashSet};
16
17 use crate::{
18     autoderef,
19     db::HirDatabase,
20     from_foreign_def_id,
21     primitive::{self, FloatTy, IntTy, UintTy},
22     static_lifetime,
23     utils::all_super_traits,
24     AdtId, Canonical, CanonicalVarKinds, DebruijnIndex, FnPointer, FnSig, ForeignDefId,
25     InEnvironment, Interner, Scalar, Substitution, TraitEnvironment, Ty, TyBuilder, TyExt, TyKind,
26     TypeWalk,
27 };
28
29 /// This is used as a key for indexing impls.
30 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
31 pub enum TyFingerprint {
32     Str,
33     Slice,
34     Array,
35     Never,
36     RawPtr(Mutability),
37     Scalar(Scalar),
38     Adt(hir_def::AdtId),
39     Dyn(TraitId),
40     Tuple(usize),
41     ForeignType(ForeignDefId),
42     FnPtr(usize, FnSig),
43 }
44
45 impl TyFingerprint {
46     /// Creates a TyFingerprint for looking up an impl. Only certain types can
47     /// have impls: if we have some `struct S`, we can have an `impl S`, but not
48     /// `impl &S`. Hence, this will return `None` for reference types and such.
49     pub fn for_impl(ty: &Ty) -> Option<TyFingerprint> {
50         let fp = match ty.kind(&Interner) {
51             TyKind::Str => TyFingerprint::Str,
52             TyKind::Never => TyFingerprint::Never,
53             TyKind::Slice(..) => TyFingerprint::Slice,
54             TyKind::Array(..) => TyFingerprint::Array,
55             TyKind::Scalar(scalar) => TyFingerprint::Scalar(*scalar),
56             TyKind::Adt(AdtId(adt), _) => TyFingerprint::Adt(*adt),
57             TyKind::Tuple(cardinality, _) => TyFingerprint::Tuple(*cardinality),
58             TyKind::Raw(mutability, ..) => TyFingerprint::RawPtr(*mutability),
59             TyKind::Foreign(alias_id, ..) => TyFingerprint::ForeignType(*alias_id),
60             TyKind::Function(FnPointer { sig, substitution: substs, .. }) => {
61                 TyFingerprint::FnPtr(substs.0.len(&Interner) - 1, *sig)
62             }
63             TyKind::Dyn(_) => ty.dyn_trait().map(|trait_| TyFingerprint::Dyn(trait_))?,
64             _ => return None,
65         };
66         Some(fp)
67     }
68 }
69
70 pub(crate) const ALL_INT_FPS: [TyFingerprint; 12] = [
71     TyFingerprint::Scalar(Scalar::Int(IntTy::I8)),
72     TyFingerprint::Scalar(Scalar::Int(IntTy::I16)),
73     TyFingerprint::Scalar(Scalar::Int(IntTy::I32)),
74     TyFingerprint::Scalar(Scalar::Int(IntTy::I64)),
75     TyFingerprint::Scalar(Scalar::Int(IntTy::I128)),
76     TyFingerprint::Scalar(Scalar::Int(IntTy::Isize)),
77     TyFingerprint::Scalar(Scalar::Uint(UintTy::U8)),
78     TyFingerprint::Scalar(Scalar::Uint(UintTy::U16)),
79     TyFingerprint::Scalar(Scalar::Uint(UintTy::U32)),
80     TyFingerprint::Scalar(Scalar::Uint(UintTy::U64)),
81     TyFingerprint::Scalar(Scalar::Uint(UintTy::U128)),
82     TyFingerprint::Scalar(Scalar::Uint(UintTy::Usize)),
83 ];
84
85 pub(crate) const ALL_FLOAT_FPS: [TyFingerprint; 2] = [
86     TyFingerprint::Scalar(Scalar::Float(FloatTy::F32)),
87     TyFingerprint::Scalar(Scalar::Float(FloatTy::F64)),
88 ];
89
90 /// Trait impls defined or available in some crate.
91 #[derive(Debug, Eq, PartialEq)]
92 pub struct TraitImpls {
93     // If the `Option<TyFingerprint>` is `None`, the impl may apply to any self type.
94     map: FxHashMap<TraitId, FxHashMap<Option<TyFingerprint>, Vec<ImplId>>>,
95 }
96
97 impl TraitImpls {
98     pub(crate) fn trait_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
99         let _p = profile::span("trait_impls_in_crate_query");
100         let mut impls = Self { map: FxHashMap::default() };
101
102         let crate_def_map = db.crate_def_map(krate);
103         collect_def_map(db, &crate_def_map, &mut impls);
104
105         return Arc::new(impls);
106
107         fn collect_def_map(db: &dyn HirDatabase, def_map: &DefMap, impls: &mut TraitImpls) {
108             for (_module_id, module_data) in def_map.modules() {
109                 for impl_id in module_data.scope.impls() {
110                     let target_trait = match db.impl_trait(impl_id) {
111                         Some(tr) => tr.skip_binders().hir_trait_id(),
112                         None => continue,
113                     };
114                     let self_ty = db.impl_self_ty(impl_id);
115                     let self_ty_fp = TyFingerprint::for_impl(self_ty.skip_binders());
116                     impls
117                         .map
118                         .entry(target_trait)
119                         .or_default()
120                         .entry(self_ty_fp)
121                         .or_default()
122                         .push(impl_id);
123                 }
124
125                 // To better support custom derives, collect impls in all unnamed const items.
126                 // const _: () = { ... };
127                 for konst in module_data.scope.unnamed_consts() {
128                     let body = db.body(konst.into());
129                     for (_, block_def_map) in body.blocks(db.upcast()) {
130                         collect_def_map(db, &block_def_map, impls);
131                     }
132                 }
133             }
134         }
135     }
136
137     pub(crate) fn trait_impls_in_deps_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
138         let _p = profile::span("trait_impls_in_deps_query");
139         let crate_graph = db.crate_graph();
140         let mut res = Self { map: FxHashMap::default() };
141
142         for krate in crate_graph.transitive_deps(krate) {
143             res.merge(&db.trait_impls_in_crate(krate));
144         }
145
146         Arc::new(res)
147     }
148
149     fn merge(&mut self, other: &Self) {
150         for (trait_, other_map) in &other.map {
151             let map = self.map.entry(*trait_).or_default();
152             for (fp, impls) in other_map {
153                 let vec = map.entry(*fp).or_default();
154                 vec.extend(impls);
155             }
156         }
157     }
158
159     /// Queries all trait impls for the given type.
160     pub fn for_self_ty(&self, fp: TyFingerprint) -> impl Iterator<Item = ImplId> + '_ {
161         self.map
162             .values()
163             .flat_map(move |impls| impls.get(&None).into_iter().chain(impls.get(&Some(fp))))
164             .flat_map(|it| it.iter().copied())
165     }
166
167     /// Queries all impls of the given trait.
168     pub fn for_trait(&self, trait_: TraitId) -> impl Iterator<Item = ImplId> + '_ {
169         self.map
170             .get(&trait_)
171             .into_iter()
172             .flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
173     }
174
175     /// Queries all impls of `trait_` that may apply to `self_ty`.
176     pub fn for_trait_and_self_ty(
177         &self,
178         trait_: TraitId,
179         self_ty: TyFingerprint,
180     ) -> impl Iterator<Item = ImplId> + '_ {
181         self.map
182             .get(&trait_)
183             .into_iter()
184             .flat_map(move |map| map.get(&None).into_iter().chain(map.get(&Some(self_ty))))
185             .flat_map(|v| v.iter().copied())
186     }
187
188     pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
189         self.map.values().flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
190     }
191 }
192
193 /// Inherent impls defined in some crate.
194 ///
195 /// Inherent impls can only be defined in the crate that also defines the self type of the impl
196 /// (note that some primitives are considered to be defined by both libcore and liballoc).
197 ///
198 /// This makes inherent impl lookup easier than trait impl lookup since we only have to consider a
199 /// single crate.
200 #[derive(Debug, Eq, PartialEq)]
201 pub struct InherentImpls {
202     map: FxHashMap<TyFingerprint, Vec<ImplId>>,
203 }
204
205 impl InherentImpls {
206     pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
207         let mut map: FxHashMap<_, Vec<_>> = FxHashMap::default();
208
209         let crate_def_map = db.crate_def_map(krate);
210         for (_module_id, module_data) in crate_def_map.modules() {
211             for impl_id in module_data.scope.impls() {
212                 let data = db.impl_data(impl_id);
213                 if data.target_trait.is_some() {
214                     continue;
215                 }
216
217                 let self_ty = db.impl_self_ty(impl_id);
218                 if let Some(fp) = TyFingerprint::for_impl(self_ty.skip_binders()) {
219                     map.entry(fp).or_default().push(impl_id);
220                 }
221             }
222         }
223
224         // NOTE: We're not collecting inherent impls from unnamed consts here, we intentionally only
225         // support trait impls there.
226
227         Arc::new(Self { map })
228     }
229
230     pub fn for_self_ty(&self, self_ty: &Ty) -> &[ImplId] {
231         match TyFingerprint::for_impl(self_ty) {
232             Some(fp) => self.map.get(&fp).map(|vec| vec.as_ref()).unwrap_or(&[]),
233             None => &[],
234         }
235     }
236
237     pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
238         self.map.values().flat_map(|v| v.iter().copied())
239     }
240 }
241
242 impl Ty {
243     pub fn def_crates(
244         &self,
245         db: &dyn HirDatabase,
246         cur_crate: CrateId,
247     ) -> Option<ArrayVec<CrateId, 2>> {
248         // Types like slice can have inherent impls in several crates, (core and alloc).
249         // The corresponding impls are marked with lang items, so we can use them to find the required crates.
250         macro_rules! lang_item_crate {
251             ($($name:expr),+ $(,)?) => {{
252                 let mut v = ArrayVec::<LangItemTarget, 2>::new();
253                 $(
254                     v.extend(db.lang_item(cur_crate, $name.into()));
255                 )+
256                 v
257             }};
258         }
259
260         let mod_to_crate_ids = |module: ModuleId| Some(std::iter::once(module.krate()).collect());
261
262         let lang_item_targets = match self.kind(&Interner) {
263             TyKind::Adt(AdtId(def_id), _) => {
264                 return mod_to_crate_ids(def_id.module(db.upcast()));
265             }
266             TyKind::Foreign(id) => {
267                 return mod_to_crate_ids(
268                     from_foreign_def_id(*id).lookup(db.upcast()).module(db.upcast()),
269                 );
270             }
271             TyKind::Scalar(Scalar::Bool) => lang_item_crate!("bool"),
272             TyKind::Scalar(Scalar::Char) => lang_item_crate!("char"),
273             TyKind::Scalar(Scalar::Float(f)) => match f {
274                 // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime)
275                 FloatTy::F32 => lang_item_crate!("f32", "f32_runtime"),
276                 FloatTy::F64 => lang_item_crate!("f64", "f64_runtime"),
277             },
278             &TyKind::Scalar(Scalar::Int(t)) => {
279                 lang_item_crate!(primitive::int_ty_to_string(t))
280             }
281             &TyKind::Scalar(Scalar::Uint(t)) => {
282                 lang_item_crate!(primitive::uint_ty_to_string(t))
283             }
284             TyKind::Str => lang_item_crate!("str_alloc", "str"),
285             TyKind::Slice(_) => lang_item_crate!("slice_alloc", "slice"),
286             TyKind::Raw(Mutability::Not, _) => lang_item_crate!("const_ptr"),
287             TyKind::Raw(Mutability::Mut, _) => lang_item_crate!("mut_ptr"),
288             TyKind::Dyn(_) => {
289                 return self.dyn_trait().and_then(|trait_| {
290                     mod_to_crate_ids(GenericDefId::TraitId(trait_).module(db.upcast()))
291                 });
292             }
293             _ => return None,
294         };
295         let res = lang_item_targets
296             .into_iter()
297             .filter_map(|it| match it {
298                 LangItemTarget::ImplDefId(it) => Some(it),
299                 _ => None,
300             })
301             .map(|it| it.lookup(db.upcast()).container.krate())
302             .collect();
303         Some(res)
304     }
305 }
306
307 /// Look up the method with the given name, returning the actual autoderefed
308 /// receiver type (but without autoref applied yet).
309 pub(crate) fn lookup_method(
310     ty: &Canonical<Ty>,
311     db: &dyn HirDatabase,
312     env: Arc<TraitEnvironment>,
313     krate: CrateId,
314     traits_in_scope: &FxHashSet<TraitId>,
315     visible_from_module: Option<ModuleId>,
316     name: &Name,
317 ) -> Option<(Ty, FunctionId)> {
318     iterate_method_candidates(
319         ty,
320         db,
321         env,
322         krate,
323         &traits_in_scope,
324         visible_from_module,
325         Some(name),
326         LookupMode::MethodCall,
327         |ty, f| match f {
328             AssocItemId::FunctionId(f) => Some((ty.clone(), f)),
329             _ => None,
330         },
331     )
332 }
333
334 /// Whether we're looking up a dotted method call (like `v.len()`) or a path
335 /// (like `Vec::new`).
336 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
337 pub enum LookupMode {
338     /// Looking up a method call like `v.len()`: We only consider candidates
339     /// that have a `self` parameter, and do autoderef.
340     MethodCall,
341     /// Looking up a path like `Vec::new` or `Vec::default`: We consider all
342     /// candidates including associated constants, but don't do autoderef.
343     Path,
344 }
345
346 // This would be nicer if it just returned an iterator, but that runs into
347 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
348 // FIXME add a context type here?
349 pub fn iterate_method_candidates<T>(
350     ty: &Canonical<Ty>,
351     db: &dyn HirDatabase,
352     env: Arc<TraitEnvironment>,
353     krate: CrateId,
354     traits_in_scope: &FxHashSet<TraitId>,
355     visible_from_module: Option<ModuleId>,
356     name: Option<&Name>,
357     mode: LookupMode,
358     mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>,
359 ) -> Option<T> {
360     let mut slot = None;
361     iterate_method_candidates_impl(
362         ty,
363         db,
364         env,
365         krate,
366         traits_in_scope,
367         visible_from_module,
368         name,
369         mode,
370         &mut |ty, item| {
371             assert!(slot.is_none());
372             slot = callback(ty, item);
373             slot.is_some()
374         },
375     );
376     slot
377 }
378
379 fn iterate_method_candidates_impl(
380     ty: &Canonical<Ty>,
381     db: &dyn HirDatabase,
382     env: Arc<TraitEnvironment>,
383     krate: CrateId,
384     traits_in_scope: &FxHashSet<TraitId>,
385     visible_from_module: Option<ModuleId>,
386     name: Option<&Name>,
387     mode: LookupMode,
388     callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
389 ) -> bool {
390     match mode {
391         LookupMode::MethodCall => {
392             // For method calls, rust first does any number of autoderef, and then one
393             // autoref (i.e. when the method takes &self or &mut self). We just ignore
394             // the autoref currently -- when we find a method matching the given name,
395             // we assume it fits.
396
397             // Also note that when we've got a receiver like &S, even if the method we
398             // find in the end takes &self, we still do the autoderef step (just as
399             // rustc does an autoderef and then autoref again).
400             let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
401
402             // We have to be careful about the order we're looking at candidates
403             // in here. Consider the case where we're resolving `x.clone()`
404             // where `x: &Vec<_>`. This resolves to the clone method with self
405             // type `Vec<_>`, *not* `&_`. I.e. we need to consider methods where
406             // the receiver type exactly matches before cases where we have to
407             // do autoref. But in the autoderef steps, the `&_` self type comes
408             // up *before* the `Vec<_>` self type.
409             //
410             // On the other hand, we don't want to just pick any by-value method
411             // before any by-autoref method; it's just that we need to consider
412             // the methods by autoderef order of *receiver types*, not *self
413             // types*.
414
415             let deref_chain = autoderef_method_receiver(db, krate, ty);
416             for i in 0..deref_chain.len() {
417                 if iterate_method_candidates_with_autoref(
418                     &deref_chain[i..],
419                     db,
420                     env.clone(),
421                     krate,
422                     traits_in_scope,
423                     visible_from_module,
424                     name,
425                     callback,
426                 ) {
427                     return true;
428                 }
429             }
430             false
431         }
432         LookupMode::Path => {
433             // No autoderef for path lookups
434             iterate_method_candidates_for_self_ty(
435                 &ty,
436                 db,
437                 env,
438                 krate,
439                 traits_in_scope,
440                 visible_from_module,
441                 name,
442                 callback,
443             )
444         }
445     }
446 }
447
448 fn iterate_method_candidates_with_autoref(
449     deref_chain: &[Canonical<Ty>],
450     db: &dyn HirDatabase,
451     env: Arc<TraitEnvironment>,
452     krate: CrateId,
453     traits_in_scope: &FxHashSet<TraitId>,
454     visible_from_module: Option<ModuleId>,
455     name: Option<&Name>,
456     mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
457 ) -> bool {
458     if iterate_method_candidates_by_receiver(
459         &deref_chain[0],
460         &deref_chain[1..],
461         db,
462         env.clone(),
463         krate,
464         &traits_in_scope,
465         visible_from_module,
466         name,
467         &mut callback,
468     ) {
469         return true;
470     }
471     let refed = Canonical {
472         binders: deref_chain[0].binders.clone(),
473         value: TyKind::Ref(Mutability::Not, static_lifetime(), deref_chain[0].value.clone())
474             .intern(&Interner),
475     };
476     if iterate_method_candidates_by_receiver(
477         &refed,
478         deref_chain,
479         db,
480         env.clone(),
481         krate,
482         &traits_in_scope,
483         visible_from_module,
484         name,
485         &mut callback,
486     ) {
487         return true;
488     }
489     let ref_muted = Canonical {
490         binders: deref_chain[0].binders.clone(),
491         value: TyKind::Ref(Mutability::Mut, static_lifetime(), deref_chain[0].value.clone())
492             .intern(&Interner),
493     };
494     if iterate_method_candidates_by_receiver(
495         &ref_muted,
496         deref_chain,
497         db,
498         env,
499         krate,
500         &traits_in_scope,
501         visible_from_module,
502         name,
503         &mut callback,
504     ) {
505         return true;
506     }
507     false
508 }
509
510 fn iterate_method_candidates_by_receiver(
511     receiver_ty: &Canonical<Ty>,
512     rest_of_deref_chain: &[Canonical<Ty>],
513     db: &dyn HirDatabase,
514     env: Arc<TraitEnvironment>,
515     krate: CrateId,
516     traits_in_scope: &FxHashSet<TraitId>,
517     visible_from_module: Option<ModuleId>,
518     name: Option<&Name>,
519     mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
520 ) -> bool {
521     // We're looking for methods with *receiver* type receiver_ty. These could
522     // be found in any of the derefs of receiver_ty, so we have to go through
523     // that.
524     for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
525         if iterate_inherent_methods(
526             self_ty,
527             db,
528             name,
529             Some(receiver_ty),
530             krate,
531             visible_from_module,
532             &mut callback,
533         ) {
534             return true;
535         }
536     }
537     for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
538         if iterate_trait_method_candidates(
539             self_ty,
540             db,
541             env.clone(),
542             krate,
543             &traits_in_scope,
544             name,
545             Some(receiver_ty),
546             &mut callback,
547         ) {
548             return true;
549         }
550     }
551     false
552 }
553
554 fn iterate_method_candidates_for_self_ty(
555     self_ty: &Canonical<Ty>,
556     db: &dyn HirDatabase,
557     env: Arc<TraitEnvironment>,
558     krate: CrateId,
559     traits_in_scope: &FxHashSet<TraitId>,
560     visible_from_module: Option<ModuleId>,
561     name: Option<&Name>,
562     mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
563 ) -> bool {
564     if iterate_inherent_methods(self_ty, db, name, None, krate, visible_from_module, &mut callback)
565     {
566         return true;
567     }
568     iterate_trait_method_candidates(self_ty, db, env, krate, traits_in_scope, name, None, callback)
569 }
570
571 fn iterate_trait_method_candidates(
572     self_ty: &Canonical<Ty>,
573     db: &dyn HirDatabase,
574     env: Arc<TraitEnvironment>,
575     krate: CrateId,
576     traits_in_scope: &FxHashSet<TraitId>,
577     name: Option<&Name>,
578     receiver_ty: Option<&Canonical<Ty>>,
579     callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
580 ) -> bool {
581     // if ty is `dyn Trait`, the trait doesn't need to be in scope
582     let inherent_trait =
583         self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t));
584     let env_traits = if let TyKind::Placeholder(_) = self_ty.value.kind(&Interner) {
585         // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
586         env.traits_in_scope_from_clauses(&self_ty.value)
587             .flat_map(|t| all_super_traits(db.upcast(), t))
588             .collect()
589     } else {
590         Vec::new()
591     };
592     let traits =
593         inherent_trait.chain(env_traits.into_iter()).chain(traits_in_scope.iter().copied());
594     'traits: for t in traits {
595         let data = db.trait_data(t);
596
597         // we'll be lazy about checking whether the type implements the
598         // trait, but if we find out it doesn't, we'll skip the rest of the
599         // iteration
600         let mut known_implemented = false;
601         for (_name, item) in data.items.iter() {
602             // Don't pass a `visible_from_module` down to `is_valid_candidate`,
603             // since only inherent methods should be included into visibility checking.
604             if !is_valid_candidate(db, name, receiver_ty, *item, self_ty, None) {
605                 continue;
606             }
607             if !known_implemented {
608                 let goal = generic_implements_goal(db, env.clone(), t, self_ty.clone());
609                 if db.trait_solve(krate, goal).is_none() {
610                     continue 'traits;
611                 }
612             }
613             known_implemented = true;
614             if callback(&self_ty.value, *item) {
615                 return true;
616             }
617         }
618     }
619     false
620 }
621
622 fn iterate_inherent_methods(
623     self_ty: &Canonical<Ty>,
624     db: &dyn HirDatabase,
625     name: Option<&Name>,
626     receiver_ty: Option<&Canonical<Ty>>,
627     krate: CrateId,
628     visible_from_module: Option<ModuleId>,
629     callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
630 ) -> bool {
631     let def_crates = match self_ty.value.def_crates(db, krate) {
632         Some(k) => k,
633         None => return false,
634     };
635     for krate in def_crates {
636         let impls = db.inherent_impls_in_crate(krate);
637
638         for &impl_def in impls.for_self_ty(&self_ty.value) {
639             for &item in db.impl_data(impl_def).items.iter() {
640                 if !is_valid_candidate(db, name, receiver_ty, item, self_ty, visible_from_module) {
641                     continue;
642                 }
643                 // we have to check whether the self type unifies with the type
644                 // that the impl is for. If we have a receiver type, this
645                 // already happens in `is_valid_candidate` above; if not, we
646                 // check it here
647                 if receiver_ty.is_none() && inherent_impl_substs(db, impl_def, self_ty).is_none() {
648                     cov_mark::hit!(impl_self_type_match_without_receiver);
649                     continue;
650                 }
651                 if callback(&self_ty.value, item) {
652                     return true;
653                 }
654             }
655         }
656     }
657     false
658 }
659
660 /// Returns the self type for the index trait call.
661 pub fn resolve_indexing_op(
662     db: &dyn HirDatabase,
663     ty: &Canonical<Ty>,
664     env: Arc<TraitEnvironment>,
665     krate: CrateId,
666     index_trait: TraitId,
667 ) -> Option<Canonical<Ty>> {
668     let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
669     let deref_chain = autoderef_method_receiver(db, krate, ty);
670     for ty in deref_chain {
671         let goal = generic_implements_goal(db, env.clone(), index_trait, ty.clone());
672         if db.trait_solve(krate, goal).is_some() {
673             return Some(ty);
674         }
675     }
676     None
677 }
678
679 fn is_valid_candidate(
680     db: &dyn HirDatabase,
681     name: Option<&Name>,
682     receiver_ty: Option<&Canonical<Ty>>,
683     item: AssocItemId,
684     self_ty: &Canonical<Ty>,
685     visible_from_module: Option<ModuleId>,
686 ) -> bool {
687     match item {
688         AssocItemId::FunctionId(m) => {
689             let data = db.function_data(m);
690             if let Some(name) = name {
691                 if &data.name != name {
692                     return false;
693                 }
694             }
695             if let Some(receiver_ty) = receiver_ty {
696                 if !data.has_self_param() {
697                     return false;
698                 }
699                 let transformed_receiver_ty = match transform_receiver_ty(db, m, self_ty) {
700                     Some(ty) => ty,
701                     None => return false,
702                 };
703                 if transformed_receiver_ty != receiver_ty.value {
704                     return false;
705                 }
706             }
707             if let Some(from_module) = visible_from_module {
708                 if !db.function_visibility(m).is_visible_from(db.upcast(), from_module) {
709                     cov_mark::hit!(autoderef_candidate_not_visible);
710                     return false;
711                 }
712             }
713
714             true
715         }
716         AssocItemId::ConstId(c) => {
717             let data = db.const_data(c);
718             name.map_or(true, |name| data.name.as_ref() == Some(name)) && receiver_ty.is_none()
719         }
720         _ => false,
721     }
722 }
723
724 pub(crate) fn inherent_impl_substs(
725     db: &dyn HirDatabase,
726     impl_id: ImplId,
727     self_ty: &Canonical<Ty>,
728 ) -> Option<Substitution> {
729     // we create a var for each type parameter of the impl; we need to keep in
730     // mind here that `self_ty` might have vars of its own
731     let self_ty_vars = self_ty.binders.len(&Interner);
732     let vars = TyBuilder::subst_for_def(db, impl_id)
733         .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty_vars)
734         .build();
735     let self_ty_with_vars = db.impl_self_ty(impl_id).substitute(&Interner, &vars);
736     let mut kinds = self_ty.binders.interned().to_vec();
737     kinds.extend(
738         iter::repeat(chalk_ir::WithKind::new(
739             chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
740             UniverseIndex::ROOT,
741         ))
742         .take(vars.len(&Interner)),
743     );
744     let tys = Canonical {
745         binders: CanonicalVarKinds::from_iter(&Interner, kinds),
746         value: (self_ty_with_vars, self_ty.value.clone()),
747     };
748     let substs = super::infer::unify(&tys)?;
749     // We only want the substs for the vars we added, not the ones from self_ty.
750     // Also, if any of the vars we added are still in there, we replace them by
751     // Unknown. I think this can only really happen if self_ty contained
752     // Unknown, and in that case we want the result to contain Unknown in those
753     // places again.
754     let suffix =
755         Substitution::from_iter(&Interner, substs.iter(&Interner).cloned().skip(self_ty_vars));
756     Some(fallback_bound_vars(suffix, self_ty_vars))
757 }
758
759 /// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
760 /// num_vars_to_keep) by `TyKind::Unknown`.
761 fn fallback_bound_vars(s: Substitution, num_vars_to_keep: usize) -> Substitution {
762     s.fold_binders(
763         &mut |ty, binders| {
764             if let TyKind::BoundVar(bound) = ty.kind(&Interner) {
765                 if bound.index >= num_vars_to_keep && bound.debruijn >= binders {
766                     TyKind::Error.intern(&Interner)
767                 } else {
768                     ty
769                 }
770             } else {
771                 ty
772             }
773         },
774         DebruijnIndex::INNERMOST,
775     )
776 }
777
778 fn transform_receiver_ty(
779     db: &dyn HirDatabase,
780     function_id: FunctionId,
781     self_ty: &Canonical<Ty>,
782 ) -> Option<Ty> {
783     let substs = match function_id.lookup(db.upcast()).container {
784         AssocContainerId::TraitId(_) => TyBuilder::subst_for_def(db, function_id)
785             .push(self_ty.value.clone())
786             .fill_with_unknown()
787             .build(),
788         AssocContainerId::ImplId(impl_id) => {
789             let impl_substs = inherent_impl_substs(db, impl_id, &self_ty)?;
790             TyBuilder::subst_for_def(db, function_id)
791                 .use_parent_substs(&impl_substs)
792                 .fill_with_unknown()
793                 .build()
794         }
795         AssocContainerId::ModuleId(_) => unreachable!(),
796     };
797     let sig = db.callable_item_signature(function_id.into());
798     Some(sig.map(|s| s.params()[0].clone()).substitute(&Interner, &substs))
799 }
800
801 pub fn implements_trait(
802     ty: &Canonical<Ty>,
803     db: &dyn HirDatabase,
804     env: Arc<TraitEnvironment>,
805     krate: CrateId,
806     trait_: TraitId,
807 ) -> bool {
808     let goal = generic_implements_goal(db, env, trait_, ty.clone());
809     let solution = db.trait_solve(krate, goal);
810
811     solution.is_some()
812 }
813
814 pub fn implements_trait_unique(
815     ty: &Canonical<Ty>,
816     db: &dyn HirDatabase,
817     env: Arc<TraitEnvironment>,
818     krate: CrateId,
819     trait_: TraitId,
820 ) -> bool {
821     let goal = generic_implements_goal(db, env, trait_, ty.clone());
822     let solution = db.trait_solve(krate, goal);
823
824     matches!(solution, Some(crate::Solution::Unique(_)))
825 }
826
827 /// This creates Substs for a trait with the given Self type and type variables
828 /// for all other parameters, to query Chalk with it.
829 fn generic_implements_goal(
830     db: &dyn HirDatabase,
831     env: Arc<TraitEnvironment>,
832     trait_: TraitId,
833     self_ty: Canonical<Ty>,
834 ) -> Canonical<InEnvironment<super::DomainGoal>> {
835     let mut kinds = self_ty.binders.interned().to_vec();
836     let trait_ref = TyBuilder::trait_ref(db, trait_)
837         .push(self_ty.value)
838         .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
839         .build();
840     kinds.extend(
841         iter::repeat(chalk_ir::WithKind::new(
842             chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
843             UniverseIndex::ROOT,
844         ))
845         .take(trait_ref.substitution.len(&Interner) - 1),
846     );
847     let obligation = trait_ref.cast(&Interner);
848     Canonical {
849         binders: CanonicalVarKinds::from_iter(&Interner, kinds),
850         value: InEnvironment::new(env.env.clone(), obligation),
851     }
852 }
853
854 fn autoderef_method_receiver(
855     db: &dyn HirDatabase,
856     krate: CrateId,
857     ty: InEnvironment<Canonical<Ty>>,
858 ) -> Vec<Canonical<Ty>> {
859     let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
860     // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
861     if let Some(TyKind::Array(parameters, _)) =
862         deref_chain.last().map(|ty| ty.value.kind(&Interner))
863     {
864         let kinds = deref_chain.last().unwrap().binders.clone();
865         let unsized_ty = TyKind::Slice(parameters.clone()).intern(&Interner);
866         deref_chain.push(Canonical { value: unsized_ty, binders: kinds })
867     }
868     deref_chain
869 }