1 //! Method lookup: the secret sauce of Rust. See the [rustc guide] for more information.
3 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/method-lookup.html
9 pub use self::suggest::{SelfSource, TraitInfo};
10 pub use self::CandidateSource::*;
11 pub use self::MethodError::*;
13 use crate::check::FnCtxt;
14 use crate::namespace::Namespace;
15 use errors::{Applicability, DiagnosticBuilder};
17 use rustc::hir::def::{CtorOf, DefKind};
18 use rustc::hir::def_id::DefId;
19 use rustc::infer::{self, InferOk};
21 use rustc::ty::subst::Subst;
22 use rustc::ty::subst::{InternalSubsts, SubstsRef};
23 use rustc::ty::GenericParamDefKind;
24 use rustc::ty::{self, ToPolyTraitRef, ToPredicate, TraitRef, Ty, TypeFoldable};
25 use rustc_data_structures::sync::Lrc;
29 use self::probe::{IsSuggestion, ProbeScope};
31 pub fn provide(providers: &mut ty::query::Providers<'_>) {
32 suggest::provide(providers);
33 probe::provide(providers);
36 #[derive(Clone, Copy, Debug)]
37 pub struct MethodCallee<'tcx> {
38 /// Impl method ID, for inherent methods, or trait method ID, otherwise.
40 pub substs: SubstsRef<'tcx>,
42 /// Instantiated method signature, i.e., it has been
43 /// substituted, normalized, and has had late-bound
44 /// lifetimes replaced with inference variables.
45 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, also the caller may have
60 // forgotten to import a trait.
61 IllegalSizedBound(Vec<DefId>, bool),
63 // Found a match, but the return type is wrong
67 // Contains a list of static methods that may apply, a list of unsatisfied trait predicates which
68 // 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: Vec<TraitRef<'tcx>>,
72 pub out_of_scope_traits: Vec<DefId>,
73 pub lev_candidate: Option<ty::AssocItem>,
74 pub mode: probe::Mode,
77 impl<'tcx> NoMatchData<'tcx> {
79 static_candidates: Vec<CandidateSource>,
80 unsatisfied_predicates: Vec<TraitRef<'tcx>>,
81 out_of_scope_traits: Vec<DefId>,
82 lev_candidate: Option<ty::AssocItem>,
87 unsatisfied_predicates,
95 // A pared down enum describing just the places from which a method
96 // candidate can arise. Used for error reporting only.
97 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
98 pub enum CandidateSource {
100 TraitSource(DefId /* trait id */),
103 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
104 /// Determines whether the type `self_ty` supports a method name `method_name` or not.
105 pub fn method_exists(
107 method_name: ast::Ident,
109 call_expr_id: hir::HirId,
112 let mode = probe::Mode::MethodCall;
113 match self.probe_for_name(
120 ProbeScope::TraitsInScope,
123 Err(NoMatch(..)) => false,
124 Err(Ambiguity(..)) => true,
125 Err(PrivateMatch(..)) => allow_private,
126 Err(IllegalSizedBound(..)) => true,
127 Err(BadReturnType) => bug!("no return type expectations but got BadReturnType"),
131 /// Adds a suggestion to call the given method to the provided diagnostic.
132 crate fn suggest_method_call(
134 err: &mut DiagnosticBuilder<'a>,
136 method_name: ast::Ident,
138 call_expr_id: hir::HirId,
140 let has_params = self
143 probe::Mode::MethodCall,
148 ProbeScope::TraitsInScope,
151 let sig = self.tcx.fn_sig(pick.item.def_id);
152 Ok(sig.inputs().skip_binder().len() > 1)
155 let (suggestion, applicability) = if has_params.unwrap_or_default() {
156 (format!("{}(...)", method_name), Applicability::HasPlaceholders)
158 (format!("{}()", method_name), Applicability::MaybeIncorrect)
161 err.span_suggestion(method_name.span, msg, suggestion, applicability);
164 /// Performs method lookup. If lookup is successful, it will return the callee
165 /// and store an appropriate adjustment for the self-expr. In some cases it may
166 /// report an error (e.g., invoking the `drop` method).
170 /// Given a method call like `foo.bar::<T1,...Tn>(...)`:
172 /// * `fcx`: the surrounding `FnCtxt` (!)
173 /// * `span`: the span for the method call
174 /// * `method_name`: the name of the method being called (`bar`)
175 /// * `self_ty`: the (unadjusted) type of the self expression (`foo`)
176 /// * `supplied_method_types`: the explicit method type parameters, if any (`T1..Tn`)
177 /// * `self_expr`: the self expression (`foo`)
178 pub fn lookup_method(
181 segment: &hir::PathSegment,
183 call_expr: &'tcx hir::Expr,
184 self_expr: &'tcx hir::Expr,
185 ) -> Result<MethodCallee<'tcx>, MethodError<'tcx>> {
187 "lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
188 segment.ident, self_ty, call_expr, self_expr
192 self.lookup_probe(span, segment.ident, self_ty, call_expr, ProbeScope::TraitsInScope)?;
194 for import_id in &pick.import_ids {
195 let import_def_id = self.tcx.hir().local_def_id(*import_id);
196 debug!("used_trait_import: {:?}", import_def_id);
197 Lrc::get_mut(&mut self.tables.borrow_mut().used_trait_imports)
199 .insert(import_def_id);
202 self.tcx.check_stability(pick.item.def_id, Some(call_expr.hir_id), span);
205 self.confirm_method(span, self_expr, call_expr, self_ty, pick.clone(), segment);
207 if result.illegal_sized_bound {
208 let mut needs_mut = false;
209 if let ty::Ref(region, t_type, mutability) = self_ty.kind {
210 let trait_type = self
212 .mk_ref(region, ty::TypeAndMut { ty: t_type, mutbl: mutability.invert() });
213 // We probe again to see if there might be a borrow mutability discrepancy.
214 match self.lookup_probe(
219 ProbeScope::TraitsInScope,
221 Ok(ref new_pick) if *new_pick != pick => {
228 // We probe again, taking all traits into account (not only those in scope).
229 let candidates = match self.lookup_probe(
234 ProbeScope::AllTraits,
236 // If we find a different result the caller probably forgot to import a trait.
237 Ok(ref new_pick) if *new_pick != pick => vec![new_pick.item.container.id()],
238 Err(Ambiguity(ref sources)) => sources
240 .filter_map(|source| {
242 // Note: this cannot come from an inherent impl,
243 // because the first probing succeeded.
244 ImplSource(def) => self.tcx.trait_id_of_impl(def),
245 TraitSource(_) => None,
252 return Err(IllegalSizedBound(candidates, needs_mut));
261 method_name: ast::Ident,
263 call_expr: &'tcx hir::Expr,
265 ) -> probe::PickResult<'tcx> {
266 let mode = probe::Mode::MethodCall;
267 let self_ty = self.resolve_vars_if_possible(&self_ty);
279 /// `lookup_method_in_trait` is used for overloaded operators.
280 /// It does a very narrow slice of what the normal probe/confirm path does.
281 /// In particular, it doesn't really do any probing: it simply constructs
282 /// an obligation for a particular trait with the given self type and checks
283 /// whether that trait is implemented.
285 // FIXME(#18741): it seems likely that we can consolidate some of this
286 // code with the other method-lookup code. In particular, the second half
287 // of this method is basically the same as confirmation.
288 pub fn lookup_method_in_trait(
294 opt_input_types: Option<&[Ty<'tcx>]>,
295 ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
297 "lookup_in_trait_adjusted(self_ty={:?}, \
298 m_name={}, trait_def_id={:?})",
299 self_ty, m_name, trait_def_id
302 // Construct a trait-reference `self_ty : Trait<input_tys>`
303 let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| {
305 GenericParamDefKind::Lifetime | GenericParamDefKind::Const => {}
306 GenericParamDefKind::Type { .. } => {
307 if param.index == 0 {
308 return self_ty.into();
309 } else if let Some(ref input_types) = opt_input_types {
310 return input_types[param.index as usize - 1].into();
314 self.var_for_def(span, param)
317 let trait_ref = ty::TraitRef::new(trait_def_id, substs);
319 // Construct an obligation
320 let poly_trait_ref = trait_ref.to_poly_trait_ref();
321 let obligation = traits::Obligation::misc(
325 poly_trait_ref.to_predicate(),
328 // Now we want to know if this can be matched
329 if !self.predicate_may_hold(&obligation) {
330 debug!("--> Cannot match obligation");
331 return None; // Cannot be matched, no such method resolution is possible.
334 // Trait must have a method named `m_name` and it should not have
335 // type parameters or early-bound regions.
337 let method_item = match self.associated_item(trait_def_id, m_name, Namespace::Value) {
338 Some(method_item) => method_item,
340 tcx.sess.delay_span_bug(
342 "operator trait does not have corresponding operator method",
347 let def_id = method_item.def_id;
348 let generics = tcx.generics_of(def_id);
349 assert_eq!(generics.params.len(), 0);
351 debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
352 let mut obligations = vec![];
354 // Instantiate late-bound regions and substitute the trait
355 // parameters into the method type to get the actual method type.
357 // N.B., instantiate late-bound regions first so that
358 // `instantiate_type_scheme` can normalize associated types that
359 // may reference those regions.
360 let fn_sig = tcx.fn_sig(def_id);
361 let fn_sig = self.replace_bound_vars_with_fresh_vars(span, infer::FnCall, &fn_sig).0;
362 let fn_sig = fn_sig.subst(self.tcx, substs);
363 let fn_sig = match self.normalize_associated_types_in_as_infer_ok(span, &fn_sig) {
364 InferOk { value, obligations: o } => {
365 obligations.extend(o);
370 // Register obligations for the parameters. This will include the
371 // `Self` parameter, which in turn has a bound of the main trait,
372 // so this also effectively registers `obligation` as well. (We
373 // used to register `obligation` explicitly, but that resulted in
374 // double error messages being reported.)
376 // Note that as the method comes from a trait, it should not have
377 // any late-bound regions appearing in its bounds.
378 let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
379 let bounds = match self.normalize_associated_types_in_as_infer_ok(span, &bounds) {
380 InferOk { value, obligations: o } => {
381 obligations.extend(o);
385 assert!(!bounds.has_escaping_bound_vars());
387 let cause = traits::ObligationCause::misc(span, self.body_id);
388 obligations.extend(traits::predicates_for_generics(cause.clone(), self.param_env, &bounds));
390 // Also add an obligation for the method type being well-formed.
391 let method_ty = tcx.mk_fn_ptr(ty::Binder::bind(fn_sig));
393 "lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
394 method_ty, obligation
396 obligations.push(traits::Obligation::new(
399 ty::Predicate::WellFormed(method_ty),
402 let callee = MethodCallee { def_id, substs: trait_ref.substs, sig: fn_sig };
404 debug!("callee = {:?}", callee);
406 Some(InferOk { obligations, value: callee })
412 method_name: ast::Ident,
415 ) -> Result<(DefKind, DefId), MethodError<'tcx>> {
417 "resolve_ufcs: method_name={:?} self_ty={:?} expr_id={:?}",
418 method_name, self_ty, expr_id,
423 // Check if we have an enum variant.
424 if let ty::Adt(adt_def, _) = self_ty.kind {
425 if adt_def.is_enum() {
426 let variant_def = adt_def
429 .find(|vd| tcx.hygienic_eq(method_name, vd.ident, adt_def.did));
430 if let Some(variant_def) = variant_def {
431 // Braced variants generate unusable names in value namespace (reserved for
432 // possible future use), so variants resolved as associated items may refer to
433 // them as well. It's ok to use the variant's id as a ctor id since an
434 // error will be reported on any use of such resolution anyway.
435 let ctor_def_id = variant_def.ctor_def_id.unwrap_or(variant_def.def_id);
436 tcx.check_stability(ctor_def_id, Some(expr_id), span);
438 DefKind::Ctor(CtorOf::Variant, variant_def.ctor_kind),
445 let pick = self.probe_for_name(
452 ProbeScope::TraitsInScope,
454 debug!("resolve_ufcs: pick={:?}", pick);
455 for import_id in pick.import_ids {
456 let import_def_id = tcx.hir().local_def_id(import_id);
457 debug!("resolve_ufcs: used_trait_import: {:?}", import_def_id);
458 Lrc::get_mut(&mut self.tables.borrow_mut().used_trait_imports)
460 .insert(import_def_id);
463 let def_kind = pick.item.def_kind();
464 debug!("resolve_ufcs: def_kind={:?}, def_id={:?}", def_kind, pick.item.def_id);
465 tcx.check_stability(pick.item.def_id, Some(expr_id), span);
466 Ok((def_kind, pick.item.def_id))
469 /// Finds item with name `item_name` defined in impl/trait `def_id`
470 /// and return it, or `None`, if no such item was defined there.
471 pub fn associated_item(
474 item_name: ast::Ident,
476 ) -> Option<ty::AssocItem> {
477 self.tcx.associated_items(def_id).find(|item| {
478 Namespace::from(item.kind) == ns && self.tcx.hygienic_eq(item_name, item.ident, def_id)