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