2 use rustc::hir::def::Def;
4 use rustc_const_eval::lookup_const_by_id;
5 use syntax::ast::LitKind;
6 use syntax::codemap::Span;
7 use utils::{span_lint, span_lint_and_then};
10 /// **What it does:** Checks for incompatible bit masks in comparisons.
12 /// The formula for detecting if an expression of the type `_ <bit_op> m
13 /// <cmp_op> c` (where `<bit_op>` is one of {`&`, `|`} and `<cmp_op>` is one of
14 /// {`!=`, `>=`, `>`, `!=`, `>=`, `>`}) can be determined from the following
17 /// |Comparison |Bit Op|Example |is always|Formula |
18 /// |------------|------|------------|---------|----------------------|
19 /// |`==` or `!=`| `&` |`x & 2 == 3`|`false` |`c & m != c` |
20 /// |`<` or `>=`| `&` |`x & 2 < 3` |`true` |`m < c` |
21 /// |`>` or `<=`| `&` |`x & 1 > 1` |`false` |`m <= c` |
22 /// |`==` or `!=`| `|` |`x | 1 == 0`|`false` |`c | m != c` |
23 /// |`<` or `>=`| `|` |`x | 1 < 1` |`false` |`m >= c` |
24 /// |`<=` or `>` | `|` |`x | 1 > 0` |`true` |`m > c` |
26 /// **Why is this bad?** If the bits that the comparison cares about are always
27 /// set to zero or one by the bit mask, the comparison is constant `true` or
28 /// `false` (depending on mask, compared value, and operators).
30 /// So the code is actively misleading, and the only reason someone would write
31 /// this intentionally is to win an underhanded Rust contest or create a
32 /// test-case for this lint.
34 /// **Known problems:** None.
38 /// if (x & 1 == 2) { … }
43 "expressions of the form `_ & mask == select` that will only ever return `true` or `false`"
46 /// **What it does:** Checks for bit masks in comparisons which can be removed
47 /// without changing the outcome. The basic structure can be seen in the
50 /// |Comparison| Bit Op |Example |equals |
51 /// |----------|---------|-----------|-------|
52 /// |`>` / `<=`|`|` / `^`|`x | 2 > 3`|`x > 3`|
53 /// |`<` / `>=`|`|` / `^`|`x ^ 1 < 4`|`x < 4`|
55 /// **Why is this bad?** Not equally evil as [`bad_bit_mask`](#bad_bit_mask),
56 /// but still a bit misleading, because the bit mask is ineffective.
58 /// **Known problems:** False negatives: This lint will only match instances
59 /// where we have figured out the math (which is for a power-of-two compared
60 /// value). This means things like `x | 1 >= 7` (which would be better written
61 /// as `x >= 6`) will not be reported (but bit masks like this are fairly
66 /// if (x | 1 > 3) { … }
69 pub INEFFECTIVE_BIT_MASK,
71 "expressions where a bit mask will be rendered useless by a comparison, e.g. `(x | 1) > 2`"
74 /// **What it does:** Checks for bit masks that can be replaced by a call
75 /// to `trailing_zeros`
77 /// **Why is this bad?** `x.trailing_zeros() > 4` is much clearer than `x & 15
80 /// **Known problems:** llvm generates better code for `x & 15 == 0` on x86
89 "expressions where a bit mask is less readable than the corresponding method call"
92 #[derive(Copy, Clone)]
95 impl LintPass for BitMask {
96 fn get_lints(&self) -> LintArray {
97 lint_array!(BAD_BIT_MASK, INEFFECTIVE_BIT_MASK, VERBOSE_BIT_MASK)
101 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BitMask {
102 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
103 if let ExprBinary(ref cmp, ref left, ref right) = e.node {
104 if cmp.node.is_comparison() {
105 if let Some(cmp_opt) = fetch_int_literal(cx, right) {
106 check_compare(cx, left, cmp.node, cmp_opt, &e.span)
107 } else if let Some(cmp_val) = fetch_int_literal(cx, left) {
108 check_compare(cx, right, invert_cmp(cmp.node), cmp_val, &e.span)
113 let Expr_::ExprBinary(ref op, ref left, ref right) = e.node,
114 BinOp_::BiEq == op.node,
115 let Expr_::ExprBinary(ref op1, ref left1, ref right1) = left.node,
116 BinOp_::BiBitAnd == op1.node,
117 let Expr_::ExprLit(ref lit) = right1.node,
118 let LitKind::Int(n, _) = lit.node,
119 let Expr_::ExprLit(ref lit1) = right.node,
120 let LitKind::Int(0, _) = lit1.node,
121 n.leading_zeros() == n.count_zeros(),
123 span_lint_and_then(cx,
126 "bit mask could be simplified with a call to `trailing_zeros`",
128 let sugg = Sugg::hir(cx, left1, "...").maybe_par();
129 db.span_suggestion(e.span, "try", format!("{}.trailing_zeros() >= {}", sugg, n.count_ones()));
135 fn invert_cmp(cmp: BinOp_) -> BinOp_ {
148 fn check_compare(cx: &LateContext, bit_op: &Expr, cmp_op: BinOp_, cmp_value: u128, span: &Span) {
149 if let ExprBinary(ref op, ref left, ref right) = bit_op.node {
150 if op.node != BiBitAnd && op.node != BiBitOr {
153 fetch_int_literal(cx, right)
154 .or_else(|| fetch_int_literal(cx, left))
155 .map_or((), |mask| check_bit_mask(cx, op.node, cmp_op, mask, cmp_value, span))
159 fn check_bit_mask(cx: &LateContext, bit_op: BinOp_, cmp_op: BinOp_, mask_value: u128, cmp_value: u128, span: &Span) {
161 BiEq | BiNe => match bit_op {
162 BiBitAnd => if mask_value & cmp_value != cmp_value {
169 "incompatible bit mask: `_ & {}` can never be equal to `{}`",
175 } else if mask_value == 0 {
176 span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
178 BiBitOr => if mask_value | cmp_value != cmp_value {
184 "incompatible bit mask: `_ | {}` can never be equal to `{}`",
192 BiLt | BiGe => match bit_op {
193 BiBitAnd => if mask_value < cmp_value {
199 "incompatible bit mask: `_ & {}` will always be lower than `{}`",
204 } else if mask_value == 0 {
205 span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
207 BiBitOr => if mask_value >= cmp_value {
213 "incompatible bit mask: `_ | {}` will never be lower than `{}`",
219 check_ineffective_lt(cx, *span, mask_value, cmp_value, "|");
221 BiBitXor => check_ineffective_lt(cx, *span, mask_value, cmp_value, "^"),
224 BiLe | BiGt => match bit_op {
225 BiBitAnd => if mask_value <= cmp_value {
231 "incompatible bit mask: `_ & {}` will never be higher than `{}`",
236 } else if mask_value == 0 {
237 span_lint(cx, BAD_BIT_MASK, *span, "&-masking with zero");
239 BiBitOr => if mask_value > cmp_value {
245 "incompatible bit mask: `_ | {}` will always be higher than `{}`",
251 check_ineffective_gt(cx, *span, mask_value, cmp_value, "|");
253 BiBitXor => check_ineffective_gt(cx, *span, mask_value, cmp_value, "^"),
260 fn check_ineffective_lt(cx: &LateContext, span: Span, m: u128, c: u128, op: &str) {
261 if c.is_power_of_two() && m < c {
264 INEFFECTIVE_BIT_MASK,
267 "ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
276 fn check_ineffective_gt(cx: &LateContext, span: Span, m: u128, c: u128, op: &str) {
277 if (c + 1).is_power_of_two() && m <= c {
280 INEFFECTIVE_BIT_MASK,
283 "ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
292 fn fetch_int_literal(cx: &LateContext, lit: &Expr) -> Option<u128> {
293 use rustc::ty::subst::Substs;
295 ExprLit(ref lit_ptr) => {
296 if let LitKind::Int(value, _) = lit_ptr.node {
297 Some(value) // TODO: Handle sign
302 ExprPath(ref qpath) => {
303 let def = cx.tables.qpath_def(qpath, lit.hir_id);
304 if let Def::Const(def_id) = def {
305 lookup_const_by_id(cx.tcx, cx.param_env.and((def_id, Substs::empty()))).and_then(|(l, _ty)| {
306 let body = if let Some(id) = cx.tcx.hir.as_local_node_id(l) {
307 cx.tcx.mir_const_qualif(def_id);
308 cx.tcx.hir.body(cx.tcx.hir.body_owned_by(id))
310 cx.tcx.sess.cstore.item_body(cx.tcx, def_id)
312 fetch_int_literal(cx, &body.value)