]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/instance.rs
refactor `ParamEnv::empty(Reveal)` into two distinct methods
[rust.git] / src / librustc / ty / instance.rs
1 // Copyright 2016 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 use hir::def_id::DefId;
12 use ty::{self, Ty, TypeFoldable, Substs, TyCtxt};
13 use ty::subst::Kind;
14 use traits;
15 use syntax::abi::Abi;
16 use util::ppaux;
17
18 use std::fmt;
19
20 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
21 pub struct Instance<'tcx> {
22     pub def: InstanceDef<'tcx>,
23     pub substs: &'tcx Substs<'tcx>,
24 }
25
26 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
27 pub enum InstanceDef<'tcx> {
28     Item(DefId),
29     Intrinsic(DefId),
30
31     /// \<fn() as FnTrait>::call_*
32     /// def-id is FnTrait::call_*
33     FnPtrShim(DefId, Ty<'tcx>),
34
35     /// <Trait as Trait>::fn
36     Virtual(DefId, usize),
37
38     /// <[mut closure] as FnOnce>::call_once
39     ClosureOnceShim { call_once: DefId },
40
41     /// drop_in_place::<T>; None for empty drop glue.
42     DropGlue(DefId, Option<Ty<'tcx>>),
43
44     ///`<T as Clone>::clone` shim.
45     CloneShim(DefId, Ty<'tcx>),
46 }
47
48 impl<'a, 'tcx> Instance<'tcx> {
49     pub fn ty(&self,
50               tcx: TyCtxt<'a, 'tcx, 'tcx>)
51               -> Ty<'tcx>
52     {
53         let ty = tcx.type_of(self.def.def_id());
54         tcx.trans_apply_param_substs(self.substs, &ty)
55     }
56 }
57
58 impl<'tcx> InstanceDef<'tcx> {
59     #[inline]
60     pub fn def_id(&self) -> DefId {
61         match *self {
62             InstanceDef::Item(def_id) |
63             InstanceDef::FnPtrShim(def_id, _) |
64             InstanceDef::Virtual(def_id, _) |
65             InstanceDef::Intrinsic(def_id, ) |
66             InstanceDef::ClosureOnceShim { call_once: def_id } |
67             InstanceDef::DropGlue(def_id, _) |
68             InstanceDef::CloneShim(def_id, _) => def_id
69         }
70     }
71
72     #[inline]
73     pub fn attrs<'a>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::Attributes<'tcx> {
74         tcx.get_attrs(self.def_id())
75     }
76
77     pub fn is_inline<'a>(
78         &self,
79         tcx: TyCtxt<'a, 'tcx, 'tcx>
80     ) -> bool {
81         use hir::map::DefPathData;
82         let def_id = match *self {
83             ty::InstanceDef::Item(def_id) => def_id,
84             ty::InstanceDef::DropGlue(_, Some(_)) => return false,
85             _ => return true
86         };
87         match tcx.def_key(def_id).disambiguated_data.data {
88             DefPathData::StructCtor |
89             DefPathData::EnumVariant(..) |
90             DefPathData::ClosureExpr => true,
91             _ => false
92         }
93     }
94
95     pub fn requires_local<'a>(
96         &self,
97         tcx: TyCtxt<'a, 'tcx, 'tcx>
98     ) -> bool {
99         if self.is_inline(tcx) {
100             return true
101         }
102         if let ty::InstanceDef::DropGlue(..) = *self {
103             // Drop glue wants to be instantiated at every translation
104             // unit, but without an #[inline] hint. We should make this
105             // available to normal end-users.
106             return true
107         }
108         let trans_fn_attrs = tcx.trans_fn_attrs(self.def_id());
109         trans_fn_attrs.requests_inline() || tcx.is_const_fn(self.def_id())
110     }
111 }
112
113 impl<'tcx> fmt::Display for Instance<'tcx> {
114     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115         ppaux::parameterized(f, self.substs, self.def_id(), &[])?;
116         match self.def {
117             InstanceDef::Item(_) => Ok(()),
118             InstanceDef::Intrinsic(_) => {
119                 write!(f, " - intrinsic")
120             }
121             InstanceDef::Virtual(_, num) => {
122                 write!(f, " - shim(#{})", num)
123             }
124             InstanceDef::FnPtrShim(_, ty) => {
125                 write!(f, " - shim({:?})", ty)
126             }
127             InstanceDef::ClosureOnceShim { .. } => {
128                 write!(f, " - shim")
129             }
130             InstanceDef::DropGlue(_, ty) => {
131                 write!(f, " - shim({:?})", ty)
132             }
133             InstanceDef::CloneShim(_, ty) => {
134                 write!(f, " - shim({:?})", ty)
135             }
136         }
137     }
138 }
139
140 impl<'a, 'b, 'tcx> Instance<'tcx> {
141     pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>)
142                -> Instance<'tcx> {
143         assert!(!substs.has_escaping_regions(),
144                 "substs of instance {:?} not normalized for trans: {:?}",
145                 def_id, substs);
146         Instance { def: InstanceDef::Item(def_id), substs: substs }
147     }
148
149     pub fn mono(tcx: TyCtxt<'a, 'tcx, 'b>, def_id: DefId) -> Instance<'tcx> {
150         Instance::new(def_id, tcx.global_tcx().empty_substs_for_def_id(def_id))
151     }
152
153     #[inline]
154     pub fn def_id(&self) -> DefId {
155         self.def.def_id()
156     }
157
158     /// Resolve a (def_id, substs) pair to an (optional) instance -- most commonly,
159     /// this is used to find the precise code that will run for a trait method invocation,
160     /// if known.
161     ///
162     /// Returns `None` if we cannot resolve `Instance` to a specific instance.
163     /// For example, in a context like this,
164     ///
165     /// ```
166     /// fn foo<T: Debug>(t: T) { ... }
167     /// ```
168     ///
169     /// trying to resolve `Debug::fmt` applied to `T` will yield `None`, because we do not
170     /// know what code ought to run. (Note that this setting is also affected by the
171     /// `RevealMode` in the parameter environment.)
172     ///
173     /// Presuming that coherence and type-check have succeeded, if this method is invoked
174     /// in a monomorphic context (i.e., like during trans), then it is guaranteed to return
175     /// `Some`.
176     pub fn resolve(tcx: TyCtxt<'a, 'tcx, 'tcx>,
177                    param_env: ty::ParamEnv<'tcx>,
178                    def_id: DefId,
179                    substs: &'tcx Substs<'tcx>) -> Option<Instance<'tcx>> {
180         debug!("resolve(def_id={:?}, substs={:?})", def_id, substs);
181         let result = if let Some(trait_def_id) = tcx.trait_of_item(def_id) {
182             debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env);
183             let item = tcx.associated_item(def_id);
184             resolve_associated_item(tcx, &item, param_env, trait_def_id, substs)
185         } else {
186             let ty = tcx.type_of(def_id);
187             let item_type = tcx.trans_apply_param_substs_env(substs, param_env, &ty);
188
189             let def = match item_type.sty {
190                 ty::TyFnDef(..) if {
191                     let f = item_type.fn_sig(tcx);
192                     f.abi() == Abi::RustIntrinsic ||
193                         f.abi() == Abi::PlatformIntrinsic
194                 } =>
195                 {
196                     debug!(" => intrinsic");
197                     ty::InstanceDef::Intrinsic(def_id)
198                 }
199                 _ => {
200                     if Some(def_id) == tcx.lang_items().drop_in_place_fn() {
201                         let ty = substs.type_at(0);
202                         if ty.needs_drop(tcx, ty::ParamEnv::reveal_all()) {
203                             debug!(" => nontrivial drop glue");
204                             ty::InstanceDef::DropGlue(def_id, Some(ty))
205                         } else {
206                             debug!(" => trivial drop glue");
207                             ty::InstanceDef::DropGlue(def_id, None)
208                         }
209                     } else {
210                         debug!(" => free item");
211                         ty::InstanceDef::Item(def_id)
212                     }
213                 }
214             };
215             Some(Instance {
216                 def: def,
217                 substs: substs
218             })
219         };
220         debug!("resolve(def_id={:?}, substs={:?}) = {:?}", def_id, substs, result);
221         result
222     }
223
224     pub fn resolve_closure(
225                     tcx: TyCtxt<'a, 'tcx, 'tcx>,
226                     def_id: DefId,
227                     substs: ty::ClosureSubsts<'tcx>,
228                     requested_kind: ty::ClosureKind)
229     -> Instance<'tcx>
230     {
231         let actual_kind = substs.closure_kind(def_id, tcx);
232
233         match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
234             Ok(true) => fn_once_adapter_instance(tcx, def_id, substs),
235             _ => Instance::new(def_id, substs.substs)
236         }
237     }
238 }
239
240 fn resolve_associated_item<'a, 'tcx>(
241     tcx: TyCtxt<'a, 'tcx, 'tcx>,
242     trait_item: &ty::AssociatedItem,
243     param_env: ty::ParamEnv<'tcx>,
244     trait_id: DefId,
245     rcvr_substs: &'tcx Substs<'tcx>,
246 ) -> Option<Instance<'tcx>> {
247     let def_id = trait_item.def_id;
248     debug!("resolve_associated_item(trait_item={:?}, \
249                                     trait_id={:?}, \
250            rcvr_substs={:?})",
251            def_id, trait_id, rcvr_substs);
252
253     let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
254     let vtbl = tcx.trans_fulfill_obligation((param_env, ty::Binder(trait_ref)));
255
256     // Now that we know which impl is being used, we can dispatch to
257     // the actual function:
258     match vtbl {
259         traits::VtableImpl(impl_data) => {
260             let (def_id, substs) = traits::find_associated_item(
261                 tcx, trait_item, rcvr_substs, &impl_data);
262             let substs = tcx.erase_regions(&substs);
263             Some(ty::Instance::new(def_id, substs))
264         }
265         traits::VtableGenerator(closure_data) => {
266             Some(Instance {
267                 def: ty::InstanceDef::Item(closure_data.closure_def_id),
268                 substs: closure_data.substs.substs
269             })
270         }
271         traits::VtableClosure(closure_data) => {
272             let trait_closure_kind = tcx.lang_items().fn_trait_kind(trait_id).unwrap();
273             Some(Instance::resolve_closure(tcx, closure_data.closure_def_id, closure_data.substs,
274                                  trait_closure_kind))
275         }
276         traits::VtableFnPointer(ref data) => {
277             Some(Instance {
278                 def: ty::InstanceDef::FnPtrShim(trait_item.def_id, data.fn_ty),
279                 substs: rcvr_substs
280             })
281         }
282         traits::VtableObject(ref data) => {
283             let index = tcx.get_vtable_index_of_object_method(data, def_id);
284             Some(Instance {
285                 def: ty::InstanceDef::Virtual(def_id, index),
286                 substs: rcvr_substs
287             })
288         }
289         traits::VtableBuiltin(..) => {
290             if let Some(_) = tcx.lang_items().clone_trait() {
291                 Some(Instance {
292                     def: ty::InstanceDef::CloneShim(def_id, trait_ref.self_ty()),
293                     substs: rcvr_substs
294                 })
295             } else {
296                 None
297             }
298         }
299         traits::VtableAutoImpl(..) | traits::VtableParam(..) => None
300     }
301 }
302
303 fn needs_fn_once_adapter_shim<'a, 'tcx>(actual_closure_kind: ty::ClosureKind,
304                               trait_closure_kind: ty::ClosureKind)
305     -> Result<bool, ()>
306 {
307     match (actual_closure_kind, trait_closure_kind) {
308         (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
309             (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
310             (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
311                 // No adapter needed.
312                 Ok(false)
313             }
314         (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
315             // The closure fn `llfn` is a `fn(&self, ...)`.  We want a
316             // `fn(&mut self, ...)`. In fact, at trans time, these are
317             // basically the same thing, so we can just return llfn.
318             Ok(false)
319         }
320         (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
321             (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
322                 // The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
323                 // self, ...)`.  We want a `fn(self, ...)`. We can produce
324                 // this by doing something like:
325                 //
326                 //     fn call_once(self, ...) { call_mut(&self, ...) }
327                 //     fn call_once(mut self, ...) { call_mut(&mut self, ...) }
328                 //
329                 // These are both the same at trans time.
330                 Ok(true)
331         }
332         (ty::ClosureKind::FnMut, _) |
333         (ty::ClosureKind::FnOnce, _) => Err(())
334     }
335 }
336
337 fn fn_once_adapter_instance<'a, 'tcx>(
338                             tcx: TyCtxt<'a, 'tcx, 'tcx>,
339                             closure_did: DefId,
340                             substs: ty::ClosureSubsts<'tcx>,
341                             ) -> Instance<'tcx> {
342     debug!("fn_once_adapter_shim({:?}, {:?})",
343     closure_did,
344     substs);
345     let fn_once = tcx.lang_items().fn_once_trait().unwrap();
346     let call_once = tcx.associated_items(fn_once)
347         .find(|it| it.kind == ty::AssociatedKind::Method)
348         .unwrap().def_id;
349     let def = ty::InstanceDef::ClosureOnceShim { call_once };
350
351     let self_ty = tcx.mk_closure_from_closure_substs(
352         closure_did, substs);
353
354     let sig = substs.closure_sig(closure_did, tcx);
355     let sig = tcx.erase_late_bound_regions_and_normalize(&sig);
356     assert_eq!(sig.inputs().len(), 1);
357     let substs = tcx.mk_substs([Kind::from(self_ty), sig.inputs()[0].into()].iter().cloned());
358
359     debug!("fn_once_adapter_shim: self_ty={:?} sig={:?}", self_ty, sig);
360     Instance { def, substs }
361 }