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