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