]> git.lizzy.rs Git - rust.git/blob - src/enum_clike.rs
Merge pull request #681 from oli-obk/split
[rust.git] / src / enum_clike.rs
1 //! lint on C-like enums that are `repr(isize/usize)` and have values that don't fit into an `i32`
2
3 use rustc::lint::*;
4 use rustc::middle::const_val::ConstVal;
5 use rustc_const_math::*;
6 use rustc::hir::*;
7 use utils::span_lint;
8
9 /// **What it does:** Lints on C-like enums that are `repr(isize/usize)` and have values that don't fit into an `i32`.
10 ///
11 /// **Why is this bad?** This will truncate the variant value on 32bit architectures, but works fine on 64 bit.
12 ///
13 /// **Known problems:** None
14 ///
15 /// **Example:** `#[repr(usize)] enum NonPortable { X = 0x1_0000_0000, Y = 0 }`
16 declare_lint! {
17     pub ENUM_CLIKE_UNPORTABLE_VARIANT, Warn,
18     "finds C-like enums that are `repr(isize/usize)` and have values that don't fit into an `i32`"
19 }
20
21 pub struct EnumClikeUnportableVariant;
22
23 impl LintPass for EnumClikeUnportableVariant {
24     fn get_lints(&self) -> LintArray {
25         lint_array!(ENUM_CLIKE_UNPORTABLE_VARIANT)
26     }
27 }
28
29 impl LateLintPass for EnumClikeUnportableVariant {
30     #[allow(cast_possible_truncation, cast_sign_loss)]
31     fn check_item(&mut self, cx: &LateContext, item: &Item) {
32         if let ItemEnum(ref def, _) = item.node {
33             for var in &def.variants {
34                 let variant = &var.node;
35                 if let Some(ref disr) = variant.disr_expr {
36                     use rustc_const_eval::*;
37                     let bad = match eval_const_expr_partial(cx.tcx, &**disr, EvalHint::ExprTypeChecked, None) {
38                         Ok(ConstVal::Integral(Usize(Us64(i)))) => i as u32 as u64 != i,
39                         Ok(ConstVal::Integral(Isize(Is64(i)))) => i as i32 as i64 != i,
40                         _ => false,
41                     };
42                     if bad {
43                         span_lint(cx,
44                                   ENUM_CLIKE_UNPORTABLE_VARIANT,
45                                   var.span,
46                                   "Clike enum variant discriminant is not portable to 32-bit targets");
47                     }
48                 }
49             }
50         }
51     }
52 }