]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/intrinsicck.rs
introduce Guard enum
[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 rustc_target::spec::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,
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         self.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
70         self.tcx.item_name(def_id) == "transmute"
71     }
72
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);
76
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) {
80                 return;
81             }
82
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::TyFnDef(..), 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")
93                         .emit();
94                     return;
95                 }
96             }
97         }
98
99         // Try to display a sensible error with as much information as possible.
100         let skeleton_string = |ty: Ty<'tcx>, sk| {
101             match sk {
102                 Ok(SizeSkeleton::Known(size)) => {
103                     format!("{} bits", size.bits())
104                 }
105                 Ok(SizeSkeleton::Pointer { tail, .. }) => {
106                     format!("pointer to {}", tail)
107                 }
108                 Err(LayoutError::Unknown(bad)) => {
109                     if bad == ty {
110                         "this type's size can vary".to_string()
111                     } else {
112                         format!("size can vary because of {}", bad)
113                     }
114                 }
115                 Err(err) => err.to_string()
116             }
117         };
118
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)))
123             .emit();
124     }
125 }
126
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
130     }
131
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);
139     }
140 }
141
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
145     }
146
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)
150         } else {
151             Def::Err
152         };
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);
160             }
161         }
162
163         intravisit::walk_expr(self, expr);
164     }
165 }