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