]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/method/mod.rs
shrinking the deprecated method span
[rust.git] / compiler / rustc_typeck / src / check / method / mod.rs
1 //! Method lookup: the secret sauce of Rust. See the [rustc dev guide] for more information.
2 //!
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/method-lookup.html
4
5 mod confirm;
6 pub mod probe;
7 mod suggest;
8
9 pub use self::suggest::{SelfSource, TraitInfo};
10 pub use self::CandidateSource::*;
11 pub use self::MethodError::*;
12
13 use crate::check::FnCtxt;
14 use rustc_data_structures::sync::Lrc;
15 use rustc_errors::{Applicability, DiagnosticBuilder};
16 use rustc_hir as hir;
17 use rustc_hir::def::{CtorOf, DefKind, Namespace};
18 use rustc_hir::def_id::DefId;
19 use rustc_infer::infer::{self, InferOk};
20 use rustc_middle::ty::subst::Subst;
21 use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
22 use rustc_middle::ty::GenericParamDefKind;
23 use rustc_middle::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TypeFoldable, WithConstness};
24 use rustc_span::symbol::Ident;
25 use rustc_span::Span;
26 use rustc_trait_selection::traits;
27 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
28
29 use self::probe::{IsSuggestion, ProbeScope};
30
31 pub fn provide(providers: &mut ty::query::Providers) {
32     suggest::provide(providers);
33     probe::provide(providers);
34 }
35
36 #[derive(Clone, Copy, Debug)]
37 pub struct MethodCallee<'tcx> {
38     /// Impl method ID, for inherent methods, or trait method ID, otherwise.
39     pub def_id: DefId,
40     pub substs: SubstsRef<'tcx>,
41
42     /// Instantiated method signature, i.e., it has been
43     /// substituted, normalized, and has had late-bound
44     /// lifetimes replaced with inference variables.
45     pub sig: ty::FnSig<'tcx>,
46 }
47
48 #[derive(Debug)]
49 pub enum MethodError<'tcx> {
50     // Did not find an applicable method, but we did find various near-misses that may work.
51     NoMatch(NoMatchData<'tcx>),
52
53     // Multiple methods might apply.
54     Ambiguity(Vec<CandidateSource>),
55
56     // Found an applicable method, but it is not visible. The third argument contains a list of
57     // not-in-scope traits which may work.
58     PrivateMatch(DefKind, DefId, Vec<DefId>),
59
60     // Found a `Self: Sized` bound where `Self` is a trait object, also the caller may have
61     // forgotten to import a trait.
62     IllegalSizedBound(Vec<DefId>, bool, Span),
63
64     // Found a match, but the return type is wrong
65     BadReturnType,
66 }
67
68 // Contains a list of static methods that may apply, a list of unsatisfied trait predicates which
69 // could lead to matches if satisfied, and a list of not-in-scope traits which may work.
70 #[derive(Debug)]
71 pub struct NoMatchData<'tcx> {
72     pub static_candidates: Vec<CandidateSource>,
73     pub unsatisfied_predicates: Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>)>,
74     pub out_of_scope_traits: Vec<DefId>,
75     pub lev_candidate: Option<ty::AssocItem>,
76     pub mode: probe::Mode,
77 }
78
79 impl<'tcx> NoMatchData<'tcx> {
80     pub fn new(
81         static_candidates: Vec<CandidateSource>,
82         unsatisfied_predicates: Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>)>,
83         out_of_scope_traits: Vec<DefId>,
84         lev_candidate: Option<ty::AssocItem>,
85         mode: probe::Mode,
86     ) -> Self {
87         NoMatchData {
88             static_candidates,
89             unsatisfied_predicates,
90             out_of_scope_traits,
91             lev_candidate,
92             mode,
93         }
94     }
95 }
96
97 // A pared down enum describing just the places from which a method
98 // candidate can arise. Used for error reporting only.
99 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
100 pub enum CandidateSource {
101     ImplSource(DefId),
102     TraitSource(DefId /* trait id */),
103 }
104
105 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
106     /// Determines whether the type `self_ty` supports a method name `method_name` or not.
107     #[instrument(level = "debug", skip(self))]
108     pub fn method_exists(
109         &self,
110         method_name: Ident,
111         self_ty: Ty<'tcx>,
112         call_expr_id: hir::HirId,
113         allow_private: bool,
114     ) -> bool {
115         let mode = probe::Mode::MethodCall;
116         match self.probe_for_name(
117             method_name.span,
118             mode,
119             method_name,
120             IsSuggestion(false),
121             self_ty,
122             call_expr_id,
123             ProbeScope::TraitsInScope,
124         ) {
125             Ok(..) => true,
126             Err(NoMatch(..)) => false,
127             Err(Ambiguity(..)) => true,
128             Err(PrivateMatch(..)) => allow_private,
129             Err(IllegalSizedBound(..)) => true,
130             Err(BadReturnType) => bug!("no return type expectations but got BadReturnType"),
131         }
132     }
133
134     /// Adds a suggestion to call the given method to the provided diagnostic.
135     #[instrument(level = "debug", skip(self, err, call_expr))]
136     crate fn suggest_method_call(
137         &self,
138         err: &mut DiagnosticBuilder<'a>,
139         msg: &str,
140         method_name: Ident,
141         self_ty: Ty<'tcx>,
142         call_expr: &hir::Expr<'_>,
143     ) {
144         let params = self
145             .probe_for_name(
146                 method_name.span,
147                 probe::Mode::MethodCall,
148                 method_name,
149                 IsSuggestion(false),
150                 self_ty,
151                 call_expr.hir_id,
152                 ProbeScope::TraitsInScope,
153             )
154             .map(|pick| {
155                 let sig = self.tcx.fn_sig(pick.item.def_id);
156                 sig.inputs().skip_binder().len().saturating_sub(1)
157             })
158             .unwrap_or(0);
159
160         // Account for `foo.bar<T>`;
161         let sugg_span = call_expr.span.shrink_to_hi();
162         let (suggestion, applicability) = (
163             format!("({})", (0..params).map(|_| "_").collect::<Vec<_>>().join(", ")),
164             if params > 0 { Applicability::HasPlaceholders } else { Applicability::MaybeIncorrect },
165         );
166
167         err.span_suggestion_verbose(sugg_span, msg, suggestion, applicability);
168     }
169
170     /// Performs method lookup. If lookup is successful, it will return the callee
171     /// and store an appropriate adjustment for the self-expr. In some cases it may
172     /// report an error (e.g., invoking the `drop` method).
173     ///
174     /// # Arguments
175     ///
176     /// Given a method call like `foo.bar::<T1,...Tn>(...)`:
177     ///
178     /// * `self`:                  the surrounding `FnCtxt` (!)
179     /// * `self_ty`:               the (unadjusted) type of the self expression (`foo`)
180     /// * `segment`:               the name and generic arguments of the method (`bar::<T1, ...Tn>`)
181     /// * `span`:                  the span for the method call
182     /// * `call_expr`:             the complete method call: (`foo.bar::<T1,...Tn>(...)`)
183     /// * `self_expr`:             the self expression (`foo`)
184     #[instrument(level = "debug", skip(self, call_expr, self_expr))]
185     pub fn lookup_method(
186         &self,
187         self_ty: Ty<'tcx>,
188         segment: &hir::PathSegment<'_>,
189         span: Span,
190         call_expr: &'tcx hir::Expr<'tcx>,
191         self_expr: &'tcx hir::Expr<'tcx>,
192     ) -> Result<MethodCallee<'tcx>, MethodError<'tcx>> {
193         debug!(
194             "lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
195             segment.ident, self_ty, call_expr, self_expr
196         );
197
198         let pick =
199             self.lookup_probe(span, segment.ident, self_ty, call_expr, ProbeScope::TraitsInScope)?;
200
201         for import_id in &pick.import_ids {
202             debug!("used_trait_import: {:?}", import_id);
203             Lrc::get_mut(&mut self.typeck_results.borrow_mut().used_trait_imports)
204                 .unwrap()
205                 .insert(*import_id);
206         }
207
208         self.tcx.check_stability(pick.item.def_id, Some(call_expr.hir_id), span, None);
209
210         let result =
211             self.confirm_method(span, self_expr, call_expr, self_ty, pick.clone(), segment);
212         debug!("result = {:?}", result);
213
214         if let Some(span) = result.illegal_sized_bound {
215             let mut needs_mut = false;
216             if let ty::Ref(region, t_type, mutability) = self_ty.kind() {
217                 let trait_type = self
218                     .tcx
219                     .mk_ref(region, ty::TypeAndMut { ty: t_type, mutbl: mutability.invert() });
220                 // We probe again to see if there might be a borrow mutability discrepancy.
221                 match self.lookup_probe(
222                     span,
223                     segment.ident,
224                     trait_type,
225                     call_expr,
226                     ProbeScope::TraitsInScope,
227                 ) {
228                     Ok(ref new_pick) if *new_pick != pick => {
229                         needs_mut = true;
230                     }
231                     _ => {}
232                 }
233             }
234
235             // We probe again, taking all traits into account (not only those in scope).
236             let candidates = match self.lookup_probe(
237                 span,
238                 segment.ident,
239                 self_ty,
240                 call_expr,
241                 ProbeScope::AllTraits,
242             ) {
243                 // If we find a different result the caller probably forgot to import a trait.
244                 Ok(ref new_pick) if *new_pick != pick => vec![new_pick.item.container.id()],
245                 Err(Ambiguity(ref sources)) => sources
246                     .iter()
247                     .filter_map(|source| {
248                         match *source {
249                             // Note: this cannot come from an inherent impl,
250                             // because the first probing succeeded.
251                             ImplSource(def) => self.tcx.trait_id_of_impl(def),
252                             TraitSource(_) => None,
253                         }
254                     })
255                     .collect(),
256                 _ => Vec::new(),
257             };
258
259             return Err(IllegalSizedBound(candidates, needs_mut, span));
260         }
261
262         Ok(result.callee)
263     }
264
265     #[instrument(level = "debug", skip(self, call_expr))]
266     pub fn lookup_probe(
267         &self,
268         span: Span,
269         method_name: Ident,
270         self_ty: Ty<'tcx>,
271         call_expr: &'tcx hir::Expr<'tcx>,
272         scope: ProbeScope,
273     ) -> probe::PickResult<'tcx> {
274         let mode = probe::Mode::MethodCall;
275         let self_ty = self.resolve_vars_if_possible(self_ty);
276         self.probe_for_name(
277             span,
278             mode,
279             method_name,
280             IsSuggestion(false),
281             self_ty,
282             call_expr.hir_id,
283             scope,
284         )
285     }
286
287     /// `lookup_method_in_trait` is used for overloaded operators.
288     /// It does a very narrow slice of what the normal probe/confirm path does.
289     /// In particular, it doesn't really do any probing: it simply constructs
290     /// an obligation for a particular trait with the given self type and checks
291     /// whether that trait is implemented.
292     //
293     // FIXME(#18741): it seems likely that we can consolidate some of this
294     // code with the other method-lookup code. In particular, the second half
295     // of this method is basically the same as confirmation.
296     #[instrument(level = "debug", skip(self, span, opt_input_types))]
297     pub fn lookup_method_in_trait(
298         &self,
299         span: Span,
300         m_name: Ident,
301         trait_def_id: DefId,
302         self_ty: Ty<'tcx>,
303         opt_input_types: Option<&[Ty<'tcx>]>,
304     ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
305         debug!(
306             "lookup_in_trait_adjusted(self_ty={:?}, m_name={}, trait_def_id={:?})",
307             self_ty, m_name, trait_def_id
308         );
309
310         // Construct a trait-reference `self_ty : Trait<input_tys>`
311         let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
312             match param.kind {
313                 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => {}
314                 GenericParamDefKind::Type { .. } => {
315                     if param.index == 0 {
316                         return self_ty.into();
317                     } else if let Some(ref input_types) = opt_input_types {
318                         return input_types[param.index as usize - 1].into();
319                     }
320                 }
321             }
322             self.var_for_def(span, param)
323         });
324
325         let trait_ref = ty::TraitRef::new(trait_def_id, substs);
326
327         // Construct an obligation
328         let poly_trait_ref = trait_ref.to_poly_trait_ref();
329         let obligation = traits::Obligation::misc(
330             span,
331             self.body_id,
332             self.param_env,
333             poly_trait_ref.without_const().to_predicate(self.tcx),
334         );
335
336         // Now we want to know if this can be matched
337         if !self.predicate_may_hold(&obligation) {
338             debug!("--> Cannot match obligation");
339             return None; // Cannot be matched, no such method resolution is possible.
340         }
341
342         // Trait must have a method named `m_name` and it should not have
343         // type parameters or early-bound regions.
344         let tcx = self.tcx;
345         let method_item = match self.associated_item(trait_def_id, m_name, Namespace::ValueNS) {
346             Some(method_item) => method_item,
347             None => {
348                 tcx.sess.delay_span_bug(
349                     span,
350                     "operator trait does not have corresponding operator method",
351                 );
352                 return None;
353             }
354         };
355         let def_id = method_item.def_id;
356         let generics = tcx.generics_of(def_id);
357         assert_eq!(generics.params.len(), 0);
358
359         debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
360         let mut obligations = vec![];
361
362         // Instantiate late-bound regions and substitute the trait
363         // parameters into the method type to get the actual method type.
364         //
365         // N.B., instantiate late-bound regions first so that
366         // `instantiate_type_scheme` can normalize associated types that
367         // may reference those regions.
368         let fn_sig = tcx.fn_sig(def_id);
369         let fn_sig = self.replace_bound_vars_with_fresh_vars(span, infer::FnCall, fn_sig).0;
370         let fn_sig = fn_sig.subst(self.tcx, substs);
371
372         let InferOk { value, obligations: o } =
373             self.normalize_associated_types_in_as_infer_ok(span, fn_sig);
374         let fn_sig = {
375             obligations.extend(o);
376             value
377         };
378
379         // Register obligations for the parameters. This will include the
380         // `Self` parameter, which in turn has a bound of the main trait,
381         // so this also effectively registers `obligation` as well.  (We
382         // used to register `obligation` explicitly, but that resulted in
383         // double error messages being reported.)
384         //
385         // Note that as the method comes from a trait, it should not have
386         // any late-bound regions appearing in its bounds.
387         let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
388
389         let InferOk { value, obligations: o } =
390             self.normalize_associated_types_in_as_infer_ok(span, bounds);
391         let bounds = {
392             obligations.extend(o);
393             value
394         };
395
396         assert!(!bounds.has_escaping_bound_vars());
397
398         let cause = traits::ObligationCause::misc(span, self.body_id);
399         obligations.extend(traits::predicates_for_generics(cause.clone(), self.param_env, bounds));
400
401         // Also add an obligation for the method type being well-formed.
402         let method_ty = tcx.mk_fn_ptr(ty::Binder::bind(fn_sig, tcx));
403         debug!(
404             "lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
405             method_ty, obligation
406         );
407         obligations.push(traits::Obligation::new(
408             cause,
409             self.param_env,
410             ty::PredicateKind::WellFormed(method_ty.into()).to_predicate(tcx),
411         ));
412
413         let callee = MethodCallee { def_id, substs: trait_ref.substs, sig: fn_sig };
414
415         debug!("callee = {:?}", callee);
416
417         Some(InferOk { obligations, value: callee })
418     }
419
420     #[instrument(level = "debug", skip(self))]
421     pub fn resolve_ufcs(
422         &self,
423         span: Span,
424         method_name: Ident,
425         self_ty: Ty<'tcx>,
426         expr_id: hir::HirId,
427     ) -> Result<(DefKind, DefId), MethodError<'tcx>> {
428         debug!(
429             "resolve_ufcs: method_name={:?} self_ty={:?} expr_id={:?}",
430             method_name, self_ty, expr_id,
431         );
432
433         let tcx = self.tcx;
434
435         // Check if we have an enum variant.
436         if let ty::Adt(adt_def, _) = self_ty.kind() {
437             if adt_def.is_enum() {
438                 let variant_def = adt_def
439                     .variants
440                     .iter()
441                     .find(|vd| tcx.hygienic_eq(method_name, vd.ident, adt_def.did));
442                 if let Some(variant_def) = variant_def {
443                     // Braced variants generate unusable names in value namespace (reserved for
444                     // possible future use), so variants resolved as associated items may refer to
445                     // them as well. It's ok to use the variant's id as a ctor id since an
446                     // error will be reported on any use of such resolution anyway.
447                     let ctor_def_id = variant_def.ctor_def_id.unwrap_or(variant_def.def_id);
448                     tcx.check_stability(ctor_def_id, Some(expr_id), span, Some(method_name.span));
449                     return Ok((
450                         DefKind::Ctor(CtorOf::Variant, variant_def.ctor_kind),
451                         ctor_def_id,
452                     ));
453                 }
454             }
455         }
456
457         let pick = self.probe_for_name(
458             span,
459             probe::Mode::Path,
460             method_name,
461             IsSuggestion(false),
462             self_ty,
463             expr_id,
464             ProbeScope::TraitsInScope,
465         )?;
466         debug!("resolve_ufcs: pick={:?}", pick);
467         {
468             let mut typeck_results = self.typeck_results.borrow_mut();
469             let used_trait_imports = Lrc::get_mut(&mut typeck_results.used_trait_imports).unwrap();
470             for import_id in pick.import_ids {
471                 debug!("resolve_ufcs: used_trait_import: {:?}", import_id);
472                 used_trait_imports.insert(import_id);
473             }
474         }
475
476         let def_kind = pick.item.kind.as_def_kind();
477         debug!("resolve_ufcs: def_kind={:?}, def_id={:?}", def_kind, pick.item.def_id);
478         tcx.check_stability(pick.item.def_id, Some(expr_id), span, Some(method_name.span));
479         Ok((def_kind, pick.item.def_id))
480     }
481
482     /// Finds item with name `item_name` defined in impl/trait `def_id`
483     /// and return it, or `None`, if no such item was defined there.
484     pub fn associated_item(
485         &self,
486         def_id: DefId,
487         item_name: Ident,
488         ns: Namespace,
489     ) -> Option<ty::AssocItem> {
490         self.tcx
491             .associated_items(def_id)
492             .find_by_name_and_namespace(self.tcx, item_name, ns, def_id)
493             .copied()
494     }
495 }