]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/monomorphize/mod.rs
refactor `ParamEnv::empty(Reveal)` into two distinct methods
[rust.git] / src / librustc_mir / monomorphize / mod.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 rustc::hir::def_id::DefId;
12 use rustc::middle::lang_items::DropInPlaceFnLangItem;
13 use rustc::traits;
14 use rustc::ty::adjustment::CustomCoerceUnsized;
15 use rustc::ty::subst::Kind;
16 use rustc::ty::{self, Ty, TyCtxt};
17
18 pub use rustc::ty::Instance;
19 pub use self::item::{MonoItem, MonoItemExt};
20
21 pub mod collector;
22 pub mod item;
23 pub mod partitioning;
24
25 #[inline(never)] // give this a place in the profiler
26 pub fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trans_items: I)
27     where I: Iterator<Item=&'a MonoItem<'tcx>>
28 {
29     let mut symbols: Vec<_> = trans_items.map(|trans_item| {
30         (trans_item, trans_item.symbol_name(tcx))
31     }).collect();
32
33     (&mut symbols[..]).sort_by(|&(_, ref sym1), &(_, ref sym2)|{
34         sym1.cmp(sym2)
35     });
36
37     for pair in (&symbols[..]).windows(2) {
38         let sym1 = &pair[0].1;
39         let sym2 = &pair[1].1;
40
41         if *sym1 == *sym2 {
42             let trans_item1 = pair[0].0;
43             let trans_item2 = pair[1].0;
44
45             let span1 = trans_item1.local_span(tcx);
46             let span2 = trans_item2.local_span(tcx);
47
48             // Deterministically select one of the spans for error reporting
49             let span = match (span1, span2) {
50                 (Some(span1), Some(span2)) => {
51                     Some(if span1.lo().0 > span2.lo().0 {
52                         span1
53                     } else {
54                         span2
55                     })
56                 }
57                 (Some(span), None) |
58                 (None, Some(span)) => Some(span),
59                 _ => None
60             };
61
62             let error_message = format!("symbol `{}` is already defined", sym1);
63
64             if let Some(span) = span {
65                 tcx.sess.span_fatal(span, &error_message)
66             } else {
67                 tcx.sess.fatal(&error_message)
68             }
69         }
70     }
71 }
72
73 fn fn_once_adapter_instance<'a, 'tcx>(
74     tcx: TyCtxt<'a, 'tcx, 'tcx>,
75     closure_did: DefId,
76     substs: ty::ClosureSubsts<'tcx>,
77     ) -> Instance<'tcx> {
78     debug!("fn_once_adapter_shim({:?}, {:?})",
79            closure_did,
80            substs);
81     let fn_once = tcx.lang_items().fn_once_trait().unwrap();
82     let call_once = tcx.associated_items(fn_once)
83         .find(|it| it.kind == ty::AssociatedKind::Method)
84         .unwrap().def_id;
85     let def = ty::InstanceDef::ClosureOnceShim { call_once };
86
87     let self_ty = tcx.mk_closure_from_closure_substs(
88         closure_did, substs);
89
90     let sig = substs.closure_sig(closure_did, tcx);
91     let sig = tcx.erase_late_bound_regions_and_normalize(&sig);
92     assert_eq!(sig.inputs().len(), 1);
93     let substs = tcx.mk_substs([
94         Kind::from(self_ty),
95         sig.inputs()[0].into(),
96     ].iter().cloned());
97
98     debug!("fn_once_adapter_shim: self_ty={:?} sig={:?}", self_ty, sig);
99     Instance { def, substs }
100 }
101
102 fn needs_fn_once_adapter_shim(actual_closure_kind: ty::ClosureKind,
103                               trait_closure_kind: ty::ClosureKind)
104                               -> Result<bool, ()>
105 {
106     match (actual_closure_kind, trait_closure_kind) {
107         (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
108         (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
109         (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
110             // No adapter needed.
111            Ok(false)
112         }
113         (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
114             // The closure fn `llfn` is a `fn(&self, ...)`.  We want a
115             // `fn(&mut self, ...)`. In fact, at trans time, these are
116             // basically the same thing, so we can just return llfn.
117             Ok(false)
118         }
119         (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
120         (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
121             // The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
122             // self, ...)`.  We want a `fn(self, ...)`. We can produce
123             // this by doing something like:
124             //
125             //     fn call_once(self, ...) { call_mut(&self, ...) }
126             //     fn call_once(mut self, ...) { call_mut(&mut self, ...) }
127             //
128             // These are both the same at trans time.
129             Ok(true)
130         }
131         _ => Err(()),
132     }
133 }
134
135 pub fn resolve_closure<'a, 'tcx> (
136     tcx: TyCtxt<'a, 'tcx, 'tcx>,
137     def_id: DefId,
138     substs: ty::ClosureSubsts<'tcx>,
139     requested_kind: ty::ClosureKind)
140     -> Instance<'tcx>
141 {
142     let actual_kind = substs.closure_kind(def_id, tcx);
143
144     match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
145         Ok(true) => fn_once_adapter_instance(tcx, def_id, substs),
146         _ => Instance::new(def_id, substs.substs)
147     }
148 }
149
150 pub fn resolve_drop_in_place<'a, 'tcx>(
151     tcx: TyCtxt<'a, 'tcx, 'tcx>,
152     ty: Ty<'tcx>)
153     -> ty::Instance<'tcx>
154 {
155     let def_id = tcx.require_lang_item(DropInPlaceFnLangItem);
156     let substs = tcx.intern_substs(&[ty.into()]);
157     Instance::resolve(tcx, ty::ParamEnv::reveal_all(), def_id, substs).unwrap()
158 }
159
160 pub fn custom_coerce_unsize_info<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
161                                            source_ty: Ty<'tcx>,
162                                            target_ty: Ty<'tcx>)
163                                            -> CustomCoerceUnsized {
164     let def_id = tcx.lang_items().coerce_unsized_trait().unwrap();
165
166     let trait_ref = ty::Binder(ty::TraitRef {
167         def_id: def_id,
168         substs: tcx.mk_substs_trait(source_ty, &[target_ty])
169     });
170
171     match tcx.trans_fulfill_obligation( (ty::ParamEnv::reveal_all(), trait_ref)) {
172         traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
173             tcx.coerce_unsized_info(impl_def_id).custom_kind.unwrap()
174         }
175         vtable => {
176             bug!("invalid CoerceUnsized vtable: {:?}", vtable);
177         }
178     }
179 }