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