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