]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/mod.rs
3ddeba9d44012b3735a30f5f5b810e3290a51ac3
[rust.git] / src / librustc_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 `README.md`.
12
13 use check::FnCtxt;
14 use hir::def::Def;
15 use hir::def_id::DefId;
16 use rustc::ty::subst::Substs;
17 use rustc::traits;
18 use rustc::ty::{self, Ty, ToPredicate, ToPolyTraitRef, TraitRef, TypeFoldable};
19 use rustc::ty::subst::Subst;
20 use rustc::infer::{self, InferOk};
21
22 use syntax::ast;
23 use syntax_pos::Span;
24
25 use rustc::hir;
26
27 pub use self::MethodError::*;
28 pub use self::CandidateSource::*;
29
30 mod confirm;
31 pub mod probe;
32 mod suggest;
33
34 use self::probe::{IsSuggestion, ProbeScope};
35
36 #[derive(Clone, Copy, Debug)]
37 pub struct MethodCallee<'tcx> {
38     /// Impl method ID, for inherent methods, or trait method ID, otherwise.
39     pub def_id: DefId,
40     pub substs: &'tcx Substs<'tcx>,
41
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>,
46 }
47
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>),
51
52     // Multiple methods might apply.
53     Ambiguity(Vec<CandidateSource>),
54
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>),
58
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>),
62
63     // Found a match, but the return type is wrong
64     BadReturnType,
65 }
66
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::AssociatedItem>,
74     pub mode: probe::Mode,
75 }
76
77 impl<'tcx> NoMatchData<'tcx> {
78     pub fn new(static_candidates: Vec<CandidateSource>,
79                unsatisfied_predicates: Vec<TraitRef<'tcx>>,
80                out_of_scope_traits: Vec<DefId>,
81                lev_candidate: Option<ty::AssociatedItem>,
82                mode: probe::Mode)
83                -> Self {
84         NoMatchData {
85             static_candidates,
86             unsatisfied_predicates,
87             out_of_scope_traits,
88             lev_candidate,
89             mode,
90         }
91     }
92 }
93
94 // A pared down enum describing just the places from which a method
95 // candidate can arise. Used for error reporting only.
96 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
97 pub enum CandidateSource {
98     ImplSource(DefId),
99     TraitSource(// trait id
100                 DefId),
101 }
102
103 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
104     /// Determines whether the type `self_ty` supports a method name `method_name` or not.
105     pub fn method_exists(&self,
106                          span: Span,
107                          method_name: ast::Name,
108                          self_ty: Ty<'tcx>,
109                          call_expr_id: ast::NodeId,
110                          allow_private: bool)
111                          -> bool {
112         let mode = probe::Mode::MethodCall;
113         match self.probe_for_name(span, mode, method_name, IsSuggestion(false),
114                                   self_ty, call_expr_id, ProbeScope::TraitsInScope) {
115             Ok(..) => true,
116             Err(NoMatch(..)) => false,
117             Err(Ambiguity(..)) => true,
118             Err(PrivateMatch(..)) => allow_private,
119             Err(IllegalSizedBound(..)) => true,
120             Err(BadReturnType) => {
121                 bug!("no return type expectations but got BadReturnType")
122             }
123
124         }
125     }
126
127     /// Performs method lookup. If lookup is successful, it will return the callee
128     /// and store an appropriate adjustment for the self-expr. In some cases it may
129     /// report an error (e.g., invoking the `drop` method).
130     ///
131     /// # Arguments
132     ///
133     /// Given a method call like `foo.bar::<T1,...Tn>(...)`:
134     ///
135     /// * `fcx`:                   the surrounding `FnCtxt` (!)
136     /// * `span`:                  the span for the method call
137     /// * `method_name`:           the name of the method being called (`bar`)
138     /// * `self_ty`:               the (unadjusted) type of the self expression (`foo`)
139     /// * `supplied_method_types`: the explicit method type parameters, if any (`T1..Tn`)
140     /// * `self_expr`:             the self expression (`foo`)
141     pub fn lookup_method(&self,
142                          self_ty: Ty<'tcx>,
143                          segment: &hir::PathSegment,
144                          span: Span,
145                          call_expr: &'gcx hir::Expr,
146                          self_expr: &'gcx hir::Expr)
147                          -> Result<MethodCallee<'tcx>, MethodError<'tcx>> {
148         debug!("lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
149                segment.name,
150                self_ty,
151                call_expr,
152                self_expr);
153
154         let pick = self.lookup_probe(
155             span,
156             segment.name,
157             self_ty,
158             call_expr,
159             ProbeScope::TraitsInScope
160         )?;
161
162         if let Some(import_id) = pick.import_id {
163             let import_def_id = self.tcx.hir.local_def_id(import_id);
164             debug!("used_trait_import: {:?}", import_def_id);
165             self.tables.borrow_mut().used_trait_imports.insert(import_def_id);
166         }
167
168         self.tcx.check_stability(pick.item.def_id, call_expr.id, span);
169
170         let result = self.confirm_method(span,
171                                          self_expr,
172                                          call_expr,
173                                          self_ty,
174                                          pick.clone(),
175                                          segment);
176
177         if result.illegal_sized_bound {
178             // We probe again, taking all traits into account (not only those in scope).
179             let candidates =
180                 match self.lookup_probe(span,
181                                         segment.name,
182                                         self_ty,
183                                         call_expr,
184                                         ProbeScope::AllTraits) {
185
186                     // If we find a different result the caller probably forgot to import a trait.
187                     Ok(ref new_pick) if *new_pick != pick => vec![new_pick.item.container.id()],
188                     Err(Ambiguity(ref sources)) => {
189                         sources.iter()
190                                .filter_map(|source| {
191                                    match *source {
192                                        // Note: this cannot come from an inherent impl,
193                                        // because the first probing succeeded.
194                                        ImplSource(def) => self.tcx.trait_id_of_impl(def),
195                                        TraitSource(_) => None,
196                                    }
197                                })
198                                .collect()
199                     }
200                     _ => Vec::new(),
201                 };
202
203             return Err(IllegalSizedBound(candidates));
204         }
205
206         Ok(result.callee)
207     }
208
209     fn lookup_probe(&self,
210                     span: Span,
211                     method_name: ast::Name,
212                     self_ty: Ty<'tcx>,
213                     call_expr: &'gcx hir::Expr,
214                     scope: ProbeScope)
215                     -> probe::PickResult<'tcx> {
216         let mode = probe::Mode::MethodCall;
217         let self_ty = self.resolve_type_vars_if_possible(&self_ty);
218         self.probe_for_name(span, mode, method_name, IsSuggestion(false),
219                             self_ty, call_expr.id, scope)
220     }
221
222     /// `lookup_method_in_trait` is used for overloaded operators.
223     /// It does a very narrow slice of what the normal probe/confirm path does.
224     /// In particular, it doesn't really do any probing: it simply constructs
225     /// an obligation for a particular trait with the given self-type and checks
226     /// whether that trait is implemented.
227     ///
228     /// FIXME(#18741) -- It seems likely that we can consolidate some of this
229     /// code with the other method-lookup code. In particular, the second half
230     /// of this method is basically the same as confirmation.
231     pub fn lookup_method_in_trait(&self,
232                                   span: Span,
233                                   m_name: ast::Name,
234                                   trait_def_id: DefId,
235                                   self_ty: Ty<'tcx>,
236                                   opt_input_types: Option<&[Ty<'tcx>]>)
237                                   -> Option<InferOk<'tcx, MethodCallee<'tcx>>> {
238         debug!("lookup_in_trait_adjusted(self_ty={:?}, \
239                 m_name={}, trait_def_id={:?})",
240                self_ty,
241                m_name,
242                trait_def_id);
243
244         // Construct a trait-reference `self_ty : Trait<input_tys>`
245         let substs = Substs::for_item(self.tcx,
246                                       trait_def_id,
247                                       |def, _| self.region_var_for_def(span, def),
248                                       |def, substs| {
249             if def.index == 0 {
250                 self_ty
251             } else if let Some(ref input_types) = opt_input_types {
252                 input_types[def.index as usize - 1]
253             } else {
254                 self.type_var_for_def(span, def, substs)
255             }
256         });
257
258         let trait_ref = ty::TraitRef::new(trait_def_id, substs);
259
260         // Construct an obligation
261         let poly_trait_ref = trait_ref.to_poly_trait_ref();
262         let obligation =
263             traits::Obligation::misc(span,
264                                      self.body_id,
265                                      self.param_env,
266                                      poly_trait_ref.to_predicate());
267
268         // Now we want to know if this can be matched
269         let mut selcx = traits::SelectionContext::new(self);
270         if !selcx.evaluate_obligation(&obligation) {
271             debug!("--> Cannot match obligation");
272             return None; // Cannot be matched, no such method resolution is possible.
273         }
274
275         // Trait must have a method named `m_name` and it should not have
276         // type parameters or early-bound regions.
277         let tcx = self.tcx;
278         let method_item = self.associated_item(trait_def_id, m_name).unwrap();
279         let def_id = method_item.def_id;
280         let generics = tcx.generics_of(def_id);
281         assert_eq!(generics.types.len(), 0);
282         assert_eq!(generics.regions.len(), 0);
283
284         debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
285         let mut obligations = vec![];
286
287         // Instantiate late-bound regions and substitute the trait
288         // parameters into the method type to get the actual method type.
289         //
290         // NB: Instantiate late-bound regions first so that
291         // `instantiate_type_scheme` can normalize associated types that
292         // may reference those regions.
293         let fn_sig = tcx.fn_sig(def_id);
294         let fn_sig = self.replace_late_bound_regions_with_fresh_var(span,
295                                                                     infer::FnCall,
296                                                                     &fn_sig).0;
297         let fn_sig = fn_sig.subst(self.tcx, substs);
298         let fn_sig = match self.normalize_associated_types_in_as_infer_ok(span, &fn_sig) {
299             InferOk { value, obligations: o } => {
300                 obligations.extend(o);
301                 value
302             }
303         };
304
305         // Register obligations for the parameters.  This will include the
306         // `Self` parameter, which in turn has a bound of the main trait,
307         // so this also effectively registers `obligation` as well.  (We
308         // used to register `obligation` explicitly, but that resulted in
309         // double error messages being reported.)
310         //
311         // Note that as the method comes from a trait, it should not have
312         // any late-bound regions appearing in its bounds.
313         let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
314         let bounds = match self.normalize_associated_types_in_as_infer_ok(span, &bounds) {
315             InferOk { value, obligations: o } => {
316                 obligations.extend(o);
317                 value
318             }
319         };
320         assert!(!bounds.has_escaping_regions());
321
322         let cause = traits::ObligationCause::misc(span, self.body_id);
323         obligations.extend(traits::predicates_for_generics(cause.clone(),
324                                                            self.param_env,
325                                                            &bounds));
326
327         // Also add an obligation for the method type being well-formed.
328         let method_ty = tcx.mk_fn_ptr(ty::Binder(fn_sig));
329         debug!("lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
330                method_ty,
331                obligation);
332         obligations.push(traits::Obligation::new(cause,
333                                                  self.param_env,
334                                                  ty::Predicate::WellFormed(method_ty)));
335
336         let callee = MethodCallee {
337             def_id,
338             substs: trait_ref.substs,
339             sig: fn_sig,
340         };
341
342         debug!("callee = {:?}", callee);
343
344         Some(InferOk {
345             obligations,
346             value: callee
347         })
348     }
349
350     pub fn resolve_ufcs(&self,
351                         span: Span,
352                         method_name: ast::Name,
353                         self_ty: Ty<'tcx>,
354                         expr_id: ast::NodeId)
355                         -> Result<Def, MethodError<'tcx>> {
356         let mode = probe::Mode::Path;
357         let pick = self.probe_for_name(span, mode, method_name, IsSuggestion(false),
358                                        self_ty, expr_id, ProbeScope::TraitsInScope)?;
359
360         if let Some(import_id) = pick.import_id {
361             let import_def_id = self.tcx.hir.local_def_id(import_id);
362             debug!("used_trait_import: {:?}", import_def_id);
363             self.tables.borrow_mut().used_trait_imports.insert(import_def_id);
364         }
365
366         let def = pick.item.def();
367         self.tcx.check_stability(def.def_id(), expr_id, span);
368
369         Ok(def)
370     }
371
372     /// Find item with name `item_name` defined in impl/trait `def_id`
373     /// and return it, or `None`, if no such item was defined there.
374     pub fn associated_item(&self, def_id: DefId, item_name: ast::Name)
375                            -> Option<ty::AssociatedItem> {
376         self.tcx.associated_items(def_id)
377                 .find(|item| self.tcx.hygienic_eq(item_name, item.name, def_id))
378
379     }
380 }