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.
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.
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};
19 use syntax::abi::RustIntrinsic;
21 use syntax::codemap::Span;
22 use rustc_front::intravisit::{self, Visitor, FnKind};
25 pub fn check_crate(tcx: &ctxt) {
26 let mut visitor = IntrinsicCheckingVisitor {
28 param_envs: Vec::new(),
29 dummy_sized_ty: tcx.types.isize,
30 dummy_unsized_ty: tcx.mk_slice(tcx.types.isize),
32 tcx.map.krate().visit_all_items(&mut visitor);
35 struct IntrinsicCheckingVisitor<'a, 'tcx: 'a> {
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>>,
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>,
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,
58 intrinsic && self.tcx.item_name(def_id).as_str() == "transmute"
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
65 let param_env = match self.param_envs.last() {
68 self.tcx.sess.span_bug(
70 "transmute encountered outside of any fn");
74 // Simple case: no type parameters involved.
76 !from.has_param_types() && !from.has_self_ty() &&
77 !to.has_param_types() && !to.has_self_ty()
79 let restriction = TransmuteRestriction {
83 substituted_from: from,
87 self.push_transmute_restriction(restriction);
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.
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)
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.
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:
128 // fn bar<T: ?Sized, U>() {
133 // fn baz<T: ?Sized, U: ?Sized>() {
137 // // T=[int], U=[int]
141 // In all cases, we keep the original unsubstituted types
142 // around for error reporting.
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");
153 let mut substs = param_env.free_substs.clone();
154 self.with_each_combination(
157 param_env.free_substs.types.iter_enumerated(),
160 let restriction = TransmuteRestriction {
164 substituted_from: from.subst(self.tcx, substs),
165 substituted_to: to.subst(self.tcx, substs),
168 self.push_transmute_restriction(restriction);
172 fn with_each_combination(&self,
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>))
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.
185 match types_in_scope.next() {
187 debug!("with_each_combination(substs={:?})",
193 Some((space, index, ¶m_ty)) => {
194 debug!("with_each_combination: space={:?}, index={}, param_ty={:?}",
195 space, index, param_ty);
197 if !param_ty.is_sized(param_env, span) {
198 debug!("with_each_combination: param_ty is not known to be sized");
200 substs.types.get_mut_slice(space)[index] = self.dummy_unsized_ty;
201 self.with_each_combination(span, param_env, types_in_scope.clone(),
205 substs.types.get_mut_slice(space)[index] = self.dummy_sized_ty;
206 self.with_each_combination(span, param_env, types_in_scope,
212 fn push_transmute_restriction(&self, restriction: TransmuteRestriction<'tcx>) {
213 debug!("Pushing transmute restriction: {:?}", restriction);
214 self.tcx.transmute_restrictions.borrow_mut().push(restriction);
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) {
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();
228 FnKind::Closure(..) => {
229 intravisit::walk_fn(self, fk, fd, b, s);
235 fn visit_expr(&mut self, expr: &hir::Expr) {
236 if let hir::ExprPath(..) = expr.node {
237 match self.tcx.resolve_expr(expr) {
238 DefFn(did, _) if self.def_id_is_transmute(did) => {
239 let typ = self.tcx.node_id_to_type(expr.id);
241 TyBareFn(_, ref bare_fn_ty) if bare_fn_ty.abi == RustIntrinsic => {
242 if let ty::FnConverging(to) = bare_fn_ty.sig.0.output {
243 let from = bare_fn_ty.sig.0.inputs[0];
244 self.check_transmute(expr.span, from, to, expr.id);
250 .span_bug(expr.span, "transmute wasn't a bare fn?!");
258 intravisit::walk_expr(self, expr);
262 impl<'tcx> fmt::Debug for TransmuteRestriction<'tcx> {
263 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
264 write!(f, "TransmuteRestriction(id={}, original=({:?},{:?}), substituted=({:?},{:?}))",
268 self.substituted_from,