2 use rustc_errors::struct_span_err;
4 use rustc_index::vec::Idx;
5 use rustc_middle::ty::layout::{LayoutError, SizeSkeleton};
6 use rustc_middle::ty::{self, Ty, TyCtxt};
7 use rustc_target::abi::{Pointer, VariantIdx};
11 /// If the type is `Option<T>`, it will return `T`, otherwise
12 /// the type itself. Works on most `Option`-like types.
13 fn unpack_option_like<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
14 let ty::Adt(def, substs) = *ty.kind() else { return ty };
16 if def.variants().len() == 2 && !def.repr().c() && def.repr().int.is_none() {
19 let one = VariantIdx::new(1);
20 let zero = VariantIdx::new(0);
22 if def.variant(zero).fields.is_empty() {
24 } else if def.variant(one).fields.is_empty() {
30 if def.variant(data_idx).fields.len() == 1 {
31 return def.variant(data_idx).fields[0].ty(tcx, substs);
38 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
39 pub fn check_transmute(&self, from: Ty<'tcx>, to: Ty<'tcx>, hir_id: HirId) {
41 let span = tcx.hir().span(hir_id);
42 let normalize = |ty| {
43 let ty = self.resolve_vars_if_possible(ty);
44 self.tcx.normalize_erasing_regions(self.param_env, ty)
46 let from = normalize(from);
47 let to = normalize(to);
50 // Transmutes that are only changing lifetimes are always ok.
55 let skel = |ty| SizeSkeleton::compute(ty, tcx, self.param_env);
56 let sk_from = skel(from);
58 trace!(?sk_from, ?sk_to);
60 // Check for same size using the skeletons.
61 if let (Ok(sk_from), Ok(sk_to)) = (sk_from, sk_to) {
62 if sk_from.same_size(sk_to) {
66 // Special-case transmuting from `typeof(function)` and
67 // `Option<typeof(function)>` to present a clearer error.
68 let from = unpack_option_like(tcx, from);
69 if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (from.kind(), sk_to) && size_to == Pointer.size(&tcx) {
70 struct_span_err!(tcx.sess, span, E0591, "can't transmute zero-sized type")
71 .note(&format!("source type: {from}"))
72 .note(&format!("target type: {to}"))
73 .help("cast with `as` to a pointer instead")
79 // Try to display a sensible error with as much information as possible.
80 let skeleton_string = |ty: Ty<'tcx>, sk| match sk {
81 Ok(SizeSkeleton::Known(size)) => format!("{} bits", size.bits()),
82 Ok(SizeSkeleton::Pointer { tail, .. }) => format!("pointer to `{tail}`"),
83 Err(LayoutError::Unknown(bad)) => {
85 "this type does not have a fixed size".to_owned()
87 format!("size can vary because of {bad}")
90 Err(err) => err.to_string(),
93 let mut err = struct_span_err!(
97 "cannot transmute between types of different sizes, \
98 or dependently-sized types"
101 err.note(&format!("`{from}` does not have a fixed size"));
103 err.note(&format!("source type: `{}` ({})", from, skeleton_string(from, sk_from)))
104 .note(&format!("target type: `{}` ({})", to, skeleton_string(to, sk_to)));