1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Method lookup: the secret sauce of Rust. See `README.md`.
15 use hir::def_id::DefId;
16 use rustc::ty::subst::Substs;
18 use rustc::ty::{self, ToPredicate, ToPolyTraitRef, TraitRef, TypeFoldable};
19 use rustc::ty::subst::Subst;
20 use rustc::infer::{self, InferOk};
27 pub use self::MethodError::*;
28 pub use self::CandidateSource::*;
34 use self::probe::{IsSuggestion, ProbeScope};
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: &'tcx Substs<'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 second argument contains a list of
56 // not-in-scope traits which may work.
57 PrivateMatch(Def, 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>),
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 mode: probe::Mode,
76 impl<'tcx> NoMatchData<'tcx> {
77 pub fn new(static_candidates: Vec<CandidateSource>,
78 unsatisfied_predicates: Vec<TraitRef<'tcx>>,
79 out_of_scope_traits: Vec<DefId>,
84 unsatisfied_predicates,
91 // A pared down enum describing just the places from which a method
92 // candidate can arise. Used for error reporting only.
93 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
94 pub enum CandidateSource {
96 TraitSource(// trait id
100 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
101 /// Determines whether the type `self_ty` supports a method name `method_name` or not.
102 pub fn method_exists(&self,
104 method_name: ast::Name,
105 self_ty: ty::Ty<'tcx>,
106 call_expr_id: ast::NodeId,
109 let mode = probe::Mode::MethodCall;
110 match self.probe_for_name(span, mode, method_name, IsSuggestion(false),
111 self_ty, call_expr_id, ProbeScope::TraitsInScope) {
113 Err(NoMatch(..)) => false,
114 Err(Ambiguity(..)) => true,
115 Err(PrivateMatch(..)) => allow_private,
116 Err(IllegalSizedBound(..)) => true,
117 Err(BadReturnType) => {
118 bug!("no return type expectations but got BadReturnType")
124 /// Performs method lookup. If lookup is successful, it will return the callee
125 /// and store an appropriate adjustment for the self-expr. In some cases it may
126 /// report an error (e.g., invoking the `drop` method).
130 /// Given a method call like `foo.bar::<T1,...Tn>(...)`:
132 /// * `fcx`: the surrounding `FnCtxt` (!)
133 /// * `span`: the span for the method call
134 /// * `method_name`: the name of the method being called (`bar`)
135 /// * `self_ty`: the (unadjusted) type of the self expression (`foo`)
136 /// * `supplied_method_types`: the explicit method type parameters, if any (`T1..Tn`)
137 /// * `self_expr`: the self expression (`foo`)
138 pub fn lookup_method(&self,
139 self_ty: ty::Ty<'tcx>,
140 segment: &hir::PathSegment,
142 call_expr: &'gcx hir::Expr,
143 self_expr: &'gcx hir::Expr)
144 -> Result<MethodCallee<'tcx>, MethodError<'tcx>> {
145 debug!("lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
151 let pick = self.lookup_probe(
156 ProbeScope::TraitsInScope
159 if let Some(import_id) = pick.import_id {
160 let import_def_id = self.tcx.hir.local_def_id(import_id);
161 debug!("used_trait_import: {:?}", import_def_id);
162 self.tables.borrow_mut().used_trait_imports.insert(import_def_id);
165 self.tcx.check_stability(pick.item.def_id, call_expr.id, span);
167 let result = self.confirm_method(span,
174 if result.illegal_sized_bound {
175 // We probe again, taking all traits into account (not only those in scope).
177 match self.lookup_probe(span,
181 ProbeScope::AllTraits) {
183 // If we find a different result the caller probably forgot to import a trait.
184 Ok(ref new_pick) if *new_pick != pick => vec![new_pick.item.container.id()],
185 Err(Ambiguity(ref sources)) => {
187 .filter_map(|source| {
189 // Note: this cannot come from an inherent impl,
190 // because the first probing succeeded.
191 ImplSource(def) => self.tcx.trait_id_of_impl(def),
192 TraitSource(_) => None,
200 return Err(IllegalSizedBound(candidates));
206 fn lookup_probe(&self,
208 method_name: ast::Name,
209 self_ty: ty::Ty<'tcx>,
210 call_expr: &'gcx hir::Expr,
212 -> probe::PickResult<'tcx> {
213 let mode = probe::Mode::MethodCall;
214 let self_ty = self.resolve_type_vars_if_possible(&self_ty);
215 self.probe_for_name(span, mode, method_name, IsSuggestion(false),
216 self_ty, call_expr.id, scope)
219 /// `lookup_method_in_trait` is used for overloaded operators.
220 /// It does a very narrow slice of what the normal probe/confirm path does.
221 /// In particular, it doesn't really do any probing: it simply constructs
222 /// an obligation for a particular trait with the given self-type and checks
223 /// whether that trait is implemented.
225 /// FIXME(#18741) -- It seems likely that we can consolidate some of this
226 /// code with the other method-lookup code. In particular, the second half
227 /// of this method is basically the same as confirmation.
228 pub fn lookup_method_in_trait(&self,
232 self_ty: ty::Ty<'tcx>,
233 opt_input_types: Option<&[ty::Ty<'tcx>]>)
234 -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
235 debug!("lookup_in_trait_adjusted(self_ty={:?}, \
236 m_name={}, trait_def_id={:?})",
241 // Construct a trait-reference `self_ty : Trait<input_tys>`
242 let substs = Substs::for_item(self.tcx,
244 |def, _| self.region_var_for_def(span, def),
248 } else if let Some(ref input_types) = opt_input_types {
249 input_types[def.index as usize - 1]
251 self.type_var_for_def(span, def, substs)
255 let trait_ref = ty::TraitRef::new(trait_def_id, substs);
257 // Construct an obligation
258 let poly_trait_ref = trait_ref.to_poly_trait_ref();
260 traits::Obligation::misc(span,
263 poly_trait_ref.to_predicate());
265 // Now we want to know if this can be matched
266 let mut selcx = traits::SelectionContext::new(self);
267 if !selcx.evaluate_obligation(&obligation) {
268 debug!("--> Cannot match obligation");
269 return None; // Cannot be matched, no such method resolution is possible.
272 // Trait must have a method named `m_name` and it should not have
273 // type parameters or early-bound regions.
275 let method_item = self.associated_item(trait_def_id, m_name).unwrap();
276 let def_id = method_item.def_id;
277 let generics = tcx.generics_of(def_id);
278 assert_eq!(generics.types.len(), 0);
279 assert_eq!(generics.regions.len(), 0);
281 debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
282 let mut obligations = vec![];
284 // Instantiate late-bound regions and substitute the trait
285 // parameters into the method type to get the actual method type.
287 // NB: Instantiate late-bound regions first so that
288 // `instantiate_type_scheme` can normalize associated types that
289 // may reference those regions.
290 let fn_sig = tcx.fn_sig(def_id);
291 let fn_sig = self.replace_late_bound_regions_with_fresh_var(span,
294 let fn_sig = fn_sig.subst(self.tcx, substs);
295 let fn_sig = match self.normalize_associated_types_in_as_infer_ok(span, &fn_sig) {
296 InferOk { value, obligations: o } => {
297 obligations.extend(o);
302 // Register obligations for the parameters. This will include the
303 // `Self` parameter, which in turn has a bound of the main trait,
304 // so this also effectively registers `obligation` as well. (We
305 // used to register `obligation` explicitly, but that resulted in
306 // double error messages being reported.)
308 // Note that as the method comes from a trait, it should not have
309 // any late-bound regions appearing in its bounds.
310 let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
311 let bounds = match self.normalize_associated_types_in_as_infer_ok(span, &bounds) {
312 InferOk { value, obligations: o } => {
313 obligations.extend(o);
317 assert!(!bounds.has_escaping_regions());
319 let cause = traits::ObligationCause::misc(span, self.body_id);
320 obligations.extend(traits::predicates_for_generics(cause.clone(),
324 // Also add an obligation for the method type being well-formed.
325 let method_ty = tcx.mk_fn_ptr(ty::Binder(fn_sig));
326 debug!("lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
329 obligations.push(traits::Obligation::new(cause,
331 ty::Predicate::WellFormed(method_ty)));
333 let callee = MethodCallee {
335 substs: trait_ref.substs,
339 debug!("callee = {:?}", callee);
347 pub fn resolve_ufcs(&self,
349 method_name: ast::Name,
350 self_ty: ty::Ty<'tcx>,
351 expr_id: ast::NodeId)
352 -> Result<Def, MethodError<'tcx>> {
353 let mode = probe::Mode::Path;
354 let pick = self.probe_for_name(span, mode, method_name, IsSuggestion(false),
355 self_ty, expr_id, ProbeScope::TraitsInScope)?;
357 if let Some(import_id) = pick.import_id {
358 let import_def_id = self.tcx.hir.local_def_id(import_id);
359 debug!("used_trait_import: {:?}", import_def_id);
360 self.tables.borrow_mut().used_trait_imports.insert(import_def_id);
363 let def = pick.item.def();
364 self.tcx.check_stability(def.def_id(), expr_id, span);
369 /// Find item with name `item_name` defined in impl/trait `def_id`
370 /// and return it, or `None`, if no such item was defined there.
371 pub fn associated_item(&self, def_id: DefId, item_name: ast::Name)
372 -> Option<ty::AssociatedItem> {
373 let ident = self.tcx.adjust(item_name, def_id, self.body_id).0;
374 self.tcx.associated_items(def_id).find(|item| item.name.to_ident() == ident)