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