]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/intrinsicck.rs
Auto merge of #30341 - pnkfelix:call-site-scope, r=nikomatsakis
[rust.git] / src / librustc / middle / intrinsicck.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 middle::def::DefFn;
12 use middle::def_id::DefId;
13 use middle::subst::{Subst, Substs, EnumeratedItems};
14 use middle::ty::{TransmuteRestriction, ctxt, TyBareFn};
15 use middle::ty::{self, Ty, HasTypeFlags};
16
17 use std::fmt;
18
19 use syntax::abi::RustIntrinsic;
20 use syntax::ast;
21 use syntax::codemap::Span;
22 use rustc_front::intravisit::{self, Visitor, FnKind};
23 use rustc_front::hir;
24
25 pub fn check_crate(tcx: &ctxt) {
26     let mut visitor = IntrinsicCheckingVisitor {
27         tcx: tcx,
28         param_envs: Vec::new(),
29         dummy_sized_ty: tcx.types.isize,
30         dummy_unsized_ty: tcx.mk_slice(tcx.types.isize),
31     };
32     tcx.map.krate().visit_all_items(&mut visitor);
33 }
34
35 struct IntrinsicCheckingVisitor<'a, 'tcx: 'a> {
36     tcx: &'a ctxt<'tcx>,
37
38     // As we traverse the AST, we keep a stack of the parameter
39     // environments for each function we encounter. When we find a
40     // call to `transmute`, we can check it in the context of the top
41     // of the stack (which ought not to be empty).
42     param_envs: Vec<ty::ParameterEnvironment<'a,'tcx>>,
43
44     // Dummy sized/unsized types that use to substitute for type
45     // parameters in order to estimate how big a type will be for any
46     // possible instantiation of the type parameters in scope.  See
47     // `check_transmute` for more details.
48     dummy_sized_ty: Ty<'tcx>,
49     dummy_unsized_ty: Ty<'tcx>,
50 }
51
52 impl<'a, 'tcx> IntrinsicCheckingVisitor<'a, 'tcx> {
53     fn def_id_is_transmute(&self, def_id: DefId) -> bool {
54         let intrinsic = match self.tcx.lookup_item_type(def_id).ty.sty {
55             ty::TyBareFn(_, ref bfty) => bfty.abi == RustIntrinsic,
56             _ => return false
57         };
58         intrinsic && self.tcx.item_name(def_id).as_str() == "transmute"
59     }
60
61     fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>, id: ast::NodeId) {
62         // Find the parameter environment for the most recent function that
63         // we entered.
64
65         let param_env = match self.param_envs.last() {
66             Some(p) => p,
67             None => {
68                 self.tcx.sess.span_bug(
69                     span,
70                     "transmute encountered outside of any fn");
71             }
72         };
73
74         // Simple case: no type parameters involved.
75         if
76             !from.has_param_types() && !from.has_self_ty() &&
77             !to.has_param_types() && !to.has_self_ty()
78         {
79             let restriction = TransmuteRestriction {
80                 span: span,
81                 original_from: from,
82                 original_to: to,
83                 substituted_from: from,
84                 substituted_to: to,
85                 id: id,
86             };
87             self.push_transmute_restriction(restriction);
88             return;
89         }
90
91         // The rules around type parameters are a bit subtle. We are
92         // checking these rules before monomorphization, so there may
93         // be unsubstituted type parameters present in the
94         // types. Obviously we cannot create LLVM types for those.
95         // However, if a type parameter appears only indirectly (i.e.,
96         // through a pointer), it does not necessarily affect the
97         // size, so that should be allowed. The only catch is that we
98         // DO want to be careful around unsized type parameters, since
99         // fat pointers have a different size than a thin pointer, and
100         // hence `&T` and `&U` have different sizes if `T : Sized` but
101         // `U : Sized` does not hold.
102         //
103         // However, it's not as simple as checking whether `T :
104         // Sized`, because even if `T : Sized` does not hold, that
105         // just means that `T` *may* not be sized.  After all, even a
106         // type parameter `T: ?Sized` could be bound to a sized
107         // type. (Issue #20116)
108         //
109         // To handle this, we first check for "interior" type
110         // parameters, which are always illegal. If there are none of
111         // those, then we know that the only way that all type
112         // parameters `T` are referenced indirectly, e.g. via a
113         // pointer type like `&T`. In that case, we only care whether
114         // `T` is sized or not, because that influences whether `&T`
115         // is a thin or fat pointer.
116         //
117         // One could imagine establishing a sophisticated constraint
118         // system to ensure that the transmute is legal, but instead
119         // we do something brutally dumb. We just substitute dummy
120         // sized or unsized types for every type parameter in scope,
121         // exhaustively checking all possible combinations. Here are some examples:
122         //
123         // ```
124         // fn foo<T, U>() {
125         //     // T=int, U=int
126         // }
127         //
128         // fn bar<T: ?Sized, U>() {
129         //     // T=int, U=int
130         //     // T=[int], U=int
131         // }
132         //
133         // fn baz<T: ?Sized, U: ?Sized>() {
134         //     // T=int, U=int
135         //     // T=[int], U=int
136         //     // T=int, U=[int]
137         //     // T=[int], U=[int]
138         // }
139         // ```
140         //
141         // In all cases, we keep the original unsubstituted types
142         // around for error reporting.
143
144         let from_tc = from.type_contents(self.tcx);
145         let to_tc = to.type_contents(self.tcx);
146         if from_tc.interior_param() || to_tc.interior_param() {
147             span_err!(self.tcx.sess, span, E0139,
148                       "cannot transmute to or from a type that contains \
149                        unsubstituted type parameters");
150             return;
151         }
152
153         let mut substs = param_env.free_substs.clone();
154         self.with_each_combination(
155             span,
156             param_env,
157             param_env.free_substs.types.iter_enumerated(),
158             &mut substs,
159             &mut |substs| {
160                 let restriction = TransmuteRestriction {
161                     span: span,
162                     original_from: from,
163                     original_to: to,
164                     substituted_from: from.subst(self.tcx, substs),
165                     substituted_to: to.subst(self.tcx, substs),
166                     id: id,
167                 };
168                 self.push_transmute_restriction(restriction);
169             });
170     }
171
172     fn with_each_combination(&self,
173                              span: Span,
174                              param_env: &ty::ParameterEnvironment<'a,'tcx>,
175                              mut types_in_scope: EnumeratedItems<Ty<'tcx>>,
176                              substs: &mut Substs<'tcx>,
177                              callback: &mut FnMut(&Substs<'tcx>))
178     {
179         // This parameter invokes `callback` many times with different
180         // substitutions that replace all the parameters in scope with
181         // either `int` or `[int]`, depending on whether the type
182         // parameter is known to be sized. See big comment above for
183         // an explanation of why this is a reasonable thing to do.
184
185         match types_in_scope.next() {
186             None => {
187                 debug!("with_each_combination(substs={:?})",
188                        substs);
189
190                 callback(substs);
191             }
192
193             Some((space, index, &param_ty)) => {
194                 debug!("with_each_combination: space={:?}, index={}, param_ty={:?}",
195                        space, index, param_ty);
196
197                 if !param_ty.is_sized(param_env, span) {
198                     debug!("with_each_combination: param_ty is not known to be sized");
199
200                     substs.types.get_mut_slice(space)[index] = self.dummy_unsized_ty;
201                     self.with_each_combination(span, param_env, types_in_scope.clone(),
202                                                substs, callback);
203                 }
204
205                 substs.types.get_mut_slice(space)[index] = self.dummy_sized_ty;
206                 self.with_each_combination(span, param_env, types_in_scope,
207                                            substs, callback);
208             }
209         }
210     }
211
212     fn push_transmute_restriction(&self, restriction: TransmuteRestriction<'tcx>) {
213         debug!("Pushing transmute restriction: {:?}", restriction);
214         self.tcx.transmute_restrictions.borrow_mut().push(restriction);
215     }
216 }
217
218 impl<'a, 'tcx, 'v> Visitor<'v> for IntrinsicCheckingVisitor<'a, 'tcx> {
219     fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v hir::FnDecl,
220                 b: &'v hir::Block, s: Span, id: ast::NodeId) {
221         match fk {
222             FnKind::ItemFn(..) | FnKind::Method(..) => {
223                 let param_env = ty::ParameterEnvironment::for_item(self.tcx, id);
224                 self.param_envs.push(param_env);
225                 intravisit::walk_fn(self, fk, fd, b, s);
226                 self.param_envs.pop();
227             }
228             FnKind::Closure => {
229                 intravisit::walk_fn(self, fk, fd, b, s);
230             }
231         }
232     }
233
234     fn visit_expr(&mut self, expr: &hir::Expr) {
235         if let hir::ExprPath(..) = expr.node {
236             match self.tcx.resolve_expr(expr) {
237                 DefFn(did, _) if self.def_id_is_transmute(did) => {
238                     let typ = self.tcx.node_id_to_type(expr.id);
239                     match typ.sty {
240                         TyBareFn(_, ref bare_fn_ty) if bare_fn_ty.abi == RustIntrinsic => {
241                             if let ty::FnConverging(to) = bare_fn_ty.sig.0.output {
242                                 let from = bare_fn_ty.sig.0.inputs[0];
243                                 self.check_transmute(expr.span, from, to, expr.id);
244                             }
245                         }
246                         _ => {
247                             self.tcx
248                                 .sess
249                                 .span_bug(expr.span, "transmute wasn't a bare fn?!");
250                         }
251                     }
252                 }
253                 _ => {}
254             }
255         }
256
257         intravisit::walk_expr(self, expr);
258     }
259 }
260
261 impl<'tcx> fmt::Debug for TransmuteRestriction<'tcx> {
262     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
263         write!(f, "TransmuteRestriction(id={}, original=({:?},{:?}), substituted=({:?},{:?}))",
264                self.id,
265                self.original_from,
266                self.original_to,
267                self.substituted_from,
268                self.substituted_to)
269     }
270 }