]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/method_resolution.rs
Move hir_trait_id to extension trait
[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, TraitRefExt, Ty, TyBuilder,
26     TyExt, TyKind, 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 pub fn def_crates(
243     db: &dyn HirDatabase,
244     ty: &Ty,
245     cur_crate: CrateId,
246 ) -> Option<ArrayVec<CrateId, 2>> {
247     // Types like slice can have inherent impls in several crates, (core and alloc).
248     // The corresponding impls are marked with lang items, so we can use them to find the required crates.
249     macro_rules! lang_item_crate {
250             ($($name:expr),+ $(,)?) => {{
251                 let mut v = ArrayVec::<LangItemTarget, 2>::new();
252                 $(
253                     v.extend(db.lang_item(cur_crate, $name.into()));
254                 )+
255                 v
256             }};
257         }
258
259     let mod_to_crate_ids = |module: ModuleId| Some(std::iter::once(module.krate()).collect());
260
261     let lang_item_targets = match ty.kind(&Interner) {
262         TyKind::Adt(AdtId(def_id), _) => {
263             return mod_to_crate_ids(def_id.module(db.upcast()));
264         }
265         TyKind::Foreign(id) => {
266             return mod_to_crate_ids(
267                 from_foreign_def_id(*id).lookup(db.upcast()).module(db.upcast()),
268             );
269         }
270         TyKind::Scalar(Scalar::Bool) => lang_item_crate!("bool"),
271         TyKind::Scalar(Scalar::Char) => lang_item_crate!("char"),
272         TyKind::Scalar(Scalar::Float(f)) => match f {
273             // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime)
274             FloatTy::F32 => lang_item_crate!("f32", "f32_runtime"),
275             FloatTy::F64 => lang_item_crate!("f64", "f64_runtime"),
276         },
277         &TyKind::Scalar(Scalar::Int(t)) => {
278             lang_item_crate!(primitive::int_ty_to_string(t))
279         }
280         &TyKind::Scalar(Scalar::Uint(t)) => {
281             lang_item_crate!(primitive::uint_ty_to_string(t))
282         }
283         TyKind::Str => lang_item_crate!("str_alloc", "str"),
284         TyKind::Slice(_) => lang_item_crate!("slice_alloc", "slice"),
285         TyKind::Raw(Mutability::Not, _) => lang_item_crate!("const_ptr"),
286         TyKind::Raw(Mutability::Mut, _) => lang_item_crate!("mut_ptr"),
287         TyKind::Dyn(_) => {
288             return ty.dyn_trait().and_then(|trait_| {
289                 mod_to_crate_ids(GenericDefId::TraitId(trait_).module(db.upcast()))
290             });
291         }
292         _ => return None,
293     };
294     let res = lang_item_targets
295         .into_iter()
296         .filter_map(|it| match it {
297             LangItemTarget::ImplDefId(it) => Some(it),
298             _ => None,
299         })
300         .map(|it| it.lookup(db.upcast()).container.krate())
301         .collect();
302     Some(res)
303 }
304
305 /// Look up the method with the given name, returning the actual autoderefed
306 /// receiver type (but without autoref applied yet).
307 pub(crate) fn lookup_method(
308     ty: &Canonical<Ty>,
309     db: &dyn HirDatabase,
310     env: Arc<TraitEnvironment>,
311     krate: CrateId,
312     traits_in_scope: &FxHashSet<TraitId>,
313     visible_from_module: Option<ModuleId>,
314     name: &Name,
315 ) -> Option<(Ty, FunctionId)> {
316     iterate_method_candidates(
317         ty,
318         db,
319         env,
320         krate,
321         &traits_in_scope,
322         visible_from_module,
323         Some(name),
324         LookupMode::MethodCall,
325         |ty, f| match f {
326             AssocItemId::FunctionId(f) => Some((ty.clone(), f)),
327             _ => None,
328         },
329     )
330 }
331
332 /// Whether we're looking up a dotted method call (like `v.len()`) or a path
333 /// (like `Vec::new`).
334 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
335 pub enum LookupMode {
336     /// Looking up a method call like `v.len()`: We only consider candidates
337     /// that have a `self` parameter, and do autoderef.
338     MethodCall,
339     /// Looking up a path like `Vec::new` or `Vec::default`: We consider all
340     /// candidates including associated constants, but don't do autoderef.
341     Path,
342 }
343
344 // This would be nicer if it just returned an iterator, but that runs into
345 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
346 // FIXME add a context type here?
347 pub fn iterate_method_candidates<T>(
348     ty: &Canonical<Ty>,
349     db: &dyn HirDatabase,
350     env: Arc<TraitEnvironment>,
351     krate: CrateId,
352     traits_in_scope: &FxHashSet<TraitId>,
353     visible_from_module: Option<ModuleId>,
354     name: Option<&Name>,
355     mode: LookupMode,
356     mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>,
357 ) -> Option<T> {
358     let mut slot = None;
359     iterate_method_candidates_impl(
360         ty,
361         db,
362         env,
363         krate,
364         traits_in_scope,
365         visible_from_module,
366         name,
367         mode,
368         &mut |ty, item| {
369             assert!(slot.is_none());
370             slot = callback(ty, item);
371             slot.is_some()
372         },
373     );
374     slot
375 }
376
377 fn iterate_method_candidates_impl(
378     ty: &Canonical<Ty>,
379     db: &dyn HirDatabase,
380     env: Arc<TraitEnvironment>,
381     krate: CrateId,
382     traits_in_scope: &FxHashSet<TraitId>,
383     visible_from_module: Option<ModuleId>,
384     name: Option<&Name>,
385     mode: LookupMode,
386     callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
387 ) -> bool {
388     match mode {
389         LookupMode::MethodCall => {
390             // For method calls, rust first does any number of autoderef, and then one
391             // autoref (i.e. when the method takes &self or &mut self). We just ignore
392             // the autoref currently -- when we find a method matching the given name,
393             // we assume it fits.
394
395             // Also note that when we've got a receiver like &S, even if the method we
396             // find in the end takes &self, we still do the autoderef step (just as
397             // rustc does an autoderef and then autoref again).
398             let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
399
400             // We have to be careful about the order we're looking at candidates
401             // in here. Consider the case where we're resolving `x.clone()`
402             // where `x: &Vec<_>`. This resolves to the clone method with self
403             // type `Vec<_>`, *not* `&_`. I.e. we need to consider methods where
404             // the receiver type exactly matches before cases where we have to
405             // do autoref. But in the autoderef steps, the `&_` self type comes
406             // up *before* the `Vec<_>` self type.
407             //
408             // On the other hand, we don't want to just pick any by-value method
409             // before any by-autoref method; it's just that we need to consider
410             // the methods by autoderef order of *receiver types*, not *self
411             // types*.
412
413             let deref_chain = autoderef_method_receiver(db, krate, ty);
414             for i in 0..deref_chain.len() {
415                 if iterate_method_candidates_with_autoref(
416                     &deref_chain[i..],
417                     db,
418                     env.clone(),
419                     krate,
420                     traits_in_scope,
421                     visible_from_module,
422                     name,
423                     callback,
424                 ) {
425                     return true;
426                 }
427             }
428             false
429         }
430         LookupMode::Path => {
431             // No autoderef for path lookups
432             iterate_method_candidates_for_self_ty(
433                 &ty,
434                 db,
435                 env,
436                 krate,
437                 traits_in_scope,
438                 visible_from_module,
439                 name,
440                 callback,
441             )
442         }
443     }
444 }
445
446 fn iterate_method_candidates_with_autoref(
447     deref_chain: &[Canonical<Ty>],
448     db: &dyn HirDatabase,
449     env: Arc<TraitEnvironment>,
450     krate: CrateId,
451     traits_in_scope: &FxHashSet<TraitId>,
452     visible_from_module: Option<ModuleId>,
453     name: Option<&Name>,
454     mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
455 ) -> bool {
456     if iterate_method_candidates_by_receiver(
457         &deref_chain[0],
458         &deref_chain[1..],
459         db,
460         env.clone(),
461         krate,
462         &traits_in_scope,
463         visible_from_module,
464         name,
465         &mut callback,
466     ) {
467         return true;
468     }
469     let refed = Canonical {
470         binders: deref_chain[0].binders.clone(),
471         value: TyKind::Ref(Mutability::Not, static_lifetime(), deref_chain[0].value.clone())
472             .intern(&Interner),
473     };
474     if iterate_method_candidates_by_receiver(
475         &refed,
476         deref_chain,
477         db,
478         env.clone(),
479         krate,
480         &traits_in_scope,
481         visible_from_module,
482         name,
483         &mut callback,
484     ) {
485         return true;
486     }
487     let ref_muted = Canonical {
488         binders: deref_chain[0].binders.clone(),
489         value: TyKind::Ref(Mutability::Mut, static_lifetime(), deref_chain[0].value.clone())
490             .intern(&Interner),
491     };
492     if iterate_method_candidates_by_receiver(
493         &ref_muted,
494         deref_chain,
495         db,
496         env,
497         krate,
498         &traits_in_scope,
499         visible_from_module,
500         name,
501         &mut callback,
502     ) {
503         return true;
504     }
505     false
506 }
507
508 fn iterate_method_candidates_by_receiver(
509     receiver_ty: &Canonical<Ty>,
510     rest_of_deref_chain: &[Canonical<Ty>],
511     db: &dyn HirDatabase,
512     env: Arc<TraitEnvironment>,
513     krate: CrateId,
514     traits_in_scope: &FxHashSet<TraitId>,
515     visible_from_module: Option<ModuleId>,
516     name: Option<&Name>,
517     mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
518 ) -> bool {
519     // We're looking for methods with *receiver* type receiver_ty. These could
520     // be found in any of the derefs of receiver_ty, so we have to go through
521     // that.
522     for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
523         if iterate_inherent_methods(
524             self_ty,
525             db,
526             name,
527             Some(receiver_ty),
528             krate,
529             visible_from_module,
530             &mut callback,
531         ) {
532             return true;
533         }
534     }
535     for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
536         if iterate_trait_method_candidates(
537             self_ty,
538             db,
539             env.clone(),
540             krate,
541             &traits_in_scope,
542             name,
543             Some(receiver_ty),
544             &mut callback,
545         ) {
546             return true;
547         }
548     }
549     false
550 }
551
552 fn iterate_method_candidates_for_self_ty(
553     self_ty: &Canonical<Ty>,
554     db: &dyn HirDatabase,
555     env: Arc<TraitEnvironment>,
556     krate: CrateId,
557     traits_in_scope: &FxHashSet<TraitId>,
558     visible_from_module: Option<ModuleId>,
559     name: Option<&Name>,
560     mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
561 ) -> bool {
562     if iterate_inherent_methods(self_ty, db, name, None, krate, visible_from_module, &mut callback)
563     {
564         return true;
565     }
566     iterate_trait_method_candidates(self_ty, db, env, krate, traits_in_scope, name, None, callback)
567 }
568
569 fn iterate_trait_method_candidates(
570     self_ty: &Canonical<Ty>,
571     db: &dyn HirDatabase,
572     env: Arc<TraitEnvironment>,
573     krate: CrateId,
574     traits_in_scope: &FxHashSet<TraitId>,
575     name: Option<&Name>,
576     receiver_ty: Option<&Canonical<Ty>>,
577     callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
578 ) -> bool {
579     // if ty is `dyn Trait`, the trait doesn't need to be in scope
580     let inherent_trait =
581         self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t));
582     let env_traits = if let TyKind::Placeholder(_) = self_ty.value.kind(&Interner) {
583         // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
584         env.traits_in_scope_from_clauses(&self_ty.value)
585             .flat_map(|t| all_super_traits(db.upcast(), t))
586             .collect()
587     } else {
588         Vec::new()
589     };
590     let traits =
591         inherent_trait.chain(env_traits.into_iter()).chain(traits_in_scope.iter().copied());
592     'traits: for t in traits {
593         let data = db.trait_data(t);
594
595         // we'll be lazy about checking whether the type implements the
596         // trait, but if we find out it doesn't, we'll skip the rest of the
597         // iteration
598         let mut known_implemented = false;
599         for (_name, item) in data.items.iter() {
600             // Don't pass a `visible_from_module` down to `is_valid_candidate`,
601             // since only inherent methods should be included into visibility checking.
602             if !is_valid_candidate(db, name, receiver_ty, *item, self_ty, None) {
603                 continue;
604             }
605             if !known_implemented {
606                 let goal = generic_implements_goal(db, env.clone(), t, self_ty.clone());
607                 if db.trait_solve(krate, goal).is_none() {
608                     continue 'traits;
609                 }
610             }
611             known_implemented = true;
612             if callback(&self_ty.value, *item) {
613                 return true;
614             }
615         }
616     }
617     false
618 }
619
620 fn iterate_inherent_methods(
621     self_ty: &Canonical<Ty>,
622     db: &dyn HirDatabase,
623     name: Option<&Name>,
624     receiver_ty: Option<&Canonical<Ty>>,
625     krate: CrateId,
626     visible_from_module: Option<ModuleId>,
627     callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
628 ) -> bool {
629     let def_crates = match def_crates(db, &self_ty.value, krate) {
630         Some(k) => k,
631         None => return false,
632     };
633     for krate in def_crates {
634         let impls = db.inherent_impls_in_crate(krate);
635
636         for &impl_def in impls.for_self_ty(&self_ty.value) {
637             for &item in db.impl_data(impl_def).items.iter() {
638                 if !is_valid_candidate(db, name, receiver_ty, item, self_ty, visible_from_module) {
639                     continue;
640                 }
641                 // we have to check whether the self type unifies with the type
642                 // that the impl is for. If we have a receiver type, this
643                 // already happens in `is_valid_candidate` above; if not, we
644                 // check it here
645                 if receiver_ty.is_none() && inherent_impl_substs(db, impl_def, self_ty).is_none() {
646                     cov_mark::hit!(impl_self_type_match_without_receiver);
647                     continue;
648                 }
649                 if callback(&self_ty.value, item) {
650                     return true;
651                 }
652             }
653         }
654     }
655     false
656 }
657
658 /// Returns the self type for the index trait call.
659 pub fn resolve_indexing_op(
660     db: &dyn HirDatabase,
661     ty: &Canonical<Ty>,
662     env: Arc<TraitEnvironment>,
663     krate: CrateId,
664     index_trait: TraitId,
665 ) -> Option<Canonical<Ty>> {
666     let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
667     let deref_chain = autoderef_method_receiver(db, krate, ty);
668     for ty in deref_chain {
669         let goal = generic_implements_goal(db, env.clone(), index_trait, ty.clone());
670         if db.trait_solve(krate, goal).is_some() {
671             return Some(ty);
672         }
673     }
674     None
675 }
676
677 fn is_valid_candidate(
678     db: &dyn HirDatabase,
679     name: Option<&Name>,
680     receiver_ty: Option<&Canonical<Ty>>,
681     item: AssocItemId,
682     self_ty: &Canonical<Ty>,
683     visible_from_module: Option<ModuleId>,
684 ) -> bool {
685     match item {
686         AssocItemId::FunctionId(m) => {
687             let data = db.function_data(m);
688             if let Some(name) = name {
689                 if &data.name != name {
690                     return false;
691                 }
692             }
693             if let Some(receiver_ty) = receiver_ty {
694                 if !data.has_self_param() {
695                     return false;
696                 }
697                 let transformed_receiver_ty = match transform_receiver_ty(db, m, self_ty) {
698                     Some(ty) => ty,
699                     None => return false,
700                 };
701                 if transformed_receiver_ty != receiver_ty.value {
702                     return false;
703                 }
704             }
705             if let Some(from_module) = visible_from_module {
706                 if !db.function_visibility(m).is_visible_from(db.upcast(), from_module) {
707                     cov_mark::hit!(autoderef_candidate_not_visible);
708                     return false;
709                 }
710             }
711
712             true
713         }
714         AssocItemId::ConstId(c) => {
715             let data = db.const_data(c);
716             name.map_or(true, |name| data.name.as_ref() == Some(name)) && receiver_ty.is_none()
717         }
718         _ => false,
719     }
720 }
721
722 pub(crate) fn inherent_impl_substs(
723     db: &dyn HirDatabase,
724     impl_id: ImplId,
725     self_ty: &Canonical<Ty>,
726 ) -> Option<Substitution> {
727     // we create a var for each type parameter of the impl; we need to keep in
728     // mind here that `self_ty` might have vars of its own
729     let self_ty_vars = self_ty.binders.len(&Interner);
730     let vars = TyBuilder::subst_for_def(db, impl_id)
731         .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty_vars)
732         .build();
733     let self_ty_with_vars = db.impl_self_ty(impl_id).substitute(&Interner, &vars);
734     let mut kinds = self_ty.binders.interned().to_vec();
735     kinds.extend(
736         iter::repeat(chalk_ir::WithKind::new(
737             chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
738             UniverseIndex::ROOT,
739         ))
740         .take(vars.len(&Interner)),
741     );
742     let tys = Canonical {
743         binders: CanonicalVarKinds::from_iter(&Interner, kinds),
744         value: (self_ty_with_vars, self_ty.value.clone()),
745     };
746     let substs = super::infer::unify(&tys)?;
747     // We only want the substs for the vars we added, not the ones from self_ty.
748     // Also, if any of the vars we added are still in there, we replace them by
749     // Unknown. I think this can only really happen if self_ty contained
750     // Unknown, and in that case we want the result to contain Unknown in those
751     // places again.
752     let suffix =
753         Substitution::from_iter(&Interner, substs.iter(&Interner).cloned().skip(self_ty_vars));
754     Some(fallback_bound_vars(suffix, self_ty_vars))
755 }
756
757 /// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
758 /// num_vars_to_keep) by `TyKind::Unknown`.
759 fn fallback_bound_vars(s: Substitution, num_vars_to_keep: usize) -> Substitution {
760     s.fold_binders(
761         &mut |ty, binders| {
762             if let TyKind::BoundVar(bound) = ty.kind(&Interner) {
763                 if bound.index >= num_vars_to_keep && bound.debruijn >= binders {
764                     TyKind::Error.intern(&Interner)
765                 } else {
766                     ty
767                 }
768             } else {
769                 ty
770             }
771         },
772         DebruijnIndex::INNERMOST,
773     )
774 }
775
776 fn transform_receiver_ty(
777     db: &dyn HirDatabase,
778     function_id: FunctionId,
779     self_ty: &Canonical<Ty>,
780 ) -> Option<Ty> {
781     let substs = match function_id.lookup(db.upcast()).container {
782         AssocContainerId::TraitId(_) => TyBuilder::subst_for_def(db, function_id)
783             .push(self_ty.value.clone())
784             .fill_with_unknown()
785             .build(),
786         AssocContainerId::ImplId(impl_id) => {
787             let impl_substs = inherent_impl_substs(db, impl_id, &self_ty)?;
788             TyBuilder::subst_for_def(db, function_id)
789                 .use_parent_substs(&impl_substs)
790                 .fill_with_unknown()
791                 .build()
792         }
793         AssocContainerId::ModuleId(_) => unreachable!(),
794     };
795     let sig = db.callable_item_signature(function_id.into());
796     Some(sig.map(|s| s.params()[0].clone()).substitute(&Interner, &substs))
797 }
798
799 pub fn implements_trait(
800     ty: &Canonical<Ty>,
801     db: &dyn HirDatabase,
802     env: Arc<TraitEnvironment>,
803     krate: CrateId,
804     trait_: TraitId,
805 ) -> bool {
806     let goal = generic_implements_goal(db, env, trait_, ty.clone());
807     let solution = db.trait_solve(krate, goal);
808
809     solution.is_some()
810 }
811
812 pub fn implements_trait_unique(
813     ty: &Canonical<Ty>,
814     db: &dyn HirDatabase,
815     env: Arc<TraitEnvironment>,
816     krate: CrateId,
817     trait_: TraitId,
818 ) -> bool {
819     let goal = generic_implements_goal(db, env, trait_, ty.clone());
820     let solution = db.trait_solve(krate, goal);
821
822     matches!(solution, Some(crate::Solution::Unique(_)))
823 }
824
825 /// This creates Substs for a trait with the given Self type and type variables
826 /// for all other parameters, to query Chalk with it.
827 fn generic_implements_goal(
828     db: &dyn HirDatabase,
829     env: Arc<TraitEnvironment>,
830     trait_: TraitId,
831     self_ty: Canonical<Ty>,
832 ) -> Canonical<InEnvironment<super::DomainGoal>> {
833     let mut kinds = self_ty.binders.interned().to_vec();
834     let trait_ref = TyBuilder::trait_ref(db, trait_)
835         .push(self_ty.value)
836         .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
837         .build();
838     kinds.extend(
839         iter::repeat(chalk_ir::WithKind::new(
840             chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
841             UniverseIndex::ROOT,
842         ))
843         .take(trait_ref.substitution.len(&Interner) - 1),
844     );
845     let obligation = trait_ref.cast(&Interner);
846     Canonical {
847         binders: CanonicalVarKinds::from_iter(&Interner, kinds),
848         value: InEnvironment::new(env.env.clone(), obligation),
849     }
850 }
851
852 fn autoderef_method_receiver(
853     db: &dyn HirDatabase,
854     krate: CrateId,
855     ty: InEnvironment<Canonical<Ty>>,
856 ) -> Vec<Canonical<Ty>> {
857     let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
858     // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
859     if let Some(TyKind::Array(parameters, _)) =
860         deref_chain.last().map(|ty| ty.value.kind(&Interner))
861     {
862         let kinds = deref_chain.last().unwrap().binders.clone();
863         let unsized_ty = TyKind::Slice(parameters.clone()).intern(&Interner);
864         deref_chain.push(Canonical { value: unsized_ty, binders: kinds })
865     }
866     deref_chain
867 }