1 //! Method lookup: the secret sauce of Rust. See the [rustc dev guide] for more information.
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/method-lookup.html
10 pub use self::suggest::SelfSource;
11 pub use self::MethodError::*;
13 use crate::check::{Expectation, FnCtxt};
14 use crate::ObligationCause;
15 use rustc_data_structures::sync::Lrc;
16 use rustc_errors::{Applicability, Diagnostic};
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::ty::subst::Subst;
22 use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
23 use rustc_middle::ty::{
24 self, AssocKind, DefIdTree, GenericParamDefKind, ProjectionPredicate, ProjectionTy, Term,
25 ToPredicate, Ty, TypeVisitable,
27 use rustc_span::symbol::Ident;
29 use rustc_trait_selection::traits;
30 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
32 use self::probe::{IsSuggestion, ProbeScope};
34 pub fn provide(providers: &mut ty::query::Providers) {
35 probe::provide(providers);
38 #[derive(Clone, Copy, Debug)]
39 pub struct MethodCallee<'tcx> {
40 /// Impl method ID, for inherent methods, or trait method ID, otherwise.
42 pub substs: SubstsRef<'tcx>,
44 /// Instantiated method signature, i.e., it has been
45 /// substituted, normalized, and has had late-bound
46 /// lifetimes replaced with inference variables.
47 pub sig: ty::FnSig<'tcx>,
51 pub enum MethodError<'tcx> {
52 // Did not find an applicable method, but we did find various near-misses that may work.
53 NoMatch(NoMatchData<'tcx>),
55 // Multiple methods might apply.
56 Ambiguity(Vec<CandidateSource>),
58 // Found an applicable method, but it is not visible. The third argument contains a list of
59 // not-in-scope traits which may work.
60 PrivateMatch(DefKind, DefId, Vec<DefId>),
62 // Found a `Self: Sized` bound where `Self` is a trait object, also the caller may have
63 // forgotten to import a trait.
64 IllegalSizedBound(Vec<DefId>, bool, Span),
66 // Found a match, but the return type is wrong
70 // Contains a list of static methods that may apply, a list of unsatisfied trait predicates which
71 // could lead to matches if satisfied, and a list of not-in-scope traits which may work.
73 pub struct NoMatchData<'tcx> {
74 pub static_candidates: Vec<CandidateSource>,
75 pub unsatisfied_predicates:
76 Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>,
77 pub out_of_scope_traits: Vec<DefId>,
78 pub lev_candidate: Option<ty::AssocItem>,
79 pub mode: probe::Mode,
82 // A pared down enum describing just the places from which a method
83 // candidate can arise. Used for error reporting only.
84 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
85 pub enum CandidateSource {
87 Trait(DefId /* trait id */),
90 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
91 /// Determines whether the type `self_ty` supports a method name `method_name` or not.
92 #[instrument(level = "debug", skip(self))]
97 call_expr_id: hir::HirId,
100 let mode = probe::Mode::MethodCall;
101 match self.probe_for_name(
108 ProbeScope::TraitsInScope,
111 Err(NoMatch(..)) => false,
112 Err(Ambiguity(..)) => true,
113 Err(PrivateMatch(..)) => allow_private,
114 Err(IllegalSizedBound(..)) => true,
115 Err(BadReturnType) => bug!("no return type expectations but got BadReturnType"),
119 /// Adds a suggestion to call the given method to the provided diagnostic.
120 #[instrument(level = "debug", skip(self, err, call_expr))]
121 pub(crate) fn suggest_method_call(
123 err: &mut Diagnostic,
127 call_expr: &hir::Expr<'_>,
133 probe::Mode::MethodCall,
138 ProbeScope::TraitsInScope,
141 let sig = self.tcx.fn_sig(pick.item.def_id);
142 sig.inputs().skip_binder().len().saturating_sub(1)
146 // Account for `foo.bar<T>`;
147 let sugg_span = span.unwrap_or(call_expr.span).shrink_to_hi();
148 let (suggestion, applicability) = (
149 format!("({})", (0..params).map(|_| "_").collect::<Vec<_>>().join(", ")),
150 if params > 0 { Applicability::HasPlaceholders } else { Applicability::MaybeIncorrect },
153 err.span_suggestion_verbose(sugg_span, msg, suggestion, applicability);
156 /// Performs method lookup. If lookup is successful, it will return the callee
157 /// and store an appropriate adjustment for the self-expr. In some cases it may
158 /// report an error (e.g., invoking the `drop` method).
162 /// Given a method call like `foo.bar::<T1,...Tn>(a, b + 1, ...)`:
164 /// * `self`: the surrounding `FnCtxt` (!)
165 /// * `self_ty`: the (unadjusted) type of the self expression (`foo`)
166 /// * `segment`: the name and generic arguments of the method (`bar::<T1, ...Tn>`)
167 /// * `span`: the span for the method call
168 /// * `call_expr`: the complete method call: (`foo.bar::<T1,...Tn>(...)`)
169 /// * `self_expr`: the self expression (`foo`)
170 /// * `args`: the expressions of the arguments (`a, b + 1, ...`)
171 #[instrument(level = "debug", skip(self, call_expr, self_expr))]
172 pub fn lookup_method(
175 segment: &hir::PathSegment<'_>,
177 call_expr: &'tcx hir::Expr<'tcx>,
178 self_expr: &'tcx hir::Expr<'tcx>,
179 args: &'tcx [hir::Expr<'tcx>],
180 ) -> Result<MethodCallee<'tcx>, MethodError<'tcx>> {
182 "lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
183 segment.ident, self_ty, call_expr, self_expr
187 self.lookup_probe(span, segment.ident, self_ty, call_expr, ProbeScope::TraitsInScope)?;
189 self.lint_dot_call_from_2018(self_ty, segment, span, call_expr, self_expr, &pick, args);
191 for import_id in &pick.import_ids {
192 debug!("used_trait_import: {:?}", import_id);
193 Lrc::get_mut(&mut self.typeck_results.borrow_mut().used_trait_imports)
198 self.tcx.check_stability(pick.item.def_id, Some(call_expr.hir_id), span, None);
201 self.confirm_method(span, self_expr, call_expr, self_ty, pick.clone(), segment);
202 debug!("result = {:?}", result);
204 if let Some(span) = result.illegal_sized_bound {
205 let mut needs_mut = false;
206 if let ty::Ref(region, t_type, mutability) = self_ty.kind() {
207 let trait_type = self
209 .mk_ref(*region, ty::TypeAndMut { ty: *t_type, mutbl: mutability.invert() });
210 // We probe again to see if there might be a borrow mutability discrepancy.
211 match self.lookup_probe(
216 ProbeScope::TraitsInScope,
218 Ok(ref new_pick) if *new_pick != pick => {
225 // We probe again, taking all traits into account (not only those in scope).
226 let mut candidates = match self.lookup_probe(
231 ProbeScope::AllTraits,
233 // If we find a different result the caller probably forgot to import a trait.
234 Ok(ref new_pick) if *new_pick != pick => vec![new_pick.item.container.id()],
235 Err(Ambiguity(ref sources)) => sources
237 .filter_map(|source| {
239 // Note: this cannot come from an inherent impl,
240 // because the first probing succeeded.
241 CandidateSource::Impl(def) => self.tcx.trait_id_of_impl(def),
242 CandidateSource::Trait(_) => None,
248 candidates.retain(|candidate| *candidate != self.tcx.parent(result.callee.def_id));
250 return Err(IllegalSizedBound(candidates, needs_mut, span));
256 #[instrument(level = "debug", skip(self, call_expr))]
262 call_expr: &'tcx hir::Expr<'tcx>,
264 ) -> probe::PickResult<'tcx> {
265 let mode = probe::Mode::MethodCall;
266 let self_ty = self.resolve_vars_if_possible(self_ty);
278 pub(super) fn obligation_for_method(
283 opt_input_types: Option<&[Ty<'tcx>]>,
284 ) -> (traits::Obligation<'tcx, ty::Predicate<'tcx>>, &'tcx ty::List<ty::subst::GenericArg<'tcx>>)
286 // Construct a trait-reference `self_ty : Trait<input_tys>`
287 let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
289 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => {}
290 GenericParamDefKind::Type { .. } => {
291 if param.index == 0 {
292 return self_ty.into();
293 } else if let Some(input_types) = opt_input_types {
294 return input_types[param.index as usize - 1].into();
298 self.var_for_def(span, param)
301 let trait_ref = ty::TraitRef::new(trait_def_id, substs);
303 // Construct an obligation
304 let poly_trait_ref = ty::Binder::dummy(trait_ref);
306 traits::Obligation::misc(
310 poly_trait_ref.without_const().to_predicate(self.tcx),
316 pub(super) fn obligation_for_op_method(
321 opt_input_type: Option<Ty<'tcx>>,
322 opt_input_expr: Option<&'tcx hir::Expr<'tcx>>,
323 expected: Expectation<'tcx>,
324 ) -> (traits::Obligation<'tcx, ty::Predicate<'tcx>>, &'tcx ty::List<ty::subst::GenericArg<'tcx>>)
326 // Construct a trait-reference `self_ty : Trait<input_tys>`
327 let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
329 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => {}
330 GenericParamDefKind::Type { .. } => {
331 if param.index == 0 {
332 return self_ty.into();
333 } else if let Some(input_type) = opt_input_type {
334 return input_type.into();
338 self.var_for_def(span, param)
341 let trait_ref = ty::TraitRef::new(trait_def_id, substs);
343 // Construct an obligation
344 let poly_trait_ref = ty::Binder::dummy(trait_ref);
346 expected.only_has_type(self).and_then(|ty| (!ty.needs_infer()).then(|| ty));
347 let opt_output_assoc_item = self.tcx.associated_items(trait_def_id).find_by_name_and_kind(
349 Ident::from_str("Output"),
354 opt_output_ty.zip(opt_output_assoc_item).map(|(output_ty, output_assoc_item)| {
355 ty::Binder::dummy(ty::PredicateKind::Projection(ProjectionPredicate {
356 projection_ty: ProjectionTy { substs, item_def_id: output_assoc_item.def_id },
357 term: Term::Ty(output_ty),
359 .to_predicate(self.tcx)
363 traits::Obligation::new(
364 traits::ObligationCause::new(
368 rhs_span: opt_input_expr.map(|expr| expr.span),
369 is_lit: opt_input_expr
370 .map_or(false, |expr| matches!(expr.kind, hir::ExprKind::Lit(_))),
375 poly_trait_ref.without_const().to_predicate(self.tcx),
381 /// `lookup_method_in_trait` is used for overloaded operators.
382 /// It does a very narrow slice of what the normal probe/confirm path does.
383 /// In particular, it doesn't really do any probing: it simply constructs
384 /// an obligation for a particular trait with the given self type and checks
385 /// whether that trait is implemented.
386 #[instrument(level = "debug", skip(self, span, opt_input_types))]
387 pub(super) fn lookup_method_in_trait(
393 opt_input_types: Option<&[Ty<'tcx>]>,
394 ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
396 "lookup_in_trait_adjusted(self_ty={:?}, m_name={}, trait_def_id={:?}, opt_input_types={:?})",
397 self_ty, m_name, trait_def_id, opt_input_types
400 let (obligation, substs) =
401 self.obligation_for_method(span, trait_def_id, self_ty, opt_input_types);
402 self.construct_obligation_for_trait(
413 pub(super) fn lookup_op_method_in_trait(
419 opt_input_type: Option<Ty<'tcx>>,
420 opt_input_expr: Option<&'tcx hir::Expr<'tcx>>,
421 expected: Expectation<'tcx>,
422 ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
423 let (obligation, substs) = self.obligation_for_op_method(
431 self.construct_obligation_for_trait(
442 // FIXME(#18741): it seems likely that we can consolidate some of this
443 // code with the other method-lookup code. In particular, the second half
444 // of this method is basically the same as confirmation.
445 fn construct_obligation_for_trait(
450 obligation: traits::PredicateObligation<'tcx>,
451 substs: &'tcx ty::List<ty::subst::GenericArg<'tcx>>,
452 opt_input_expr: Option<&'tcx hir::Expr<'tcx>>,
454 ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
457 // Now we want to know if this can be matched
458 if !self.predicate_may_hold(&obligation) {
459 debug!("--> Cannot match obligation");
460 // Cannot be matched, no such method resolution is possible.
464 // Trait must have a method named `m_name` and it should not have
465 // type parameters or early-bound regions.
467 let Some(method_item) = self.associated_value(trait_def_id, m_name) else {
468 tcx.sess.delay_span_bug(
470 "operator trait does not have corresponding operator method",
474 let def_id = method_item.def_id;
475 let generics = tcx.generics_of(def_id);
476 assert_eq!(generics.params.len(), 0);
478 debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
479 let mut obligations = vec![];
481 // Instantiate late-bound regions and substitute the trait
482 // parameters into the method type to get the actual method type.
484 // N.B., instantiate late-bound regions first so that
485 // `instantiate_type_scheme` can normalize associated types that
486 // may reference those regions.
487 let fn_sig = tcx.bound_fn_sig(def_id);
488 let fn_sig = fn_sig.subst(self.tcx, substs);
489 let fn_sig = self.replace_bound_vars_with_fresh_vars(span, infer::FnCall, fn_sig);
491 let InferOk { value, obligations: o } = if is_op {
492 self.normalize_op_associated_types_in_as_infer_ok(span, fn_sig, opt_input_expr)
494 self.normalize_associated_types_in_as_infer_ok(span, fn_sig)
497 obligations.extend(o);
501 // Register obligations for the parameters. This will include the
502 // `Self` parameter, which in turn has a bound of the main trait,
503 // so this also effectively registers `obligation` as well. (We
504 // used to register `obligation` explicitly, but that resulted in
505 // double error messages being reported.)
507 // Note that as the method comes from a trait, it should not have
508 // any late-bound regions appearing in its bounds.
509 let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
511 let InferOk { value, obligations: o } = if is_op {
512 self.normalize_op_associated_types_in_as_infer_ok(span, bounds, opt_input_expr)
514 self.normalize_associated_types_in_as_infer_ok(span, bounds)
517 obligations.extend(o);
521 assert!(!bounds.has_escaping_bound_vars());
523 let cause = if is_op {
524 ObligationCause::new(
528 rhs_span: opt_input_expr.map(|expr| expr.span),
529 is_lit: opt_input_expr
530 .map_or(false, |expr| matches!(expr.kind, hir::ExprKind::Lit(_))),
535 traits::ObligationCause::misc(span, self.body_id)
537 obligations.extend(traits::predicates_for_generics(cause.clone(), self.param_env, bounds));
539 // Also add an obligation for the method type being well-formed.
540 let method_ty = tcx.mk_fn_ptr(ty::Binder::dummy(fn_sig));
542 "lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
543 method_ty, obligation
545 obligations.push(traits::Obligation::new(
548 ty::Binder::dummy(ty::PredicateKind::WellFormed(method_ty.into())).to_predicate(tcx),
551 let callee = MethodCallee { def_id, substs, sig: fn_sig };
553 debug!("callee = {:?}", callee);
555 Some(InferOk { obligations, value: callee })
558 /// Performs a [full-qualified function call] (formerly "universal function call") lookup. If
559 /// lookup is successful, it will return the type of definition and the [`DefId`] of the found
560 /// function definition.
562 /// [full-qualified function call]: https://doc.rust-lang.org/reference/expressions/call-expr.html#disambiguating-function-calls
566 /// Given a function call like `Foo::bar::<T1,...Tn>(...)`:
568 /// * `self`: the surrounding `FnCtxt` (!)
569 /// * `span`: the span of the call, excluding arguments (`Foo::bar::<T1, ...Tn>`)
570 /// * `method_name`: the identifier of the function within the container type (`bar`)
571 /// * `self_ty`: the type to search within (`Foo`)
572 /// * `self_ty_span` the span for the type being searched within (span of `Foo`)
573 /// * `expr_id`: the [`hir::HirId`] of the expression composing the entire call
574 #[instrument(level = "debug", skip(self))]
575 pub fn resolve_fully_qualified_call(
582 ) -> Result<(DefKind, DefId), MethodError<'tcx>> {
584 "resolve_fully_qualified_call: method_name={:?} self_ty={:?} expr_id={:?}",
585 method_name, self_ty, expr_id,
590 // Check if we have an enum variant.
591 if let ty::Adt(adt_def, _) = self_ty.kind() {
592 if adt_def.is_enum() {
593 let variant_def = adt_def
596 .find(|vd| tcx.hygienic_eq(method_name, vd.ident(tcx), adt_def.did()));
597 if let Some(variant_def) = variant_def {
598 // Braced variants generate unusable names in value namespace (reserved for
599 // possible future use), so variants resolved as associated items may refer to
600 // them as well. It's ok to use the variant's id as a ctor id since an
601 // error will be reported on any use of such resolution anyway.
602 let ctor_def_id = variant_def.ctor_def_id.unwrap_or(variant_def.def_id);
603 tcx.check_stability(ctor_def_id, Some(expr_id), span, Some(method_name.span));
605 DefKind::Ctor(CtorOf::Variant, variant_def.ctor_kind),
612 let pick = self.probe_for_name(
619 ProbeScope::TraitsInScope,
622 self.lint_fully_qualified_call_from_2018(
631 debug!("resolve_fully_qualified_call: pick={:?}", pick);
633 let mut typeck_results = self.typeck_results.borrow_mut();
634 let used_trait_imports = Lrc::get_mut(&mut typeck_results.used_trait_imports).unwrap();
635 for import_id in pick.import_ids {
636 debug!("resolve_fully_qualified_call: used_trait_import: {:?}", import_id);
637 used_trait_imports.insert(import_id);
641 let def_kind = pick.item.kind.as_def_kind();
643 "resolve_fully_qualified_call: def_kind={:?}, def_id={:?}",
644 def_kind, pick.item.def_id
646 tcx.check_stability(pick.item.def_id, Some(expr_id), span, Some(method_name.span));
647 Ok((def_kind, pick.item.def_id))
650 /// Finds item with name `item_name` defined in impl/trait `def_id`
651 /// and return it, or `None`, if no such item was defined there.
652 pub fn associated_value(&self, def_id: DefId, item_name: Ident) -> Option<ty::AssocItem> {
654 .associated_items(def_id)
655 .find_by_name_and_namespace(self.tcx, item_name, Namespace::ValueNS, def_id)