rust/clippy_lints/src/enum_clike.rs

79 lines
3.0 KiB
Rust
Raw Normal View History

2017-08-09 02:30:56 -05:00
//! lint on C-like enums that are `repr(isize/usize)` and have values that
//! don't fit into an `i32`
2018-11-27 14:14:15 -06:00
use crate::consts::{miri_to_const, Constant};
2018-05-30 03:15:50 -05:00
use crate::utils::span_lint;
use rustc::ty;
use rustc::ty::util::IntTypeExt;
2020-01-06 10:39:50 -06:00
use rustc_hir::*;
2020-01-12 00:08:41 -06:00
use rustc_lint::{LateContext, LateLintPass};
2020-01-11 05:37:08 -06:00
use rustc_session::{declare_lint_pass, declare_tool_lint};
2019-05-12 14:53:28 -05:00
use std::convert::TryFrom;
use syntax::ast::{IntTy, UintTy};
2018-03-28 08:24:26 -05:00
declare_clippy_lint! {
/// **What it does:** Checks for C-like enumerations that are
/// `repr(isize/usize)` and have values that don't fit into an `i32`.
///
/// **Why is this bad?** This will truncate the variant value on 32 bit
/// architectures, but works fine on 64 bit.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// # #[cfg(target_pointer_width = "64")]
/// #[repr(usize)]
/// enum NonPortable {
/// X = 0x1_0000_0000,
/// Y = 0,
/// }
/// ```
pub ENUM_CLIKE_UNPORTABLE_VARIANT,
2018-03-28 08:24:26 -05:00
correctness,
"C-like enums that are `repr(isize/usize)` and have values that don't fit into an `i32`"
}
2019-04-08 15:43:55 -05:00
declare_lint_pass!(UnportableVariant => [ENUM_CLIKE_UNPORTABLE_VARIANT]);
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnportableVariant {
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap, clippy::cast_sign_loss)]
2019-12-22 08:42:41 -06:00
fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
2018-03-13 05:38:11 -05:00
if cx.tcx.data_layout.pointer_size.bits() != 64 {
return;
}
2019-09-27 10:16:06 -05:00
if let ItemKind::Enum(def, _) = &item.kind {
2019-12-22 08:56:34 -06:00
for var in def.variants {
2019-08-15 02:59:08 -05:00
if let Some(anon_const) = &var.disr_expr {
let def_id = cx.tcx.hir().body_owner_def_id(anon_const.body);
2019-12-22 17:39:33 -06:00
let constant = cx.tcx.const_eval_poly(def_id).ok();
if let Some(Constant::Int(val)) = constant.and_then(miri_to_const) {
let mut ty = cx.tcx.type_of(def_id);
if let ty::Adt(adt, _) = ty.kind {
2018-03-13 05:38:11 -05:00
if adt.is_enum() {
ty = adt.repr.discr_type().to_ty(cx.tcx);
}
}
match ty.kind {
ty::Int(IntTy::Isize) => {
2018-03-13 05:38:11 -05:00
let val = ((val as i128) << 64) >> 64;
2019-05-12 14:53:28 -05:00
if i32::try_from(val).is_ok() {
2018-03-13 05:38:11 -05:00
continue;
}
2018-11-27 14:14:15 -06:00
},
ty::Uint(UintTy::Usize) if val > u128::from(u32::max_value()) => {},
2018-03-13 05:38:11 -05:00
_ => continue,
}
2017-08-09 02:30:56 -05:00
span_lint(
cx,
ENUM_CLIKE_UNPORTABLE_VARIANT,
var.span,
"Clike enum variant discriminant is not portable to 32-bit targets",
);
2018-03-13 05:38:11 -05:00
};
}
}
}
}
}