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