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 `doc.rs`.
14 use middle::subst::{Subst};
18 use middle::typeck::astconv::AstConv;
19 use middle::typeck::check::{FnCtxt};
20 use middle::typeck::check::{impl_self_ty};
21 use middle::typeck::check::vtable;
22 use middle::typeck::check::vtable::select_new_fcx_obligations;
23 use middle::typeck::infer;
24 use middle::typeck::{MethodCallee};
25 use middle::typeck::{MethodParam, MethodTypeParam};
26 use util::ppaux::{Repr, UserString};
29 use syntax::ast::{DefId};
31 use syntax::codemap::Span;
33 pub use self::MethodError::*;
34 pub use self::CandidateSource::*;
40 pub enum MethodError {
41 // Did not find an applicable method, but we did find various
42 // static methods that may apply.
43 NoMatch(Vec<CandidateSource>),
45 // Multiple methods might apply.
46 Ambiguity(Vec<CandidateSource>),
49 // A pared down enum describing just the places from which a method
50 // candidate can arise. Used for error reporting only.
51 #[deriving(PartialOrd, Ord, PartialEq, Eq)]
52 pub enum CandidateSource {
53 ImplSource(ast::DefId),
54 TraitSource(/* trait id */ ast::DefId),
57 type MethodIndex = uint; // just for doc purposes
59 /// Determines whether the type `self_ty` supports a method name `method_name` or not.
60 pub fn exists<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
62 method_name: ast::Name,
64 call_expr_id: ast::NodeId)
67 match probe::probe(fcx, span, method_name, self_ty, call_expr_id) {
69 Err(NoMatch(_)) => false,
70 Err(Ambiguity(_)) => true,
74 /// Performs method lookup. If lookup is successful, it will return the callee and store an
75 /// appropriate adjustment for the self-expr. In some cases it may report an error (e.g., invoking
76 /// the `drop` method).
80 /// Given a method call like `foo.bar::<T1,...Tn>(...)`:
82 /// * `fcx`: the surrounding `FnCtxt` (!)
83 /// * `span`: the span for the method call
84 /// * `method_name`: the name of the method being called (`bar`)
85 /// * `self_ty`: the (unadjusted) type of the self expression (`foo`)
86 /// * `supplied_method_types`: the explicit method type parameters, if any (`T1..Tn`)
87 /// * `self_expr`: the self expression (`foo`)
88 pub fn lookup<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
90 method_name: ast::Name,
92 supplied_method_types: Vec<Ty<'tcx>>,
93 call_expr: &ast::Expr,
94 self_expr: &ast::Expr)
95 -> Result<MethodCallee<'tcx>, MethodError>
97 debug!("lookup(method_name={}, self_ty={}, call_expr={}, self_expr={})",
98 method_name.repr(fcx.tcx()),
99 self_ty.repr(fcx.tcx()),
100 call_expr.repr(fcx.tcx()),
101 self_expr.repr(fcx.tcx()));
103 let pick = try!(probe::probe(fcx, span, method_name, self_ty, call_expr.id));
104 Ok(confirm::confirm(fcx, span, self_expr, call_expr, self_ty, pick, supplied_method_types))
107 pub fn lookup_in_trait<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>,
109 self_expr: Option<&'a ast::Expr>,
113 opt_input_types: Option<Vec<Ty<'tcx>>>)
114 -> Option<MethodCallee<'tcx>>
116 lookup_in_trait_adjusted(fcx, span, self_expr, m_name, trait_def_id,
117 ty::AutoDerefRef { autoderefs: 0, autoref: None },
118 self_ty, opt_input_types)
121 /// `lookup_in_trait_adjusted` is used for overloaded operators. It does a very narrow slice of
122 /// what the normal probe/confirm path does. In particular, it doesn't really do any probing: it
123 /// simply constructs an obligation for a particular trait with the given self-type and checks
124 /// whether that trait is implemented.
126 /// FIXME(#18741) -- It seems likely that we can consolidate some of this code with the other
127 /// method-lookup code. In particular, autoderef on index is basically identical to autoderef with
128 /// normal probes, except that the test also looks for built-in indexing. Also, the second half of
129 /// this method is basically the same as confirmation.
130 pub fn lookup_in_trait_adjusted<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>,
132 self_expr: Option<&'a ast::Expr>,
135 autoderefref: ty::AutoDerefRef<'tcx>,
137 opt_input_types: Option<Vec<Ty<'tcx>>>)
138 -> Option<MethodCallee<'tcx>>
140 debug!("lookup_in_trait_adjusted(self_ty={}, self_expr={}, m_name={}, trait_def_id={})",
141 self_ty.repr(fcx.tcx()),
142 self_expr.repr(fcx.tcx()),
143 m_name.repr(fcx.tcx()),
144 trait_def_id.repr(fcx.tcx()));
146 let trait_def = ty::lookup_trait_def(fcx.tcx(), trait_def_id);
148 let expected_number_of_input_types = trait_def.generics.types.len(subst::TypeSpace);
149 let input_types = match opt_input_types {
150 Some(input_types) => {
151 assert_eq!(expected_number_of_input_types, input_types.len());
156 fcx.inh.infcx.next_ty_vars(expected_number_of_input_types)
160 let number_assoc_types = trait_def.generics.types.len(subst::AssocSpace);
161 let assoc_types = fcx.inh.infcx.next_ty_vars(number_assoc_types);
163 assert_eq!(trait_def.generics.types.len(subst::FnSpace), 0);
164 assert!(trait_def.generics.regions.is_empty());
166 // Construct a trait-reference `self_ty : Trait<input_tys>`
167 let substs = subst::Substs::new_trait(input_types, Vec::new(), assoc_types, self_ty);
168 let trait_ref = Rc::new(ty::TraitRef::new(trait_def_id, substs));
170 // Construct an obligation
171 let obligation = traits::Obligation::misc(span, trait_ref.clone());
173 // Now we want to know if this can be matched
174 let mut selcx = traits::SelectionContext::new(fcx.infcx(),
177 if !selcx.evaluate_obligation(&obligation) {
178 debug!("--> Cannot match obligation");
179 return None; // Cannot be matched, no such method resolution is possible.
182 // Trait must have a method named `m_name` and it should not have
183 // type parameters or early-bound regions.
185 let (method_num, method_ty) = trait_method(tcx, trait_def_id, m_name).unwrap();
186 assert_eq!(method_ty.generics.types.len(subst::FnSpace), 0);
187 assert_eq!(method_ty.generics.regions.len(subst::FnSpace), 0);
189 // Substitute the trait parameters into the method type and
190 // instantiate late-bound regions to get the actual method type.
192 // Note that as the method comes from a trait, it can only have
193 // late-bound regions from the fn itself, not the impl.
194 let ref bare_fn_ty = method_ty.fty;
195 let fn_sig = bare_fn_ty.sig.subst(tcx, &trait_ref.substs);
196 let fn_sig = fcx.infcx().replace_late_bound_regions_with_fresh_var(span,
199 let transformed_self_ty = fn_sig.inputs[0];
200 let fty = ty::mk_bare_fn(tcx, ty::BareFnTy {
202 fn_style: bare_fn_ty.fn_style,
203 abi: bare_fn_ty.abi.clone(),
206 debug!("matched method fty={} obligation={}",
208 obligation.repr(fcx.tcx()));
210 // Register obligations for the parameters. This will include the
211 // `Self` parameter, which in turn has a bound of the main trait,
212 // so this also effectively registers `obligation` as well. (We
213 // used to register `obligation` explicitly, but that resulted in
214 // double error messages being reported.)
216 // Note that as the method comes from a trait, it should not have
217 // any late-bound regions appearing in its bounds.
218 let method_bounds = method_ty.generics.to_bounds(fcx.tcx(), &trait_ref.substs);
219 assert!(!method_bounds.has_escaping_regions());
220 fcx.add_obligations_for_parameters(
221 traits::ObligationCause::misc(span),
225 // FIXME(#18653) -- Try to resolve obligations, giving us more
226 // typing information, which can sometimes be needed to avoid
227 // pathological region inference failures.
228 vtable::select_new_fcx_obligations(fcx);
230 // Insert any adjustments needed (always an autoref of some mutability).
235 debug!("inserting adjustment if needed (self-id = {}, \
236 base adjustment = {}, explicit self = {})",
237 self_expr.id, autoderefref, method_ty.explicit_self);
239 match method_ty.explicit_self {
240 ty::ByValueExplicitSelfCategory => {
241 // Trait method is fn(self), no transformation needed.
242 if !autoderefref.is_identity() {
243 fcx.write_adjustment(
246 ty::AdjustDerefRef(autoderefref));
250 ty::ByReferenceExplicitSelfCategory(..) => {
251 // Trait method is fn(&self) or fn(&mut self), need an
252 // autoref. Pull the region etc out of the type of first argument.
253 match transformed_self_ty.sty {
254 ty::ty_rptr(region, ty::mt { mutbl, ty: _ }) => {
255 let ty::AutoDerefRef { autoderefs, autoref } = autoderefref;
256 let autoref = autoref.map(|r| box r);
257 fcx.write_adjustment(
260 ty::AdjustDerefRef(ty::AutoDerefRef {
261 autoderefs: autoderefs,
262 autoref: Some(ty::AutoPtr(region, mutbl, autoref))
267 fcx.tcx().sess.span_bug(
270 "trait method is &self but first arg is: {}",
271 transformed_self_ty.repr(fcx.tcx())).as_slice());
277 fcx.tcx().sess.span_bug(
280 "unexpected explicit self type in operator method: {}",
281 method_ty.explicit_self).as_slice());
287 let callee = MethodCallee {
288 origin: MethodTypeParam(MethodParam{trait_ref: trait_ref.clone(),
289 method_num: method_num}),
291 substs: trait_ref.substs.clone()
294 debug!("callee = {}", callee.repr(fcx.tcx()));
299 pub fn report_error<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
302 method_name: ast::Name,
306 NoMatch(static_sources) => {
308 let method_ustring = method_name.user_string(cx);
310 // True if the type is a struct and contains a field with
311 // the same name as the not-found method
312 let is_field = match rcvr_ty.sty {
314 ty::lookup_struct_fields(cx, did)
316 .any(|f| f.name.user_string(cx) == method_ustring),
320 fcx.type_error_message(
323 format!("type `{}` does not implement any \
324 method in scope named `{}`",
331 // If the method has the name of a field, give a help note
333 cx.sess.span_note(span,
334 format!("use `(s.{0})(...)` if you meant to call the \
335 function stored in the `{0}` field", method_ustring).as_slice());
338 if static_sources.len() > 0 {
339 fcx.tcx().sess.fileline_note(
341 "found defined static methods, maybe a `self` is missing?");
343 report_candidates(fcx, span, method_name, static_sources);
347 Ambiguity(sources) => {
348 span_err!(fcx.sess(), span, E0034,
349 "multiple applicable methods in scope");
351 report_candidates(fcx, span, method_name, sources);
355 fn report_candidates(fcx: &FnCtxt,
357 method_name: ast::Name,
358 mut sources: Vec<CandidateSource>) {
362 for (idx, source) in sources.iter().enumerate() {
364 ImplSource(impl_did) => {
365 // Provide the best span we can. Use the method, if local to crate, else
366 // the impl, if local to crate (method may be defaulted), else the call site.
367 let method = impl_method(fcx.tcx(), impl_did, method_name).unwrap();
368 let impl_span = fcx.tcx().map.def_id_span(impl_did, span);
369 let method_span = fcx.tcx().map.def_id_span(method.def_id, impl_span);
371 let impl_ty = impl_self_ty(fcx, span, impl_did).ty;
373 let insertion = match impl_trait_ref(fcx.tcx(), impl_did) {
375 Some(trait_ref) => format!(" of the trait `{}`",
376 ty::item_path_str(fcx.tcx(),
380 span_note!(fcx.sess(), method_span,
381 "candidate #{} is defined in an impl{} for the type `{}`",
384 impl_ty.user_string(fcx.tcx()));
386 TraitSource(trait_did) => {
387 let (_, method) = trait_method(fcx.tcx(), trait_did, method_name).unwrap();
388 let method_span = fcx.tcx().map.def_id_span(method.def_id, span);
389 span_note!(fcx.sess(), method_span,
390 "candidate #{} is defined in the trait `{}`",
392 ty::item_path_str(fcx.tcx(), trait_did));
399 /// Find method with name `method_name` defined in `trait_def_id` and return it, along with its
400 /// index (or `None`, if no such method).
401 fn trait_method<'tcx>(tcx: &ty::ctxt<'tcx>,
402 trait_def_id: ast::DefId,
403 method_name: ast::Name)
404 -> Option<(uint, Rc<ty::Method<'tcx>>)>
406 let trait_items = ty::trait_items(tcx, trait_def_id);
410 .find(|&(_, ref item)| item.name() == method_name)
411 .and_then(|(idx, item)| item.as_opt_method().map(|m| (idx, m)))
414 fn impl_method<'tcx>(tcx: &ty::ctxt<'tcx>,
415 impl_def_id: ast::DefId,
416 method_name: ast::Name)
417 -> Option<Rc<ty::Method<'tcx>>>
419 let impl_items = tcx.impl_items.borrow();
420 let impl_items = impl_items.get(&impl_def_id).unwrap();
423 .map(|&did| ty::impl_or_trait_item(tcx, did.def_id()))
424 .find(|m| m.name() == method_name)
425 .and_then(|item| item.as_opt_method())