]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/method/mod.rs
Fix conversion from Miri Value to ConstValue
[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-nursery.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::subst::Subst;
23 use rustc::infer::{self, InferOk};
24
25 use syntax::ast;
26 use syntax_pos::Span;
27
28 use rustc::hir;
29
30 use rustc_data_structures::sync::Lrc;
31
32 pub use self::MethodError::*;
33 pub use self::CandidateSource::*;
34 pub use self::suggest::TraitInfo;
35
36 mod confirm;
37 pub mod probe;
38 mod suggest;
39
40 use self::probe::{IsSuggestion, ProbeScope};
41
42 pub fn provide(providers: &mut ty::maps::Providers) {
43     suggest::provide(providers);
44 }
45
46 #[derive(Clone, Copy, Debug)]
47 pub struct MethodCallee<'tcx> {
48     /// Impl method ID, for inherent methods, or trait method ID, otherwise.
49     pub def_id: DefId,
50     pub substs: &'tcx Substs<'tcx>,
51
52     /// Instantiated method signature, i.e. it has been
53     /// substituted, normalized, and has had late-bound
54     /// lifetimes replaced with inference variables.
55     pub sig: ty::FnSig<'tcx>,
56 }
57
58 pub enum MethodError<'tcx> {
59     // Did not find an applicable method, but we did find various near-misses that may work.
60     NoMatch(NoMatchData<'tcx>),
61
62     // Multiple methods might apply.
63     Ambiguity(Vec<CandidateSource>),
64
65     // Found an applicable method, but it is not visible. The second argument contains a list of
66     // not-in-scope traits which may work.
67     PrivateMatch(Def, Vec<DefId>),
68
69     // Found a `Self: Sized` bound where `Self` is a trait object, also the caller may have
70     // forgotten to import a trait.
71     IllegalSizedBound(Vec<DefId>),
72
73     // Found a match, but the return type is wrong
74     BadReturnType,
75 }
76
77 // Contains a list of static methods that may apply, a list of unsatisfied trait predicates which
78 // could lead to matches if satisfied, and a list of not-in-scope traits which may work.
79 pub struct NoMatchData<'tcx> {
80     pub static_candidates: Vec<CandidateSource>,
81     pub unsatisfied_predicates: Vec<TraitRef<'tcx>>,
82     pub out_of_scope_traits: Vec<DefId>,
83     pub lev_candidate: Option<ty::AssociatedItem>,
84     pub mode: probe::Mode,
85 }
86
87 impl<'tcx> NoMatchData<'tcx> {
88     pub fn new(static_candidates: Vec<CandidateSource>,
89                unsatisfied_predicates: Vec<TraitRef<'tcx>>,
90                out_of_scope_traits: Vec<DefId>,
91                lev_candidate: Option<ty::AssociatedItem>,
92                mode: probe::Mode)
93                -> Self {
94         NoMatchData {
95             static_candidates,
96             unsatisfied_predicates,
97             out_of_scope_traits,
98             lev_candidate,
99             mode,
100         }
101     }
102 }
103
104 // A pared down enum describing just the places from which a method
105 // candidate can arise. Used for error reporting only.
106 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
107 pub enum CandidateSource {
108     ImplSource(DefId),
109     TraitSource(// trait id
110                 DefId),
111 }
112
113 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
114     /// Determines whether the type `self_ty` supports a method name `method_name` or not.
115     pub fn method_exists(&self,
116                          span: Span,
117                          method_name: ast::Name,
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(span, mode, method_name, IsSuggestion(false),
124                                   self_ty, call_expr_id, ProbeScope::TraitsInScope) {
125             Ok(..) => true,
126             Err(NoMatch(..)) => false,
127             Err(Ambiguity(..)) => true,
128             Err(PrivateMatch(..)) => allow_private,
129             Err(IllegalSizedBound(..)) => true,
130             Err(BadReturnType) => {
131                 bug!("no return type expectations but got BadReturnType")
132             }
133
134         }
135     }
136
137     /// Performs method lookup. If lookup is successful, it will return the callee
138     /// and store an appropriate adjustment for the self-expr. In some cases it may
139     /// report an error (e.g., invoking the `drop` method).
140     ///
141     /// # Arguments
142     ///
143     /// Given a method call like `foo.bar::<T1,...Tn>(...)`:
144     ///
145     /// * `fcx`:                   the surrounding `FnCtxt` (!)
146     /// * `span`:                  the span for the method call
147     /// * `method_name`:           the name of the method being called (`bar`)
148     /// * `self_ty`:               the (unadjusted) type of the self expression (`foo`)
149     /// * `supplied_method_types`: the explicit method type parameters, if any (`T1..Tn`)
150     /// * `self_expr`:             the self expression (`foo`)
151     pub fn lookup_method(&self,
152                          self_ty: Ty<'tcx>,
153                          segment: &hir::PathSegment,
154                          span: Span,
155                          call_expr: &'gcx hir::Expr,
156                          self_expr: &'gcx hir::Expr)
157                          -> Result<MethodCallee<'tcx>, MethodError<'tcx>> {
158         debug!("lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})",
159                segment.name,
160                self_ty,
161                call_expr,
162                self_expr);
163
164         let pick = self.lookup_probe(
165             span,
166             segment.name,
167             self_ty,
168             call_expr,
169             ProbeScope::TraitsInScope
170         )?;
171
172         if let Some(import_id) = pick.import_id {
173             let import_def_id = self.tcx.hir.local_def_id(import_id);
174             debug!("used_trait_import: {:?}", import_def_id);
175             Lrc::get_mut(&mut self.tables.borrow_mut().used_trait_imports)
176                                         .unwrap().insert(import_def_id);
177         }
178
179         self.tcx.check_stability(pick.item.def_id, Some(call_expr.id), span);
180
181         let result = self.confirm_method(span,
182                                          self_expr,
183                                          call_expr,
184                                          self_ty,
185                                          pick.clone(),
186                                          segment);
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.name,
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::Name,
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::Name,
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,
257                                       trait_def_id,
258                                       |def, _| self.region_var_for_def(span, def),
259                                       |def, _substs| {
260             if def.index == 0 {
261                 self_ty
262             } else if let Some(ref input_types) = opt_input_types {
263                 input_types[def.index as usize - 1]
264             } else {
265                 self.type_var_for_def(span, def)
266             }
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 = self.associated_item(trait_def_id, m_name, Namespace::Value).unwrap();
289         let def_id = method_item.def_id;
290         let generics = tcx.generics_of(def_id);
291         assert_eq!(generics.types.len(), 0);
292         assert_eq!(generics.regions.len(), 0);
293
294         debug!("lookup_in_trait_adjusted: method_item={:?}", method_item);
295         let mut obligations = vec![];
296
297         // Instantiate late-bound regions and substitute the trait
298         // parameters into the method type to get the actual method type.
299         //
300         // NB: Instantiate late-bound regions first so that
301         // `instantiate_type_scheme` can normalize associated types that
302         // may reference those regions.
303         let fn_sig = tcx.fn_sig(def_id);
304         let fn_sig = self.replace_late_bound_regions_with_fresh_var(span,
305                                                                     infer::FnCall,
306                                                                     &fn_sig).0;
307         let fn_sig = fn_sig.subst(self.tcx, substs);
308         let fn_sig = match self.normalize_associated_types_in_as_infer_ok(span, &fn_sig) {
309             InferOk { value, obligations: o } => {
310                 obligations.extend(o);
311                 value
312             }
313         };
314
315         // Register obligations for the parameters.  This will include the
316         // `Self` parameter, which in turn has a bound of the main trait,
317         // so this also effectively registers `obligation` as well.  (We
318         // used to register `obligation` explicitly, but that resulted in
319         // double error messages being reported.)
320         //
321         // Note that as the method comes from a trait, it should not have
322         // any late-bound regions appearing in its bounds.
323         let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
324         let bounds = match self.normalize_associated_types_in_as_infer_ok(span, &bounds) {
325             InferOk { value, obligations: o } => {
326                 obligations.extend(o);
327                 value
328             }
329         };
330         assert!(!bounds.has_escaping_regions());
331
332         let cause = traits::ObligationCause::misc(span, self.body_id);
333         obligations.extend(traits::predicates_for_generics(cause.clone(),
334                                                            self.param_env,
335                                                            &bounds));
336
337         // Also add an obligation for the method type being well-formed.
338         let method_ty = tcx.mk_fn_ptr(ty::Binder::bind(fn_sig));
339         debug!("lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
340                method_ty,
341                obligation);
342         obligations.push(traits::Obligation::new(cause,
343                                                  self.param_env,
344                                                  ty::Predicate::WellFormed(method_ty)));
345
346         let callee = MethodCallee {
347             def_id,
348             substs: trait_ref.substs,
349             sig: fn_sig,
350         };
351
352         debug!("callee = {:?}", callee);
353
354         Some(InferOk {
355             obligations,
356             value: callee
357         })
358     }
359
360     pub fn resolve_ufcs(&self,
361                         span: Span,
362                         method_name: ast::Name,
363                         self_ty: Ty<'tcx>,
364                         expr_id: ast::NodeId)
365                         -> Result<Def, MethodError<'tcx>> {
366         let mode = probe::Mode::Path;
367         let pick = self.probe_for_name(span, mode, method_name, IsSuggestion(false),
368                                        self_ty, expr_id, ProbeScope::TraitsInScope)?;
369
370         if let Some(import_id) = pick.import_id {
371             let import_def_id = self.tcx.hir.local_def_id(import_id);
372             debug!("used_trait_import: {:?}", import_def_id);
373             Lrc::get_mut(&mut self.tables.borrow_mut().used_trait_imports)
374                                         .unwrap().insert(import_def_id);
375         }
376
377         let def = pick.item.def();
378         self.tcx.check_stability(def.def_id(), Some(expr_id), span);
379
380         Ok(def)
381     }
382
383     /// Find item with name `item_name` defined in impl/trait `def_id`
384     /// and return it, or `None`, if no such item was defined there.
385     pub fn associated_item(&self, def_id: DefId, item_name: ast::Name, ns: Namespace)
386                            -> Option<ty::AssociatedItem> {
387         self.tcx.associated_items(def_id)
388                 .find(|item| Namespace::from(item.kind) == ns &&
389                              self.tcx.hygienic_eq(item_name, item.name, def_id))
390     }
391 }