]> git.lizzy.rs Git - rust.git/commitdiff
identity_op lint fix for '&' with unsigned types
authorYury Krivopalov <ykrivopalov@yandex.ru>
Sat, 30 Sep 2017 08:33:15 +0000 (11:33 +0300)
committerYury Krivopalov <ykrivopalov@yandex.ru>
Sat, 14 Oct 2017 09:21:23 +0000 (12:21 +0300)
clippy_lints/src/identity_op.rs
tests/ui/identity_op.rs
tests/ui/identity_op.stderr

index a409f4c7d65c96a34b3391872f1b5e1dea00710f..21aa914155e05a655f01a539657f31f70c7d47db 100644 (file)
@@ -1,9 +1,9 @@
 use consts::{constant_simple, Constant};
-use rustc::lint::*;
 use rustc::hir::*;
+use rustc::lint::*;
+use rustc_const_math::ConstInt;
 use syntax::codemap::Span;
 use utils::{in_macro, snippet, span_lint};
-use syntax::attr::IntType::{SignedInt, UnsignedInt};
 
 /// **What it does:** Checks for identity operations, e.g. `x + 0`.
 ///
@@ -58,15 +58,28 @@ fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
     }
 }
 
+fn no_zeros(v: &ConstInt) -> bool {
+    match *v {
+        ConstInt::I8(i) => i.count_zeros() == 0,
+        ConstInt::I16(i) => i.count_zeros() == 0,
+        ConstInt::I32(i) => i.count_zeros() == 0,
+        ConstInt::I64(i) => i.count_zeros() == 0,
+        ConstInt::I128(i) => i.count_zeros() == 0,
+        ConstInt::U8(i) => i.count_zeros() == 0,
+        ConstInt::U16(i) => i.count_zeros() == 0,
+        ConstInt::U32(i) => i.count_zeros() == 0,
+        ConstInt::U64(i) => i.count_zeros() == 0,
+        ConstInt::U128(i) => i.count_zeros() == 0,
+        _ => false
+    }
+}
+
 #[allow(cast_possible_wrap)]
 fn check(cx: &LateContext, e: &Expr, m: i8, span: Span, arg: Span) {
     if let Some(Constant::Int(v)) = constant_simple(cx, e) {
         if match m {
             0 => v.to_u128_unchecked() == 0,
-            -1 => match v.int_type() {
-                SignedInt(_) => (v.to_u128_unchecked() as i128 == -1),
-                UnsignedInt(_) => false,
-            },
+            -1 => no_zeros(&v),
             1 => v.to_u128_unchecked() == 1,
             _ => unreachable!(),
         } {
index b474344977c8c1ea0fd6d93aae2c88927b25b489..1ed9f974d436c2b4c0f3e863755b137e41a80229 100644 (file)
@@ -27,4 +27,7 @@ fn main() {
 
     x & NEG_ONE;  //no error, as we skip lookups (for now)
     -1 & x;
+
+    let u : u8 = 0;
+    u & 255;
 }
index 30367c989ec883e0db1695cfdb3cfdc64b056ac9..c1ce8d2ec4cd5c616aa620408d67ea3243acb985 100644 (file)
@@ -42,3 +42,9 @@ error: the operation is ineffective. Consider reducing it to `x`
 29 |     -1 & x;
    |     ^^^^^^
 
+error: the operation is ineffective. Consider reducing it to `u`
+  --> $DIR/identity_op.rs:32:5
+   |
+32 |     u & 255;
+   |     ^^^^^^^
+