rust-clippy/clippy_lints/src/bit_mask.rs

321 lines
11 KiB
Rust
Raw Normal View History

use rustc::hir::*;
use rustc::hir::def::Def;
use rustc::lint::*;
use rustc_const_eval::lookup_const_by_id;
2016-02-12 17:35:44 +00:00
use syntax::ast::LitKind;
2017-04-27 12:00:35 +00:00
use syntax::codemap::Span;
use utils::{span_lint, span_lint_and_then};
use utils::sugg::Sugg;
/// **What it does:** Checks for incompatible bit masks in comparisons.
///
/// The formula for detecting if an expression of the type `_ <bit_op> m
/// <cmp_op> c` (where `<bit_op>` is one of {`&`, `|`} and `<cmp_op>` is one of
/// {`!=`, `>=`, `>`, `!=`, `>=`, `>`}) can be determined from the following
/// table:
///
2016-03-28 19:23:21 +00:00
/// |Comparison |Bit Op|Example |is always|Formula |
/// |------------|------|------------|---------|----------------------|
/// |`==` or `!=`| `&` |`x & 2 == 3`|`false` |`c & m != c` |
/// |`<` or `>=`| `&` |`x & 2 < 3` |`true` |`m < c` |
/// |`>` or `<=`| `&` |`x & 1 > 1` |`false` |`m <= c` |
/// |`==` or `!=`| `|` |`x | 1 == 0`|`false` |`c | m != c` |
/// |`<` or `>=`| `|` |`x | 1 < 1` |`false` |`m >= c` |
/// |`<=` or `>` | `|` |`x | 1 > 0` |`true` |`m > c` |
///
/// **Why is this bad?** If the bits that the comparison cares about are always
/// set to zero or one by the bit mask, the comparison is constant `true` or
/// `false` (depending on mask, compared value, and operators).
///
/// So the code is actively misleading, and the only reason someone would write
/// this intentionally is to win an underhanded Rust contest or create a
/// test-case for this lint.
///
/// **Known problems:** None.
///
2016-07-15 22:25:44 +00:00
/// **Example:**
/// ```rust
/// if (x & 1 == 2) { … }
/// ```
declare_lint! {
pub BAD_BIT_MASK,
2015-09-06 14:09:35 +00:00
Warn,
"expressions of the form `_ & mask == select` that will only ever return `true` or `false`"
}
/// **What it does:** Checks for bit masks in comparisons which can be removed
/// without changing the outcome. The basic structure can be seen in the
/// following table:
///
2016-03-19 16:48:29 +00:00
/// |Comparison| Bit Op |Example |equals |
/// |----------|---------|-----------|-------|
/// |`>` / `<=`|`|` / `^`|`x | 2 > 3`|`x > 3`|
/// |`<` / `>=`|`|` / `^`|`x ^ 1 < 4`|`x < 4`|
///
/// **Why is this bad?** Not equally evil as [`bad_bit_mask`](#bad_bit_mask),
/// but still a bit misleading, because the bit mask is ineffective.
///
/// **Known problems:** False negatives: This lint will only match instances
/// where we have figured out the math (which is for a power-of-two compared
/// value). This means things like `x | 1 >= 7` (which would be better written
/// as `x >= 6`) will not be reported (but bit masks like this are fairly
/// uncommon).
///
2016-07-15 22:25:44 +00:00
/// **Example:**
/// ```rust
/// if (x | 1 > 3) { … }
/// ```
2015-05-15 12:09:29 +00:00
declare_lint! {
pub INEFFECTIVE_BIT_MASK,
Warn,
"expressions where a bit mask will be rendered useless by a comparison, e.g. `(x | 1) > 2`"
2015-05-15 12:09:29 +00:00
}
/// **What it does:** Checks for bit masks that can be replaced by a call
/// to `trailing_zeros`
///
2017-08-09 07:30:56 +00:00
/// **Why is this bad?** `x.trailing_zeros() > 4` is much clearer than `x & 15
/// == 0`
///
2017-07-10 07:50:36 +00:00
/// **Known problems:** llvm generates better code for `x & 15 == 0` on x86
///
/// **Example:**
/// ```rust
/// x & 0x1111 == 0
/// ```
declare_lint! {
pub VERBOSE_BIT_MASK,
Warn,
"expressions where a bit mask is less readable than the corresponding method call"
}
2017-08-09 07:30:56 +00:00
#[derive(Copy, Clone)]
pub struct BitMask;
impl LintPass for BitMask {
fn get_lints(&self) -> LintArray {
lint_array!(BAD_BIT_MASK, INEFFECTIVE_BIT_MASK, VERBOSE_BIT_MASK)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BitMask {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
if let ExprBinary(ref cmp, ref left, ref right) = e.node {
if cmp.node.is_comparison() {
2016-06-05 23:16:16 +00:00
if let Some(cmp_opt) = fetch_int_literal(cx, right) {
check_compare(cx, left, cmp.node, cmp_opt, &e.span)
} else if let Some(cmp_val) = fetch_int_literal(cx, left) {
check_compare(cx, right, invert_cmp(cmp.node), cmp_val, &e.span)
}
}
}
if_let_chain!{[
let Expr_::ExprBinary(ref op, ref left, ref right) = e.node,
BinOp_::BiEq == op.node,
let Expr_::ExprBinary(ref op1, ref left1, ref right1) = left.node,
BinOp_::BiBitAnd == op1.node,
let Expr_::ExprLit(ref lit) = right1.node,
let LitKind::Int(n, _) = lit.node,
let Expr_::ExprLit(ref lit1) = right.node,
let LitKind::Int(0, _) = lit1.node,
n.leading_zeros() == n.count_zeros(),
], {
span_lint_and_then(cx,
VERBOSE_BIT_MASK,
e.span,
"bit mask could be simplified with a call to `trailing_zeros`",
|db| {
let sugg = Sugg::hir(cx, left1, "...").maybe_par();
db.span_suggestion(e.span, "try", format!("{}.trailing_zeros() >= {}", sugg, n.count_ones()));
});
}}
}
}
2016-01-04 04:26:12 +00:00
fn invert_cmp(cmp: BinOp_) -> BinOp_ {
match cmp {
BiEq => BiEq,
BiNe => BiNe,
BiLt => BiGt,
BiGt => BiLt,
BiLe => BiGe,
BiGe => BiLe,
2016-01-04 04:26:12 +00:00
_ => BiOr, // Dummy
}
}
fn check_compare(cx: &LateContext, bit_op: &Expr, cmp_op: BinOp_, cmp_value: u128, span: &Span) {
2015-09-19 03:02:56 +00:00
if let ExprBinary(ref op, ref left, ref right) = bit_op.node {
if op.node != BiBitAnd && op.node != BiBitOr {
return;
}
2016-01-04 04:26:12 +00:00
fetch_int_literal(cx, right)
.or_else(|| fetch_int_literal(cx, left))
.map_or((), |mask| check_bit_mask(cx, op.node, cmp_op, mask, cmp_value, span))
}
}
fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value: u128, cmp_value: u128, span: &Span) {
match cmp_op {
2017-09-05 09:33:04 +00:00
BiEq | BiNe => match bit_op {
BiBitAnd => if mask_value & cmp_value != cmp_value {
if cmp_value != 0 {
span_lint(
cx,
BAD_BIT_MASK,
*span,
&format!(
"incompatible bit mask: `_ & {}` can never be equal to `{}`",
mask_value,
cmp_value
),
);
}
} else if mask_value == 0 {
span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
},
BiBitOr => if mask_value | cmp_value != cmp_value {
span_lint(
cx,
BAD_BIT_MASK,
*span,
&format!(
"incompatible bit mask: `_ | {}` can never be equal to `{}`",
mask_value,
cmp_value
),
);
},
_ => (),
2016-12-20 17:21:30 +00:00
},
2017-09-05 09:33:04 +00:00
BiLt | BiGe => match bit_op {
BiBitAnd => if mask_value < cmp_value {
span_lint(
cx,
BAD_BIT_MASK,
*span,
&format!(
"incompatible bit mask: `_ & {}` will always be lower than `{}`",
mask_value,
cmp_value
),
);
} else if mask_value == 0 {
span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
},
BiBitOr => if mask_value >= cmp_value {
span_lint(
cx,
BAD_BIT_MASK,
*span,
&format!(
"incompatible bit mask: `_ | {}` will never be lower than `{}`",
mask_value,
cmp_value
),
);
} else {
check_ineffective_lt(cx, *span, mask_value, cmp_value, "|");
},
BiBitXor => check_ineffective_lt(cx, *span, mask_value, cmp_value, "^"),
_ => (),
2016-12-20 17:21:30 +00:00
},
2017-09-05 09:33:04 +00:00
BiLe | BiGt => match bit_op {
BiBitAnd => if mask_value <= cmp_value {
span_lint(
cx,
BAD_BIT_MASK,
*span,
&format!(
"incompatible bit mask: `_ & {}` will never be higher than `{}`",
mask_value,
cmp_value
),
);
} else if mask_value == 0 {
span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
},
BiBitOr => if mask_value > cmp_value {
span_lint(
cx,
BAD_BIT_MASK,
*span,
&format!(
"incompatible bit mask: `_ | {}` will always be higher than `{}`",
mask_value,
cmp_value
),
);
} else {
check_ineffective_gt(cx, *span, mask_value, cmp_value, "|");
},
BiBitXor => check_ineffective_gt(cx, *span, mask_value, cmp_value, "^"),
_ => (),
2016-12-20 17:21:30 +00:00
},
2016-01-04 04:26:12 +00:00
_ => (),
}
}
fn check_ineffective_lt(cx: &LateContext, span: Span, m: u128, c: u128, op: &str) {
2015-08-19 07:07:50 +00:00
if c.is_power_of_two() && m < c {
2017-08-09 07:30:56 +00:00
span_lint(
cx,
INEFFECTIVE_BIT_MASK,
span,
&format!(
"ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
op,
m,
c
),
);
2015-08-19 07:07:50 +00:00
}
}
fn check_ineffective_gt(cx: &LateContext, span: Span, m: u128, c: u128, op: &str) {
2015-08-19 07:07:50 +00:00
if (c + 1).is_power_of_two() && m <= c {
2017-08-09 07:30:56 +00:00
span_lint(
cx,
INEFFECTIVE_BIT_MASK,
span,
&format!(
"ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
op,
m,
c
),
);
2015-08-19 07:07:50 +00:00
}
}
fn fetch_int_literal(cx: &LateContext, lit: &Expr) -> Option<u128> {
use rustc::ty::subst::Substs;
2015-08-21 18:44:48 +00:00
match lit.node {
ExprLit(ref lit_ptr) => {
2016-02-12 17:35:44 +00:00
if let LitKind::Int(value, _) = lit_ptr.node {
2017-01-17 18:30:32 +00:00
Some(value) // TODO: Handle sign
2016-01-04 04:26:12 +00:00
} else {
None
}
2016-12-20 17:21:30 +00:00
},
ExprPath(ref qpath) => {
2017-08-15 09:10:49 +00:00
let def = cx.tables.qpath_def(qpath, lit.hir_id);
if let Def::Const(def_id) = def {
2017-07-31 10:37:38 +00:00
lookup_const_by_id(cx.tcx, cx.param_env.and((def_id, Substs::empty()))).and_then(|(l, _ty)| {
2017-04-24 11:35:14 +00:00
let body = if let Some(id) = cx.tcx.hir.as_local_node_id(l) {
2017-04-27 12:00:35 +00:00
cx.tcx.mir_const_qualif(def_id);
2017-04-24 11:35:14 +00:00
cx.tcx.hir.body(cx.tcx.hir.body_owned_by(id))
} else {
cx.tcx.sess.cstore.item_body(cx.tcx, def_id)
};
fetch_int_literal(cx, &body.value)
})
} else {
None
2015-05-07 04:41:54 +00:00
}
2016-12-20 17:21:30 +00:00
},
2016-01-04 04:26:12 +00:00
_ => None,
}
}