]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/enum_clike.rs
Update to latest master
[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 rustc::ty;
8 use rustc::traits::Reveal;
9 use rustc::ty::subst::Substs;
10 use utils::span_lint;
11
12 /// **What it does:** Checks for C-like enumerations that are
13 /// `repr(isize/usize)` and have values that don't fit into an `i32`.
14 ///
15 /// **Why is this bad?** This will truncate the variant value on 32 bit
16 /// architectures, but works fine on 64 bit.
17 ///
18 /// **Known problems:** None.
19 ///
20 /// **Example:**
21 /// ```rust
22 /// #[repr(usize)]
23 /// enum NonPortable {
24 ///     X = 0x1_0000_0000,
25 ///     Y = 0
26 /// }
27 /// ```
28 declare_lint! {
29     pub ENUM_CLIKE_UNPORTABLE_VARIANT,
30     Warn,
31     "C-like enums that are `repr(isize/usize)` and have values that don't fit into an `i32`"
32 }
33
34 pub struct UnportableVariant;
35
36 impl LintPass for UnportableVariant {
37     fn get_lints(&self) -> LintArray {
38         lint_array!(ENUM_CLIKE_UNPORTABLE_VARIANT)
39     }
40 }
41
42 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnportableVariant {
43     #[allow(cast_possible_truncation, cast_sign_loss)]
44     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
45         if let ItemEnum(ref def, _) = item.node {
46             for var in &def.variants {
47                 let variant = &var.node;
48                 if let Some(body_id) = variant.disr_expr {
49                     let expr = &cx.tcx.hir.body(body_id).value;
50                     let did = cx.tcx.hir.body_owner_def_id(body_id);
51                     let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
52                     let substs = Substs::identity_for_item(cx.tcx.global_tcx(), did);
53                     let bad = match cx.tcx.at(expr.span).const_eval(param_env.and((did, substs))) {
54                         Ok(ConstVal::Integral(Usize(Us64(i)))) => i as u32 as u64 != i,
55                         Ok(ConstVal::Integral(Isize(Is64(i)))) => i as i32 as i64 != i,
56                         _ => false,
57                     };
58                     if bad {
59                         span_lint(cx,
60                                   ENUM_CLIKE_UNPORTABLE_VARIANT,
61                                   var.span,
62                                   "Clike enum variant discriminant is not portable to 32-bit targets");
63                     }
64                 }
65             }
66         }
67     }
68 }