]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/method_resolution.rs
Include more info in assert
[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 use stdx::always;
17
18 use crate::{
19     autoderef,
20     db::HirDatabase,
21     from_foreign_def_id,
22     primitive::{self, FloatTy, IntTy, UintTy},
23     static_lifetime,
24     utils::all_super_traits,
25     AdtId, Canonical, CanonicalVarKinds, DebruijnIndex, ForeignDefId, HirDisplay, InEnvironment,
26     Interner, Scalar, Substitution, TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyExt, TyKind,
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     // These are lang item impls:
33     Str,
34     Slice,
35     Array,
36     Never,
37     RawPtr(Mutability),
38     Scalar(Scalar),
39     // These can have user-defined impls:
40     Adt(hir_def::AdtId),
41     Dyn(TraitId),
42     ForeignType(ForeignDefId),
43     // These only exist for trait impls
44     Unit,
45     Unnameable,
46     Function(u32),
47 }
48
49 impl TyFingerprint {
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_))?,
65             _ => return None,
66         };
67         Some(fp)
68     }
69
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);
87                 } else {
88                     TyFingerprint::Unit
89                 }
90             }
91             TyKind::AssociatedType(_, _)
92             | TyKind::OpaqueType(_, _)
93             | TyKind::FnDef(_, _)
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)
99             }
100             TyKind::Alias(_)
101             | TyKind::Placeholder(_)
102             | TyKind::BoundVar(_)
103             | TyKind::InferenceVar(_, _)
104             | TyKind::Error => return None,
105         };
106         Some(fp)
107     }
108 }
109
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)),
123 ];
124
125 pub(crate) const ALL_FLOAT_FPS: [TyFingerprint; 2] = [
126     TyFingerprint::Scalar(Scalar::Float(FloatTy::F32)),
127     TyFingerprint::Scalar(Scalar::Float(FloatTy::F64)),
128 ];
129
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>>>,
135 }
136
137 impl TraitImpls {
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() };
141
142         let crate_def_map = db.crate_def_map(krate);
143         collect_def_map(db, &crate_def_map, &mut impls);
144
145         return Arc::new(impls);
146
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(),
152                         None => continue,
153                     };
154                     let self_ty = db.impl_self_ty(impl_id);
155                     let self_ty_fp = TyFingerprint::for_trait_impl(self_ty.skip_binders());
156                     impls
157                         .map
158                         .entry(target_trait)
159                         .or_default()
160                         .entry(self_ty_fp)
161                         .or_default()
162                         .push(impl_id);
163                 }
164
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);
171                     }
172                 }
173             }
174         }
175     }
176
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() };
181
182         for krate in crate_graph.transitive_deps(krate) {
183             res.merge(&db.trait_impls_in_crate(krate));
184         }
185
186         Arc::new(res)
187     }
188
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();
194                 vec.extend(impls);
195             }
196         }
197     }
198
199     /// Queries all trait impls for the given type.
200     pub fn for_self_ty_without_blanket_impls(
201         &self,
202         fp: TyFingerprint,
203     ) -> impl Iterator<Item = ImplId> + '_ {
204         self.map
205             .values()
206             .flat_map(move |impls| impls.get(&Some(fp)).into_iter())
207             .flat_map(|it| it.iter().copied())
208     }
209
210     /// Queries all impls of the given trait.
211     pub fn for_trait(&self, trait_: TraitId) -> impl Iterator<Item = ImplId> + '_ {
212         self.map
213             .get(&trait_)
214             .into_iter()
215             .flat_map(|map| map.values().flat_map(|v| v.iter().copied()))
216     }
217
218     /// Queries all impls of `trait_` that may apply to `self_ty`.
219     pub fn for_trait_and_self_ty(
220         &self,
221         trait_: TraitId,
222         self_ty: TyFingerprint,
223     ) -> impl Iterator<Item = ImplId> + '_ {
224         self.map
225             .get(&trait_)
226             .into_iter()
227             .flat_map(move |map| map.get(&None).into_iter().chain(map.get(&Some(self_ty))))
228             .flat_map(|v| v.iter().copied())
229     }
230
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()))
233     }
234 }
235
236 /// Inherent impls defined in some crate.
237 ///
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).
240 ///
241 /// This makes inherent impl lookup easier than trait impl lookup since we only have to consider a
242 /// single crate.
243 #[derive(Debug, Eq, PartialEq)]
244 pub struct InherentImpls {
245     map: FxHashMap<TyFingerprint, Vec<ImplId>>,
246 }
247
248 impl InherentImpls {
249     pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> {
250         let mut map: FxHashMap<_, Vec<_>> = FxHashMap::default();
251
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() {
257                     continue;
258                 }
259
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);
265                 }
266             }
267         }
268
269         // NOTE: We're not collecting inherent impls from unnamed consts here, we intentionally only
270         // support trait impls there.
271
272         Arc::new(Self { map })
273     }
274
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(&[]),
278             None => &[],
279         }
280     }
281
282     pub fn all_impls(&self) -> impl Iterator<Item = ImplId> + '_ {
283         self.map.values().flat_map(|v| v.iter().copied())
284     }
285 }
286
287 pub fn def_crates(
288     db: &dyn HirDatabase,
289     ty: &Ty,
290     cur_crate: CrateId,
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();
297                 $(
298                     v.extend(db.lang_item(cur_crate, $name.into()));
299                 )+
300                 v
301             }};
302         }
303
304     let mod_to_crate_ids = |module: ModuleId| Some(std::iter::once(module.krate()).collect());
305
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()));
309         }
310         TyKind::Foreign(id) => {
311             return mod_to_crate_ids(
312                 from_foreign_def_id(*id).lookup(db.upcast()).module(db.upcast()),
313             );
314         }
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"),
321         },
322         &TyKind::Scalar(Scalar::Int(t)) => {
323             lang_item_crate!(primitive::int_ty_to_string(t))
324         }
325         &TyKind::Scalar(Scalar::Uint(t)) => {
326             lang_item_crate!(primitive::uint_ty_to_string(t))
327         }
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"),
332         TyKind::Dyn(_) => {
333             return ty.dyn_trait().and_then(|trait_| {
334                 mod_to_crate_ids(GenericDefId::TraitId(trait_).module(db.upcast()))
335             });
336         }
337         _ => return None,
338     };
339     let res = lang_item_targets
340         .into_iter()
341         .filter_map(|it| match it {
342             LangItemTarget::ImplDefId(it) => Some(it),
343             _ => None,
344         })
345         .map(|it| it.lookup(db.upcast()).container.krate())
346         .collect();
347     Some(res)
348 }
349
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(
353     ty: &Canonical<Ty>,
354     db: &dyn HirDatabase,
355     env: Arc<TraitEnvironment>,
356     krate: CrateId,
357     traits_in_scope: &FxHashSet<TraitId>,
358     visible_from_module: Option<ModuleId>,
359     name: &Name,
360 ) -> Option<(Ty, FunctionId)> {
361     iterate_method_candidates(
362         ty,
363         db,
364         env,
365         krate,
366         &traits_in_scope,
367         visible_from_module,
368         Some(name),
369         LookupMode::MethodCall,
370         |ty, f| match f {
371             AssocItemId::FunctionId(f) => Some((ty.clone(), f)),
372             _ => None,
373         },
374     )
375 }
376
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.
383     MethodCall,
384     /// Looking up a path like `Vec::new` or `Vec::default`: We consider all
385     /// candidates including associated constants, but don't do autoderef.
386     Path,
387 }
388
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>(
393     ty: &Canonical<Ty>,
394     db: &dyn HirDatabase,
395     env: Arc<TraitEnvironment>,
396     krate: CrateId,
397     traits_in_scope: &FxHashSet<TraitId>,
398     visible_from_module: Option<ModuleId>,
399     name: Option<&Name>,
400     mode: LookupMode,
401     mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>,
402 ) -> Option<T> {
403     let mut slot = None;
404     iterate_method_candidates_impl(
405         ty,
406         db,
407         env,
408         krate,
409         traits_in_scope,
410         visible_from_module,
411         name,
412         mode,
413         &mut |ty, item| {
414             assert!(slot.is_none());
415             slot = callback(ty, item);
416             slot.is_some()
417         },
418     );
419     slot
420 }
421
422 fn iterate_method_candidates_impl(
423     ty: &Canonical<Ty>,
424     db: &dyn HirDatabase,
425     env: Arc<TraitEnvironment>,
426     krate: CrateId,
427     traits_in_scope: &FxHashSet<TraitId>,
428     visible_from_module: Option<ModuleId>,
429     name: Option<&Name>,
430     mode: LookupMode,
431     callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
432 ) -> bool {
433     match mode {
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.
439
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() };
444
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.
452             //
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
456             // types*.
457
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(
461                     &deref_chain[i..],
462                     db,
463                     env.clone(),
464                     krate,
465                     traits_in_scope,
466                     visible_from_module,
467                     name,
468                     callback,
469                 ) {
470                     return true;
471                 }
472             }
473             false
474         }
475         LookupMode::Path => {
476             // No autoderef for path lookups
477             iterate_method_candidates_for_self_ty(
478                 &ty,
479                 db,
480                 env,
481                 krate,
482                 traits_in_scope,
483                 visible_from_module,
484                 name,
485                 callback,
486             )
487         }
488     }
489 }
490
491 fn iterate_method_candidates_with_autoref(
492     deref_chain: &[Canonical<Ty>],
493     db: &dyn HirDatabase,
494     env: Arc<TraitEnvironment>,
495     krate: CrateId,
496     traits_in_scope: &FxHashSet<TraitId>,
497     visible_from_module: Option<ModuleId>,
498     name: Option<&Name>,
499     mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
500 ) -> bool {
501     if iterate_method_candidates_by_receiver(
502         &deref_chain[0],
503         &deref_chain[1..],
504         db,
505         env.clone(),
506         krate,
507         &traits_in_scope,
508         visible_from_module,
509         name,
510         &mut callback,
511     ) {
512         return true;
513     }
514     let refed = Canonical {
515         binders: deref_chain[0].binders.clone(),
516         value: TyKind::Ref(Mutability::Not, static_lifetime(), deref_chain[0].value.clone())
517             .intern(&Interner),
518     };
519     if iterate_method_candidates_by_receiver(
520         &refed,
521         deref_chain,
522         db,
523         env.clone(),
524         krate,
525         &traits_in_scope,
526         visible_from_module,
527         name,
528         &mut callback,
529     ) {
530         return true;
531     }
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())
535             .intern(&Interner),
536     };
537     if iterate_method_candidates_by_receiver(
538         &ref_muted,
539         deref_chain,
540         db,
541         env,
542         krate,
543         &traits_in_scope,
544         visible_from_module,
545         name,
546         &mut callback,
547     ) {
548         return true;
549     }
550     false
551 }
552
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>,
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     // 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
566     // that.
567     for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
568         if iterate_inherent_methods(
569             self_ty,
570             db,
571             name,
572             Some(receiver_ty),
573             krate,
574             visible_from_module,
575             &mut callback,
576         ) {
577             return true;
578         }
579     }
580     for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
581         if iterate_trait_method_candidates(
582             self_ty,
583             db,
584             env.clone(),
585             krate,
586             &traits_in_scope,
587             name,
588             Some(receiver_ty),
589             &mut callback,
590         ) {
591             return true;
592         }
593     }
594     false
595 }
596
597 fn iterate_method_candidates_for_self_ty(
598     self_ty: &Canonical<Ty>,
599     db: &dyn HirDatabase,
600     env: Arc<TraitEnvironment>,
601     krate: CrateId,
602     traits_in_scope: &FxHashSet<TraitId>,
603     visible_from_module: Option<ModuleId>,
604     name: Option<&Name>,
605     mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
606 ) -> bool {
607     if iterate_inherent_methods(self_ty, db, name, None, krate, visible_from_module, &mut callback)
608     {
609         return true;
610     }
611     iterate_trait_method_candidates(self_ty, db, env, krate, traits_in_scope, name, None, callback)
612 }
613
614 fn iterate_trait_method_candidates(
615     self_ty: &Canonical<Ty>,
616     db: &dyn HirDatabase,
617     env: Arc<TraitEnvironment>,
618     krate: CrateId,
619     traits_in_scope: &FxHashSet<TraitId>,
620     name: Option<&Name>,
621     receiver_ty: Option<&Canonical<Ty>>,
622     callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
623 ) -> bool {
624     // if ty is `dyn Trait`, the trait doesn't need to be in scope
625     let inherent_trait =
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))
631             .collect()
632     } else {
633         Vec::new()
634     };
635     let traits =
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);
639
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
642         // iteration
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) {
648                 continue;
649             }
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() {
653                     continue 'traits;
654                 }
655             }
656             known_implemented = true;
657             // FIXME: we shouldn't be ignoring the binders here
658             if callback(&self_ty.value, *item) {
659                 return true;
660             }
661         }
662     }
663     false
664 }
665
666 fn iterate_inherent_methods(
667     self_ty: &Canonical<Ty>,
668     db: &dyn HirDatabase,
669     name: Option<&Name>,
670     receiver_ty: Option<&Canonical<Ty>>,
671     krate: CrateId,
672     visible_from_module: Option<ModuleId>,
673     callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
674 ) -> bool {
675     let def_crates = match def_crates(db, &self_ty.value, krate) {
676         Some(k) => k,
677         None => return false,
678     };
679     for krate in def_crates {
680         let impls = db.inherent_impls_in_crate(krate);
681
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) {
685                     continue;
686                 }
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
690                 // check it here
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);
693                     continue;
694                 }
695                 if callback(&self_ty.value, item) {
696                     return true;
697                 }
698             }
699         }
700     }
701     false
702 }
703
704 /// Returns the self type for the index trait call.
705 pub fn resolve_indexing_op(
706     db: &dyn HirDatabase,
707     ty: &Canonical<Ty>,
708     env: Arc<TraitEnvironment>,
709     krate: CrateId,
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() {
717             return Some(ty);
718         }
719     }
720     None
721 }
722
723 fn is_valid_candidate(
724     db: &dyn HirDatabase,
725     name: Option<&Name>,
726     receiver_ty: Option<&Canonical<Ty>>,
727     item: AssocItemId,
728     self_ty: &Canonical<Ty>,
729     visible_from_module: Option<ModuleId>,
730 ) -> bool {
731     match item {
732         AssocItemId::FunctionId(m) => {
733             let data = db.function_data(m);
734             if let Some(name) = name {
735                 if &data.name != name {
736                     return false;
737                 }
738             }
739             if let Some(receiver_ty) = receiver_ty {
740                 if !data.has_self_param() {
741                     return false;
742                 }
743                 let transformed_receiver_ty = match transform_receiver_ty(db, m, self_ty) {
744                     Some(ty) => ty,
745                     None => return false,
746                 };
747                 if transformed_receiver_ty != receiver_ty.value {
748                     return false;
749                 }
750             }
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);
754                     return false;
755                 }
756             }
757
758             true
759         }
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()
763         }
764         _ => false,
765     }
766 }
767
768 pub(crate) fn inherent_impl_substs(
769     db: &dyn HirDatabase,
770     impl_id: ImplId,
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)
778         .build();
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();
781     kinds.extend(
782         iter::repeat(chalk_ir::WithKind::new(
783             chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
784             UniverseIndex::ROOT,
785         ))
786         .take(vars.len(&Interner)),
787     );
788     let tys = Canonical {
789         binders: CanonicalVarKinds::from_iter(&Interner, kinds),
790         value: (self_ty_with_vars, self_ty.value.clone()),
791     };
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
797     // places again.
798     let suffix =
799         Substitution::from_iter(&Interner, substs.iter(&Interner).cloned().skip(self_ty_vars));
800     Some(fallback_bound_vars(suffix, self_ty_vars))
801 }
802
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)
809         } else {
810             bound.shifted_in_from(binders).to_ty(&Interner)
811         }
812     })
813 }
814
815 fn transform_receiver_ty(
816     db: &dyn HirDatabase,
817     function_id: FunctionId,
818     self_ty: &Canonical<Ty>,
819 ) -> Option<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())
823             .fill_with_unknown()
824             .build(),
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)
829                 .fill_with_unknown()
830                 .build()
831         }
832         AssocContainerId::ModuleId(_) => unreachable!(),
833     };
834     let sig = db.callable_item_signature(function_id.into());
835     Some(sig.map(|s| s.params()[0].clone()).substitute(&Interner, &substs))
836 }
837
838 pub fn implements_trait(
839     ty: &Canonical<Ty>,
840     db: &dyn HirDatabase,
841     env: Arc<TraitEnvironment>,
842     krate: CrateId,
843     trait_: TraitId,
844 ) -> bool {
845     let goal = generic_implements_goal(db, env, trait_, ty.clone());
846     let solution = db.trait_solve(krate, goal);
847
848     solution.is_some()
849 }
850
851 pub fn implements_trait_unique(
852     ty: &Canonical<Ty>,
853     db: &dyn HirDatabase,
854     env: Arc<TraitEnvironment>,
855     krate: CrateId,
856     trait_: TraitId,
857 ) -> bool {
858     let goal = generic_implements_goal(db, env, trait_, ty.clone());
859     let solution = db.trait_solve(krate, goal);
860
861     matches!(solution, Some(crate::Solution::Unique(_)))
862 }
863
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>,
869     trait_: TraitId,
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_)
874         .push(self_ty.value)
875         .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
876         .build();
877     kinds.extend(
878         iter::repeat(chalk_ir::WithKind::new(
879             chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
880             UniverseIndex::ROOT,
881         ))
882         .take(trait_ref.substitution.len(&Interner) - 1),
883     );
884     let obligation = trait_ref.cast(&Interner);
885     Canonical {
886         binders: CanonicalVarKinds::from_iter(&Interner, kinds),
887         value: InEnvironment::new(&env.env, obligation),
888     }
889 }
890
891 fn autoderef_method_receiver(
892     db: &dyn HirDatabase,
893     krate: CrateId,
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))
900     {
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 })
904     }
905     deref_chain
906 }