]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/mod.rs
More methods for str boxes.
[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, ToPredicate, ToPolyTraitRef, TraitRef, TypeFoldable};
19 use rustc::ty::adjustment::{Adjustment, Adjust, AutoBorrow};
20 use rustc::ty::subst::Subst;
21 use rustc::infer::{self, InferOk};
22
23 use syntax::ast;
24 use syntax_pos::Span;
25
26 use rustc::hir;
27
28 pub use self::MethodError::*;
29 pub use self::CandidateSource::*;
30
31 pub use self::suggest::AllTraitsVec;
32
33 mod confirm;
34 pub mod probe;
35 mod suggest;
36
37 use self::probe::IsSuggestion;
38
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>),
42
43     // Multiple methods might apply.
44     Ambiguity(Vec<CandidateSource>),
45
46     // Using a `Fn`/`FnMut`/etc method on a raw closure type before we have inferred its kind.
47     ClosureAmbiguity(// DefId of fn trait
48                      DefId),
49
50     // Found an applicable method, but it is not visible.
51     PrivateMatch(Def),
52 }
53
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,
61 }
62
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>,
67                mode: probe::Mode)
68                -> Self {
69         NoMatchData {
70             static_candidates: static_candidates,
71             unsatisfied_predicates: unsatisfied_predicates,
72             out_of_scope_traits: out_of_scope_traits,
73             mode: mode,
74         }
75     }
76 }
77
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 {
82     ImplSource(DefId),
83     TraitSource(// trait id
84                 DefId),
85 }
86
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,
90                          span: Span,
91                          method_name: ast::Name,
92                          self_ty: ty::Ty<'tcx>,
93                          call_expr_id: ast::NodeId,
94                          allow_private: bool)
95                          -> bool {
96         let mode = probe::Mode::MethodCall;
97         match self.probe_for_name(span, mode, method_name, IsSuggestion(false),
98                                   self_ty, call_expr_id) {
99             Ok(..) => true,
100             Err(NoMatch(..)) => false,
101             Err(Ambiguity(..)) => true,
102             Err(ClosureAmbiguity(..)) => true,
103             Err(PrivateMatch(..)) => allow_private,
104         }
105     }
106
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).
110     ///
111     /// # Arguments
112     ///
113     /// Given a method call like `foo.bar::<T1,...Tn>(...)`:
114     ///
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,
122                          span: Span,
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={:?})",
130                method_name,
131                self_ty,
132                call_expr,
133                self_expr);
134
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)?;
139
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);
144         }
145
146         self.tcx.check_stability(pick.item.def_id, call_expr.id, span);
147
148         Ok(self.confirm_method(span,
149                                self_expr,
150                                call_expr,
151                                self_ty,
152                                pick,
153                                supplied_method_types))
154     }
155
156     pub fn lookup_method_in_trait(&self,
157                                   span: Span,
158                                   self_expr: Option<&hir::Expr>,
159                                   m_name: ast::Name,
160                                   trait_def_id: DefId,
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,
165                                              self_expr,
166                                              m_name,
167                                              trait_def_id,
168                                              0,
169                                              false,
170                                              self_ty,
171                                              opt_input_types)
172     }
173
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.
179     ///
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,
186                                            span: Span,
187                                            self_expr: Option<&hir::Expr>,
188                                            m_name: ast::Name,
189                                            trait_def_id: DefId,
190                                            autoderefs: usize,
191                                            unsize: bool,
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={:?})",
197                self_ty,
198                self_expr,
199                m_name,
200                trait_def_id);
201
202         // Construct a trait-reference `self_ty : Trait<input_tys>`
203         let substs = Substs::for_item(self.tcx,
204                                       trait_def_id,
205                                       |def, _| self.region_var_for_def(span, def),
206                                       |def, substs| {
207             if def.index == 0 {
208                 self_ty
209             } else if let Some(ref input_types) = opt_input_types {
210                 input_types[def.index as usize - 1]
211             } else {
212                 self.type_var_for_def(span, def, substs)
213             }
214         });
215
216         let trait_ref = ty::TraitRef::new(trait_def_id, substs);
217
218         // Construct an obligation
219         let poly_trait_ref = trait_ref.to_poly_trait_ref();
220         let obligation =
221             traits::Obligation::misc(span, self.body_id, poly_trait_ref.to_predicate());
222
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.
228         }
229
230         // Trait must have a method named `m_name` and it should not have
231         // type parameters or early-bound regions.
232         let tcx = self.tcx;
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);
238
239         debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
240         let mut obligations = vec![];
241
242         // Instantiate late-bound regions and substitute the trait
243         // parameters into the method type to get the actual method type.
244         //
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,
251                                                                     infer::FnCall,
252                                                                     &fn_sig).0;
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);
257                 value
258             }
259         };
260         let transformed_self_ty = fn_sig.inputs()[0];
261         let method_ty = tcx.mk_fn_def(def_id, substs, ty::Binder(fn_sig));
262
263         debug!("lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
264                method_ty,
265                obligation);
266
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.)
272         //
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);
279                 value
280             }
281         };
282         assert!(!bounds.has_escaping_regions());
283
284         let cause = traits::ObligationCause::misc(span, self.body_id);
285         obligations.extend(traits::predicates_for_generics(cause.clone(), &bounds));
286
287         // Also add an obligation for the method type being well-formed.
288         obligations.push(traits::Obligation::new(cause, ty::Predicate::WellFormed(method_ty)));
289
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);
295
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))
303                 }
304                 _ => {
305                     // Trait method is fn(self), no transformation needed.
306                     assert!(!unsize);
307                     None
308                 }
309             };
310
311             self.apply_adjustment(self_expr.id, Adjustment {
312                 kind: Adjust::DerefRef {
313                     autoderefs: autoderefs,
314                     autoref: autoref,
315                     unsize: unsize
316                 },
317                 target: transformed_self_ty
318             });
319         }
320
321         let callee = ty::MethodCallee {
322             def_id: def_id,
323             ty: method_ty,
324             substs: trait_ref.substs,
325         };
326
327         debug!("callee = {:?}", callee);
328
329         Some(InferOk {
330             obligations,
331             value: callee
332         })
333     }
334
335     pub fn resolve_ufcs(&self,
336                         span: Span,
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),
343                                        self_ty, expr_id)?;
344
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);
349         }
350
351         let def = pick.item.def();
352
353         self.tcx.check_stability(def.def_id(), expr_id, span);
354
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);
359             }
360         }
361         Ok(def)
362     }
363
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)
369     }
370 }