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