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