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 rustc_target::spec::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::Adt(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 self.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
70 self.tcx.item_name(def_id) == "transmute"
73 fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>) {
74 let sk_from = SizeSkeleton::compute(from, self.tcx, self.param_env);
75 let sk_to = SizeSkeleton::compute(to, self.tcx, self.param_env);
77 // Check for same size using the skeletons.
78 if let (Ok(sk_from), Ok(sk_to)) = (sk_from, sk_to) {
79 if sk_from.same_size(sk_to) {
83 // Special-case transmutting from `typeof(function)` and
84 // `Option<typeof(function)>` to present a clearer error.
85 let from = unpack_option_like(self.tcx.global_tcx(), from);
86 if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (&from.sty, sk_to) {
87 if size_to == Pointer.size(self.tcx) {
88 struct_span_err!(self.tcx.sess, span, E0591,
89 "can't transmute zero-sized type")
90 .note(&format!("source type: {}", from))
91 .note(&format!("target type: {}", to))
92 .help("cast with `as` to a pointer instead")
99 // Try to display a sensible error with as much information as possible.
100 let skeleton_string = |ty: Ty<'tcx>, sk| {
102 Ok(SizeSkeleton::Known(size)) => {
103 format!("{} bits", size.bits())
105 Ok(SizeSkeleton::Pointer { tail, .. }) => {
106 format!("pointer to {}", tail)
108 Err(LayoutError::Unknown(bad)) => {
110 "this type's size can vary".to_owned()
112 format!("size can vary because of {}", bad)
115 Err(err) => err.to_string()
119 struct_span_err!(self.tcx.sess, span, E0512,
120 "transmute called with types of different sizes")
121 .note(&format!("source type: {} ({})", from, skeleton_string(from, sk_from)))
122 .note(&format!("target type: {} ({})", to, skeleton_string(to, sk_to)))
127 impl<'a, 'tcx> Visitor<'tcx> for ItemVisitor<'a, 'tcx> {
128 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
129 NestedVisitorMap::None
132 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
133 let owner_def_id = self.tcx.hir.body_owner_def_id(body_id);
134 let body = self.tcx.hir.body(body_id);
135 let param_env = self.tcx.param_env(owner_def_id);
136 let tables = self.tcx.typeck_tables_of(owner_def_id);
137 ExprVisitor { tcx: self.tcx, param_env, tables }.visit_body(body);
138 self.visit_body(body);
142 impl<'a, 'tcx> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
143 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
144 NestedVisitorMap::None
147 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
148 let def = if let hir::ExprKind::Path(ref qpath) = expr.node {
149 self.tables.qpath_def(qpath, expr.hir_id)
153 if let Def::Fn(did) = def {
154 if self.def_id_is_transmute(did) {
155 let typ = self.tables.node_id_to_type(expr.hir_id);
156 let sig = typ.fn_sig(self.tcx);
157 let from = sig.inputs().skip_binder()[0];
158 let to = *sig.output().skip_binder();
159 self.check_transmute(expr.span, from, to);
163 intravisit::walk_expr(self, expr);