Skip to content

Commit f68e408

Browse files
author
Yury Krivopalov
committed
identity_op lint fix for '&' with unsigned types
1 parent f0aa2c1 commit f68e408

File tree

3 files changed

+28
-6
lines changed

3 files changed

+28
-6
lines changed

clippy_lints/src/identity_op.rs

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
use consts::{constant_simple, Constant};
2-
use rustc::lint::*;
32
use rustc::hir::*;
3+
use rustc::lint::*;
4+
use rustc_const_math::ConstInt;
45
use syntax::codemap::Span;
56
use utils::{in_macro, snippet, span_lint};
6-
use syntax::attr::IntType::{SignedInt, UnsignedInt};
77

88
/// **What it does:** Checks for identity operations, e.g. `x + 0`.
99
///
@@ -58,15 +58,28 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IdentityOp {
5858
}
5959
}
6060

61+
fn no_zeros(v: &ConstInt) -> bool {
62+
match *v {
63+
ConstInt::I8(i) => i.count_zeros() == 0,
64+
ConstInt::I16(i) => i.count_zeros() == 0,
65+
ConstInt::I32(i) => i.count_zeros() == 0,
66+
ConstInt::I64(i) => i.count_zeros() == 0,
67+
ConstInt::I128(i) => i.count_zeros() == 0,
68+
ConstInt::U8(i) => i.count_zeros() == 0,
69+
ConstInt::U16(i) => i.count_zeros() == 0,
70+
ConstInt::U32(i) => i.count_zeros() == 0,
71+
ConstInt::U64(i) => i.count_zeros() == 0,
72+
ConstInt::U128(i) => i.count_zeros() == 0,
73+
_ => false
74+
}
75+
}
76+
6177
#[allow(cast_possible_wrap)]
6278
fn check(cx: &LateContext, e: &Expr, m: i8, span: Span, arg: Span) {
6379
if let Some(Constant::Int(v)) = constant_simple(cx, e) {
6480
if match m {
6581
0 => v.to_u128_unchecked() == 0,
66-
-1 => match v.int_type() {
67-
SignedInt(_) => (v.to_u128_unchecked() as i128 == -1),
68-
UnsignedInt(_) => false,
69-
},
82+
-1 => no_zeros(&v),
7083
1 => v.to_u128_unchecked() == 1,
7184
_ => unreachable!(),
7285
} {

tests/ui/identity_op.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,7 @@ fn main() {
2727

2828
x & NEG_ONE; //no error, as we skip lookups (for now)
2929
-1 & x;
30+
31+
let u : u8 = 0;
32+
u & 255;
3033
}

tests/ui/identity_op.stderr

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,9 @@ error: the operation is ineffective. Consider reducing it to `x`
4242
29 | -1 & x;
4343
| ^^^^^^
4444

45+
error: the operation is ineffective. Consider reducing it to `u`
46+
--> $DIR/identity_op.rs:32:5
47+
|
48+
32 | u & 255;
49+
| ^^^^^^^
50+

0 commit comments

Comments
 (0)