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;
6 use rustc::declare_lint_pass;
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
9 use rustc::mir::interpret::GlobalId;
11 use rustc::ty::subst::InternalSubsts;
12 use rustc::ty::util::IntTypeExt;
13 use rustc_session::declare_tool_lint;
14 use std::convert::TryFrom;
15 use syntax::ast::{IntTy, UintTy};
17 declare_clippy_lint! {
18 /// **What it does:** Checks for C-like enumerations that are
19 /// `repr(isize/usize)` and have values that don't fit into an `i32`.
21 /// **Why is this bad?** This will truncate the variant value on 32 bit
22 /// architectures, but works fine on 64 bit.
24 /// **Known problems:** None.
28 /// # #[cfg(target_pointer_width = "64")]
30 /// enum NonPortable {
31 /// X = 0x1_0000_0000,
35 pub ENUM_CLIKE_UNPORTABLE_VARIANT,
37 "C-like enums that are `repr(isize/usize)` and have values that don't fit into an `i32`"
40 declare_lint_pass!(UnportableVariant => [ENUM_CLIKE_UNPORTABLE_VARIANT]);
42 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnportableVariant {
43 #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap, clippy::cast_sign_loss)]
44 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
45 if cx.tcx.data_layout.pointer_size.bits() != 64 {
48 if let ItemKind::Enum(def, _) = &item.kind {
49 for var in &def.variants {
50 if let Some(anon_const) = &var.disr_expr {
51 let param_env = ty::ParamEnv::empty();
52 let def_id = cx.tcx.hir().body_owner_def_id(anon_const.body);
53 let substs = InternalSubsts::identity_for_item(cx.tcx, def_id);
54 let instance = ty::Instance::new(def_id, substs);
59 let constant = cx.tcx.const_eval(param_env.and(c_id)).ok();
60 if let Some(Constant::Int(val)) = constant.and_then(miri_to_const) {
61 let mut ty = cx.tcx.type_of(def_id);
62 if let ty::Adt(adt, _) = ty.kind {
64 ty = adt.repr.discr_type().to_ty(cx.tcx);
68 ty::Int(IntTy::Isize) => {
69 let val = ((val as i128) << 64) >> 64;
70 if i32::try_from(val).is_ok() {
74 ty::Uint(UintTy::Usize) if val > u128::from(u32::max_value()) => {},
79 ENUM_CLIKE_UNPORTABLE_VARIANT,
81 "Clike enum variant discriminant is not portable to 32-bit targets",