1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 //! lint on C-like enums that are `repr(isize/usize)` and have values that
12 //! don't fit into an `i32`
14 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
15 use crate::rustc::{declare_tool_lint, lint_array};
16 use crate::rustc::hir::*;
18 use crate::rustc::ty::subst::Substs;
19 use crate::syntax::ast::{IntTy, UintTy};
20 use crate::utils::span_lint;
21 use crate::consts::{Constant, miri_to_const};
22 use crate::rustc::ty::util::IntTypeExt;
23 use crate::rustc::mir::interpret::GlobalId;
25 /// **What it does:** Checks for C-like enumerations that are
26 /// `repr(isize/usize)` and have values that don't fit into an `i32`.
28 /// **Why is this bad?** This will truncate the variant value on 32 bit
29 /// architectures, but works fine on 64 bit.
31 /// **Known problems:** None.
36 /// enum NonPortable {
37 /// X = 0x1_0000_0000,
41 declare_clippy_lint! {
42 pub ENUM_CLIKE_UNPORTABLE_VARIANT,
44 "C-like enums that are `repr(isize/usize)` and have values that don't fit into an `i32`"
47 pub struct UnportableVariant;
49 impl LintPass for UnportableVariant {
50 fn get_lints(&self) -> LintArray {
51 lint_array!(ENUM_CLIKE_UNPORTABLE_VARIANT)
55 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnportableVariant {
56 #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap, clippy::cast_sign_loss)]
57 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
58 if cx.tcx.data_layout.pointer_size.bits() != 64 {
61 if let ItemKind::Enum(ref def, _) = item.node {
62 for var in &def.variants {
63 let variant = &var.node;
64 if let Some(ref anon_const) = variant.disr_expr {
65 let param_env = ty::ParamEnv::empty();
66 let def_id = cx.tcx.hir.body_owner_def_id(anon_const.body);
67 let substs = Substs::identity_for_item(cx.tcx.global_tcx(), def_id);
68 let instance = ty::Instance::new(def_id, substs);
73 let constant = cx.tcx.const_eval(param_env.and(c_id)).ok();
74 if let Some(Constant::Int(val)) = constant.and_then(|c| miri_to_const(cx.tcx, c)) {
75 let mut ty = cx.tcx.type_of(def_id);
76 if let ty::Adt(adt, _) = ty.sty {
78 ty = adt.repr.discr_type().to_ty(cx.tcx);
82 ty::Int(IntTy::Isize) => {
83 let val = ((val as i128) << 64) >> 64;
84 if val <= i128::from(i32::max_value()) && val >= i128::from(i32::min_value()) {
88 ty::Uint(UintTy::Usize) if val > u128::from(u32::max_value()) => {},
93 ENUM_CLIKE_UNPORTABLE_VARIANT,
95 "Clike enum variant discriminant is not portable to 32-bit targets",