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