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.
12 use hir::def_id::DefId;
13 use ty::{self, Ty, TyCtxt};
14 use ty::layout::{LayoutError, Pointer, SizeSkeleton};
16 use syntax::abi::Abi::RustIntrinsic;
18 use hir::intravisit::{self, Visitor, NestedVisitorMap};
21 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
22 let mut visitor = ItemVisitor {
25 tcx.hir.krate().visit_all_item_likes(&mut visitor.as_deep_visitor());
28 struct ItemVisitor<'a, 'tcx: 'a> {
29 tcx: TyCtxt<'a, 'tcx, 'tcx>
32 struct ExprVisitor<'a, 'tcx: 'a> {
33 tcx: TyCtxt<'a, 'tcx, 'tcx>,
34 tables: &'tcx ty::TypeckTables<'tcx>,
35 param_env: ty::ParamEnv<'tcx>,
38 /// If the type is `Option<T>`, it will return `T`, otherwise
39 /// the type itself. Works on most `Option`-like types.
40 fn unpack_option_like<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
43 let (def, substs) = match ty.sty {
44 ty::TyAdt(def, substs) => (def, substs),
48 if def.variants.len() == 2 && !def.repr.c() && def.repr.int.is_none() {
51 if def.variants[0].fields.is_empty() {
53 } else if def.variants[1].fields.is_empty() {
59 if def.variants[data_idx].fields.len() == 1 {
60 return def.variants[data_idx].fields[0].ty(tcx, substs);
67 impl<'a, 'tcx> ExprVisitor<'a, 'tcx> {
68 fn def_id_is_transmute(&self, def_id: DefId) -> bool {
69 let intrinsic = match self.tcx.type_of(def_id).sty {
70 ty::TyFnDef(.., bfty) => bfty.abi() == RustIntrinsic,
73 intrinsic && self.tcx.item_name(def_id) == "transmute"
76 fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>) {
77 let sk_from = SizeSkeleton::compute(from, self.tcx, self.param_env);
78 let sk_to = SizeSkeleton::compute(to, self.tcx, self.param_env);
80 // Check for same size using the skeletons.
81 if let (Ok(sk_from), Ok(sk_to)) = (sk_from, sk_to) {
82 if sk_from.same_size(sk_to) {
86 // Special-case transmutting from `typeof(function)` and
87 // `Option<typeof(function)>` to present a clearer error.
88 let from = unpack_option_like(self.tcx.global_tcx(), from);
89 if let (&ty::TyFnDef(..), SizeSkeleton::Known(size_to)) = (&from.sty, sk_to) {
90 if size_to == Pointer.size(self.tcx) => {
91 struct_span_err!(self.tcx.sess, span, E0591,
92 "can't transmute zero-sized type")
93 .note(&format!("source type: {}", from))
94 .note(&format!("target type: {}", to))
95 .help("cast with `as` to a pointer instead")
102 // Try to display a sensible error with as much information as possible.
103 let skeleton_string = |ty: Ty<'tcx>, sk| {
105 Ok(SizeSkeleton::Known(size)) => {
106 format!("{} bits", size.bits())
108 Ok(SizeSkeleton::Pointer { tail, .. }) => {
109 format!("pointer to {}", tail)
111 Err(LayoutError::Unknown(bad)) => {
113 format!("this type's size can vary")
115 format!("size can vary because of {}", bad)
118 Err(err) => err.to_string()
122 struct_span_err!(self.tcx.sess, span, E0512,
123 "transmute called with types of different sizes")
124 .note(&format!("source type: {} ({})", from, skeleton_string(from, sk_from)))
125 .note(&format!("target type: {} ({})", to, skeleton_string(to, sk_to)))
130 impl<'a, 'tcx> Visitor<'tcx> for ItemVisitor<'a, 'tcx> {
131 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
132 NestedVisitorMap::None
135 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
136 let owner_def_id = self.tcx.hir.body_owner_def_id(body_id);
137 let body = self.tcx.hir.body(body_id);
138 let param_env = self.tcx.param_env(owner_def_id);
139 let tables = self.tcx.typeck_tables_of(owner_def_id);
140 ExprVisitor { tcx: self.tcx, param_env, tables }.visit_body(body);
141 self.visit_body(body);
145 impl<'a, 'tcx> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
146 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
147 NestedVisitorMap::None
150 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
151 let def = if let hir::ExprPath(ref qpath) = expr.node {
152 self.tables.qpath_def(qpath, expr.id)
157 Def::Fn(did) if self.def_id_is_transmute(did) => {
158 let typ = self.tables.node_id_to_type(expr.id);
159 let typ = self.tcx.lift_to_global(&typ).unwrap();
161 ty::TyFnDef(.., sig) if sig.abi() == RustIntrinsic => {
162 let from = sig.inputs().skip_binder()[0];
163 let to = *sig.output().skip_binder();
164 self.check_transmute(expr.span, from, to);
167 span_bug!(expr.span, "transmute wasn't a bare fn?!");
174 intravisit::walk_expr(self, expr);