]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/intrinsicck.rs
de92395ac6955b316ec88640d16f01af490baf42
[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 hir::def::Def;
12 use hir::def_id::DefId;
13 use ty::{self, Ty, TyCtxt};
14 use ty::layout::{LayoutError, Pointer, SizeSkeleton};
15
16 use syntax::abi::Abi::RustIntrinsic;
17 use syntax_pos::Span;
18 use hir::intravisit::{self, Visitor, NestedVisitorMap};
19 use hir;
20
21 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
22     let mut visitor = ItemVisitor {
23         tcx: tcx
24     };
25     tcx.hir.krate().visit_all_item_likes(&mut visitor.as_deep_visitor());
26 }
27
28 struct ItemVisitor<'a, 'tcx: 'a> {
29     tcx: TyCtxt<'a, 'tcx, 'tcx>
30 }
31
32 struct ExprVisitor<'a, 'tcx: 'a> {
33     tcx: TyCtxt<'a, 'tcx, 'tcx>,
34     tables: &'tcx ty::TypeckTables<'tcx>,
35     param_env: ty::ParamEnv<'tcx>,
36 }
37
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>,
41                                 ty: Ty<'tcx>)
42                                 -> Ty<'tcx> {
43     let (def, substs) = match ty.sty {
44         ty::TyAdt(def, substs) => (def, substs),
45         _ => return ty
46     };
47
48     if def.variants.len() == 2 && !def.repr.c() && def.repr.int.is_none() {
49         let data_idx;
50
51         if def.variants[0].fields.is_empty() {
52             data_idx = 1;
53         } else if def.variants[1].fields.is_empty() {
54             data_idx = 0;
55         } else {
56             return ty;
57         }
58
59         if def.variants[data_idx].fields.len() == 1 {
60             return def.variants[data_idx].fields[0].ty(tcx, substs);
61         }
62     }
63
64     ty
65 }
66
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,
71             _ => return false
72         };
73         intrinsic && self.tcx.item_name(def_id) == "transmute"
74     }
75
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);
79
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) {
83                 return;
84             }
85
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")
96                         .emit();
97                     return;
98                 }
99             }
100         }
101
102         // Try to display a sensible error with as much information as possible.
103         let skeleton_string = |ty: Ty<'tcx>, sk| {
104             match sk {
105                 Ok(SizeSkeleton::Known(size)) => {
106                     format!("{} bits", size.bits())
107                 }
108                 Ok(SizeSkeleton::Pointer { tail, .. }) => {
109                     format!("pointer to {}", tail)
110                 }
111                 Err(LayoutError::Unknown(bad)) => {
112                     if bad == ty {
113                         format!("this type's size can vary")
114                     } else {
115                         format!("size can vary because of {}", bad)
116                     }
117                 }
118                 Err(err) => err.to_string()
119             }
120         };
121
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)))
126             .emit();
127     }
128 }
129
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
133     }
134
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);
142     }
143 }
144
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
148     }
149
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)
153         } else {
154             Def::Err
155         };
156         match def {
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();
160                 match typ.sty {
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);
165                     }
166                     _ => {
167                         span_bug!(expr.span, "transmute wasn't a bare fn?!");
168                     }
169                 }
170             }
171             _ => {}
172         }
173
174         intravisit::walk_expr(self, expr);
175     }
176 }