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