]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/method_resolution.rs
Merge #10977
[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             for i in 0..deref_chain.len() {
545                 iterate_method_candidates_with_autoref(
546                     &deref_chain[i..],
547                     db,
548                     env.clone(),
549                     krate,
550                     traits_in_scope,
551                     visible_from_module,
552                     name,
553                     callback,
554                 )?;
555             }
556             ControlFlow::Continue(())
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 = match self_ty.value.kind(&Interner) {
720         TyKind::Placeholder(_) => {
721             // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
722             env.traits_in_scope_from_clauses(&self_ty.value)
723                 .flat_map(|t| all_super_traits(db.upcast(), t))
724                 .collect()
725         }
726         _ => Vec::new(),
727     };
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 (_name, 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         if let TyKind::Array(parameters, array_len) = self_ty.kind(&Interner) {
778             if !array_len.is_unknown() {
779                 let unknown_array_len_ty =
780                     TyKind::Array(parameters.clone(), consteval::usize_const(None))
781                         .intern(&Interner);
782
783                 Some(impls.for_self_ty(&unknown_array_len_ty))
784             } else {
785                 None
786             }
787         } else {
788             None
789         }
790     }
791     .into_iter()
792     .flatten();
793
794     impls.for_self_ty(self_ty).iter().chain(array_impls)
795 }
796
797 fn iterate_inherent_methods(
798     self_ty: &Canonical<Ty>,
799     db: &dyn HirDatabase,
800     env: Arc<TraitEnvironment>,
801     name: Option<&Name>,
802     receiver_ty: Option<&Canonical<Ty>>,
803     krate: CrateId,
804     visible_from_module: Option<ModuleId>,
805     callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
806 ) -> ControlFlow<()> {
807     let def_crates = match def_crates(db, &self_ty.value, krate) {
808         Some(k) => k,
809         None => return ControlFlow::Continue(()),
810     };
811
812     if let Some(module_id) = visible_from_module {
813         if let Some(block_id) = module_id.containing_block() {
814             if let Some(impls) = db.inherent_impls_in_block(block_id) {
815                 impls_for_self_ty(
816                     &impls,
817                     self_ty,
818                     db,
819                     env.clone(),
820                     name,
821                     receiver_ty,
822                     visible_from_module,
823                     callback,
824                 )?;
825             }
826         }
827     }
828
829     for krate in def_crates {
830         let impls = db.inherent_impls_in_crate(krate);
831         impls_for_self_ty(
832             &impls,
833             self_ty,
834             db,
835             env.clone(),
836             name,
837             receiver_ty,
838             visible_from_module,
839             callback,
840         )?;
841     }
842     return ControlFlow::Continue(());
843
844     fn impls_for_self_ty(
845         impls: &InherentImpls,
846         self_ty: &Canonical<Ty>,
847         db: &dyn HirDatabase,
848         env: Arc<TraitEnvironment>,
849         name: Option<&Name>,
850         receiver_ty: Option<&Canonical<Ty>>,
851         visible_from_module: Option<ModuleId>,
852         callback: &mut dyn FnMut(&Canonical<Ty>, AssocItemId) -> ControlFlow<()>,
853     ) -> ControlFlow<()> {
854         let impls_for_self_ty = filter_inherent_impls_for_self_ty(impls, &self_ty.value);
855         for &impl_def in impls_for_self_ty {
856             for &item in &db.impl_data(impl_def).items {
857                 if !is_valid_candidate(
858                     db,
859                     env.clone(),
860                     name,
861                     receiver_ty,
862                     item,
863                     self_ty,
864                     visible_from_module,
865                 ) {
866                     continue;
867                 }
868                 // we have to check whether the self type unifies with the type
869                 // that the impl is for. If we have a receiver type, this
870                 // already happens in `is_valid_candidate` above; if not, we
871                 // check it here
872                 if receiver_ty.is_none()
873                     && inherent_impl_substs(db, env.clone(), impl_def, self_ty).is_none()
874                 {
875                     cov_mark::hit!(impl_self_type_match_without_receiver);
876                     continue;
877                 }
878                 let receiver_ty = receiver_ty.unwrap_or(self_ty);
879                 callback(receiver_ty, item)?;
880             }
881         }
882         ControlFlow::Continue(())
883     }
884 }
885
886 /// Returns the self type for the index trait call.
887 pub fn resolve_indexing_op(
888     db: &dyn HirDatabase,
889     ty: &Canonical<Ty>,
890     env: Arc<TraitEnvironment>,
891     krate: CrateId,
892     index_trait: TraitId,
893 ) -> Option<Canonical<Ty>> {
894     let ty = InEnvironment { goal: ty.clone(), environment: env.env.clone() };
895     let deref_chain = autoderef_method_receiver(db, krate, ty);
896     for ty in deref_chain {
897         let goal = generic_implements_goal(db, env.clone(), index_trait, ty.clone());
898         if db.trait_solve(krate, goal.cast(&Interner)).is_some() {
899             return Some(ty);
900         }
901     }
902     None
903 }
904
905 fn is_transformed_receiver_ty_equal(transformed_receiver_ty: &Ty, receiver_ty: &Ty) -> bool {
906     if transformed_receiver_ty == receiver_ty {
907         return true;
908     }
909
910     // a transformed receiver may be considered equal (and a valid method call candidate) if it is an array
911     // with an unknown (i.e. generic) length, and the receiver is an array with the same item type but a known len,
912     // this allows inherent methods on arrays to be considered valid resolution candidates
913     match (transformed_receiver_ty.kind(&Interner), receiver_ty.kind(&Interner)) {
914         (
915             TyKind::Array(transformed_array_ty, transformed_array_len),
916             TyKind::Array(receiver_array_ty, receiver_array_len),
917         ) if transformed_array_ty == receiver_array_ty
918             && transformed_array_len.is_unknown()
919             && !receiver_array_len.is_unknown() =>
920         {
921             true
922         }
923         _ => false,
924     }
925 }
926
927 fn is_valid_candidate(
928     db: &dyn HirDatabase,
929     env: Arc<TraitEnvironment>,
930     name: Option<&Name>,
931     receiver_ty: Option<&Canonical<Ty>>,
932     item: AssocItemId,
933     self_ty: &Canonical<Ty>,
934     visible_from_module: Option<ModuleId>,
935 ) -> bool {
936     match item {
937         AssocItemId::FunctionId(m) => {
938             let data = db.function_data(m);
939             if let Some(name) = name {
940                 if &data.name != name {
941                     return false;
942                 }
943             }
944             if let Some(receiver_ty) = receiver_ty {
945                 if !data.has_self_param() {
946                     return false;
947                 }
948                 let transformed_receiver_ty = match transform_receiver_ty(db, env, m, self_ty) {
949                     Some(ty) => ty,
950                     None => return false,
951                 };
952
953                 if !is_transformed_receiver_ty_equal(&transformed_receiver_ty, &receiver_ty.value) {
954                     return false;
955                 }
956             }
957             if let Some(from_module) = visible_from_module {
958                 if !db.function_visibility(m).is_visible_from(db.upcast(), from_module) {
959                     cov_mark::hit!(autoderef_candidate_not_visible);
960                     return false;
961                 }
962             }
963
964             true
965         }
966         AssocItemId::ConstId(c) => {
967             let data = db.const_data(c);
968             name.map_or(true, |name| data.name.as_ref() == Some(name)) && receiver_ty.is_none()
969         }
970         _ => false,
971     }
972 }
973
974 pub(crate) fn inherent_impl_substs(
975     db: &dyn HirDatabase,
976     env: Arc<TraitEnvironment>,
977     impl_id: ImplId,
978     self_ty: &Canonical<Ty>,
979 ) -> Option<Substitution> {
980     // we create a var for each type parameter of the impl; we need to keep in
981     // mind here that `self_ty` might have vars of its own
982     let self_ty_vars = self_ty.binders.len(&Interner);
983     let vars = TyBuilder::subst_for_def(db, impl_id)
984         .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty_vars)
985         .build();
986     let self_ty_with_vars = db.impl_self_ty(impl_id).substitute(&Interner, &vars);
987     let mut kinds = self_ty.binders.interned().to_vec();
988     kinds.extend(
989         iter::repeat(chalk_ir::WithKind::new(
990             chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
991             UniverseIndex::ROOT,
992         ))
993         .take(vars.len(&Interner)),
994     );
995     let tys = Canonical {
996         binders: CanonicalVarKinds::from_iter(&Interner, kinds),
997         value: (self_ty_with_vars, self_ty.value.clone()),
998     };
999     let substs = super::infer::unify(db, env, &tys)?;
1000     // We only want the substs for the vars we added, not the ones from self_ty.
1001     // Also, if any of the vars we added are still in there, we replace them by
1002     // Unknown. I think this can only really happen if self_ty contained
1003     // Unknown, and in that case we want the result to contain Unknown in those
1004     // places again.
1005     let suffix =
1006         Substitution::from_iter(&Interner, substs.iter(&Interner).cloned().skip(self_ty_vars));
1007     Some(fallback_bound_vars(suffix, self_ty_vars))
1008 }
1009
1010 /// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
1011 /// num_vars_to_keep) by `TyKind::Unknown`.
1012 fn fallback_bound_vars(s: Substitution, num_vars_to_keep: usize) -> Substitution {
1013     crate::fold_free_vars(s, |bound, binders| {
1014         if bound.index >= num_vars_to_keep && bound.debruijn == DebruijnIndex::INNERMOST {
1015             TyKind::Error.intern(&Interner)
1016         } else {
1017             bound.shifted_in_from(binders).to_ty(&Interner)
1018         }
1019     })
1020 }
1021
1022 fn transform_receiver_ty(
1023     db: &dyn HirDatabase,
1024     env: Arc<TraitEnvironment>,
1025     function_id: FunctionId,
1026     self_ty: &Canonical<Ty>,
1027 ) -> Option<Ty> {
1028     let substs = match function_id.lookup(db.upcast()).container {
1029         ItemContainerId::TraitId(_) => TyBuilder::subst_for_def(db, function_id)
1030             .push(self_ty.value.clone())
1031             .fill_with_unknown()
1032             .build(),
1033         ItemContainerId::ImplId(impl_id) => {
1034             let impl_substs = inherent_impl_substs(db, env, impl_id, self_ty)?;
1035             TyBuilder::subst_for_def(db, function_id)
1036                 .use_parent_substs(&impl_substs)
1037                 .fill_with_unknown()
1038                 .build()
1039         }
1040         // No receiver
1041         ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => unreachable!(),
1042     };
1043     let sig = db.callable_item_signature(function_id.into());
1044     Some(sig.map(|s| s.params()[0].clone()).substitute(&Interner, &substs))
1045 }
1046
1047 pub fn implements_trait(
1048     ty: &Canonical<Ty>,
1049     db: &dyn HirDatabase,
1050     env: Arc<TraitEnvironment>,
1051     krate: CrateId,
1052     trait_: TraitId,
1053 ) -> bool {
1054     let goal = generic_implements_goal(db, env, trait_, ty.clone());
1055     let solution = db.trait_solve(krate, goal.cast(&Interner));
1056
1057     solution.is_some()
1058 }
1059
1060 pub fn implements_trait_unique(
1061     ty: &Canonical<Ty>,
1062     db: &dyn HirDatabase,
1063     env: Arc<TraitEnvironment>,
1064     krate: CrateId,
1065     trait_: TraitId,
1066 ) -> bool {
1067     let goal = generic_implements_goal(db, env, trait_, ty.clone());
1068     let solution = db.trait_solve(krate, goal.cast(&Interner));
1069
1070     matches!(solution, Some(crate::Solution::Unique(_)))
1071 }
1072
1073 /// This creates Substs for a trait with the given Self type and type variables
1074 /// for all other parameters, to query Chalk with it.
1075 fn generic_implements_goal(
1076     db: &dyn HirDatabase,
1077     env: Arc<TraitEnvironment>,
1078     trait_: TraitId,
1079     self_ty: Canonical<Ty>,
1080 ) -> Canonical<InEnvironment<super::DomainGoal>> {
1081     let mut kinds = self_ty.binders.interned().to_vec();
1082     let trait_ref = TyBuilder::trait_ref(db, trait_)
1083         .push(self_ty.value)
1084         .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
1085         .build();
1086     kinds.extend(
1087         iter::repeat(chalk_ir::WithKind::new(
1088             chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
1089             UniverseIndex::ROOT,
1090         ))
1091         .take(trait_ref.substitution.len(&Interner) - 1),
1092     );
1093     let obligation = trait_ref.cast(&Interner);
1094     Canonical {
1095         binders: CanonicalVarKinds::from_iter(&Interner, kinds),
1096         value: InEnvironment::new(&env.env, obligation),
1097     }
1098 }
1099
1100 fn autoderef_method_receiver(
1101     db: &dyn HirDatabase,
1102     krate: CrateId,
1103     ty: InEnvironment<Canonical<Ty>>,
1104 ) -> Vec<Canonical<Ty>> {
1105     let mut deref_chain: Vec<_> = autoderef::autoderef(db, Some(krate), ty).collect();
1106     // As a last step, we can do array unsizing (that's the only unsizing that rustc does for method receivers!)
1107     if let Some(TyKind::Array(parameters, _)) =
1108         deref_chain.last().map(|ty| ty.value.kind(&Interner))
1109     {
1110         let kinds = deref_chain.last().unwrap().binders.clone();
1111         let unsized_ty = TyKind::Slice(parameters.clone()).intern(&Interner);
1112         deref_chain.push(Canonical { value: unsized_ty, binders: kinds })
1113     }
1114     deref_chain
1115 }