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