]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/enum_clike.rs
TyCtxt::map is now called TyCtxt::hir
[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<'a, 'tcx> LateLintPass<'a, 'tcx> for UnportableVariant {
40     #[allow(cast_possible_truncation, cast_sign_loss)]
41     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
42         if let ItemEnum(ref def, _) = item.node {
43             for var in &def.variants {
44                 let variant = &var.node;
45                 if let Some(body_id) = variant.disr_expr {
46                     use rustc_const_eval::*;
47                     let constcx = ConstContext::new(cx.tcx, body_id);
48                     let bad = match constcx.eval(&cx.tcx.hir.body(body_id).value, EvalHint::ExprTypeChecked) {
49                         Ok(ConstVal::Integral(Usize(Us64(i)))) => i as u32 as u64 != i,
50                         Ok(ConstVal::Integral(Isize(Is64(i)))) => i as i32 as i64 != i,
51                         _ => false,
52                     };
53                     if bad {
54                         span_lint(cx,
55                                   ENUM_CLIKE_UNPORTABLE_VARIANT,
56                                   var.span,
57                                   "Clike enum variant discriminant is not portable to 32-bit targets");
58                     }
59                 }
60             }
61         }
62     }
63 }