1 //! lint on C-like enums that are `repr(isize/usize)` and have values that don't fit into an `i32`
4 use rustc::middle::const_val::ConstVal;
5 use rustc_const_math::*;
8 use rustc::traits::Reveal;
9 use rustc::ty::subst::Substs;
12 /// **What it does:** Checks for C-like enumerations that are
13 /// `repr(isize/usize)` and have values that don't fit into an `i32`.
15 /// **Why is this bad?** This will truncate the variant value on 32 bit
16 /// architectures, but works fine on 64 bit.
18 /// **Known problems:** None.
23 /// enum NonPortable {
24 /// X = 0x1_0000_0000,
29 pub ENUM_CLIKE_UNPORTABLE_VARIANT,
31 "C-like enums that are `repr(isize/usize)` and have values that don't fit into an `i32`"
34 pub struct UnportableVariant;
36 impl LintPass for UnportableVariant {
37 fn get_lints(&self) -> LintArray {
38 lint_array!(ENUM_CLIKE_UNPORTABLE_VARIANT)
42 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnportableVariant {
43 #[allow(cast_possible_truncation, cast_sign_loss)]
44 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
45 if let ItemEnum(ref def, _) = item.node {
46 for var in &def.variants {
47 let variant = &var.node;
48 if let Some(body_id) = variant.disr_expr {
49 let expr = &cx.tcx.hir.body(body_id).value;
50 let did = cx.tcx.hir.body_owner_def_id(body_id);
51 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
52 let substs = Substs::identity_for_item(cx.tcx.global_tcx(), did);
53 let bad = match cx.tcx.at(expr.span).const_eval(param_env.and((did, substs))) {
54 Ok(ConstVal::Integral(Usize(Us64(i)))) => i as u32 as u64 != i,
55 Ok(ConstVal::Integral(Isize(Is64(i)))) => i as i32 as i64 != i,
60 ENUM_CLIKE_UNPORTABLE_VARIANT,
62 "Clike enum variant discriminant is not portable to 32-bit targets");