1 //! lint on C-like enums that are `repr(isize/usize)` and have values that
2 //! don't fit into an `i32`
4 use crate::consts::{miri_to_const, Constant};
5 use crate::utils::span_lint;
7 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
8 use rustc::mir::interpret::GlobalId;
10 use rustc::ty::subst::InternalSubsts;
11 use rustc::ty::util::IntTypeExt;
12 use rustc::{declare_lint_pass, declare_tool_lint};
13 use std::convert::TryFrom;
14 use syntax::ast::{IntTy, UintTy};
16 declare_clippy_lint! {
17 /// **What it does:** Checks for C-like enumerations that are
18 /// `repr(isize/usize)` and have values that don't fit into an `i32`.
20 /// **Why is this bad?** This will truncate the variant value on 32 bit
21 /// architectures, but works fine on 64 bit.
23 /// **Known problems:** None.
28 /// enum NonPortable {
29 /// X = 0x1_0000_0000,
33 pub ENUM_CLIKE_UNPORTABLE_VARIANT,
35 "C-like enums that are `repr(isize/usize)` and have values that don't fit into an `i32`"
38 declare_lint_pass!(UnportableVariant => [ENUM_CLIKE_UNPORTABLE_VARIANT]);
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnportableVariant {
41 #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap, clippy::cast_sign_loss)]
42 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
43 if cx.tcx.data_layout.pointer_size.bits() != 64 {
46 if let ItemKind::Enum(def, _) = &item.node {
47 for var in &def.variants {
48 if let Some(anon_const) = &var.disr_expr {
49 let param_env = ty::ParamEnv::empty();
50 let def_id = cx.tcx.hir().body_owner_def_id(anon_const.body);
51 let substs = InternalSubsts::identity_for_item(cx.tcx.global_tcx(), def_id);
52 let instance = ty::Instance::new(def_id, substs);
57 let constant = cx.tcx.const_eval(param_env.and(c_id)).ok();
58 if let Some(Constant::Int(val)) = constant.and_then(miri_to_const) {
59 let mut ty = cx.tcx.type_of(def_id);
60 if let ty::Adt(adt, _) = ty.sty {
62 ty = adt.repr.discr_type().to_ty(cx.tcx);
66 ty::Int(IntTy::Isize) => {
67 let val = ((val as i128) << 64) >> 64;
68 if i32::try_from(val).is_ok() {
72 ty::Uint(UintTy::Usize) if val > u128::from(u32::max_value()) => {},
77 ENUM_CLIKE_UNPORTABLE_VARIANT,
79 "Clike enum variant discriminant is not portable to 32-bit targets",