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