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