]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/monomorphize.rs
rustdoc: pretty-print Unevaluated expressions in types.
[rust.git] / src / librustc_trans / monomorphize.rs
1 // Copyright 2012-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 use abi::Abi;
12 use common::*;
13 use glue;
14
15 use rustc::hir::def_id::DefId;
16 use rustc::middle::lang_items::DropInPlaceFnLangItem;
17 use rustc::traits;
18 use rustc::ty::adjustment::CustomCoerceUnsized;
19 use rustc::ty::subst::{Kind, Subst, Substs};
20 use rustc::ty::{self, Ty, TyCtxt};
21
22 use syntax::codemap::DUMMY_SP;
23
24 pub use rustc::ty::Instance;
25
26 fn fn_once_adapter_instance<'a, 'tcx>(
27     tcx: TyCtxt<'a, 'tcx, 'tcx>,
28     closure_did: DefId,
29     substs: ty::ClosureSubsts<'tcx>,
30     ) -> Instance<'tcx> {
31     debug!("fn_once_adapter_shim({:?}, {:?})",
32            closure_did,
33            substs);
34     let fn_once = tcx.lang_items().fn_once_trait().unwrap();
35     let call_once = tcx.associated_items(fn_once)
36         .find(|it| it.kind == ty::AssociatedKind::Method)
37         .unwrap().def_id;
38     let def = ty::InstanceDef::ClosureOnceShim { call_once };
39
40     let self_ty = tcx.mk_closure_from_closure_substs(
41         closure_did, substs);
42
43     let sig = tcx.fn_sig(closure_did).subst(tcx, substs.substs);
44     let sig = tcx.erase_late_bound_regions_and_normalize(&sig);
45     assert_eq!(sig.inputs().len(), 1);
46     let substs = tcx.mk_substs([
47         Kind::from(self_ty),
48         Kind::from(sig.inputs()[0]),
49     ].iter().cloned());
50
51     debug!("fn_once_adapter_shim: self_ty={:?} sig={:?}", self_ty, sig);
52     Instance { def, substs }
53 }
54
55 fn needs_fn_once_adapter_shim(actual_closure_kind: ty::ClosureKind,
56                               trait_closure_kind: ty::ClosureKind)
57                               -> Result<bool, ()>
58 {
59     match (actual_closure_kind, trait_closure_kind) {
60         (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
61         (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
62         (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
63             // No adapter needed.
64            Ok(false)
65         }
66         (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
67             // The closure fn `llfn` is a `fn(&self, ...)`.  We want a
68             // `fn(&mut self, ...)`. In fact, at trans time, these are
69             // basically the same thing, so we can just return llfn.
70             Ok(false)
71         }
72         (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
73         (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
74             // The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
75             // self, ...)`.  We want a `fn(self, ...)`. We can produce
76             // this by doing something like:
77             //
78             //     fn call_once(self, ...) { call_mut(&self, ...) }
79             //     fn call_once(mut self, ...) { call_mut(&mut self, ...) }
80             //
81             // These are both the same at trans time.
82             Ok(true)
83         }
84         _ => Err(()),
85     }
86 }
87
88 pub fn resolve_closure<'a, 'tcx> (
89     scx: &SharedCrateContext<'a, 'tcx>,
90     def_id: DefId,
91     substs: ty::ClosureSubsts<'tcx>,
92     requested_kind: ty::ClosureKind)
93     -> Instance<'tcx>
94 {
95     let actual_kind = scx.tcx().closure_kind(def_id);
96
97     match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
98         Ok(true) => fn_once_adapter_instance(scx.tcx(), def_id, substs),
99         _ => Instance::new(def_id, substs.substs)
100     }
101 }
102
103 fn resolve_associated_item<'a, 'tcx>(
104     scx: &SharedCrateContext<'a, 'tcx>,
105     trait_item: &ty::AssociatedItem,
106     trait_id: DefId,
107     rcvr_substs: &'tcx Substs<'tcx>
108 ) -> Instance<'tcx> {
109     let tcx = scx.tcx();
110     let def_id = trait_item.def_id;
111     debug!("resolve_associated_item(trait_item={:?}, \
112                                     trait_id={:?}, \
113                                     rcvr_substs={:?})",
114            def_id, trait_id, rcvr_substs);
115
116     let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
117     let vtbl = tcx.trans_fulfill_obligation(DUMMY_SP, ty::Binder(trait_ref));
118
119     // Now that we know which impl is being used, we can dispatch to
120     // the actual function:
121     match vtbl {
122         traits::VtableImpl(impl_data) => {
123             let (def_id, substs) = traits::find_associated_item(
124                 tcx, trait_item, rcvr_substs, &impl_data);
125             let substs = tcx.erase_regions(&substs);
126             ty::Instance::new(def_id, substs)
127         }
128         traits::VtableGenerator(closure_data) => {
129             Instance {
130                 def: ty::InstanceDef::Item(closure_data.closure_def_id),
131                 substs: closure_data.substs.substs
132             }
133         }
134         traits::VtableClosure(closure_data) => {
135             let trait_closure_kind = tcx.lang_items().fn_trait_kind(trait_id).unwrap();
136             resolve_closure(scx, closure_data.closure_def_id, closure_data.substs,
137                             trait_closure_kind)
138         }
139         traits::VtableFnPointer(ref data) => {
140             Instance {
141                 def: ty::InstanceDef::FnPtrShim(trait_item.def_id, data.fn_ty),
142                 substs: rcvr_substs
143             }
144         }
145         traits::VtableObject(ref data) => {
146             let index = tcx.get_vtable_index_of_object_method(data, def_id);
147             Instance {
148                 def: ty::InstanceDef::Virtual(def_id, index),
149                 substs: rcvr_substs
150             }
151         }
152         traits::VtableBuiltin(..) if Some(trait_id) == tcx.lang_items().clone_trait() => {
153             Instance {
154                 def: ty::InstanceDef::CloneShim(def_id, trait_ref.self_ty()),
155                 substs: rcvr_substs
156             }
157         }
158         _ => {
159             bug!("static call to invalid vtable: {:?}", vtbl)
160         }
161     }
162 }
163
164 /// The point where linking happens. Resolve a (def_id, substs)
165 /// pair to an instance.
166 pub fn resolve<'a, 'tcx>(
167     scx: &SharedCrateContext<'a, 'tcx>,
168     def_id: DefId,
169     substs: &'tcx Substs<'tcx>
170 ) -> Instance<'tcx> {
171     debug!("resolve(def_id={:?}, substs={:?})",
172            def_id, substs);
173     let result = if let Some(trait_def_id) = scx.tcx().trait_of_item(def_id) {
174         debug!(" => associated item, attempting to find impl");
175         let item = scx.tcx().associated_item(def_id);
176         resolve_associated_item(scx, &item, trait_def_id, substs)
177     } else {
178         let item_type = def_ty(scx, def_id, substs);
179         let def = match item_type.sty {
180             ty::TyFnDef(..) if {
181                     let f = item_type.fn_sig(scx.tcx());
182                     f.abi() == Abi::RustIntrinsic ||
183                     f.abi() == Abi::PlatformIntrinsic
184                 } =>
185             {
186                 debug!(" => intrinsic");
187                 ty::InstanceDef::Intrinsic(def_id)
188             }
189             _ => {
190                 if Some(def_id) == scx.tcx().lang_items().drop_in_place_fn() {
191                     let ty = substs.type_at(0);
192                     if glue::needs_drop_glue(scx, ty) {
193                         debug!(" => nontrivial drop glue");
194                         ty::InstanceDef::DropGlue(def_id, Some(ty))
195                     } else {
196                         debug!(" => trivial drop glue");
197                         ty::InstanceDef::DropGlue(def_id, None)
198                     }
199                 } else {
200                     debug!(" => free item");
201                     ty::InstanceDef::Item(def_id)
202                 }
203             }
204         };
205         Instance { def, substs }
206     };
207     debug!("resolve(def_id={:?}, substs={:?}) = {}",
208            def_id, substs, result);
209     result
210 }
211
212 pub fn resolve_drop_in_place<'a, 'tcx>(
213     scx: &SharedCrateContext<'a, 'tcx>,
214     ty: Ty<'tcx>)
215     -> ty::Instance<'tcx>
216 {
217     let def_id = scx.tcx().require_lang_item(DropInPlaceFnLangItem);
218     let substs = scx.tcx().intern_substs(&[Kind::from(ty)]);
219     resolve(scx, def_id, substs)
220 }
221
222 pub fn custom_coerce_unsize_info<'scx, 'tcx>(scx: &SharedCrateContext<'scx, 'tcx>,
223                                              source_ty: Ty<'tcx>,
224                                              target_ty: Ty<'tcx>)
225                                              -> CustomCoerceUnsized {
226     let trait_ref = ty::Binder(ty::TraitRef {
227         def_id: scx.tcx().lang_items().coerce_unsized_trait().unwrap(),
228         substs: scx.tcx().mk_substs_trait(source_ty, &[target_ty])
229     });
230
231     match scx.tcx().trans_fulfill_obligation(DUMMY_SP, trait_ref) {
232         traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
233             scx.tcx().coerce_unsized_info(impl_def_id).custom_kind.unwrap()
234         }
235         vtable => {
236             bug!("invalid CoerceUnsized vtable: {:?}", vtable);
237         }
238     }
239 }
240
241 /// Returns the normalized type of a struct field
242 pub fn field_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
243                           param_substs: &Substs<'tcx>,
244                           f: &'tcx ty::FieldDef)
245                           -> Ty<'tcx>
246 {
247     tcx.normalize_associated_type(&f.ty(tcx, param_substs))
248 }
249