]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/method_resolution.rs
Merge #9247
[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, 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     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(TyFingerprint::Dyn)?,
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(TyFingerprint::Dyn)?,
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         impls.collect_def_map(db, &crate_def_map);
143
144         return 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         return 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::Raw(Mutability::Not, _) => lang_item_crate!("const_ptr"),
352         TyKind::Raw(Mutability::Mut, _) => lang_item_crate!("mut_ptr"),
353         TyKind::Dyn(_) => {
354             return ty.dyn_trait().and_then(|trait_| {
355                 mod_to_crate_ids(GenericDefId::TraitId(trait_).module(db.upcast()))
356             });
357         }
358         _ => return None,
359     };
360     let res = lang_item_targets
361         .into_iter()
362         .filter_map(|it| match it {
363             LangItemTarget::ImplDefId(it) => Some(it),
364             _ => None,
365         })
366         .map(|it| it.lookup(db.upcast()).container.krate())
367         .collect();
368     Some(res)
369 }
370
371 /// Look up the method with the given name, returning the actual autoderefed
372 /// receiver type (but without autoref applied yet).
373 pub(crate) fn lookup_method(
374     ty: &Canonical<Ty>,
375     db: &dyn HirDatabase,
376     env: Arc<TraitEnvironment>,
377     krate: CrateId,
378     traits_in_scope: &FxHashSet<TraitId>,
379     visible_from_module: Option<ModuleId>,
380     name: &Name,
381 ) -> Option<(Ty, FunctionId)> {
382     iterate_method_candidates(
383         ty,
384         db,
385         env,
386         krate,
387         traits_in_scope,
388         visible_from_module,
389         Some(name),
390         LookupMode::MethodCall,
391         |ty, f| match f {
392             AssocItemId::FunctionId(f) => Some((ty.clone(), f)),
393             _ => None,
394         },
395     )
396 }
397
398 /// Whether we're looking up a dotted method call (like `v.len()`) or a path
399 /// (like `Vec::new`).
400 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
401 pub enum LookupMode {
402     /// Looking up a method call like `v.len()`: We only consider candidates
403     /// that have a `self` parameter, and do autoderef.
404     MethodCall,
405     /// Looking up a path like `Vec::new` or `Vec::default`: We consider all
406     /// candidates including associated constants, but don't do autoderef.
407     Path,
408 }
409
410 // This would be nicer if it just returned an iterator, but that runs into
411 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
412 // FIXME add a context type here?
413 pub fn iterate_method_candidates<T>(
414     ty: &Canonical<Ty>,
415     db: &dyn HirDatabase,
416     env: Arc<TraitEnvironment>,
417     krate: CrateId,
418     traits_in_scope: &FxHashSet<TraitId>,
419     visible_from_module: Option<ModuleId>,
420     name: Option<&Name>,
421     mode: LookupMode,
422     mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>,
423 ) -> Option<T> {
424     let mut slot = None;
425     iterate_method_candidates_impl(
426         ty,
427         db,
428         env,
429         krate,
430         traits_in_scope,
431         visible_from_module,
432         name,
433         mode,
434         &mut |ty, item| {
435             assert!(slot.is_none());
436             slot = callback(ty, item);
437             slot.is_some()
438         },
439     );
440     slot
441 }
442
443 fn iterate_method_candidates_impl(
444     ty: &Canonical<Ty>,
445     db: &dyn HirDatabase,
446     env: Arc<TraitEnvironment>,
447     krate: CrateId,
448     traits_in_scope: &FxHashSet<TraitId>,
449     visible_from_module: Option<ModuleId>,
450     name: Option<&Name>,
451     mode: LookupMode,
452     callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
453 ) -> bool {
454     match mode {
455         LookupMode::MethodCall => {
456             // For method calls, rust first does any number of autoderef, and then one
457             // autoref (i.e. when the method takes &self or &mut self). We just ignore
458             // the autoref currently -- when we find a method matching the given name,
459             // we assume it fits.
460
461             // Also note that when we've got a receiver like &S, even if the method we
462             // find in the end takes &self, we still do the autoderef step (just as
463             // rustc does an autoderef and then autoref again).
464             let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
465
466             // We have to be careful about the order we're looking at candidates
467             // in here. Consider the case where we're resolving `x.clone()`
468             // where `x: &Vec<_>`. This resolves to the clone method with self
469             // type `Vec<_>`, *not* `&_`. I.e. we need to consider methods where
470             // the receiver type exactly matches before cases where we have to
471             // do autoref. But in the autoderef steps, the `&_` self type comes
472             // up *before* the `Vec<_>` self type.
473             //
474             // On the other hand, we don't want to just pick any by-value method
475             // before any by-autoref method; it's just that we need to consider
476             // the methods by autoderef order of *receiver types*, not *self
477             // types*.
478
479             let deref_chain = autoderef_method_receiver(db, krate, ty);
480             for i in 0..deref_chain.len() {
481                 if iterate_method_candidates_with_autoref(
482                     &deref_chain[i..],
483                     db,
484                     env.clone(),
485                     krate,
486                     traits_in_scope,
487                     visible_from_module,
488                     name,
489                     callback,
490                 ) {
491                     return true;
492                 }
493             }
494             false
495         }
496         LookupMode::Path => {
497             // No autoderef for path lookups
498             iterate_method_candidates_for_self_ty(
499                 ty,
500                 db,
501                 env,
502                 krate,
503                 traits_in_scope,
504                 visible_from_module,
505                 name,
506                 callback,
507             )
508         }
509     }
510 }
511
512 fn iterate_method_candidates_with_autoref(
513     deref_chain: &[Canonical<Ty>],
514     db: &dyn HirDatabase,
515     env: Arc<TraitEnvironment>,
516     krate: CrateId,
517     traits_in_scope: &FxHashSet<TraitId>,
518     visible_from_module: Option<ModuleId>,
519     name: Option<&Name>,
520     mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
521 ) -> bool {
522     if iterate_method_candidates_by_receiver(
523         &deref_chain[0],
524         &deref_chain[1..],
525         db,
526         env.clone(),
527         krate,
528         traits_in_scope,
529         visible_from_module,
530         name,
531         &mut callback,
532     ) {
533         return true;
534     }
535     let refed = Canonical {
536         binders: deref_chain[0].binders.clone(),
537         value: TyKind::Ref(Mutability::Not, static_lifetime(), deref_chain[0].value.clone())
538             .intern(&Interner),
539     };
540     if iterate_method_candidates_by_receiver(
541         &refed,
542         deref_chain,
543         db,
544         env.clone(),
545         krate,
546         traits_in_scope,
547         visible_from_module,
548         name,
549         &mut callback,
550     ) {
551         return true;
552     }
553     let ref_muted = Canonical {
554         binders: deref_chain[0].binders.clone(),
555         value: TyKind::Ref(Mutability::Mut, static_lifetime(), deref_chain[0].value.clone())
556             .intern(&Interner),
557     };
558     if iterate_method_candidates_by_receiver(
559         &ref_muted,
560         deref_chain,
561         db,
562         env,
563         krate,
564         traits_in_scope,
565         visible_from_module,
566         name,
567         &mut callback,
568     ) {
569         return true;
570     }
571     false
572 }
573
574 fn iterate_method_candidates_by_receiver(
575     receiver_ty: &Canonical<Ty>,
576     rest_of_deref_chain: &[Canonical<Ty>],
577     db: &dyn HirDatabase,
578     env: Arc<TraitEnvironment>,
579     krate: CrateId,
580     traits_in_scope: &FxHashSet<TraitId>,
581     visible_from_module: Option<ModuleId>,
582     name: Option<&Name>,
583     mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
584 ) -> bool {
585     // We're looking for methods with *receiver* type receiver_ty. These could
586     // be found in any of the derefs of receiver_ty, so we have to go through
587     // that.
588     for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
589         if iterate_inherent_methods(
590             self_ty,
591             db,
592             env.clone(),
593             name,
594             Some(receiver_ty),
595             krate,
596             visible_from_module,
597             &mut callback,
598         ) {
599             return true;
600         }
601     }
602     for self_ty in std::iter::once(receiver_ty).chain(rest_of_deref_chain) {
603         if iterate_trait_method_candidates(
604             self_ty,
605             db,
606             env.clone(),
607             krate,
608             traits_in_scope,
609             name,
610             Some(receiver_ty),
611             &mut callback,
612         ) {
613             return true;
614         }
615     }
616     false
617 }
618
619 fn iterate_method_candidates_for_self_ty(
620     self_ty: &Canonical<Ty>,
621     db: &dyn HirDatabase,
622     env: Arc<TraitEnvironment>,
623     krate: CrateId,
624     traits_in_scope: &FxHashSet<TraitId>,
625     visible_from_module: Option<ModuleId>,
626     name: Option<&Name>,
627     mut callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
628 ) -> bool {
629     if iterate_inherent_methods(
630         self_ty,
631         db,
632         env.clone(),
633         name,
634         None,
635         krate,
636         visible_from_module,
637         &mut callback,
638     ) {
639         return true;
640     }
641     iterate_trait_method_candidates(self_ty, db, env, krate, traits_in_scope, name, None, callback)
642 }
643
644 fn iterate_trait_method_candidates(
645     self_ty: &Canonical<Ty>,
646     db: &dyn HirDatabase,
647     env: Arc<TraitEnvironment>,
648     krate: CrateId,
649     traits_in_scope: &FxHashSet<TraitId>,
650     name: Option<&Name>,
651     receiver_ty: Option<&Canonical<Ty>>,
652     callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
653 ) -> bool {
654     let receiver_is_array = matches!(self_ty.value.kind(&Interner), chalk_ir::TyKind::Array(..));
655     // if ty is `dyn Trait`, the trait doesn't need to be in scope
656     let inherent_trait =
657         self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t));
658     let env_traits = if let TyKind::Placeholder(_) = self_ty.value.kind(&Interner) {
659         // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
660         env.traits_in_scope_from_clauses(&self_ty.value)
661             .flat_map(|t| all_super_traits(db.upcast(), t))
662             .collect()
663     } else {
664         Vec::new()
665     };
666     let traits =
667         inherent_trait.chain(env_traits.into_iter()).chain(traits_in_scope.iter().copied());
668     'traits: for t in traits {
669         let data = db.trait_data(t);
670
671         // Traits annotated with `#[rustc_skip_array_during_method_dispatch]` are skipped during
672         // method resolution, if the receiver is an array, and we're compiling for editions before
673         // 2021.
674         // This is to make `[a].into_iter()` not break code with the new `IntoIterator` impl for
675         // arrays.
676         if data.skip_array_during_method_dispatch && receiver_is_array {
677             // FIXME: this should really be using the edition of the method name's span, in case it
678             // comes from a macro
679             if db.crate_graph()[krate].edition < Edition::Edition2021 {
680                 continue;
681             }
682         }
683
684         // we'll be lazy about checking whether the type implements the
685         // trait, but if we find out it doesn't, we'll skip the rest of the
686         // iteration
687         let mut known_implemented = false;
688         for (_name, item) in data.items.iter() {
689             // Don't pass a `visible_from_module` down to `is_valid_candidate`,
690             // since only inherent methods should be included into visibility checking.
691             if !is_valid_candidate(db, env.clone(), name, receiver_ty, *item, self_ty, None) {
692                 continue;
693             }
694             if !known_implemented {
695                 let goal = generic_implements_goal(db, env.clone(), t, self_ty.clone());
696                 if db.trait_solve(krate, goal.cast(&Interner)).is_none() {
697                     continue 'traits;
698                 }
699             }
700             known_implemented = true;
701             // FIXME: we shouldn't be ignoring the binders here
702             if callback(&self_ty.value, *item) {
703                 return true;
704             }
705         }
706     }
707     false
708 }
709
710 fn iterate_inherent_methods(
711     self_ty: &Canonical<Ty>,
712     db: &dyn HirDatabase,
713     env: Arc<TraitEnvironment>,
714     name: Option<&Name>,
715     receiver_ty: Option<&Canonical<Ty>>,
716     krate: CrateId,
717     visible_from_module: Option<ModuleId>,
718     callback: &mut dyn FnMut(&Ty, AssocItemId) -> bool,
719 ) -> bool {
720     let def_crates = match def_crates(db, &self_ty.value, krate) {
721         Some(k) => k,
722         None => return false,
723     };
724     for krate in def_crates {
725         let impls = db.inherent_impls_in_crate(krate);
726
727         for &impl_def in impls.for_self_ty(&self_ty.value) {
728             for &item in db.impl_data(impl_def).items.iter() {
729                 if !is_valid_candidate(
730                     db,
731                     env.clone(),
732                     name,
733                     receiver_ty,
734                     item,
735                     self_ty,
736                     visible_from_module,
737                 ) {
738                     continue;
739                 }
740                 // we have to check whether the self type unifies with the type
741                 // that the impl is for. If we have a receiver type, this
742                 // already happens in `is_valid_candidate` above; if not, we
743                 // check it here
744                 if receiver_ty.is_none()
745                     && inherent_impl_substs(db, env.clone(), impl_def, self_ty).is_none()
746                 {
747                     cov_mark::hit!(impl_self_type_match_without_receiver);
748                     continue;
749                 }
750                 let receiver_ty = receiver_ty.map(|x| &x.value).unwrap_or(&self_ty.value);
751                 if callback(receiver_ty, item) {
752                     return true;
753                 }
754             }
755         }
756     }
757     false
758 }
759
760 /// Returns the self type for the index trait call.
761 pub fn resolve_indexing_op(
762     db: &dyn HirDatabase,
763     ty: &Canonical<Ty>,
764     env: Arc<TraitEnvironment>,
765     krate: CrateId,
766     index_trait: TraitId,
767 ) -> Option<Canonical<Ty>> {
768     let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
769     let deref_chain = autoderef_method_receiver(db, krate, ty);
770     for ty in deref_chain {
771         let goal = generic_implements_goal(db, env.clone(), index_trait, ty.clone());
772         if db.trait_solve(krate, goal.cast(&Interner)).is_some() {
773             return Some(ty);
774         }
775     }
776     None
777 }
778
779 fn is_valid_candidate(
780     db: &dyn HirDatabase,
781     env: Arc<TraitEnvironment>,
782     name: Option<&Name>,
783     receiver_ty: Option<&Canonical<Ty>>,
784     item: AssocItemId,
785     self_ty: &Canonical<Ty>,
786     visible_from_module: Option<ModuleId>,
787 ) -> bool {
788     match item {
789         AssocItemId::FunctionId(m) => {
790             let data = db.function_data(m);
791             if let Some(name) = name {
792                 if &data.name != name {
793                     return false;
794                 }
795             }
796             if let Some(receiver_ty) = receiver_ty {
797                 if !data.has_self_param() {
798                     return false;
799                 }
800                 let transformed_receiver_ty = match transform_receiver_ty(db, env, m, self_ty) {
801                     Some(ty) => ty,
802                     None => return false,
803                 };
804                 if transformed_receiver_ty != receiver_ty.value {
805                     return false;
806                 }
807             }
808             if let Some(from_module) = visible_from_module {
809                 if !db.function_visibility(m).is_visible_from(db.upcast(), from_module) {
810                     cov_mark::hit!(autoderef_candidate_not_visible);
811                     return false;
812                 }
813             }
814
815             true
816         }
817         AssocItemId::ConstId(c) => {
818             let data = db.const_data(c);
819             name.map_or(true, |name| data.name.as_ref() == Some(name)) && receiver_ty.is_none()
820         }
821         _ => false,
822     }
823 }
824
825 pub(crate) fn inherent_impl_substs(
826     db: &dyn HirDatabase,
827     env: Arc<TraitEnvironment>,
828     impl_id: ImplId,
829     self_ty: &Canonical<Ty>,
830 ) -> Option<Substitution> {
831     // we create a var for each type parameter of the impl; we need to keep in
832     // mind here that `self_ty` might have vars of its own
833     let self_ty_vars = self_ty.binders.len(&Interner);
834     let vars = TyBuilder::subst_for_def(db, impl_id)
835         .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty_vars)
836         .build();
837     let self_ty_with_vars = db.impl_self_ty(impl_id).substitute(&Interner, &vars);
838     let mut kinds = self_ty.binders.interned().to_vec();
839     kinds.extend(
840         iter::repeat(chalk_ir::WithKind::new(
841             chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
842             UniverseIndex::ROOT,
843         ))
844         .take(vars.len(&Interner)),
845     );
846     let tys = Canonical {
847         binders: CanonicalVarKinds::from_iter(&Interner, kinds),
848         value: (self_ty_with_vars, self_ty.value.clone()),
849     };
850     let substs = super::infer::unify(db, env, &tys)?;
851     // We only want the substs for the vars we added, not the ones from self_ty.
852     // Also, if any of the vars we added are still in there, we replace them by
853     // Unknown. I think this can only really happen if self_ty contained
854     // Unknown, and in that case we want the result to contain Unknown in those
855     // places again.
856     let suffix =
857         Substitution::from_iter(&Interner, substs.iter(&Interner).cloned().skip(self_ty_vars));
858     Some(fallback_bound_vars(suffix, self_ty_vars))
859 }
860
861 /// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
862 /// num_vars_to_keep) by `TyKind::Unknown`.
863 fn fallback_bound_vars(s: Substitution, num_vars_to_keep: usize) -> Substitution {
864     crate::fold_free_vars(s, |bound, binders| {
865         if bound.index >= num_vars_to_keep && bound.debruijn == DebruijnIndex::INNERMOST {
866             TyKind::Error.intern(&Interner)
867         } else {
868             bound.shifted_in_from(binders).to_ty(&Interner)
869         }
870     })
871 }
872
873 fn transform_receiver_ty(
874     db: &dyn HirDatabase,
875     env: Arc<TraitEnvironment>,
876     function_id: FunctionId,
877     self_ty: &Canonical<Ty>,
878 ) -> Option<Ty> {
879     let substs = match function_id.lookup(db.upcast()).container {
880         AssocContainerId::TraitId(_) => TyBuilder::subst_for_def(db, function_id)
881             .push(self_ty.value.clone())
882             .fill_with_unknown()
883             .build(),
884         AssocContainerId::ImplId(impl_id) => {
885             let impl_substs = inherent_impl_substs(db, env, impl_id, self_ty)?;
886             TyBuilder::subst_for_def(db, function_id)
887                 .use_parent_substs(&impl_substs)
888                 .fill_with_unknown()
889                 .build()
890         }
891         AssocContainerId::ModuleId(_) => unreachable!(),
892     };
893     let sig = db.callable_item_signature(function_id.into());
894     Some(sig.map(|s| s.params()[0].clone()).substitute(&Interner, &substs))
895 }
896
897 pub fn implements_trait(
898     ty: &Canonical<Ty>,
899     db: &dyn HirDatabase,
900     env: Arc<TraitEnvironment>,
901     krate: CrateId,
902     trait_: TraitId,
903 ) -> bool {
904     let goal = generic_implements_goal(db, env, trait_, ty.clone());
905     let solution = db.trait_solve(krate, goal.cast(&Interner));
906
907     solution.is_some()
908 }
909
910 pub fn implements_trait_unique(
911     ty: &Canonical<Ty>,
912     db: &dyn HirDatabase,
913     env: Arc<TraitEnvironment>,
914     krate: CrateId,
915     trait_: TraitId,
916 ) -> bool {
917     let goal = generic_implements_goal(db, env, trait_, ty.clone());
918     let solution = db.trait_solve(krate, goal.cast(&Interner));
919
920     matches!(solution, Some(crate::Solution::Unique(_)))
921 }
922
923 /// This creates Substs for a trait with the given Self type and type variables
924 /// for all other parameters, to query Chalk with it.
925 fn generic_implements_goal(
926     db: &dyn HirDatabase,
927     env: Arc<TraitEnvironment>,
928     trait_: TraitId,
929     self_ty: Canonical<Ty>,
930 ) -> Canonical<InEnvironment<super::DomainGoal>> {
931     let mut kinds = self_ty.binders.interned().to_vec();
932     let trait_ref = TyBuilder::trait_ref(db, trait_)
933         .push(self_ty.value)
934         .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
935         .build();
936     kinds.extend(
937         iter::repeat(chalk_ir::WithKind::new(
938             chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
939             UniverseIndex::ROOT,
940         ))
941         .take(trait_ref.substitution.len(&Interner) - 1),
942     );
943     let obligation = trait_ref.cast(&Interner);
944     Canonical {
945         binders: CanonicalVarKinds::from_iter(&Interner, kinds),
946         value: InEnvironment::new(&env.env, obligation),
947     }
948 }
949
950 fn autoderef_method_receiver(
951     db: &dyn HirDatabase,
952     krate: CrateId,
953     ty: InEnvironment<Canonical<Ty>>,
954 ) -> Vec<Canonical<Ty>> {
955     let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
956     // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
957     if let Some(TyKind::Array(parameters, _)) =
958         deref_chain.last().map(|ty| ty.value.kind(&Interner))
959     {
960         let kinds = deref_chain.last().unwrap().binders.clone();
961         let unsized_ty = TyKind::Slice(parameters.clone()).intern(&Interner);
962         deref_chain.push(Canonical { value: unsized_ty, binders: kinds })
963     }
964     deref_chain
965 }