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