]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/typeck/check/method/mod.rs
/*! -> //!
[rust.git] / src / librustc / middle / typeck / check / method / mod.rs
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.
4 //
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.
10
11 //! Method lookup: the secret sauce of Rust. See `doc.rs`.
12
13 use middle::subst;
14 use middle::subst::{Subst};
15 use middle::traits;
16 use middle::ty::*;
17 use middle::ty;
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};
27
28 use std::rc::Rc;
29 use syntax::ast::{DefId};
30 use syntax::ast;
31 use syntax::codemap::Span;
32
33 pub use self::MethodError::*;
34 pub use self::CandidateSource::*;
35
36 mod confirm;
37 mod doc;
38 mod probe;
39
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>),
44
45     // Multiple methods might apply.
46     Ambiguity(Vec<CandidateSource>),
47 }
48
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),
55 }
56
57 type MethodIndex = uint; // just for doc purposes
58
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>,
61                         span: Span,
62                         method_name: ast::Name,
63                         self_ty: Ty<'tcx>,
64                         call_expr_id: ast::NodeId)
65                         -> bool
66 {
67     match probe::probe(fcx, span, method_name, self_ty, call_expr_id) {
68         Ok(_) => true,
69         Err(NoMatch(_)) => false,
70         Err(Ambiguity(_)) => true,
71     }
72 }
73
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).
77 ///
78 /// # Arguments
79 ///
80 /// Given a method call like `foo.bar::<T1,...Tn>(...)`:
81 ///
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>,
89                         span: Span,
90                         method_name: ast::Name,
91                         self_ty: Ty<'tcx>,
92                         supplied_method_types: Vec<Ty<'tcx>>,
93                         call_expr: &ast::Expr,
94                         self_expr: &ast::Expr)
95                         -> Result<MethodCallee<'tcx>, MethodError>
96 {
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()));
102
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))
105 }
106
107 pub fn lookup_in_trait<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>,
108                                  span: Span,
109                                  self_expr: Option<&'a ast::Expr>,
110                                  m_name: ast::Name,
111                                  trait_def_id: DefId,
112                                  self_ty: Ty<'tcx>,
113                                  opt_input_types: Option<Vec<Ty<'tcx>>>)
114                                  -> Option<MethodCallee<'tcx>>
115 {
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)
119 }
120
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.
125 ///
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>,
131                                           span: Span,
132                                           self_expr: Option<&'a ast::Expr>,
133                                           m_name: ast::Name,
134                                           trait_def_id: DefId,
135                                           autoderefref: ty::AutoDerefRef<'tcx>,
136                                           self_ty: Ty<'tcx>,
137                                           opt_input_types: Option<Vec<Ty<'tcx>>>)
138                                           -> Option<MethodCallee<'tcx>>
139 {
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()));
145
146     let trait_def = ty::lookup_trait_def(fcx.tcx(), trait_def_id);
147
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());
152             input_types
153         }
154
155         None => {
156             fcx.inh.infcx.next_ty_vars(expected_number_of_input_types)
157         }
158     };
159
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);
162
163     assert_eq!(trait_def.generics.types.len(subst::FnSpace), 0);
164     assert!(trait_def.generics.regions.is_empty());
165
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));
169
170     // Construct an obligation
171     let obligation = traits::Obligation::misc(span, trait_ref.clone());
172
173     // Now we want to know if this can be matched
174     let mut selcx = traits::SelectionContext::new(fcx.infcx(),
175                                                   &fcx.inh.param_env,
176                                                   fcx);
177     if !selcx.evaluate_obligation(&obligation) {
178         debug!("--> Cannot match obligation");
179         return None; // Cannot be matched, no such method resolution is possible.
180     }
181
182     // Trait must have a method named `m_name` and it should not have
183     // type parameters or early-bound regions.
184     let tcx = fcx.tcx();
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);
188
189     // Substitute the trait parameters into the method type and
190     // instantiate late-bound regions to get the actual method type.
191     //
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,
197                                                                        infer::FnCall,
198                                                                        &fn_sig).0;
199     let transformed_self_ty = fn_sig.inputs[0];
200     let fty = ty::mk_bare_fn(tcx, ty::BareFnTy {
201         sig: fn_sig,
202         fn_style: bare_fn_ty.fn_style,
203         abi: bare_fn_ty.abi.clone(),
204     });
205
206     debug!("matched method fty={} obligation={}",
207            fty.repr(fcx.tcx()),
208            obligation.repr(fcx.tcx()));
209
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.)
215     //
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),
222         &trait_ref.substs,
223         &method_bounds);
224
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);
229
230     // Insert any adjustments needed (always an autoref of some mutability).
231     match self_expr {
232         None => { }
233
234         Some(self_expr) => {
235             debug!("inserting adjustment if needed (self-id = {}, \
236                    base adjustment = {}, explicit self = {})",
237                    self_expr.id, autoderefref, method_ty.explicit_self);
238
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(
244                             self_expr.id,
245                             span,
246                             ty::AdjustDerefRef(autoderefref));
247                     }
248                 }
249
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(
258                                 self_expr.id,
259                                 span,
260                                 ty::AdjustDerefRef(ty::AutoDerefRef {
261                                     autoderefs: autoderefs,
262                                     autoref: Some(ty::AutoPtr(region, mutbl, autoref))
263                                 }));
264                         }
265
266                         _ => {
267                             fcx.tcx().sess.span_bug(
268                                 span,
269                                 format!(
270                                     "trait method is &self but first arg is: {}",
271                                     transformed_self_ty.repr(fcx.tcx())).as_slice());
272                         }
273                     }
274                 }
275
276                 _ => {
277                     fcx.tcx().sess.span_bug(
278                         span,
279                         format!(
280                             "unexpected explicit self type in operator method: {}",
281                             method_ty.explicit_self).as_slice());
282                 }
283             }
284         }
285     }
286
287     let callee = MethodCallee {
288         origin: MethodTypeParam(MethodParam{trait_ref: trait_ref.clone(),
289                                             method_num: method_num}),
290         ty: fty,
291         substs: trait_ref.substs.clone()
292     };
293
294     debug!("callee = {}", callee.repr(fcx.tcx()));
295
296     Some(callee)
297 }
298
299 pub fn report_error<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
300                               span: Span,
301                               rcvr_ty: Ty<'tcx>,
302                               method_name: ast::Name,
303                               error: MethodError)
304 {
305     match error {
306         NoMatch(static_sources) => {
307             let cx = fcx.tcx();
308             let method_ustring = method_name.user_string(cx);
309
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 {
313                 ty_struct(did, _) =>
314                     ty::lookup_struct_fields(cx, did)
315                         .iter()
316                         .any(|f| f.name.user_string(cx) == method_ustring),
317                 _ => false
318             };
319
320             fcx.type_error_message(
321                 span,
322                 |actual| {
323                     format!("type `{}` does not implement any \
324                              method in scope named `{}`",
325                             actual,
326                             method_ustring)
327                 },
328                 rcvr_ty,
329                 None);
330
331             // If the method has the name of a field, give a help note
332             if is_field {
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());
336             }
337
338             if static_sources.len() > 0 {
339                 fcx.tcx().sess.fileline_note(
340                     span,
341                     "found defined static methods, maybe a `self` is missing?");
342
343                 report_candidates(fcx, span, method_name, static_sources);
344             }
345         }
346
347         Ambiguity(sources) => {
348             span_err!(fcx.sess(), span, E0034,
349                       "multiple applicable methods in scope");
350
351             report_candidates(fcx, span, method_name, sources);
352         }
353     }
354
355     fn report_candidates(fcx: &FnCtxt,
356                          span: Span,
357                          method_name: ast::Name,
358                          mut sources: Vec<CandidateSource>) {
359         sources.sort();
360         sources.dedup();
361
362         for (idx, source) in sources.iter().enumerate() {
363             match *source {
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);
370
371                     let impl_ty = impl_self_ty(fcx, span, impl_did).ty;
372
373                     let insertion = match impl_trait_ref(fcx.tcx(), impl_did) {
374                         None => format!(""),
375                         Some(trait_ref) => format!(" of the trait `{}`",
376                                                    ty::item_path_str(fcx.tcx(),
377                                                                      trait_ref.def_id)),
378                     };
379
380                     span_note!(fcx.sess(), method_span,
381                                "candidate #{} is defined in an impl{} for the type `{}`",
382                                idx + 1u,
383                                insertion,
384                                impl_ty.user_string(fcx.tcx()));
385                 }
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 `{}`",
391                                idx + 1u,
392                                ty::item_path_str(fcx.tcx(), trait_did));
393                 }
394             }
395         }
396     }
397 }
398
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>>)>
405 {
406     let trait_items = ty::trait_items(tcx, trait_def_id);
407     trait_items
408         .iter()
409         .enumerate()
410         .find(|&(_, ref item)| item.name() == method_name)
411         .and_then(|(idx, item)| item.as_opt_method().map(|m| (idx, m)))
412 }
413
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>>>
418 {
419     let impl_items = tcx.impl_items.borrow();
420     let impl_items = impl_items.get(&impl_def_id).unwrap();
421     impl_items
422         .iter()
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())
426 }
427