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 dep_graph::DepNode;
13 use hir::def_id::DefId;
16 use ty::{self, Ty, TyCtxt};
17 use ty::layout::{LayoutError, Pointer, SizeSkeleton};
19 use syntax::abi::Abi::RustIntrinsic;
21 use hir::intravisit::{self, Visitor, NestedVisitorMap};
24 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
25 let mut visitor = ItemVisitor {
28 tcx.visit_all_item_likes_in_krate(DepNode::IntrinsicCheck, &mut visitor.as_deep_visitor());
31 struct ItemVisitor<'a, 'tcx: 'a> {
32 tcx: TyCtxt<'a, 'tcx, 'tcx>
35 struct ExprVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
36 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>
39 /// If the type is `Option<T>`, it will return `T`, otherwise
40 /// the type itself. Works on most `Option`-like types.
41 fn unpack_option_like<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
44 let (def, substs) = match ty.sty {
45 ty::TyAdt(def, substs) => (def, substs),
49 if def.variants.len() == 2 && !def.repr.c && def.repr.int.is_none() {
52 if def.variants[0].fields.is_empty() {
54 } else if def.variants[1].fields.is_empty() {
60 if def.variants[data_idx].fields.len() == 1 {
61 return def.variants[data_idx].fields[0].ty(tcx, substs);
68 impl<'a, 'gcx, 'tcx> ExprVisitor<'a, 'gcx, 'tcx> {
69 fn def_id_is_transmute(&self, def_id: DefId) -> bool {
70 let intrinsic = match self.infcx.tcx.item_type(def_id).sty {
71 ty::TyFnDef(.., bfty) => bfty.abi() == RustIntrinsic,
74 intrinsic && self.infcx.tcx.item_name(def_id) == "transmute"
77 fn check_transmute(&self, span: Span, from: Ty<'gcx>, to: Ty<'gcx>) {
78 let sk_from = SizeSkeleton::compute(from, self.infcx);
79 let sk_to = SizeSkeleton::compute(to, self.infcx);
81 // Check for same size using the skeletons.
82 if let (Ok(sk_from), Ok(sk_to)) = (sk_from, sk_to) {
83 if sk_from.same_size(sk_to) {
87 // Special-case transmutting from `typeof(function)` and
88 // `Option<typeof(function)>` to present a clearer error.
89 let from = unpack_option_like(self.infcx.tcx.global_tcx(), from);
90 match (&from.sty, sk_to) {
91 (&ty::TyFnDef(..), SizeSkeleton::Known(size_to))
92 if size_to == Pointer.size(self.infcx) => {
93 struct_span_err!(self.infcx.tcx.sess, span, E0591,
94 "`{}` is zero-sized and can't be transmuted to `{}`",
96 .span_note(span, &format!("cast with `as` to a pointer instead"))
104 // Try to display a sensible error with as much information as possible.
105 let skeleton_string = |ty: Ty<'gcx>, sk| {
107 Ok(SizeSkeleton::Known(size)) => {
108 format!("{} bits", size.bits())
110 Ok(SizeSkeleton::Pointer { tail, .. }) => {
111 format!("pointer to {}", tail)
113 Err(LayoutError::Unknown(bad)) => {
115 format!("size can vary")
117 format!("size can vary because of {}", bad)
120 Err(err) => err.to_string()
124 struct_span_err!(self.infcx.tcx.sess, span, E0512,
125 "transmute called with differently sized types: \
127 from, skeleton_string(from, sk_from),
128 to, skeleton_string(to, sk_to))
130 &format!("transmuting between {} and {}",
131 skeleton_string(from, sk_from),
132 skeleton_string(to, sk_to)))
137 impl<'a, 'tcx> Visitor<'tcx> for ItemVisitor<'a, 'tcx> {
138 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
139 NestedVisitorMap::None
142 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
143 let body = self.tcx.hir.body(body_id);
144 self.tcx.infer_ctxt(body_id, Reveal::All).enter(|infcx| {
145 let mut visitor = ExprVisitor {
148 visitor.visit_body(body);
150 self.visit_body(body);
154 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for ExprVisitor<'a, 'gcx, 'tcx> {
155 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
156 NestedVisitorMap::None
159 fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
160 let def = if let hir::ExprPath(ref qpath) = expr.node {
161 self.infcx.tables.borrow().qpath_def(qpath, expr.id)
166 Def::Fn(did) if self.def_id_is_transmute(did) => {
167 let typ = self.infcx.tables.borrow().node_id_to_type(expr.id);
168 let typ = self.infcx.tcx.lift_to_global(&typ).unwrap();
170 ty::TyFnDef(.., sig) if sig.abi() == RustIntrinsic => {
171 let from = sig.inputs().skip_binder()[0];
172 let to = *sig.output().skip_binder();
173 self.check_transmute(expr.span, from, to);
176 span_bug!(expr.span, "transmute wasn't a bare fn?!");
183 intravisit::walk_expr(self, expr);