]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/method/mod.rs
Remove an unnecessary `resolve_vars_if_possible`
[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, ToPredicate, 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         match self.probe_for_name(
97             method_name.span,
98             probe::Mode::MethodCall,
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(true),
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         self.probe_for_name(
256             span,
257             probe::Mode::MethodCall,
258             method_name,
259             IsSuggestion(false),
260             self_ty,
261             call_expr.hir_id,
262             scope,
263         )
264     }
265
266     pub(super) fn obligation_for_method(
267         &self,
268         span: Span,
269         trait_def_id: DefId,
270         self_ty: Ty<'tcx>,
271         opt_input_types: Option<&[Ty<'tcx>]>,
272     ) -> (traits::Obligation<'tcx, ty::Predicate<'tcx>>, &'tcx ty::List<ty::subst::GenericArg<'tcx>>)
273     {
274         // Construct a trait-reference `self_ty : Trait<input_tys>`
275         let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
276             match param.kind {
277                 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => {}
278                 GenericParamDefKind::Type { .. } => {
279                     if param.index == 0 {
280                         return self_ty.into();
281                     } else if let Some(input_types) = opt_input_types {
282                         return input_types[param.index as usize - 1].into();
283                     }
284                 }
285             }
286             self.var_for_def(span, param)
287         });
288
289         let trait_ref = ty::TraitRef::new(trait_def_id, substs);
290
291         // Construct an obligation
292         let poly_trait_ref = ty::Binder::dummy(trait_ref);
293         (
294             traits::Obligation::misc(
295                 span,
296                 self.body_id,
297                 self.param_env,
298                 poly_trait_ref.without_const().to_predicate(self.tcx),
299             ),
300             substs,
301         )
302     }
303
304     pub(super) fn obligation_for_op_method(
305         &self,
306         span: Span,
307         trait_def_id: DefId,
308         self_ty: Ty<'tcx>,
309         opt_input_type: Option<Ty<'tcx>>,
310         opt_input_expr: Option<&'tcx hir::Expr<'tcx>>,
311         expected: Expectation<'tcx>,
312     ) -> (traits::Obligation<'tcx, ty::Predicate<'tcx>>, &'tcx ty::List<ty::subst::GenericArg<'tcx>>)
313     {
314         // Construct a trait-reference `self_ty : Trait<input_tys>`
315         let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
316             match param.kind {
317                 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => {}
318                 GenericParamDefKind::Type { .. } => {
319                     if param.index == 0 {
320                         return self_ty.into();
321                     } else if let Some(input_type) = opt_input_type {
322                         return input_type.into();
323                     }
324                 }
325             }
326             self.var_for_def(span, param)
327         });
328
329         let trait_ref = ty::TraitRef::new(trait_def_id, substs);
330
331         // Construct an obligation
332         let poly_trait_ref = ty::Binder::dummy(trait_ref);
333         let output_ty = expected.only_has_type(self).and_then(|ty| (!ty.needs_infer()).then(|| ty));
334
335         (
336             traits::Obligation::new(
337                 traits::ObligationCause::new(
338                     span,
339                     self.body_id,
340                     traits::BinOp {
341                         rhs_span: opt_input_expr.map(|expr| expr.span),
342                         is_lit: opt_input_expr
343                             .map_or(false, |expr| matches!(expr.kind, hir::ExprKind::Lit(_))),
344                         output_ty,
345                     },
346                 ),
347                 self.param_env,
348                 poly_trait_ref.without_const().to_predicate(self.tcx),
349             ),
350             substs,
351         )
352     }
353
354     /// `lookup_method_in_trait` is used for overloaded operators.
355     /// It does a very narrow slice of what the normal probe/confirm path does.
356     /// In particular, it doesn't really do any probing: it simply constructs
357     /// an obligation for a particular trait with the given self type and checks
358     /// whether that trait is implemented.
359     #[instrument(level = "debug", skip(self, span))]
360     pub(super) fn lookup_method_in_trait(
361         &self,
362         span: Span,
363         m_name: Ident,
364         trait_def_id: DefId,
365         self_ty: Ty<'tcx>,
366         opt_input_types: Option<&[Ty<'tcx>]>,
367     ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
368         let (obligation, substs) =
369             self.obligation_for_method(span, trait_def_id, self_ty, opt_input_types);
370         self.construct_obligation_for_trait(
371             span,
372             m_name,
373             trait_def_id,
374             obligation,
375             substs,
376             None,
377             false,
378         )
379     }
380
381     pub(super) fn lookup_op_method_in_trait(
382         &self,
383         span: Span,
384         m_name: Ident,
385         trait_def_id: DefId,
386         self_ty: Ty<'tcx>,
387         opt_input_type: Option<Ty<'tcx>>,
388         opt_input_expr: Option<&'tcx hir::Expr<'tcx>>,
389         expected: Expectation<'tcx>,
390     ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
391         let (obligation, substs) = self.obligation_for_op_method(
392             span,
393             trait_def_id,
394             self_ty,
395             opt_input_type,
396             opt_input_expr,
397             expected,
398         );
399         self.construct_obligation_for_trait(
400             span,
401             m_name,
402             trait_def_id,
403             obligation,
404             substs,
405             opt_input_expr,
406             true,
407         )
408     }
409
410     // FIXME(#18741): it seems likely that we can consolidate some of this
411     // code with the other method-lookup code. In particular, the second half
412     // of this method is basically the same as confirmation.
413     fn construct_obligation_for_trait(
414         &self,
415         span: Span,
416         m_name: Ident,
417         trait_def_id: DefId,
418         obligation: traits::PredicateObligation<'tcx>,
419         substs: &'tcx ty::List<ty::subst::GenericArg<'tcx>>,
420         opt_input_expr: Option<&'tcx hir::Expr<'tcx>>,
421         is_op: bool,
422     ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
423         debug!(?obligation);
424
425         // Now we want to know if this can be matched
426         if !self.predicate_may_hold(&obligation) {
427             debug!("--> Cannot match obligation");
428             // Cannot be matched, no such method resolution is possible.
429             return None;
430         }
431
432         // Trait must have a method named `m_name` and it should not have
433         // type parameters or early-bound regions.
434         let tcx = self.tcx;
435         let Some(method_item) = self.associated_value(trait_def_id, m_name) else {
436             tcx.sess.delay_span_bug(
437                 span,
438                 "operator trait does not have corresponding operator method",
439             );
440             return None;
441         };
442         let def_id = method_item.def_id;
443         let generics = tcx.generics_of(def_id);
444
445         if generics.params.len() != 0 {
446             tcx.sess.emit_fatal(OpMethodGenericParams {
447                 span: tcx.def_span(method_item.def_id),
448                 method_name: m_name.to_string(),
449             });
450         }
451
452         debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
453         let mut obligations = vec![];
454
455         // Instantiate late-bound regions and substitute the trait
456         // parameters into the method type to get the actual method type.
457         //
458         // N.B., instantiate late-bound regions first so that
459         // `instantiate_type_scheme` can normalize associated types that
460         // may reference those regions.
461         let fn_sig = tcx.bound_fn_sig(def_id);
462         let fn_sig = fn_sig.subst(self.tcx, substs);
463         let fn_sig = self.replace_bound_vars_with_fresh_vars(span, infer::FnCall, fn_sig);
464
465         let InferOk { value, obligations: o } = if is_op {
466             self.normalize_op_associated_types_in_as_infer_ok(span, fn_sig, opt_input_expr)
467         } else {
468             self.normalize_associated_types_in_as_infer_ok(span, fn_sig)
469         };
470         let fn_sig = {
471             obligations.extend(o);
472             value
473         };
474
475         // Register obligations for the parameters. This will include the
476         // `Self` parameter, which in turn has a bound of the main trait,
477         // so this also effectively registers `obligation` as well.  (We
478         // used to register `obligation` explicitly, but that resulted in
479         // double error messages being reported.)
480         //
481         // Note that as the method comes from a trait, it should not have
482         // any late-bound regions appearing in its bounds.
483         let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
484
485         let InferOk { value, obligations: o } = if is_op {
486             self.normalize_op_associated_types_in_as_infer_ok(span, bounds, opt_input_expr)
487         } else {
488             self.normalize_associated_types_in_as_infer_ok(span, bounds)
489         };
490         let bounds = {
491             obligations.extend(o);
492             value
493         };
494
495         assert!(!bounds.has_escaping_bound_vars());
496
497         let cause = if is_op {
498             ObligationCause::new(
499                 span,
500                 self.body_id,
501                 traits::BinOp {
502                     rhs_span: opt_input_expr.map(|expr| expr.span),
503                     is_lit: opt_input_expr
504                         .map_or(false, |expr| matches!(expr.kind, hir::ExprKind::Lit(_))),
505                     output_ty: None,
506                 },
507             )
508         } else {
509             traits::ObligationCause::misc(span, self.body_id)
510         };
511         let predicates_cause = cause.clone();
512         obligations.extend(traits::predicates_for_generics(
513             move |_, _| predicates_cause.clone(),
514             self.param_env,
515             bounds,
516         ));
517
518         // Also add an obligation for the method type being well-formed.
519         let method_ty = tcx.mk_fn_ptr(ty::Binder::dummy(fn_sig));
520         debug!(
521             "lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
522             method_ty, obligation
523         );
524         obligations.push(traits::Obligation::new(
525             cause,
526             self.param_env,
527             ty::Binder::dummy(ty::PredicateKind::WellFormed(method_ty.into())).to_predicate(tcx),
528         ));
529
530         let callee = MethodCallee { def_id, substs, sig: fn_sig };
531
532         debug!("callee = {:?}", callee);
533
534         Some(InferOk { obligations, value: callee })
535     }
536
537     /// Performs a [full-qualified function call] (formerly "universal function call") lookup. If
538     /// lookup is successful, it will return the type of definition and the [`DefId`] of the found
539     /// function definition.
540     ///
541     /// [full-qualified function call]: https://doc.rust-lang.org/reference/expressions/call-expr.html#disambiguating-function-calls
542     ///
543     /// # Arguments
544     ///
545     /// Given a function call like `Foo::bar::<T1,...Tn>(...)`:
546     ///
547     /// * `self`:                  the surrounding `FnCtxt` (!)
548     /// * `span`:                  the span of the call, excluding arguments (`Foo::bar::<T1, ...Tn>`)
549     /// * `method_name`:           the identifier of the function within the container type (`bar`)
550     /// * `self_ty`:               the type to search within (`Foo`)
551     /// * `self_ty_span`           the span for the type being searched within (span of `Foo`)
552     /// * `expr_id`:               the [`hir::HirId`] of the expression composing the entire call
553     #[instrument(level = "debug", skip(self), ret)]
554     pub fn resolve_fully_qualified_call(
555         &self,
556         span: Span,
557         method_name: Ident,
558         self_ty: Ty<'tcx>,
559         self_ty_span: Span,
560         expr_id: hir::HirId,
561     ) -> Result<(DefKind, DefId), MethodError<'tcx>> {
562         let tcx = self.tcx;
563
564         // Check if we have an enum variant.
565         if let ty::Adt(adt_def, _) = self_ty.kind() {
566             if adt_def.is_enum() {
567                 let variant_def = adt_def
568                     .variants()
569                     .iter()
570                     .find(|vd| tcx.hygienic_eq(method_name, vd.ident(tcx), adt_def.did()));
571                 if let Some(variant_def) = variant_def {
572                     // Braced variants generate unusable names in value namespace (reserved for
573                     // possible future use), so variants resolved as associated items may refer to
574                     // them as well. It's ok to use the variant's id as a ctor id since an
575                     // error will be reported on any use of such resolution anyway.
576                     let ctor_def_id = variant_def.ctor_def_id.unwrap_or(variant_def.def_id);
577                     tcx.check_stability(ctor_def_id, Some(expr_id), span, Some(method_name.span));
578                     return Ok((
579                         DefKind::Ctor(CtorOf::Variant, variant_def.ctor_kind),
580                         ctor_def_id,
581                     ));
582                 }
583             }
584         }
585
586         let pick = self.probe_for_name(
587             span,
588             probe::Mode::Path,
589             method_name,
590             IsSuggestion(false),
591             self_ty,
592             expr_id,
593             ProbeScope::TraitsInScope,
594         )?;
595
596         self.lint_fully_qualified_call_from_2018(
597             span,
598             method_name,
599             self_ty,
600             self_ty_span,
601             expr_id,
602             &pick,
603         );
604
605         debug!(?pick);
606         {
607             let mut typeck_results = self.typeck_results.borrow_mut();
608             let used_trait_imports = Lrc::get_mut(&mut typeck_results.used_trait_imports).unwrap();
609             for import_id in pick.import_ids {
610                 debug!(used_trait_import=?import_id);
611                 used_trait_imports.insert(import_id);
612             }
613         }
614
615         let def_kind = pick.item.kind.as_def_kind();
616         tcx.check_stability(pick.item.def_id, Some(expr_id), span, Some(method_name.span));
617         Ok((def_kind, pick.item.def_id))
618     }
619
620     /// Finds item with name `item_name` defined in impl/trait `def_id`
621     /// and return it, or `None`, if no such item was defined there.
622     pub fn associated_value(&self, def_id: DefId, item_name: Ident) -> Option<ty::AssocItem> {
623         self.tcx
624             .associated_items(def_id)
625             .find_by_name_and_namespace(self.tcx, item_name, Namespace::ValueNS, def_id)
626             .copied()
627     }
628 }