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