mirror of
https://github.com/rust-lang/rust.git
synced 2026-04-27 18:57:42 +03:00
Truncate constants to target type in comparison (#16782)
changelog: [`bad_bit_mask`]: truncate constant to target type before warning about impossible equality Fixes rust-lang/rust-clippy#16781
This commit is contained in:
@@ -36,12 +36,19 @@ fn invert_cmp(cmp: BinOpKind) -> BinOpKind {
|
||||
}
|
||||
}
|
||||
|
||||
fn check_compare<'a>(cx: &LateContext<'a>, bit_op: &Expr<'a>, cmp_op: BinOpKind, cmp_value: u128, span: Span) {
|
||||
fn check_compare<'a>(cx: &LateContext<'a>, bit_op: &Expr<'a>, cmp_op: BinOpKind, mut cmp_value: u128, span: Span) {
|
||||
if let ExprKind::Binary(op, left, right) = &bit_op.kind {
|
||||
if op.node != BinOpKind::BitAnd && op.node != BinOpKind::BitOr || is_from_proc_macro(cx, bit_op) {
|
||||
return;
|
||||
}
|
||||
if let Some(mask) = fetch_int_literal(cx, right).or_else(|| fetch_int_literal(cx, left)) {
|
||||
let ty = cx.typeck_results().expr_ty(bit_op);
|
||||
if !ty.is_ptr_sized_integral()
|
||||
&& let bits = ty.primitive_size(cx.tcx)
|
||||
{
|
||||
// Strip high bits that don't fit into the result type as they won't be used in the comparison
|
||||
cmp_value &= bits.unsigned_int_max();
|
||||
}
|
||||
check_bit_mask(cx, op.node, cmp_op, mask, cmp_value, span);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,3 +89,13 @@ fn ineffective() {
|
||||
x | 3 > 4; // not an error (yet), better written as x >= 4
|
||||
x | 4 <= 19;
|
||||
}
|
||||
|
||||
mod issue16781 {
|
||||
fn unsigned(x: u8) -> bool {
|
||||
x & 0xf0 == 0x11 << 4
|
||||
}
|
||||
|
||||
fn signed(x: i8) -> bool {
|
||||
x & 0x70 == 0x11 << 4
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user