]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/intrinsicck.rs
9746c7ce05c116676e439a735b93a2361b27ad7c
[rust.git] / src / librustc / middle / intrinsicck.rs
1 use crate::hir::def::{Res, DefKind};
2 use crate::hir::def_id::DefId;
3 use crate::ty::{self, Ty, TyCtxt};
4 use crate::ty::layout::{LayoutError, Pointer, SizeSkeleton, VariantIdx};
5 use crate::ty::query::Providers;
6
7 use rustc_target::spec::abi::Abi::RustIntrinsic;
8 use rustc_data_structures::indexed_vec::Idx;
9 use syntax_pos::{Span, sym};
10 use crate::hir::intravisit::{self, Visitor, NestedVisitorMap};
11 use crate::hir;
12
13 fn check_mod_intrinsics<'tcx>(tcx: TyCtxt<'tcx, 'tcx>, module_def_id: DefId) {
14     tcx.hir().visit_item_likes_in_module(
15         module_def_id,
16         &mut ItemVisitor { tcx }.as_deep_visitor()
17     );
18 }
19
20 pub fn provide(providers: &mut Providers<'_>) {
21     *providers = Providers {
22         check_mod_intrinsics,
23         ..*providers
24     };
25 }
26
27 struct ItemVisitor<'tcx> {
28     tcx: TyCtxt<'tcx, 'tcx>
29 }
30
31 struct ExprVisitor<'tcx> {
32     tcx: TyCtxt<'tcx, 'tcx>,
33     tables: &'tcx ty::TypeckTables<'tcx>,
34     param_env: ty::ParamEnv<'tcx>,
35 }
36
37 /// If the type is `Option<T>`, it will return `T`, otherwise
38 /// the type itself. Works on most `Option`-like types.
39 fn unpack_option_like<'tcx>(tcx: TyCtxt<'tcx, 'tcx>,
40                                 ty: Ty<'tcx>)
41                                 -> Ty<'tcx> {
42     let (def, substs) = match ty.sty {
43         ty::Adt(def, substs) => (def, substs),
44         _ => return ty
45     };
46
47     if def.variants.len() == 2 && !def.repr.c() && def.repr.int.is_none() {
48         let data_idx;
49
50         let one = VariantIdx::new(1);
51         let zero = VariantIdx::new(0);
52
53         if def.variants[zero].fields.is_empty() {
54             data_idx = one;
55         } else if def.variants[one].fields.is_empty() {
56             data_idx = zero;
57         } else {
58             return ty;
59         }
60
61         if def.variants[data_idx].fields.len() == 1 {
62             return def.variants[data_idx].fields[0].ty(tcx, substs);
63         }
64     }
65
66     ty
67 }
68
69 impl ExprVisitor<'tcx> {
70     fn def_id_is_transmute(&self, def_id: DefId) -> bool {
71         self.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
72         self.tcx.item_name(def_id) == sym::transmute
73     }
74
75     fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>) {
76         let sk_from = SizeSkeleton::compute(from, self.tcx, self.param_env);
77         let sk_to = SizeSkeleton::compute(to, self.tcx, self.param_env);
78
79         // Check for same size using the skeletons.
80         if let (Ok(sk_from), Ok(sk_to)) = (sk_from, sk_to) {
81             if sk_from.same_size(sk_to) {
82                 return;
83             }
84
85             // Special-case transmutting from `typeof(function)` and
86             // `Option<typeof(function)>` to present a clearer error.
87             let from = unpack_option_like(self.tcx.global_tcx(), from);
88             if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (&from.sty, sk_to) {
89                 if size_to == Pointer.size(&self.tcx) {
90                     struct_span_err!(self.tcx.sess, span, E0591,
91                                      "can't transmute zero-sized type")
92                         .note(&format!("source type: {}", from))
93                         .note(&format!("target type: {}", to))
94                         .help("cast with `as` to a pointer instead")
95                         .emit();
96                     return;
97                 }
98             }
99         }
100
101         // Try to display a sensible error with as much information as possible.
102         let skeleton_string = |ty: Ty<'tcx>, sk| {
103             match sk {
104                 Ok(SizeSkeleton::Known(size)) => {
105                     format!("{} bits", size.bits())
106                 }
107                 Ok(SizeSkeleton::Pointer { tail, .. }) => {
108                     format!("pointer to `{}`", tail)
109                 }
110                 Err(LayoutError::Unknown(bad)) => {
111                     if bad == ty {
112                         "this type does not have a fixed size".to_owned()
113                     } else {
114                         format!("size can vary because of {}", bad)
115                     }
116                 }
117                 Err(err) => err.to_string()
118             }
119         };
120
121         let mut err = struct_span_err!(self.tcx.sess, span, E0512,
122                                        "cannot transmute between types of different sizes, \
123                                         or dependently-sized types");
124         if from == to {
125             err.note(&format!("`{}` does not have a fixed size", from));
126         } else {
127             err.note(&format!("source type: `{}` ({})", from, skeleton_string(from, sk_from)))
128                 .note(&format!("target type: `{}` ({})", to, skeleton_string(to, sk_to)));
129         }
130         err.emit()
131     }
132 }
133
134 impl Visitor<'tcx> for ItemVisitor<'tcx> {
135     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
136         NestedVisitorMap::None
137     }
138
139     fn visit_nested_body(&mut self, body_id: hir::BodyId) {
140         let owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
141         let body = self.tcx.hir().body(body_id);
142         let param_env = self.tcx.param_env(owner_def_id);
143         let tables = self.tcx.typeck_tables_of(owner_def_id);
144         ExprVisitor { tcx: self.tcx, param_env, tables }.visit_body(body);
145         self.visit_body(body);
146     }
147 }
148
149 impl Visitor<'tcx> for ExprVisitor<'tcx> {
150     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
151         NestedVisitorMap::None
152     }
153
154     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
155         let res = if let hir::ExprKind::Path(ref qpath) = expr.node {
156             self.tables.qpath_res(qpath, expr.hir_id)
157         } else {
158             Res::Err
159         };
160         if let Res::Def(DefKind::Fn, did) = res {
161             if self.def_id_is_transmute(did) {
162                 let typ = self.tables.node_type(expr.hir_id);
163                 let sig = typ.fn_sig(self.tcx);
164                 let from = sig.inputs().skip_binder()[0];
165                 let to = *sig.output().skip_binder();
166                 self.check_transmute(expr.span, from, to);
167             }
168         }
169
170         intravisit::walk_expr(self, expr);
171     }
172 }