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