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;
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.
61 candidates: Vec<DefId>,
64 self_expr: &'tcx hir::Expr<'tcx>,
67 // Found a match, but the return type is wrong
71 // Contains a list of static methods that may apply, a list of unsatisfied trait predicates which
72 // could lead to matches if satisfied, and a list of not-in-scope traits which may work.
74 pub struct NoMatchData<'tcx> {
75 pub static_candidates: Vec<CandidateSource>,
76 pub unsatisfied_predicates:
77 Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>,
78 pub out_of_scope_traits: Vec<DefId>,
79 pub similar_candidate: Option<ty::AssocItem>,
80 pub mode: probe::Mode,
83 // A pared down enum describing just the places from which a method
84 // candidate can arise. Used for error reporting only.
85 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
86 pub enum CandidateSource {
88 Trait(DefId /* trait id */),
91 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
92 /// Determines whether the type `self_ty` supports a method name `method_name` or not.
93 #[instrument(level = "debug", skip(self))]
98 call_expr_id: hir::HirId,
100 return_type: Option<Ty<'tcx>>,
102 match self.probe_for_name(
103 probe::Mode::MethodCall,
109 ProbeScope::TraitsInScope,
112 pick.maybe_emit_unstable_name_collision_hint(
119 Err(NoMatch(..)) => false,
120 Err(Ambiguity(..)) => true,
121 Err(PrivateMatch(..)) => allow_private,
122 Err(IllegalSizedBound { .. }) => true,
123 Err(BadReturnType) => false,
127 /// Adds a suggestion to call the given method to the provided diagnostic.
128 #[instrument(level = "debug", skip(self, err, call_expr))]
129 pub(crate) fn suggest_method_call(
131 err: &mut Diagnostic,
135 call_expr: &hir::Expr<'tcx>,
139 .lookup_probe_for_diagnostic(
143 ProbeScope::TraitsInScope,
147 let sig = self.tcx.fn_sig(pick.item.def_id);
148 sig.skip_binder().inputs().skip_binder().len().saturating_sub(1)
152 // Account for `foo.bar<T>`;
153 let sugg_span = span.unwrap_or(call_expr.span).shrink_to_hi();
154 let (suggestion, applicability) = (
155 format!("({})", (0..params).map(|_| "_").collect::<Vec<_>>().join(", ")),
156 if params > 0 { Applicability::HasPlaceholders } else { Applicability::MaybeIncorrect },
159 err.span_suggestion_verbose(sugg_span, msg, suggestion, applicability);
162 /// Performs method lookup. If lookup is successful, it will return the callee
163 /// and store an appropriate adjustment for the self-expr. In some cases it may
164 /// report an error (e.g., invoking the `drop` method).
168 /// Given a method call like `foo.bar::<T1,...Tn>(a, b + 1, ...)`:
170 /// * `self`: the surrounding `FnCtxt` (!)
171 /// * `self_ty`: the (unadjusted) type of the self expression (`foo`)
172 /// * `segment`: the name and generic arguments of the method (`bar::<T1, ...Tn>`)
173 /// * `span`: the span for the method call
174 /// * `call_expr`: the complete method call: (`foo.bar::<T1,...Tn>(...)`)
175 /// * `self_expr`: the self expression (`foo`)
176 /// * `args`: the expressions of the arguments (`a, b + 1, ...`)
177 #[instrument(level = "debug", skip(self))]
178 pub fn lookup_method(
181 segment: &hir::PathSegment<'_>,
183 call_expr: &'tcx hir::Expr<'tcx>,
184 self_expr: &'tcx hir::Expr<'tcx>,
185 args: &'tcx [hir::Expr<'tcx>],
186 ) -> Result<MethodCallee<'tcx>, MethodError<'tcx>> {
188 self.lookup_probe(segment.ident, self_ty, call_expr, ProbeScope::TraitsInScope)?;
190 self.lint_dot_call_from_2018(self_ty, segment, span, call_expr, self_expr, &pick, args);
192 for import_id in &pick.import_ids {
193 debug!("used_trait_import: {:?}", import_id);
194 Lrc::get_mut(&mut self.typeck_results.borrow_mut().used_trait_imports)
199 self.tcx.check_stability(pick.item.def_id, Some(call_expr.hir_id), span, None);
201 let result = self.confirm_method(span, self_expr, call_expr, self_ty, &pick, 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(
215 ProbeScope::TraitsInScope,
217 Ok(ref new_pick) if pick.differs_from(new_pick) => {
218 needs_mut = new_pick.self_ty.ref_mutability() != self_ty.ref_mutability();
224 // We probe again, taking all traits into account (not only those in scope).
225 let candidates = match self.lookup_probe_for_diagnostic(
229 ProbeScope::AllTraits,
232 // If we find a different result the caller probably forgot to import a trait.
233 Ok(ref new_pick) if pick.differs_from(new_pick) => {
234 vec![new_pick.item.container_id(self.tcx)]
236 Err(Ambiguity(ref sources)) => sources
238 .filter_map(|source| {
240 // Note: this cannot come from an inherent impl,
241 // because the first probing succeeded.
242 CandidateSource::Impl(def) => self.tcx.trait_id_of_impl(def),
243 CandidateSource::Trait(_) => None,
250 return Err(IllegalSizedBound { candidates, needs_mut, bound_span: span, self_expr });
256 #[instrument(level = "debug", skip(self, call_expr))]
261 call_expr: &hir::Expr<'_>,
263 ) -> probe::PickResult<'tcx> {
264 let pick = self.probe_for_name(
265 probe::Mode::MethodCall,
273 pick.maybe_emit_unstable_name_collision_hint(self.tcx, method_name.span, call_expr.hir_id);
277 pub fn lookup_probe_for_diagnostic(
281 call_expr: &hir::Expr<'_>,
283 return_type: Option<Ty<'tcx>>,
284 ) -> probe::PickResult<'tcx> {
285 let pick = self.probe_for_name(
286 probe::Mode::MethodCall,
297 pub(super) fn obligation_for_method(
299 cause: ObligationCause<'tcx>,
302 opt_input_types: Option<&[Ty<'tcx>]>,
303 ) -> (traits::Obligation<'tcx, ty::Predicate<'tcx>>, &'tcx ty::List<ty::subst::GenericArg<'tcx>>)
305 // Construct a trait-reference `self_ty : Trait<input_tys>`
306 let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
308 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => {}
309 GenericParamDefKind::Type { .. } => {
310 if param.index == 0 {
311 return self_ty.into();
312 } else if let Some(input_types) = opt_input_types {
313 return input_types[param.index as usize - 1].into();
317 self.var_for_def(cause.span, param)
320 let trait_ref = self.tcx.mk_trait_ref(trait_def_id, substs);
322 // Construct an obligation
323 let poly_trait_ref = ty::Binder::dummy(trait_ref);
325 traits::Obligation::new(
329 poly_trait_ref.without_const(),
335 /// `lookup_method_in_trait` is used for overloaded operators.
336 /// It does a very narrow slice of what the normal probe/confirm path does.
337 /// In particular, it doesn't really do any probing: it simply constructs
338 /// an obligation for a particular trait with the given self type and checks
339 /// whether that trait is implemented.
340 #[instrument(level = "debug", skip(self))]
341 pub(super) fn lookup_method_in_trait(
343 cause: ObligationCause<'tcx>,
347 opt_input_types: Option<&[Ty<'tcx>]>,
348 ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
349 let (obligation, substs) =
350 self.obligation_for_method(cause, trait_def_id, self_ty, opt_input_types);
351 self.construct_obligation_for_trait(m_name, trait_def_id, obligation, substs)
354 // FIXME(#18741): it seems likely that we can consolidate some of this
355 // code with the other method-lookup code. In particular, the second half
356 // of this method is basically the same as confirmation.
357 fn construct_obligation_for_trait(
361 obligation: traits::PredicateObligation<'tcx>,
362 substs: &'tcx ty::List<ty::subst::GenericArg<'tcx>>,
363 ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
366 // Now we want to know if this can be matched
367 if !self.predicate_may_hold(&obligation) {
368 debug!("--> Cannot match obligation");
369 // Cannot be matched, no such method resolution is possible.
373 // Trait must have a method named `m_name` and it should not have
374 // type parameters or early-bound regions.
376 let Some(method_item) = self.associated_value(trait_def_id, m_name) else {
377 tcx.sess.delay_span_bug(
378 obligation.cause.span,
379 "operator trait does not have corresponding operator method",
383 let def_id = method_item.def_id;
384 let generics = tcx.generics_of(def_id);
386 if generics.params.len() != 0 {
387 tcx.sess.emit_fatal(OpMethodGenericParams {
388 span: tcx.def_span(method_item.def_id),
389 method_name: m_name.to_string(),
393 debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
394 let mut obligations = vec![];
396 // Instantiate late-bound regions and substitute the trait
397 // parameters into the method type to get the actual method type.
399 // N.B., instantiate late-bound regions before normalizing the
400 // function signature so that normalization does not need to deal
401 // with bound regions.
402 let fn_sig = tcx.fn_sig(def_id).subst(self.tcx, substs);
404 self.replace_bound_vars_with_fresh_vars(obligation.cause.span, infer::FnCall, fn_sig);
406 let InferOk { value, obligations: o } =
407 self.at(&obligation.cause, self.param_env).normalize(fn_sig);
409 obligations.extend(o);
413 // Register obligations for the parameters. This will include the
414 // `Self` parameter, which in turn has a bound of the main trait,
415 // so this also effectively registers `obligation` as well. (We
416 // used to register `obligation` explicitly, but that resulted in
417 // double error messages being reported.)
419 // Note that as the method comes from a trait, it should not have
420 // any late-bound regions appearing in its bounds.
421 let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
423 let InferOk { value, obligations: o } =
424 self.at(&obligation.cause, self.param_env).normalize(bounds);
426 obligations.extend(o);
430 assert!(!bounds.has_escaping_bound_vars());
432 let predicates_cause = obligation.cause.clone();
433 obligations.extend(traits::predicates_for_generics(
434 move |_, _| predicates_cause.clone(),
439 // Also add an obligation for the method type being well-formed.
440 let method_ty = tcx.mk_fn_ptr(ty::Binder::dummy(fn_sig));
442 "lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
443 method_ty, obligation
445 obligations.push(traits::Obligation::new(
449 ty::Binder::dummy(ty::PredicateKind::WellFormed(method_ty.into())),
452 let callee = MethodCallee { def_id, substs, sig: fn_sig };
454 debug!("callee = {:?}", callee);
456 Some(InferOk { obligations, value: callee })
459 /// Performs a [full-qualified function call] (formerly "universal function call") lookup. If
460 /// lookup is successful, it will return the type of definition and the [`DefId`] of the found
461 /// function definition.
463 /// [full-qualified function call]: https://doc.rust-lang.org/reference/expressions/call-expr.html#disambiguating-function-calls
467 /// Given a function call like `Foo::bar::<T1,...Tn>(...)`:
469 /// * `self`: the surrounding `FnCtxt` (!)
470 /// * `span`: the span of the call, excluding arguments (`Foo::bar::<T1, ...Tn>`)
471 /// * `method_name`: the identifier of the function within the container type (`bar`)
472 /// * `self_ty`: the type to search within (`Foo`)
473 /// * `self_ty_span` the span for the type being searched within (span of `Foo`)
474 /// * `expr_id`: the [`hir::HirId`] of the expression composing the entire call
475 #[instrument(level = "debug", skip(self), ret)]
476 pub fn resolve_fully_qualified_call(
483 ) -> Result<(DefKind, DefId), MethodError<'tcx>> {
486 // Check if we have an enum variant.
487 let mut struct_variant = None;
488 if let ty::Adt(adt_def, _) = self_ty.kind() {
489 if adt_def.is_enum() {
490 let variant_def = adt_def
493 .find(|vd| tcx.hygienic_eq(method_name, vd.ident(tcx), adt_def.did()));
494 if let Some(variant_def) = variant_def {
495 if let Some((ctor_kind, ctor_def_id)) = variant_def.ctor {
500 Some(method_name.span),
502 return Ok((DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id));
504 struct_variant = Some((DefKind::Variant, variant_def.def_id));
510 let pick = self.probe_for_name(
517 ProbeScope::TraitsInScope,
519 let pick = match (pick, struct_variant) {
520 // Fall back to a resolution that will produce an error later.
521 (Err(_), Some(res)) => return Ok(res),
525 pick.maybe_emit_unstable_name_collision_hint(self.tcx, span, expr_id);
527 self.lint_fully_qualified_call_from_2018(
538 let mut typeck_results = self.typeck_results.borrow_mut();
539 let used_trait_imports = Lrc::get_mut(&mut typeck_results.used_trait_imports).unwrap();
540 for import_id in pick.import_ids {
541 debug!(used_trait_import=?import_id);
542 used_trait_imports.insert(import_id);
546 let def_kind = pick.item.kind.as_def_kind();
547 tcx.check_stability(pick.item.def_id, Some(expr_id), span, Some(method_name.span));
548 Ok((def_kind, pick.item.def_id))
551 /// Finds item with name `item_name` defined in impl/trait `def_id`
552 /// and return it, or `None`, if no such item was defined there.
553 pub fn associated_value(&self, def_id: DefId, item_name: Ident) -> Option<ty::AssocItem> {
555 .associated_items(def_id)
556 .find_by_name_and_namespace(self.tcx, item_name, Namespace::ValueNS, def_id)