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