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::adjustment::{Adjustment, Adjust, AutoBorrow};
20 use rustc::ty::subst::Subst;
21 use rustc::infer::{self, InferOk};
28 pub use self::MethodError::*;
29 pub use self::CandidateSource::*;
31 pub use self::suggest::AllTraitsVec;
37 use self::probe::IsSuggestion;
39 pub enum MethodError<'tcx> {
40 // Did not find an applicable method, but we did find various near-misses that may work.
41 NoMatch(NoMatchData<'tcx>),
43 // Multiple methods might apply.
44 Ambiguity(Vec<CandidateSource>),
46 // Using a `Fn`/`FnMut`/etc method on a raw closure type before we have inferred its kind.
47 ClosureAmbiguity(// DefId of fn trait
50 // Found an applicable method, but it is not visible.
54 // Contains a list of static methods that may apply, a list of unsatisfied trait predicates which
55 // could lead to matches if satisfied, and a list of not-in-scope traits which may work.
56 pub struct NoMatchData<'tcx> {
57 pub static_candidates: Vec<CandidateSource>,
58 pub unsatisfied_predicates: Vec<TraitRef<'tcx>>,
59 pub out_of_scope_traits: Vec<DefId>,
60 pub mode: probe::Mode,
63 impl<'tcx> NoMatchData<'tcx> {
64 pub fn new(static_candidates: Vec<CandidateSource>,
65 unsatisfied_predicates: Vec<TraitRef<'tcx>>,
66 out_of_scope_traits: Vec<DefId>,
70 static_candidates: static_candidates,
71 unsatisfied_predicates: unsatisfied_predicates,
72 out_of_scope_traits: out_of_scope_traits,
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 TraitSource(// trait id
87 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
88 /// Determines whether the type `self_ty` supports a method name `method_name` or not.
89 pub fn method_exists(&self,
91 method_name: ast::Name,
92 self_ty: ty::Ty<'tcx>,
93 call_expr_id: ast::NodeId,
96 let mode = probe::Mode::MethodCall;
97 match self.probe_for_name(span, mode, method_name, IsSuggestion(false),
98 self_ty, call_expr_id) {
100 Err(NoMatch(..)) => false,
101 Err(Ambiguity(..)) => true,
102 Err(ClosureAmbiguity(..)) => true,
103 Err(PrivateMatch(..)) => allow_private,
107 /// Performs method lookup. If lookup is successful, it will return the callee
108 /// and store an appropriate adjustment for the self-expr. In some cases it may
109 /// report an error (e.g., invoking the `drop` method).
113 /// Given a method call like `foo.bar::<T1,...Tn>(...)`:
115 /// * `fcx`: the surrounding `FnCtxt` (!)
116 /// * `span`: the span for the method call
117 /// * `method_name`: the name of the method being called (`bar`)
118 /// * `self_ty`: the (unadjusted) type of the self expression (`foo`)
119 /// * `supplied_method_types`: the explicit method type parameters, if any (`T1..Tn`)
120 /// * `self_expr`: the self expression (`foo`)
121 pub fn lookup_method(&self,
123 method_name: ast::Name,
124 self_ty: ty::Ty<'tcx>,
125 supplied_method_types: Vec<ty::Ty<'tcx>>,
126 call_expr: &'gcx hir::Expr,
127 self_expr: &'gcx hir::Expr)
128 -> Result<ty::MethodCallee<'tcx>, MethodError<'tcx>> {
129 debug!("lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
135 let mode = probe::Mode::MethodCall;
136 let self_ty = self.resolve_type_vars_if_possible(&self_ty);
137 let pick = self.probe_for_name(span, mode, method_name, IsSuggestion(false),
138 self_ty, call_expr.id)?;
140 if let Some(import_id) = pick.import_id {
141 let import_def_id = self.tcx.hir.local_def_id(import_id);
142 debug!("used_trait_import: {:?}", import_def_id);
143 self.tables.borrow_mut().used_trait_imports.insert(import_def_id);
146 self.tcx.check_stability(pick.item.def_id, call_expr.id, span);
148 Ok(self.confirm_method(span,
153 supplied_method_types))
156 pub fn lookup_method_in_trait(&self,
158 self_expr: Option<&hir::Expr>,
161 self_ty: ty::Ty<'tcx>,
162 opt_input_types: Option<Vec<ty::Ty<'tcx>>>)
163 -> Option<InferOk<'tcx, ty::MethodCallee<'tcx>>> {
164 self.lookup_method_in_trait_adjusted(span,
174 /// `lookup_in_trait_adjusted` is used for overloaded operators.
175 /// It does a very narrow slice of what the normal probe/confirm path does.
176 /// In particular, it doesn't really do any probing: it simply constructs
177 /// an obligation for aparticular trait with the given self-type and checks
178 /// whether that trait is implemented.
180 /// FIXME(#18741) -- It seems likely that we can consolidate some of this
181 /// code with the other method-lookup code. In particular, autoderef on
182 /// index is basically identical to autoderef with normal probes, except
183 /// that the test also looks for built-in indexing. Also, the second half of
184 /// this method is basically the same as confirmation.
185 pub fn lookup_method_in_trait_adjusted(&self,
187 self_expr: Option<&hir::Expr>,
192 self_ty: ty::Ty<'tcx>,
193 opt_input_types: Option<Vec<ty::Ty<'tcx>>>)
194 -> Option<InferOk<'tcx, ty::MethodCallee<'tcx>>> {
195 debug!("lookup_in_trait_adjusted(self_ty={:?}, self_expr={:?}, \
196 m_name={}, trait_def_id={:?})",
202 // Construct a trait-reference `self_ty : Trait<input_tys>`
203 let substs = Substs::for_item(self.tcx,
205 |def, _| self.region_var_for_def(span, def),
209 } else if let Some(ref input_types) = opt_input_types {
210 input_types[def.index as usize - 1]
212 self.type_var_for_def(span, def, substs)
216 let trait_ref = ty::TraitRef::new(trait_def_id, substs);
218 // Construct an obligation
219 let poly_trait_ref = trait_ref.to_poly_trait_ref();
221 traits::Obligation::misc(span, self.body_id, poly_trait_ref.to_predicate());
223 // Now we want to know if this can be matched
224 let mut selcx = traits::SelectionContext::new(self);
225 if !selcx.evaluate_obligation(&obligation) {
226 debug!("--> Cannot match obligation");
227 return None; // Cannot be matched, no such method resolution is possible.
230 // Trait must have a method named `m_name` and it should not have
231 // type parameters or early-bound regions.
233 let method_item = self.associated_item(trait_def_id, m_name).unwrap();
234 let def_id = method_item.def_id;
235 let generics = tcx.item_generics(def_id);
236 assert_eq!(generics.types.len(), 0);
237 assert_eq!(generics.regions.len(), 0);
239 debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
240 let mut obligations = vec![];
242 // Instantiate late-bound regions and substitute the trait
243 // parameters into the method type to get the actual method type.
245 // NB: Instantiate late-bound regions first so that
246 // `instantiate_type_scheme` can normalize associated types that
247 // may reference those regions.
248 let original_method_ty = tcx.item_type(def_id);
249 let fn_sig = original_method_ty.fn_sig();
250 let fn_sig = self.replace_late_bound_regions_with_fresh_var(span,
253 let fn_sig = fn_sig.subst(self.tcx, substs);
254 let fn_sig = match self.normalize_associated_types_in_as_infer_ok(span, &fn_sig) {
255 InferOk { value, obligations: o } => {
256 obligations.extend(o);
260 let transformed_self_ty = fn_sig.inputs()[0];
261 let method_ty = tcx.mk_fn_def(def_id, substs, ty::Binder(fn_sig));
263 debug!("lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
267 // Register obligations for the parameters. This will include the
268 // `Self` parameter, which in turn has a bound of the main trait,
269 // so this also effectively registers `obligation` as well. (We
270 // used to register `obligation` explicitly, but that resulted in
271 // double error messages being reported.)
273 // Note that as the method comes from a trait, it should not have
274 // any late-bound regions appearing in its bounds.
275 let bounds = self.tcx.item_predicates(def_id).instantiate(self.tcx, substs);
276 let bounds = match self.normalize_associated_types_in_as_infer_ok(span, &bounds) {
277 InferOk { value, obligations: o } => {
278 obligations.extend(o);
282 assert!(!bounds.has_escaping_regions());
284 let cause = traits::ObligationCause::misc(span, self.body_id);
285 obligations.extend(traits::predicates_for_generics(cause.clone(), &bounds));
287 // Also add an obligation for the method type being well-formed.
288 obligations.push(traits::Obligation::new(cause, ty::Predicate::WellFormed(method_ty)));
290 // Insert any adjustments needed (always an autoref of some mutability).
291 if let Some(self_expr) = self_expr {
292 debug!("lookup_in_trait_adjusted: inserting adjustment if needed \
293 (self-id={}, autoderefs={}, unsize={}, fty={:?})",
294 self_expr.id, autoderefs, unsize, original_method_ty);
296 let original_sig = original_method_ty.fn_sig();
297 let autoref = match (&original_sig.input(0).skip_binder().sty,
298 &transformed_self_ty.sty) {
299 (&ty::TyRef(..), &ty::TyRef(region, ty::TypeAndMut { mutbl, ty: _ })) => {
300 // Trait method is fn(&self) or fn(&mut self), need an
301 // autoref. Pull the region etc out of the type of first argument.
302 Some(AutoBorrow::Ref(region, mutbl))
305 // Trait method is fn(self), no transformation needed.
311 self.apply_adjustment(self_expr.id, Adjustment {
312 kind: Adjust::DerefRef {
313 autoderefs: autoderefs,
317 target: transformed_self_ty
321 let callee = ty::MethodCallee {
324 substs: trait_ref.substs,
327 debug!("callee = {:?}", callee);
335 pub fn resolve_ufcs(&self,
337 method_name: ast::Name,
338 self_ty: ty::Ty<'tcx>,
339 expr_id: ast::NodeId)
340 -> Result<Def, MethodError<'tcx>> {
341 let mode = probe::Mode::Path;
342 let pick = self.probe_for_name(span, mode, method_name, IsSuggestion(false),
345 if let Some(import_id) = pick.import_id {
346 let import_def_id = self.tcx.hir.local_def_id(import_id);
347 debug!("used_trait_import: {:?}", import_def_id);
348 self.tables.borrow_mut().used_trait_imports.insert(import_def_id);
351 let def = pick.item.def();
353 self.tcx.check_stability(def.def_id(), expr_id, span);
355 if let probe::InherentImplPick = pick.kind {
356 if !self.tcx.vis_is_accessible_from(pick.item.vis, self.body_id) {
357 let msg = format!("{} `{}` is private", def.kind_name(), method_name);
358 self.tcx.sess.span_err(span, &msg);
364 /// Find item with name `item_name` defined in impl/trait `def_id`
365 /// and return it, or `None`, if no such item was defined there.
366 pub fn associated_item(&self, def_id: DefId, item_name: ast::Name)
367 -> Option<ty::AssociatedItem> {
368 self.tcx.associated_items(def_id).find(|item| item.name == item_name)