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