1 //! lint on C-like enums that are `repr(isize/usize)` and have values that
2 //! don't fit into an `i32`
7 use rustc::ty::subst::Substs;
8 use syntax::ast::{IntTy, UintTy};
10 use consts::{Constant, miri_to_const};
11 use rustc::ty::util::IntTypeExt;
12 use rustc::mir::interpret::GlobalId;
14 /// **What it does:** Checks for C-like enumerations that are
15 /// `repr(isize/usize)` and have values that don't fit into an `i32`.
17 /// **Why is this bad?** This will truncate the variant value on 32 bit
18 /// architectures, but works fine on 64 bit.
20 /// **Known problems:** None.
25 /// enum NonPortable {
26 /// X = 0x1_0000_0000,
30 declare_clippy_lint! {
31 pub ENUM_CLIKE_UNPORTABLE_VARIANT,
33 "C-like enums that are `repr(isize/usize)` and have values that don't fit into an `i32`"
36 pub struct UnportableVariant;
38 impl LintPass for UnportableVariant {
39 fn get_lints(&self) -> LintArray {
40 lint_array!(ENUM_CLIKE_UNPORTABLE_VARIANT)
44 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnportableVariant {
45 #[allow(cast_possible_truncation, cast_sign_loss)]
46 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
47 if cx.tcx.data_layout.pointer_size.bits() != 64 {
50 if let ItemEnum(ref def, _) = item.node {
51 for var in &def.variants {
52 let variant = &var.node;
53 if let Some(ref anon_const) = variant.disr_expr {
54 let param_env = ty::ParamEnv::empty();
55 let did = cx.tcx.hir.body_owner_def_id(anon_const.body);
56 let substs = Substs::identity_for_item(cx.tcx.global_tcx(), did);
57 let instance = ty::Instance::new(did, substs);
62 let constant = cx.tcx.const_eval(param_env.and(cid)).ok();
63 if let Some(Constant::Int(val)) = constant.and_then(|c| miri_to_const(cx.tcx, c)) {
64 let mut ty = cx.tcx.type_of(did);
65 if let ty::TyAdt(adt, _) = ty.sty {
67 ty = adt.repr.discr_type().to_ty(cx.tcx);
71 ty::TyInt(IntTy::Isize) => {
72 let val = ((val as i128) << 64) >> 64;
73 if val <= i128::from(i32::max_value()) && val >= i128::from(i32::min_value()) {
77 ty::TyUint(UintTy::Usize) if val > u128::from(u32::max_value()) => {},
82 ENUM_CLIKE_UNPORTABLE_VARIANT,
84 "Clike enum variant discriminant is not portable to 32-bit targets",