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