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