]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/intrinsicck.rs
435dd05358d47e11162b8248ce191666a1e7b452
[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 infer::InferCtxt;
14 use traits::Reveal;
15 use ty::{self, Ty, TyCtxt};
16 use ty::layout::{LayoutError, Pointer, SizeSkeleton};
17
18 use syntax::abi::Abi::RustIntrinsic;
19 use syntax_pos::Span;
20 use hir::intravisit::{self, Visitor, NestedVisitorMap};
21 use hir;
22
23 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
24     let mut visitor = ItemVisitor {
25         tcx: tcx
26     };
27     tcx.hir.krate().visit_all_item_likes(&mut visitor.as_deep_visitor());
28 }
29
30 struct ItemVisitor<'a, 'tcx: 'a> {
31     tcx: TyCtxt<'a, 'tcx, 'tcx>
32 }
33
34 struct ExprVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
35     infcx: &'a InferCtxt<'a, 'gcx, '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, 'gcx, 'tcx> ExprVisitor<'a, 'gcx, 'tcx> {
68     fn def_id_is_transmute(&self, def_id: DefId) -> bool {
69         let intrinsic = match self.infcx.tcx.type_of(def_id).sty {
70             ty::TyFnDef(.., bfty) => bfty.abi() == RustIntrinsic,
71             _ => return false
72         };
73         intrinsic && self.infcx.tcx.item_name(def_id) == "transmute"
74     }
75
76     fn check_transmute(&self, span: Span, from: Ty<'gcx>, to: Ty<'gcx>) {
77         let sk_from = SizeSkeleton::compute(from, self.infcx);
78         let sk_to = SizeSkeleton::compute(to, self.infcx);
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.infcx.tcx.global_tcx(), from);
89             match (&from.sty, sk_to) {
90                 (&ty::TyFnDef(..), SizeSkeleton::Known(size_to))
91                         if size_to == Pointer.size(self.infcx) => {
92                     struct_span_err!(self.infcx.tcx.sess, span, E0591,
93                                      "`{}` is zero-sized and can't be transmuted to `{}`",
94                                      from, to)
95                         .span_note(span, &format!("cast with `as` to a pointer instead"))
96                         .emit();
97                     return;
98                 }
99                 _ => {}
100             }
101         }
102
103         // Try to display a sensible error with as much information as possible.
104         let skeleton_string = |ty: Ty<'gcx>, sk| {
105             match sk {
106                 Ok(SizeSkeleton::Known(size)) => {
107                     format!("{} bits", size.bits())
108                 }
109                 Ok(SizeSkeleton::Pointer { tail, .. }) => {
110                     format!("pointer to {}", tail)
111                 }
112                 Err(LayoutError::Unknown(bad)) => {
113                     if bad == ty {
114                         format!("size can vary")
115                     } else {
116                         format!("size can vary because of {}", bad)
117                     }
118                 }
119                 Err(err) => err.to_string()
120             }
121         };
122
123         struct_span_err!(self.infcx.tcx.sess, span, E0512,
124                   "transmute called with differently sized types: \
125                    {} ({}) to {} ({})",
126                   from, skeleton_string(from, sk_from),
127                   to, skeleton_string(to, sk_to))
128             .span_label(span,
129                 &format!("transmuting between {} and {}",
130                     skeleton_string(from, sk_from),
131                     skeleton_string(to, sk_to)))
132             .emit();
133     }
134 }
135
136 impl<'a, 'tcx> Visitor<'tcx> for ItemVisitor<'a, 'tcx> {
137     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
138         NestedVisitorMap::None
139     }
140
141     fn visit_nested_body(&mut self, body_id: hir::BodyId) {
142         let body = self.tcx.hir.body(body_id);
143         self.tcx.infer_ctxt(body_id, Reveal::All).enter(|infcx| {
144             let mut visitor = ExprVisitor {
145                 infcx: &infcx
146             };
147             visitor.visit_body(body);
148         });
149         self.visit_body(body);
150     }
151 }
152
153 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for ExprVisitor<'a, 'gcx, 'tcx> {
154     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
155         NestedVisitorMap::None
156     }
157
158     fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
159         let def = if let hir::ExprPath(ref qpath) = expr.node {
160             self.infcx.tables.borrow().qpath_def(qpath, expr.id)
161         } else {
162             Def::Err
163         };
164         match def {
165             Def::Fn(did) if self.def_id_is_transmute(did) => {
166                 let typ = self.infcx.tables.borrow().node_id_to_type(expr.id);
167                 let typ = self.infcx.tcx.lift_to_global(&typ).unwrap();
168                 match typ.sty {
169                     ty::TyFnDef(.., sig) if sig.abi() == RustIntrinsic => {
170                         let from = sig.inputs().skip_binder()[0];
171                         let to = *sig.output().skip_binder();
172                         self.check_transmute(expr.span, from, to);
173                     }
174                     _ => {
175                         span_bug!(expr.span, "transmute wasn't a bare fn?!");
176                     }
177                 }
178             }
179             _ => {}
180         }
181
182         intravisit::walk_expr(self, expr);
183     }
184 }