]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/method/mod.rs
Convert predicates into Predicate in the Obligation constructor
[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::{Expectation, 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, DefIdTree, GenericParamDefKind, Ty, TypeVisitable};
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     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(Vec<DefId>, bool, Span),
61
62     // Found a match, but the return type is wrong
63     BadReturnType,
64 }
65
66 // Contains a list of static methods that may apply, a list of unsatisfied trait predicates which
67 // could lead to matches if satisfied, and a list of not-in-scope traits which may work.
68 #[derive(Debug)]
69 pub struct NoMatchData<'tcx> {
70     pub static_candidates: Vec<CandidateSource>,
71     pub unsatisfied_predicates:
72         Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>,
73     pub out_of_scope_traits: Vec<DefId>,
74     pub lev_candidate: Option<ty::AssocItem>,
75     pub mode: probe::Mode,
76 }
77
78 // A pared down enum describing just the places from which a method
79 // candidate can arise. Used for error reporting only.
80 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
81 pub enum CandidateSource {
82     Impl(DefId),
83     Trait(DefId /* trait id */),
84 }
85
86 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
87     /// Determines whether the type `self_ty` supports a method name `method_name` or not.
88     #[instrument(level = "debug", skip(self))]
89     pub fn method_exists(
90         &self,
91         method_name: Ident,
92         self_ty: Ty<'tcx>,
93         call_expr_id: hir::HirId,
94         allow_private: bool,
95     ) -> bool {
96         let mode = probe::Mode::MethodCall;
97         match self.probe_for_name(
98             method_name.span,
99             mode,
100             method_name,
101             IsSuggestion(false),
102             self_ty,
103             call_expr_id,
104             ProbeScope::TraitsInScope,
105         ) {
106             Ok(..) => true,
107             Err(NoMatch(..)) => false,
108             Err(Ambiguity(..)) => true,
109             Err(PrivateMatch(..)) => allow_private,
110             Err(IllegalSizedBound(..)) => true,
111             Err(BadReturnType) => bug!("no return type expectations but got BadReturnType"),
112         }
113     }
114
115     /// Adds a suggestion to call the given method to the provided diagnostic.
116     #[instrument(level = "debug", skip(self, err, call_expr))]
117     pub(crate) fn suggest_method_call(
118         &self,
119         err: &mut Diagnostic,
120         msg: &str,
121         method_name: Ident,
122         self_ty: Ty<'tcx>,
123         call_expr: &hir::Expr<'_>,
124         span: Option<Span>,
125     ) {
126         let params = self
127             .probe_for_name(
128                 method_name.span,
129                 probe::Mode::MethodCall,
130                 method_name,
131                 IsSuggestion(false),
132                 self_ty,
133                 call_expr.hir_id,
134                 ProbeScope::TraitsInScope,
135             )
136             .map(|pick| {
137                 let sig = self.tcx.fn_sig(pick.item.def_id);
138                 sig.inputs().skip_binder().len().saturating_sub(1)
139             })
140             .unwrap_or(0);
141
142         // Account for `foo.bar<T>`;
143         let sugg_span = span.unwrap_or(call_expr.span).shrink_to_hi();
144         let (suggestion, applicability) = (
145             format!("({})", (0..params).map(|_| "_").collect::<Vec<_>>().join(", ")),
146             if params > 0 { Applicability::HasPlaceholders } else { Applicability::MaybeIncorrect },
147         );
148
149         err.span_suggestion_verbose(sugg_span, msg, suggestion, applicability);
150     }
151
152     /// Performs method lookup. If lookup is successful, it will return the callee
153     /// and store an appropriate adjustment for the self-expr. In some cases it may
154     /// report an error (e.g., invoking the `drop` method).
155     ///
156     /// # Arguments
157     ///
158     /// Given a method call like `foo.bar::<T1,...Tn>(a, b + 1, ...)`:
159     ///
160     /// * `self`:                  the surrounding `FnCtxt` (!)
161     /// * `self_ty`:               the (unadjusted) type of the self expression (`foo`)
162     /// * `segment`:               the name and generic arguments of the method (`bar::<T1, ...Tn>`)
163     /// * `span`:                  the span for the method call
164     /// * `call_expr`:             the complete method call: (`foo.bar::<T1,...Tn>(...)`)
165     /// * `self_expr`:             the self expression (`foo`)
166     /// * `args`:                  the expressions of the arguments (`a, b + 1, ...`)
167     #[instrument(level = "debug", skip(self))]
168     pub fn lookup_method(
169         &self,
170         self_ty: Ty<'tcx>,
171         segment: &hir::PathSegment<'_>,
172         span: Span,
173         call_expr: &'tcx hir::Expr<'tcx>,
174         self_expr: &'tcx hir::Expr<'tcx>,
175         args: &'tcx [hir::Expr<'tcx>],
176     ) -> Result<MethodCallee<'tcx>, MethodError<'tcx>> {
177         let pick =
178             self.lookup_probe(span, segment.ident, self_ty, call_expr, ProbeScope::TraitsInScope)?;
179
180         self.lint_dot_call_from_2018(self_ty, segment, span, call_expr, self_expr, &pick, args);
181
182         for import_id in &pick.import_ids {
183             debug!("used_trait_import: {:?}", import_id);
184             Lrc::get_mut(&mut self.typeck_results.borrow_mut().used_trait_imports)
185                 .unwrap()
186                 .insert(*import_id);
187         }
188
189         self.tcx.check_stability(pick.item.def_id, Some(call_expr.hir_id), span, None);
190
191         let result =
192             self.confirm_method(span, self_expr, call_expr, self_ty, pick.clone(), segment);
193         debug!("result = {:?}", result);
194
195         if let Some(span) = result.illegal_sized_bound {
196             let mut needs_mut = false;
197             if let ty::Ref(region, t_type, mutability) = self_ty.kind() {
198                 let trait_type = self
199                     .tcx
200                     .mk_ref(*region, ty::TypeAndMut { ty: *t_type, mutbl: mutability.invert() });
201                 // We probe again to see if there might be a borrow mutability discrepancy.
202                 match self.lookup_probe(
203                     span,
204                     segment.ident,
205                     trait_type,
206                     call_expr,
207                     ProbeScope::TraitsInScope,
208                 ) {
209                     Ok(ref new_pick) if *new_pick != pick => {
210                         needs_mut = true;
211                     }
212                     _ => {}
213                 }
214             }
215
216             // We probe again, taking all traits into account (not only those in scope).
217             let mut candidates = match self.lookup_probe(
218                 span,
219                 segment.ident,
220                 self_ty,
221                 call_expr,
222                 ProbeScope::AllTraits,
223             ) {
224                 // If we find a different result the caller probably forgot to import a trait.
225                 Ok(ref new_pick) if *new_pick != pick => vec![new_pick.item.container_id(self.tcx)],
226                 Err(Ambiguity(ref sources)) => sources
227                     .iter()
228                     .filter_map(|source| {
229                         match *source {
230                             // Note: this cannot come from an inherent impl,
231                             // because the first probing succeeded.
232                             CandidateSource::Impl(def) => self.tcx.trait_id_of_impl(def),
233                             CandidateSource::Trait(_) => None,
234                         }
235                     })
236                     .collect(),
237                 _ => Vec::new(),
238             };
239             candidates.retain(|candidate| *candidate != self.tcx.parent(result.callee.def_id));
240
241             return Err(IllegalSizedBound(candidates, needs_mut, span));
242         }
243
244         Ok(result.callee)
245     }
246
247     #[instrument(level = "debug", skip(self, call_expr))]
248     pub fn lookup_probe(
249         &self,
250         span: Span,
251         method_name: Ident,
252         self_ty: Ty<'tcx>,
253         call_expr: &'tcx hir::Expr<'tcx>,
254         scope: ProbeScope,
255     ) -> probe::PickResult<'tcx> {
256         let mode = probe::Mode::MethodCall;
257         let self_ty = self.resolve_vars_if_possible(self_ty);
258         self.probe_for_name(
259             span,
260             mode,
261             method_name,
262             IsSuggestion(false),
263             self_ty,
264             call_expr.hir_id,
265             scope,
266         )
267     }
268
269     pub(super) fn obligation_for_method(
270         &self,
271         span: Span,
272         trait_def_id: DefId,
273         self_ty: Ty<'tcx>,
274         opt_input_types: Option<&[Ty<'tcx>]>,
275     ) -> (traits::Obligation<'tcx, ty::Predicate<'tcx>>, &'tcx ty::List<ty::subst::GenericArg<'tcx>>)
276     {
277         // Construct a trait-reference `self_ty : Trait<input_tys>`
278         let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
279             match param.kind {
280                 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => {}
281                 GenericParamDefKind::Type { .. } => {
282                     if param.index == 0 {
283                         return self_ty.into();
284                     } else if let Some(input_types) = opt_input_types {
285                         return input_types[param.index as usize - 1].into();
286                     }
287                 }
288             }
289             self.var_for_def(span, param)
290         });
291
292         let trait_ref = ty::TraitRef::new(trait_def_id, substs);
293
294         // Construct an obligation
295         let poly_trait_ref = ty::Binder::dummy(trait_ref);
296         (
297             traits::Obligation::misc(
298                 self.tcx,
299                 span,
300                 self.body_id,
301                 self.param_env,
302                 poly_trait_ref.without_const(),
303             ),
304             substs,
305         )
306     }
307
308     pub(super) fn obligation_for_op_method(
309         &self,
310         span: Span,
311         trait_def_id: DefId,
312         self_ty: Ty<'tcx>,
313         opt_input_type: Option<Ty<'tcx>>,
314         opt_input_expr: Option<&'tcx hir::Expr<'tcx>>,
315         expected: Expectation<'tcx>,
316     ) -> (traits::Obligation<'tcx, ty::Predicate<'tcx>>, &'tcx ty::List<ty::subst::GenericArg<'tcx>>)
317     {
318         // Construct a trait-reference `self_ty : Trait<input_tys>`
319         let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
320             match param.kind {
321                 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => {}
322                 GenericParamDefKind::Type { .. } => {
323                     if param.index == 0 {
324                         return self_ty.into();
325                     } else if let Some(input_type) = opt_input_type {
326                         return input_type.into();
327                     }
328                 }
329             }
330             self.var_for_def(span, param)
331         });
332
333         let trait_ref = ty::TraitRef::new(trait_def_id, substs);
334
335         // Construct an obligation
336         let poly_trait_ref = ty::Binder::dummy(trait_ref);
337         let output_ty = expected.only_has_type(self).and_then(|ty| (!ty.needs_infer()).then(|| ty));
338
339         (
340             traits::Obligation::new(
341                 self.tcx,
342                 traits::ObligationCause::new(
343                     span,
344                     self.body_id,
345                     traits::BinOp {
346                         rhs_span: opt_input_expr.map(|expr| expr.span),
347                         is_lit: opt_input_expr
348                             .map_or(false, |expr| matches!(expr.kind, hir::ExprKind::Lit(_))),
349                         output_ty,
350                     },
351                 ),
352                 self.param_env,
353                 poly_trait_ref.without_const(),
354             ),
355             substs,
356         )
357     }
358
359     /// `lookup_method_in_trait` is used for overloaded operators.
360     /// It does a very narrow slice of what the normal probe/confirm path does.
361     /// In particular, it doesn't really do any probing: it simply constructs
362     /// an obligation for a particular trait with the given self type and checks
363     /// whether that trait is implemented.
364     #[instrument(level = "debug", skip(self, span))]
365     pub(super) fn lookup_method_in_trait(
366         &self,
367         span: Span,
368         m_name: Ident,
369         trait_def_id: DefId,
370         self_ty: Ty<'tcx>,
371         opt_input_types: Option<&[Ty<'tcx>]>,
372     ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
373         let (obligation, substs) =
374             self.obligation_for_method(span, trait_def_id, self_ty, opt_input_types);
375         self.construct_obligation_for_trait(
376             span,
377             m_name,
378             trait_def_id,
379             obligation,
380             substs,
381             None,
382             false,
383         )
384     }
385
386     pub(super) fn lookup_op_method_in_trait(
387         &self,
388         span: Span,
389         m_name: Ident,
390         trait_def_id: DefId,
391         self_ty: Ty<'tcx>,
392         opt_input_type: Option<Ty<'tcx>>,
393         opt_input_expr: Option<&'tcx hir::Expr<'tcx>>,
394         expected: Expectation<'tcx>,
395     ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
396         let (obligation, substs) = self.obligation_for_op_method(
397             span,
398             trait_def_id,
399             self_ty,
400             opt_input_type,
401             opt_input_expr,
402             expected,
403         );
404         self.construct_obligation_for_trait(
405             span,
406             m_name,
407             trait_def_id,
408             obligation,
409             substs,
410             opt_input_expr,
411             true,
412         )
413     }
414
415     // FIXME(#18741): it seems likely that we can consolidate some of this
416     // code with the other method-lookup code. In particular, the second half
417     // of this method is basically the same as confirmation.
418     fn construct_obligation_for_trait(
419         &self,
420         span: Span,
421         m_name: Ident,
422         trait_def_id: DefId,
423         obligation: traits::PredicateObligation<'tcx>,
424         substs: &'tcx ty::List<ty::subst::GenericArg<'tcx>>,
425         opt_input_expr: Option<&'tcx hir::Expr<'tcx>>,
426         is_op: bool,
427     ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
428         debug!(?obligation);
429
430         // Now we want to know if this can be matched
431         if !self.predicate_may_hold(&obligation) {
432             debug!("--> Cannot match obligation");
433             // Cannot be matched, no such method resolution is possible.
434             return None;
435         }
436
437         // Trait must have a method named `m_name` and it should not have
438         // type parameters or early-bound regions.
439         let tcx = self.tcx;
440         let Some(method_item) = self.associated_value(trait_def_id, m_name) else {
441             tcx.sess.delay_span_bug(
442                 span,
443                 "operator trait does not have corresponding operator method",
444             );
445             return None;
446         };
447         let def_id = method_item.def_id;
448         let generics = tcx.generics_of(def_id);
449
450         if generics.params.len() != 0 {
451             tcx.sess.emit_fatal(OpMethodGenericParams {
452                 span: tcx.def_span(method_item.def_id),
453                 method_name: m_name.to_string(),
454             });
455         }
456
457         debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
458         let mut obligations = vec![];
459
460         // Instantiate late-bound regions and substitute the trait
461         // parameters into the method type to get the actual method type.
462         //
463         // N.B., instantiate late-bound regions first so that
464         // `instantiate_type_scheme` can normalize associated types that
465         // may reference those regions.
466         let fn_sig = tcx.bound_fn_sig(def_id);
467         let fn_sig = fn_sig.subst(self.tcx, substs);
468         let fn_sig = self.replace_bound_vars_with_fresh_vars(span, infer::FnCall, fn_sig);
469
470         let InferOk { value, obligations: o } = if is_op {
471             self.normalize_op_associated_types_in_as_infer_ok(span, fn_sig, opt_input_expr)
472         } else {
473             self.normalize_associated_types_in_as_infer_ok(span, fn_sig)
474         };
475         let fn_sig = {
476             obligations.extend(o);
477             value
478         };
479
480         // Register obligations for the parameters. This will include the
481         // `Self` parameter, which in turn has a bound of the main trait,
482         // so this also effectively registers `obligation` as well.  (We
483         // used to register `obligation` explicitly, but that resulted in
484         // double error messages being reported.)
485         //
486         // Note that as the method comes from a trait, it should not have
487         // any late-bound regions appearing in its bounds.
488         let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
489
490         let InferOk { value, obligations: o } = if is_op {
491             self.normalize_op_associated_types_in_as_infer_ok(span, bounds, opt_input_expr)
492         } else {
493             self.normalize_associated_types_in_as_infer_ok(span, bounds)
494         };
495         let bounds = {
496             obligations.extend(o);
497             value
498         };
499
500         assert!(!bounds.has_escaping_bound_vars());
501
502         let cause = if is_op {
503             ObligationCause::new(
504                 span,
505                 self.body_id,
506                 traits::BinOp {
507                     rhs_span: opt_input_expr.map(|expr| expr.span),
508                     is_lit: opt_input_expr
509                         .map_or(false, |expr| matches!(expr.kind, hir::ExprKind::Lit(_))),
510                     output_ty: None,
511                 },
512             )
513         } else {
514             traits::ObligationCause::misc(span, self.body_id)
515         };
516         let predicates_cause = cause.clone();
517         obligations.extend(traits::predicates_for_generics(
518             move |_, _| predicates_cause.clone(),
519             self.param_env,
520             bounds,
521         ));
522
523         // Also add an obligation for the method type being well-formed.
524         let method_ty = tcx.mk_fn_ptr(ty::Binder::dummy(fn_sig));
525         debug!(
526             "lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
527             method_ty, obligation
528         );
529         obligations.push(traits::Obligation::new(
530             tcx,
531             cause,
532             self.param_env,
533             ty::Binder::dummy(ty::PredicateKind::WellFormed(method_ty.into())),
534         ));
535
536         let callee = MethodCallee { def_id, substs, sig: fn_sig };
537
538         debug!("callee = {:?}", callee);
539
540         Some(InferOk { obligations, value: callee })
541     }
542
543     /// Performs a [full-qualified function call] (formerly "universal function call") lookup. If
544     /// lookup is successful, it will return the type of definition and the [`DefId`] of the found
545     /// function definition.
546     ///
547     /// [full-qualified function call]: https://doc.rust-lang.org/reference/expressions/call-expr.html#disambiguating-function-calls
548     ///
549     /// # Arguments
550     ///
551     /// Given a function call like `Foo::bar::<T1,...Tn>(...)`:
552     ///
553     /// * `self`:                  the surrounding `FnCtxt` (!)
554     /// * `span`:                  the span of the call, excluding arguments (`Foo::bar::<T1, ...Tn>`)
555     /// * `method_name`:           the identifier of the function within the container type (`bar`)
556     /// * `self_ty`:               the type to search within (`Foo`)
557     /// * `self_ty_span`           the span for the type being searched within (span of `Foo`)
558     /// * `expr_id`:               the [`hir::HirId`] of the expression composing the entire call
559     #[instrument(level = "debug", skip(self), ret)]
560     pub fn resolve_fully_qualified_call(
561         &self,
562         span: Span,
563         method_name: Ident,
564         self_ty: Ty<'tcx>,
565         self_ty_span: Span,
566         expr_id: hir::HirId,
567     ) -> Result<(DefKind, DefId), MethodError<'tcx>> {
568         let tcx = self.tcx;
569
570         // Check if we have an enum variant.
571         if let ty::Adt(adt_def, _) = self_ty.kind() {
572             if adt_def.is_enum() {
573                 let variant_def = adt_def
574                     .variants()
575                     .iter()
576                     .find(|vd| tcx.hygienic_eq(method_name, vd.ident(tcx), adt_def.did()));
577                 if let Some(variant_def) = variant_def {
578                     // Braced variants generate unusable names in value namespace (reserved for
579                     // possible future use), so variants resolved as associated items may refer to
580                     // them as well. It's ok to use the variant's id as a ctor id since an
581                     // error will be reported on any use of such resolution anyway.
582                     let ctor_def_id = variant_def.ctor_def_id.unwrap_or(variant_def.def_id);
583                     tcx.check_stability(ctor_def_id, Some(expr_id), span, Some(method_name.span));
584                     return Ok((
585                         DefKind::Ctor(CtorOf::Variant, variant_def.ctor_kind),
586                         ctor_def_id,
587                     ));
588                 }
589             }
590         }
591
592         let pick = self.probe_for_name(
593             span,
594             probe::Mode::Path,
595             method_name,
596             IsSuggestion(false),
597             self_ty,
598             expr_id,
599             ProbeScope::TraitsInScope,
600         )?;
601
602         self.lint_fully_qualified_call_from_2018(
603             span,
604             method_name,
605             self_ty,
606             self_ty_span,
607             expr_id,
608             &pick,
609         );
610
611         debug!(?pick);
612         {
613             let mut typeck_results = self.typeck_results.borrow_mut();
614             let used_trait_imports = Lrc::get_mut(&mut typeck_results.used_trait_imports).unwrap();
615             for import_id in pick.import_ids {
616                 debug!(used_trait_import=?import_id);
617                 used_trait_imports.insert(import_id);
618             }
619         }
620
621         let def_kind = pick.item.kind.as_def_kind();
622         tcx.check_stability(pick.item.def_id, Some(expr_id), span, Some(method_name.span));
623         Ok((def_kind, pick.item.def_id))
624     }
625
626     /// Finds item with name `item_name` defined in impl/trait `def_id`
627     /// and return it, or `None`, if no such item was defined there.
628     pub fn associated_value(&self, def_id: DefId, item_name: Ident) -> Option<ty::AssocItem> {
629         self.tcx
630             .associated_items(def_id)
631             .find_by_name_and_namespace(self.tcx, item_name, Namespace::ValueNS, def_id)
632             .copied()
633     }
634 }