1 use crate::hir::def::Def;
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;
7 use rustc_target::spec::abi::Abi::RustIntrinsic;
8 use rustc_data_structures::indexed_vec::Idx;
10 use crate::hir::intravisit::{self, Visitor, NestedVisitorMap};
13 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
14 for &module in tcx.hir().krate().modules.keys() {
15 tcx.ensure().check_mod_intrinsics(tcx.hir().local_def_id(module));
19 fn check_mod_intrinsics<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>, module_def_id: DefId) {
20 tcx.hir().visit_item_likes_in_module(
22 &mut ItemVisitor { tcx }.as_deep_visitor()
26 pub fn provide(providers: &mut Providers<'_>) {
27 *providers = Providers {
33 struct ItemVisitor<'a, 'tcx: 'a> {
34 tcx: TyCtxt<'a, 'tcx, 'tcx>
37 struct ExprVisitor<'a, 'tcx: 'a> {
38 tcx: TyCtxt<'a, 'tcx, 'tcx>,
39 tables: &'tcx ty::TypeckTables<'tcx>,
40 param_env: ty::ParamEnv<'tcx>,
43 /// If the type is `Option<T>`, it will return `T`, otherwise
44 /// the type itself. Works on most `Option`-like types.
45 fn unpack_option_like<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
48 let (def, substs) = match ty.sty {
49 ty::Adt(def, substs) => (def, substs),
53 if def.variants.len() == 2 && !def.repr.c() && def.repr.int.is_none() {
56 let one = VariantIdx::new(1);
57 let zero = VariantIdx::new(0);
59 if def.variants[zero].fields.is_empty() {
61 } else if def.variants[one].fields.is_empty() {
67 if def.variants[data_idx].fields.len() == 1 {
68 return def.variants[data_idx].fields[0].ty(tcx, substs);
75 impl<'a, 'tcx> ExprVisitor<'a, 'tcx> {
76 fn def_id_is_transmute(&self, def_id: DefId) -> bool {
77 self.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
78 self.tcx.item_name(def_id) == "transmute"
81 fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>) {
82 let sk_from = SizeSkeleton::compute(from, self.tcx, self.param_env);
83 let sk_to = SizeSkeleton::compute(to, self.tcx, self.param_env);
85 // Check for same size using the skeletons.
86 if let (Ok(sk_from), Ok(sk_to)) = (sk_from, sk_to) {
87 if sk_from.same_size(sk_to) {
91 // Special-case transmutting from `typeof(function)` and
92 // `Option<typeof(function)>` to present a clearer error.
93 let from = unpack_option_like(self.tcx.global_tcx(), from);
94 if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (&from.sty, sk_to) {
95 if size_to == Pointer.size(&self.tcx) {
96 struct_span_err!(self.tcx.sess, span, E0591,
97 "can't transmute zero-sized type")
98 .note(&format!("source type: {}", from))
99 .note(&format!("target type: {}", to))
100 .help("cast with `as` to a pointer instead")
107 // Try to display a sensible error with as much information as possible.
108 let skeleton_string = |ty: Ty<'tcx>, sk| {
110 Ok(SizeSkeleton::Known(size)) => {
111 format!("{} bits", size.bits())
113 Ok(SizeSkeleton::Pointer { tail, .. }) => {
114 format!("pointer to `{}`", tail)
116 Err(LayoutError::Unknown(bad)) => {
118 "this type does not have a fixed size".to_owned()
120 format!("size can vary because of {}", bad)
123 Err(err) => err.to_string()
127 let mut err = struct_span_err!(self.tcx.sess, span, E0512,
128 "cannot transmute between types of different sizes, \
129 or dependently-sized types");
131 err.note(&format!("`{}` does not have a fixed size", from));
133 err.note(&format!("source type: `{}` ({})", from, skeleton_string(from, sk_from)))
134 .note(&format!("target type: `{}` ({})", to, skeleton_string(to, sk_to)));
140 impl<'a, 'tcx> Visitor<'tcx> for ItemVisitor<'a, 'tcx> {
141 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
142 NestedVisitorMap::None
145 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
146 let owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
147 let body = self.tcx.hir().body(body_id);
148 let param_env = self.tcx.param_env(owner_def_id);
149 let tables = self.tcx.typeck_tables_of(owner_def_id);
150 ExprVisitor { tcx: self.tcx, param_env, tables }.visit_body(body);
151 self.visit_body(body);
155 impl<'a, 'tcx> Visitor<'tcx> for ExprVisitor<'a, 'tcx> {
156 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
157 NestedVisitorMap::None
160 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
161 let def = if let hir::ExprKind::Path(ref qpath) = expr.node {
162 self.tables.qpath_def(qpath, expr.hir_id)
166 if let Def::Fn(did) = def {
167 if self.def_id_is_transmute(did) {
168 let typ = self.tables.node_id_to_type(expr.hir_id);
169 let sig = typ.fn_sig(self.tcx);
170 let from = sig.inputs().skip_binder()[0];
171 let to = *sig.output().skip_binder();
172 self.check_transmute(expr.span, from, to);
176 intravisit::walk_expr(self, expr);