]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/method_resolution.rs
Merge #11107
[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
546             deref_chains.try_for_each(|deref_chain| {
547                 iterate_method_candidates_with_autoref(
548                     deref_chain,
549                     db,
550                     env.clone(),
551                     krate,
552                     traits_in_scope,
553                     visible_from_module,
554                     name,
555                     callback,
556                 )
557             })
558         }
559         LookupMode::Path => {
560             // No autoderef for path lookups
561             iterate_method_candidates_for_self_ty(
562                 ty,
563                 db,
564                 env,
565                 krate,
566                 traits_in_scope,
567                 visible_from_module,
568                 name,
569                 callback,
570             )
571         }
572     }
573 }
574
575 fn iterate_method_candidates_with_autoref(
576     deref_chain: &[Canonical<Ty>],
577     db: &dyn HirDatabase,
578     env: Arc<TraitEnvironment>,
579     krate: CrateId,
580     traits_in_scope: &FxHashSet<TraitId>,
581     visible_from_module: Option<ModuleId>,
582     name: Option<&Name>,
583     mut callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
584 ) -> ControlFlow<()> {
585     let (receiver_ty, rest) = match deref_chain.split_first() {
586         Some((rec, rest)) => (rec.clone(), rest),
587         None => {
588             never!("received empty deref-chain");
589             return ControlFlow::Break(());
590         }
591     };
592     iterate_method_candidates_by_receiver(
593         &receiver_ty,
594         &rest,
595         db,
596         env.clone(),
597         krate,
598         traits_in_scope,
599         visible_from_module,
600         name,
601         &mut callback,
602     )?;
603
604     let refed = Canonical {
605         binders: receiver_ty.binders.clone(),
606         value: TyKind::Ref(Mutability::Not, static_lifetime(), receiver_ty.value.clone())
607             .intern(Interner),
608     };
609
610     iterate_method_candidates_by_receiver(
611         &refed,
612         deref_chain,
613         db,
614         env.clone(),
615         krate,
616         traits_in_scope,
617         visible_from_module,
618         name,
619         &mut callback,
620     )?;
621
622     let ref_muted = Canonical {
623         binders: receiver_ty.binders,
624         value: TyKind::Ref(Mutability::Mut, static_lifetime(), receiver_ty.value).intern(Interner),
625     };
626
627     iterate_method_candidates_by_receiver(
628         &ref_muted,
629         deref_chain,
630         db,
631         env,
632         krate,
633         traits_in_scope,
634         visible_from_module,
635         name,
636         &mut callback,
637     )
638 }
639
640 fn iterate_method_candidates_by_receiver(
641     receiver_ty: &Canonical<Ty>,
642     rest_of_deref_chain: &[Canonical<Ty>],
643     db: &dyn HirDatabase,
644     env: Arc<TraitEnvironment>,
645     krate: CrateId,
646     traits_in_scope: &FxHashSet<TraitId>,
647     visible_from_module: Option<ModuleId>,
648     name: Option<&Name>,
649     mut callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
650 ) -> ControlFlow<()> {
651     // We're looking for methods with *receiver* type receiver_ty. These could
652     // be found in any of the derefs of receiver_ty, so we have to go through
653     // that.
654     for self_ty in iter::once(receiver_ty).chain(rest_of_deref_chain) {
655         iterate_inherent_methods(
656             self_ty,
657             db,
658             env.clone(),
659             name,
660             Some(receiver_ty),
661             krate,
662             visible_from_module,
663             &mut callback,
664         )?
665     }
666
667     for self_ty in iter::once(receiver_ty).chain(rest_of_deref_chain) {
668         iterate_trait_method_candidates(
669             self_ty,
670             db,
671             env.clone(),
672             krate,
673             traits_in_scope,
674             name,
675             Some(receiver_ty),
676             &mut callback,
677         )?
678     }
679
680     ControlFlow::Continue(())
681 }
682
683 fn iterate_method_candidates_for_self_ty(
684     self_ty: &Canonical<Ty>,
685     db: &dyn HirDatabase,
686     env: Arc<TraitEnvironment>,
687     krate: CrateId,
688     traits_in_scope: &FxHashSet<TraitId>,
689     visible_from_module: Option<ModuleId>,
690     name: Option<&Name>,
691     mut callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
692 ) -> ControlFlow<()> {
693     iterate_inherent_methods(
694         self_ty,
695         db,
696         env.clone(),
697         name,
698         None,
699         krate,
700         visible_from_module,
701         &mut callback,
702     )?;
703     iterate_trait_method_candidates(self_ty, db, env, krate, traits_in_scope, name, None, callback)
704 }
705
706 fn iterate_trait_method_candidates(
707     self_ty: &Canonical<Ty>,
708     db: &dyn HirDatabase,
709     env: Arc<TraitEnvironment>,
710     krate: CrateId,
711     traits_in_scope: &FxHashSet<TraitId>,
712     name: Option<&Name>,
713     receiver_ty: Option<&Canonical<Ty>>,
714     callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
715 ) -> ControlFlow<()> {
716     let receiver_is_array = matches!(self_ty.value.kind(Interner), chalk_ir::TyKind::Array(..));
717     // if ty is `dyn Trait`, the trait doesn't need to be in scope
718     let inherent_trait =
719         self_ty.value.dyn_trait().into_iter().flat_map(|t| all_super_traits(db.upcast(), t));
720     let env_traits = matches!(self_ty.value.kind(Interner), TyKind::Placeholder(_))
721         // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
722         .then(|| {
723             env.traits_in_scope_from_clauses(self_ty.value.clone())
724                 .flat_map(|t| all_super_traits(db.upcast(), t))
725         })
726         .into_iter()
727         .flatten();
728     let traits = inherent_trait.chain(env_traits).chain(traits_in_scope.iter().copied());
729
730     'traits: for t in traits {
731         let data = db.trait_data(t);
732
733         // Traits annotated with `#[rustc_skip_array_during_method_dispatch]` are skipped during
734         // method resolution, if the receiver is an array, and we're compiling for editions before
735         // 2021.
736         // This is to make `[a].into_iter()` not break code with the new `IntoIterator` impl for
737         // arrays.
738         if data.skip_array_during_method_dispatch && receiver_is_array {
739             // FIXME: this should really be using the edition of the method name's span, in case it
740             // comes from a macro
741             if db.crate_graph()[krate].edition < Edition::Edition2021 {
742                 continue;
743             }
744         }
745
746         // we'll be lazy about checking whether the type implements the
747         // trait, but if we find out it doesn't, we'll skip the rest of the
748         // iteration
749         let mut known_implemented = false;
750         for &(_, item) in data.items.iter() {
751             // Don't pass a `visible_from_module` down to `is_valid_candidate`,
752             // since only inherent methods should be included into visibility checking.
753             if !is_valid_candidate(db, env.clone(), name, receiver_ty, item, self_ty, None) {
754                 continue;
755             }
756             if !known_implemented {
757                 let goal = generic_implements_goal(db, env.clone(), t, self_ty.clone());
758                 if db.trait_solve(krate, goal.cast(Interner)).is_none() {
759                     continue 'traits;
760                 }
761             }
762             known_implemented = true;
763             // FIXME: we shouldn't be ignoring the binders here
764             callback(self_ty, item)?
765         }
766     }
767     ControlFlow::Continue(())
768 }
769
770 fn filter_inherent_impls_for_self_ty<'i>(
771     impls: &'i InherentImpls,
772     self_ty: &Ty,
773 ) -> impl Iterator<Item = &'i ImplId> {
774     // inherent methods on arrays are fingerprinted as [T; {unknown}], so we must also consider them when
775     // resolving a method call on an array with a known len
776     let array_impls = {
777         match self_ty.kind(Interner) {
778             TyKind::Array(parameters, array_len) if !array_len.is_unknown() => {
779                 let unknown_array_len_ty =
780                     TyKind::Array(parameters.clone(), consteval::usize_const(None));
781
782                 Some(impls.for_self_ty(&unknown_array_len_ty.intern(Interner)))
783             }
784             _ => None,
785         }
786     }
787     .into_iter()
788     .flatten();
789
790     impls.for_self_ty(self_ty).iter().chain(array_impls)
791 }
792
793 fn iterate_inherent_methods(
794     self_ty: &Canonical<Ty>,
795     db: &dyn HirDatabase,
796     env: Arc<TraitEnvironment>,
797     name: Option<&Name>,
798     receiver_ty: Option<&Canonical<Ty>>,
799     krate: CrateId,
800     visible_from_module: Option<ModuleId>,
801     callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
802 ) -> ControlFlow<()> {
803     let def_crates = match def_crates(db, &self_ty.value, krate) {
804         Some(k) => k,
805         None => return ControlFlow::Continue(()),
806     };
807
808     if let Some(module_id) = visible_from_module {
809         if let Some(block_id) = module_id.containing_block() {
810             if let Some(impls) = db.inherent_impls_in_block(block_id) {
811                 impls_for_self_ty(
812                     &impls,
813                     self_ty,
814                     db,
815                     env.clone(),
816                     name,
817                     receiver_ty,
818                     visible_from_module,
819                     callback,
820                 )?;
821             }
822         }
823     }
824
825     for krate in def_crates {
826         let impls = db.inherent_impls_in_crate(krate);
827         impls_for_self_ty(
828             &impls,
829             self_ty,
830             db,
831             env.clone(),
832             name,
833             receiver_ty,
834             visible_from_module,
835             callback,
836         )?;
837     }
838     return ControlFlow::Continue(());
839
840     fn impls_for_self_ty(
841         impls: &InherentImpls,
842         self_ty: &Canonical<Ty>,
843         db: &dyn HirDatabase,
844         env: Arc<TraitEnvironment>,
845         name: Option<&Name>,
846         receiver_ty: Option<&Canonical<Ty>>,
847         visible_from_module: Option<ModuleId>,
848         callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
849     ) -> ControlFlow<()> {
850         let impls_for_self_ty = filter_inherent_impls_for_self_ty(impls, &self_ty.value);
851         for &impl_def in impls_for_self_ty {
852             for &item in &db.impl_data(impl_def).items {
853                 if !is_valid_candidate(
854                     db,
855                     env.clone(),
856                     name,
857                     receiver_ty,
858                     item,
859                     self_ty,
860                     visible_from_module,
861                 ) {
862                     continue;
863                 }
864                 // we have to check whether the self type unifies with the type
865                 // that the impl is for. If we have a receiver type, this
866                 // already happens in `is_valid_candidate` above; if not, we
867                 // check it here
868                 if receiver_ty.is_none()
869                     && inherent_impl_substs(db, env.clone(), impl_def, self_ty).is_none()
870                 {
871                     cov_mark::hit!(impl_self_type_match_without_receiver);
872                     continue;
873                 }
874                 let receiver_ty = receiver_ty.unwrap_or(self_ty);
875                 callback(receiver_ty, item)?;
876             }
877         }
878         ControlFlow::Continue(())
879     }
880 }
881
882 /// Returns the self type for the index trait call.
883 pub fn resolve_indexing_op(
884     db: &dyn HirDatabase,
885     ty: &Canonical<Ty>,
886     env: Arc<TraitEnvironment>,
887     krate: CrateId,
888     index_trait: TraitId,
889 ) -> Option<Canonical<Ty>> {
890     let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
891     let deref_chain = autoderef_method_receiver(db, krate, ty);
892     for ty in deref_chain {
893         let goal = generic_implements_goal(db, env.clone(), index_trait, ty.clone());
894         if db.trait_solve(krate, goal.cast(Interner)).is_some() {
895             return Some(ty);
896         }
897     }
898     None
899 }
900
901 fn is_transformed_receiver_ty_equal(transformed_receiver_ty: &Ty, receiver_ty: &Ty) -> bool {
902     if transformed_receiver_ty == receiver_ty {
903         return true;
904     }
905
906     // a transformed receiver may be considered equal (and a valid method call candidate) if it is an array
907     // with an unknown (i.e. generic) length, and the receiver is an array with the same item type but a known len,
908     // this allows inherent methods on arrays to be considered valid resolution candidates
909     match (transformed_receiver_ty.kind(Interner), receiver_ty.kind(Interner)) {
910         (
911             TyKind::Array(transformed_array_ty, transformed_array_len),
912             TyKind::Array(receiver_array_ty, receiver_array_len),
913         ) if transformed_array_ty == receiver_array_ty
914             && transformed_array_len.is_unknown()
915             && !receiver_array_len.is_unknown() =>
916         {
917             true
918         }
919         _ => false,
920     }
921 }
922
923 fn is_valid_candidate(
924     db: &dyn HirDatabase,
925     env: Arc<TraitEnvironment>,
926     name: Option<&Name>,
927     receiver_ty: Option<&Canonical<Ty>>,
928     item: AssocItemId,
929     self_ty: &Canonical<Ty>,
930     visible_from_module: Option<ModuleId>,
931 ) -> bool {
932     match item {
933         AssocItemId::FunctionId(m) => {
934             let data = db.function_data(m);
935             if let Some(name) = name {
936                 if &data.name != name {
937                     return false;
938                 }
939             }
940             if let Some(receiver_ty) = receiver_ty {
941                 if !data.has_self_param() {
942                     return false;
943                 }
944                 let transformed_receiver_ty = match transform_receiver_ty(db, env, m, self_ty) {
945                     Some(ty) => ty,
946                     None => return false,
947                 };
948
949                 if !is_transformed_receiver_ty_equal(&transformed_receiver_ty, &receiver_ty.value) {
950                     return false;
951                 }
952             }
953             if let Some(from_module) = visible_from_module {
954                 if !db.function_visibility(m).is_visible_from(db.upcast(), from_module) {
955                     cov_mark::hit!(autoderef_candidate_not_visible);
956                     return false;
957                 }
958             }
959
960             true
961         }
962         AssocItemId::ConstId(c) => {
963             let data = db.const_data(c);
964             name.map_or(true, |name| data.name.as_ref() == Some(name)) && receiver_ty.is_none()
965         }
966         _ => false,
967     }
968 }
969
970 pub(crate) fn inherent_impl_substs(
971     db: &dyn HirDatabase,
972     env: Arc<TraitEnvironment>,
973     impl_id: ImplId,
974     self_ty: &Canonical<Ty>,
975 ) -> Option<Substitution> {
976     // we create a var for each type parameter of the impl; we need to keep in
977     // mind here that `self_ty` might have vars of its own
978     let self_ty_vars = self_ty.binders.len(Interner);
979     let vars = TyBuilder::subst_for_def(db, impl_id)
980         .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty_vars)
981         .build();
982     let self_ty_with_vars = db.impl_self_ty(impl_id).substitute(Interner, &vars);
983     let mut kinds = self_ty.binders.interned().to_vec();
984     kinds.extend(
985         iter::repeat(chalk_ir::WithKind::new(
986             chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
987             UniverseIndex::ROOT,
988         ))
989         .take(vars.len(Interner)),
990     );
991     let tys = Canonical {
992         binders: CanonicalVarKinds::from_iter(Interner, kinds),
993         value: (self_ty_with_vars, self_ty.value.clone()),
994     };
995     let substs = super::infer::unify(db, env, &tys)?;
996     // We only want the substs for the vars we added, not the ones from self_ty.
997     // Also, if any of the vars we added are still in there, we replace them by
998     // Unknown. I think this can only really happen if self_ty contained
999     // Unknown, and in that case we want the result to contain Unknown in those
1000     // places again.
1001     let suffix =
1002         Substitution::from_iter(Interner, substs.iter(Interner).cloned().skip(self_ty_vars));
1003     Some(fallback_bound_vars(suffix, self_ty_vars))
1004 }
1005
1006 /// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
1007 /// num_vars_to_keep) by `TyKind::Unknown`.
1008 fn fallback_bound_vars(s: Substitution, num_vars_to_keep: usize) -> Substitution {
1009     crate::fold_free_vars(s, |bound, binders| {
1010         if bound.index >= num_vars_to_keep && bound.debruijn == DebruijnIndex::INNERMOST {
1011             TyKind::Error.intern(Interner)
1012         } else {
1013             bound.shifted_in_from(binders).to_ty(Interner)
1014         }
1015     })
1016 }
1017
1018 fn transform_receiver_ty(
1019     db: &dyn HirDatabase,
1020     env: Arc<TraitEnvironment>,
1021     function_id: FunctionId,
1022     self_ty: &Canonical<Ty>,
1023 ) -> Option<Ty> {
1024     let substs = match function_id.lookup(db.upcast()).container {
1025         ItemContainerId::TraitId(_) => TyBuilder::subst_for_def(db, function_id)
1026             .push(self_ty.value.clone())
1027             .fill_with_unknown()
1028             .build(),
1029         ItemContainerId::ImplId(impl_id) => {
1030             let impl_substs = inherent_impl_substs(db, env, impl_id, self_ty)?;
1031             TyBuilder::subst_for_def(db, function_id)
1032                 .use_parent_substs(&impl_substs)
1033                 .fill_with_unknown()
1034                 .build()
1035         }
1036         // No receiver
1037         ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => unreachable!(),
1038     };
1039     let sig = db.callable_item_signature(function_id.into());
1040     Some(sig.map(|s| s.params()[0].clone()).substitute(Interner, &substs))
1041 }
1042
1043 pub fn implements_trait(
1044     ty: &Canonical<Ty>,
1045     db: &dyn HirDatabase,
1046     env: Arc<TraitEnvironment>,
1047     krate: CrateId,
1048     trait_: TraitId,
1049 ) -> bool {
1050     let goal = generic_implements_goal(db, env, trait_, ty.clone());
1051     let solution = db.trait_solve(krate, goal.cast(Interner));
1052
1053     solution.is_some()
1054 }
1055
1056 pub fn implements_trait_unique(
1057     ty: &Canonical<Ty>,
1058     db: &dyn HirDatabase,
1059     env: Arc<TraitEnvironment>,
1060     krate: CrateId,
1061     trait_: TraitId,
1062 ) -> bool {
1063     let goal = generic_implements_goal(db, env, trait_, ty.clone());
1064     let solution = db.trait_solve(krate, goal.cast(Interner));
1065
1066     matches!(solution, Some(crate::Solution::Unique(_)))
1067 }
1068
1069 /// This creates Substs for a trait with the given Self type and type variables
1070 /// for all other parameters, to query Chalk with it.
1071 fn generic_implements_goal(
1072     db: &dyn HirDatabase,
1073     env: Arc<TraitEnvironment>,
1074     trait_: TraitId,
1075     self_ty: Canonical<Ty>,
1076 ) -> Canonical<InEnvironment<super::DomainGoal>> {
1077     let mut kinds = self_ty.binders.interned().to_vec();
1078     let trait_ref = TyBuilder::trait_ref(db, trait_)
1079         .push(self_ty.value)
1080         .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
1081         .build();
1082     kinds.extend(
1083         iter::repeat(chalk_ir::WithKind::new(
1084             chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
1085             UniverseIndex::ROOT,
1086         ))
1087         .take(trait_ref.substitution.len(Interner) - 1),
1088     );
1089     let obligation = trait_ref.cast(Interner);
1090     Canonical {
1091         binders: CanonicalVarKinds::from_iter(Interner, kinds),
1092         value: InEnvironment::new(&env.env, obligation),
1093     }
1094 }
1095
1096 fn autoderef_method_receiver(
1097     db: &dyn HirDatabase,
1098     krate: CrateId,
1099     ty: InEnvironment<Canonical<Ty>>,
1100 ) -> Vec<Canonical<Ty>> {
1101     let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
1102     // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
1103     if let Some(TyKind::Array(parameters, _)) = 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 }