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