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