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.
10 //! lint on C-like enums that are `repr(isize/usize)` and have values that
11 //! don't fit into an `i32`
13 use crate::consts::{miri_to_const, Constant};
14 use crate::rustc::hir::*;
15 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
16 use crate::rustc::mir::interpret::GlobalId;
18 use crate::rustc::ty::subst::Substs;
19 use crate::rustc::ty::util::IntTypeExt;
20 use crate::rustc::{declare_tool_lint, lint_array};
21 use crate::syntax::ast::{IntTy, UintTy};
22 use crate::utils::span_lint;
24 /// **What it does:** Checks for C-like enumerations that are
25 /// `repr(isize/usize)` and have values that don't fit into an `i32`.
27 /// **Why is this bad?** This will truncate the variant value on 32 bit
28 /// architectures, but works fine on 64 bit.
30 /// **Known problems:** None.
35 /// enum NonPortable {
36 /// X = 0x1_0000_0000,
40 declare_clippy_lint! {
41 pub ENUM_CLIKE_UNPORTABLE_VARIANT,
43 "C-like enums that are `repr(isize/usize)` and have values that don't fit into an `i32`"
46 pub struct UnportableVariant;
48 impl LintPass for UnportableVariant {
49 fn get_lints(&self) -> LintArray {
50 lint_array!(ENUM_CLIKE_UNPORTABLE_VARIANT)
54 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnportableVariant {
55 #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap, clippy::cast_sign_loss)]
56 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
57 if cx.tcx.data_layout.pointer_size.bits() != 64 {
60 if let ItemKind::Enum(ref def, _) = item.node {
61 for var in &def.variants {
62 let variant = &var.node;
63 if let Some(ref anon_const) = variant.disr_expr {
64 let param_env = ty::ParamEnv::empty();
65 let def_id = cx.tcx.hir.body_owner_def_id(anon_const.body);
66 let substs = Substs::identity_for_item(cx.tcx.global_tcx(), def_id);
67 let instance = ty::Instance::new(def_id, substs);
72 let constant = cx.tcx.const_eval(param_env.and(c_id)).ok();
73 if let Some(Constant::Int(val)) = constant.and_then(|c| miri_to_const(cx.tcx, c)) {
74 let mut ty = cx.tcx.type_of(def_id);
75 if let ty::Adt(adt, _) = ty.sty {
77 ty = adt.repr.discr_type().to_ty(cx.tcx);
81 ty::Int(IntTy::Isize) => {
82 let val = ((val as i128) << 64) >> 64;
83 if val <= i128::from(i32::max_value()) && val >= i128::from(i32::min_value()) {
87 ty::Uint(UintTy::Usize) if val > u128::from(u32::max_value()) => {},
92 ENUM_CLIKE_UNPORTABLE_VARIANT,
94 "Clike enum variant discriminant is not portable to 32-bit targets",