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