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::errors::OpMethodGenericParams;
14 use crate::{Expectation, FnCtxt};
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::traits::ObligationCause;
22 use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
23 use rustc_middle::ty::{self, GenericParamDefKind, Ty, TypeVisitable};
24 use rustc_span::symbol::Ident;
26 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
27 use rustc_trait_selection::traits::{self, NormalizeExt};
29 use self::probe::{IsSuggestion, ProbeScope};
31 pub fn provide(providers: &mut ty::query::Providers) {
32 probe::provide(providers);
35 #[derive(Clone, Copy, Debug)]
36 pub struct MethodCallee<'tcx> {
37 /// Impl method ID, for inherent methods, or trait method ID, otherwise.
39 pub substs: SubstsRef<'tcx>,
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>,
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>),
52 // Multiple methods might apply.
53 Ambiguity(Vec<CandidateSource>),
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>),
59 // Found a `Self: Sized` bound where `Self` is a trait object.
60 IllegalSizedBound(Vec<DefId>, bool, Span),
62 // Found a match, but the return type is wrong
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.
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,
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 {
83 Trait(DefId /* trait id */),
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))]
93 call_expr_id: hir::HirId,
96 match self.probe_for_name(
97 probe::Mode::MethodCall,
102 ProbeScope::TraitsInScope,
105 pick.maybe_emit_unstable_name_collision_hint(
112 Err(NoMatch(..)) => false,
113 Err(Ambiguity(..)) => true,
114 Err(PrivateMatch(..)) => allow_private,
115 Err(IllegalSizedBound(..)) => true,
116 Err(BadReturnType) => bug!("no return type expectations but got BadReturnType"),
120 /// Adds a suggestion to call the given method to the provided diagnostic.
121 #[instrument(level = "debug", skip(self, err, call_expr))]
122 pub(crate) fn suggest_method_call(
124 err: &mut Diagnostic,
128 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))]
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 self.lookup_probe(segment.ident, self_ty, call_expr, ProbeScope::TraitsInScope)?;
184 self.lint_dot_call_from_2018(self_ty, segment, span, call_expr, self_expr, &pick, args);
186 for import_id in &pick.import_ids {
187 debug!("used_trait_import: {:?}", import_id);
188 Lrc::get_mut(&mut self.typeck_results.borrow_mut().used_trait_imports)
193 self.tcx.check_stability(pick.item.def_id, Some(call_expr.hir_id), span, None);
195 let result = self.confirm_method(span, self_expr, call_expr, self_ty, &pick, segment);
196 debug!("result = {:?}", result);
198 if let Some(span) = result.illegal_sized_bound {
199 let mut needs_mut = false;
200 if let ty::Ref(region, t_type, mutability) = self_ty.kind() {
201 let trait_type = self
203 .mk_ref(*region, ty::TypeAndMut { ty: *t_type, mutbl: mutability.invert() });
204 // We probe again to see if there might be a borrow mutability discrepancy.
205 match self.lookup_probe(
209 ProbeScope::TraitsInScope,
211 Ok(ref new_pick) if pick.differs_from(new_pick) => {
212 needs_mut = new_pick.self_ty.ref_mutability() != self_ty.ref_mutability();
218 // We probe again, taking all traits into account (not only those in scope).
220 match self.lookup_probe(segment.ident, self_ty, call_expr, ProbeScope::AllTraits) {
221 // If we find a different result the caller probably forgot to import a trait.
222 Ok(ref new_pick) if pick.differs_from(new_pick) => {
223 vec![new_pick.item.container_id(self.tcx)]
225 Err(Ambiguity(ref sources)) => sources
227 .filter_map(|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,
239 return Err(IllegalSizedBound(candidates, needs_mut, span));
245 #[instrument(level = "debug", skip(self, call_expr))]
250 call_expr: &'tcx hir::Expr<'tcx>,
252 ) -> probe::PickResult<'tcx> {
253 let pick = self.probe_for_name(
254 probe::Mode::MethodCall,
261 pick.maybe_emit_unstable_name_collision_hint(self.tcx, method_name.span, call_expr.hir_id);
265 pub(super) fn obligation_for_method(
270 opt_input_types: Option<&[Ty<'tcx>]>,
271 ) -> (traits::Obligation<'tcx, ty::Predicate<'tcx>>, &'tcx ty::List<ty::subst::GenericArg<'tcx>>)
273 // Construct a trait-reference `self_ty : Trait<input_tys>`
274 let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
276 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => {}
277 GenericParamDefKind::Type { .. } => {
278 if param.index == 0 {
279 return self_ty.into();
280 } else if let Some(input_types) = opt_input_types {
281 return input_types[param.index as usize - 1].into();
285 self.var_for_def(span, param)
288 let trait_ref = self.tcx.mk_trait_ref(trait_def_id, substs);
290 // Construct an obligation
291 let poly_trait_ref = ty::Binder::dummy(trait_ref);
293 traits::Obligation::misc(
298 poly_trait_ref.without_const(),
304 pub(super) fn obligation_for_op_method(
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>>)
314 // Construct a trait-reference `self_ty : Trait<input_tys>`
315 let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
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();
326 self.var_for_def(span, param)
329 let trait_ref = self.tcx.mk_trait_ref(trait_def_id, substs);
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));
336 traits::Obligation::new(
338 traits::ObligationCause::new(
342 rhs_span: opt_input_expr.map(|expr| expr.span),
343 is_lit: opt_input_expr
344 .map_or(false, |expr| matches!(expr.kind, hir::ExprKind::Lit(_))),
355 /// `lookup_method_in_trait` is used for overloaded operators.
356 /// It does a very narrow slice of what the normal probe/confirm path does.
357 /// In particular, it doesn't really do any probing: it simply constructs
358 /// an obligation for a particular trait with the given self type and checks
359 /// whether that trait is implemented.
360 #[instrument(level = "debug", skip(self, span))]
361 pub(super) fn lookup_method_in_trait(
367 opt_input_types: Option<&[Ty<'tcx>]>,
368 ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
369 let (obligation, substs) =
370 self.obligation_for_method(span, trait_def_id, self_ty, opt_input_types);
371 self.construct_obligation_for_trait(
382 pub(super) fn lookup_op_method_in_trait(
388 opt_input_type: Option<Ty<'tcx>>,
389 opt_input_expr: Option<&'tcx hir::Expr<'tcx>>,
390 expected: Expectation<'tcx>,
391 ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
392 let (obligation, substs) = self.obligation_for_op_method(
400 self.construct_obligation_for_trait(
411 // FIXME(#18741): it seems likely that we can consolidate some of this
412 // code with the other method-lookup code. In particular, the second half
413 // of this method is basically the same as confirmation.
414 fn construct_obligation_for_trait(
419 obligation: traits::PredicateObligation<'tcx>,
420 substs: &'tcx ty::List<ty::subst::GenericArg<'tcx>>,
421 opt_input_expr: Option<&'tcx hir::Expr<'tcx>>,
423 ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
426 // Now we want to know if this can be matched
427 if !self.predicate_may_hold(&obligation) {
428 debug!("--> Cannot match obligation");
429 // Cannot be matched, no such method resolution is possible.
433 // Trait must have a method named `m_name` and it should not have
434 // type parameters or early-bound regions.
436 let Some(method_item) = self.associated_value(trait_def_id, m_name) else {
437 tcx.sess.delay_span_bug(
439 "operator trait does not have corresponding operator method",
443 let def_id = method_item.def_id;
444 let generics = tcx.generics_of(def_id);
446 if generics.params.len() != 0 {
447 tcx.sess.emit_fatal(OpMethodGenericParams {
448 span: tcx.def_span(method_item.def_id),
449 method_name: m_name.to_string(),
453 debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
454 let mut obligations = vec![];
456 // Instantiate late-bound regions and substitute the trait
457 // parameters into the method type to get the actual method type.
459 // N.B., instantiate late-bound regions before normalizing the
460 // function signature so that normalization does not need to deal
461 // with bound regions.
462 let fn_sig = tcx.bound_fn_sig(def_id);
463 let fn_sig = fn_sig.subst(self.tcx, substs);
464 let fn_sig = self.replace_bound_vars_with_fresh_vars(span, infer::FnCall, fn_sig);
466 let cause = if is_op {
467 ObligationCause::new(
471 rhs_span: opt_input_expr.map(|expr| expr.span),
472 is_lit: opt_input_expr
473 .map_or(false, |expr| matches!(expr.kind, hir::ExprKind::Lit(_))),
478 traits::ObligationCause::misc(span, self.body_id)
481 let InferOk { value, obligations: o } = self.at(&cause, self.param_env).normalize(fn_sig);
483 obligations.extend(o);
487 // Register obligations for the parameters. This will include the
488 // `Self` parameter, which in turn has a bound of the main trait,
489 // so this also effectively registers `obligation` as well. (We
490 // used to register `obligation` explicitly, but that resulted in
491 // double error messages being reported.)
493 // Note that as the method comes from a trait, it should not have
494 // any late-bound regions appearing in its bounds.
495 let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
497 let InferOk { value, obligations: o } = self.at(&cause, self.param_env).normalize(bounds);
499 obligations.extend(o);
503 assert!(!bounds.has_escaping_bound_vars());
505 let predicates_cause = cause.clone();
506 obligations.extend(traits::predicates_for_generics(
507 move |_, _| predicates_cause.clone(),
512 // Also add an obligation for the method type being well-formed.
513 let method_ty = tcx.mk_fn_ptr(ty::Binder::dummy(fn_sig));
515 "lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
516 method_ty, obligation
518 obligations.push(traits::Obligation::new(
522 ty::Binder::dummy(ty::PredicateKind::WellFormed(method_ty.into())),
525 let callee = MethodCallee { def_id, substs, sig: fn_sig };
527 debug!("callee = {:?}", callee);
529 Some(InferOk { obligations, value: callee })
532 /// Performs a [full-qualified function call] (formerly "universal function call") lookup. If
533 /// lookup is successful, it will return the type of definition and the [`DefId`] of the found
534 /// function definition.
536 /// [full-qualified function call]: https://doc.rust-lang.org/reference/expressions/call-expr.html#disambiguating-function-calls
540 /// Given a function call like `Foo::bar::<T1,...Tn>(...)`:
542 /// * `self`: the surrounding `FnCtxt` (!)
543 /// * `span`: the span of the call, excluding arguments (`Foo::bar::<T1, ...Tn>`)
544 /// * `method_name`: the identifier of the function within the container type (`bar`)
545 /// * `self_ty`: the type to search within (`Foo`)
546 /// * `self_ty_span` the span for the type being searched within (span of `Foo`)
547 /// * `expr_id`: the [`hir::HirId`] of the expression composing the entire call
548 #[instrument(level = "debug", skip(self), ret)]
549 pub fn resolve_fully_qualified_call(
556 ) -> Result<(DefKind, DefId), MethodError<'tcx>> {
559 // Check if we have an enum variant.
560 let mut struct_variant = None;
561 if let ty::Adt(adt_def, _) = self_ty.kind() {
562 if adt_def.is_enum() {
563 let variant_def = adt_def
566 .find(|vd| tcx.hygienic_eq(method_name, vd.ident(tcx), adt_def.did()));
567 if let Some(variant_def) = variant_def {
568 if let Some((ctor_kind, ctor_def_id)) = variant_def.ctor {
573 Some(method_name.span),
575 return Ok((DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id));
577 struct_variant = Some((DefKind::Variant, variant_def.def_id));
583 let pick = self.probe_for_name(
589 ProbeScope::TraitsInScope,
591 let pick = match (pick, struct_variant) {
592 // Fall back to a resolution that will produce an error later.
593 (Err(_), Some(res)) => return Ok(res),
597 pick.maybe_emit_unstable_name_collision_hint(self.tcx, span, expr_id);
599 self.lint_fully_qualified_call_from_2018(
610 let mut typeck_results = self.typeck_results.borrow_mut();
611 let used_trait_imports = Lrc::get_mut(&mut typeck_results.used_trait_imports).unwrap();
612 for import_id in pick.import_ids {
613 debug!(used_trait_import=?import_id);
614 used_trait_imports.insert(import_id);
618 let def_kind = pick.item.kind.as_def_kind();
619 tcx.check_stability(pick.item.def_id, Some(expr_id), span, Some(method_name.span));
620 Ok((def_kind, pick.item.def_id))
623 /// Finds item with name `item_name` defined in impl/trait `def_id`
624 /// and return it, or `None`, if no such item was defined there.
625 pub fn associated_value(&self, def_id: DefId, item_name: Ident) -> Option<ty::AssocItem> {
627 .associated_items(def_id)
628 .find_by_name_and_namespace(self.tcx, item_name, Namespace::ValueNS, def_id)