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