3 use rustc::{declare_lint, lint_array};
4 use if_chain::if_chain;
5 use syntax::ast::LitKind;
6 use syntax::codemap::Span;
7 use crate::utils::{span_lint, span_lint_and_then};
8 use crate::utils::sugg::Sugg;
9 use crate::consts::{constant, Constant};
11 /// **What it does:** Checks for incompatible bit masks in comparisons.
13 /// The formula for detecting if an expression of the type `_ <bit_op> m
14 /// <cmp_op> c` (where `<bit_op>` is one of {`&`, `|`} and `<cmp_op>` is one of
15 /// {`!=`, `>=`, `>`, `!=`, `>=`, `>`}) can be determined from the following
18 /// |Comparison |Bit Op|Example |is always|Formula |
19 /// |------------|------|------------|---------|----------------------|
20 /// |`==` or `!=`| `&` |`x & 2 == 3`|`false` |`c & m != c` |
21 /// |`<` or `>=`| `&` |`x & 2 < 3` |`true` |`m < c` |
22 /// |`>` or `<=`| `&` |`x & 1 > 1` |`false` |`m <= c` |
23 /// |`==` or `!=`| `|` |`x | 1 == 0`|`false` |`c | m != c` |
24 /// |`<` or `>=`| `|` |`x | 1 < 1` |`false` |`m >= c` |
25 /// |`<=` or `>` | `|` |`x | 1 > 0` |`true` |`m > c` |
27 /// **Why is this bad?** If the bits that the comparison cares about are always
28 /// set to zero or one by the bit mask, the comparison is constant `true` or
29 /// `false` (depending on mask, compared value, and operators).
31 /// So the code is actively misleading, and the only reason someone would write
32 /// this intentionally is to win an underhanded Rust contest or create a
33 /// test-case for this lint.
35 /// **Known problems:** None.
39 /// if (x & 1 == 2) { … }
41 declare_clippy_lint! {
44 "expressions of the form `_ & mask == select` that will only ever return `true` or `false`"
47 /// **What it does:** Checks for bit masks in comparisons which can be removed
48 /// without changing the outcome. The basic structure can be seen in the
51 /// |Comparison| Bit Op |Example |equals |
52 /// |----------|---------|-----------|-------|
53 /// |`>` / `<=`|`|` / `^`|`x | 2 > 3`|`x > 3`|
54 /// |`<` / `>=`|`|` / `^`|`x ^ 1 < 4`|`x < 4`|
56 /// **Why is this bad?** Not equally evil as [`bad_bit_mask`](#bad_bit_mask),
57 /// but still a bit misleading, because the bit mask is ineffective.
59 /// **Known problems:** False negatives: This lint will only match instances
60 /// where we have figured out the math (which is for a power-of-two compared
61 /// value). This means things like `x | 1 >= 7` (which would be better written
62 /// as `x >= 6`) will not be reported (but bit masks like this are fairly
67 /// if (x | 1 > 3) { … }
69 declare_clippy_lint! {
70 pub INEFFECTIVE_BIT_MASK,
72 "expressions where a bit mask will be rendered useless by a comparison, e.g. `(x | 1) > 2`"
75 /// **What it does:** Checks for bit masks that can be replaced by a call
76 /// to `trailing_zeros`
78 /// **Why is this bad?** `x.trailing_zeros() > 4` is much clearer than `x & 15
81 /// **Known problems:** llvm generates better code for `x & 15 == 0` on x86
87 declare_clippy_lint! {
90 "expressions where a bit mask is less readable than the corresponding method call"
93 #[derive(Copy, Clone)]
95 verbose_bit_mask_threshold: u64,
99 pub fn new(verbose_bit_mask_threshold: u64) -> Self {
101 verbose_bit_mask_threshold,
106 impl LintPass for BitMask {
107 fn get_lints(&self) -> LintArray {
108 lint_array!(BAD_BIT_MASK, INEFFECTIVE_BIT_MASK, VERBOSE_BIT_MASK)
112 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BitMask {
113 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
114 if let ExprKind::Binary(ref cmp, ref left, ref right) = e.node {
115 if cmp.node.is_comparison() {
116 if let Some(cmp_opt) = fetch_int_literal(cx, right) {
117 check_compare(cx, left, cmp.node, cmp_opt, e.span)
118 } else if let Some(cmp_val) = fetch_int_literal(cx, left) {
119 check_compare(cx, right, invert_cmp(cmp.node), cmp_val, e.span)
124 if let ExprKind::Binary(ref op, ref left, ref right) = e.node;
125 if BinOpKind::Eq == op.node;
126 if let ExprKind::Binary(ref op1, ref left1, ref right1) = left.node;
127 if BinOpKind::BitAnd == op1.node;
128 if let ExprKind::Lit(ref lit) = right1.node;
129 if let LitKind::Int(n, _) = lit.node;
130 if let ExprKind::Lit(ref lit1) = right.node;
131 if let LitKind::Int(0, _) = lit1.node;
132 if n.leading_zeros() == n.count_zeros();
133 if n > u128::from(self.verbose_bit_mask_threshold);
135 span_lint_and_then(cx,
138 "bit mask could be simplified with a call to `trailing_zeros`",
140 let sugg = Sugg::hir(cx, left1, "...").maybe_par();
141 db.span_suggestion(e.span, "try", format!("{}.trailing_zeros() >= {}", sugg, n.count_ones()));
148 fn invert_cmp(cmp: BinOpKind) -> BinOpKind {
150 BinOpKind::Eq => BinOpKind::Eq,
151 BinOpKind::Ne => BinOpKind::Ne,
152 BinOpKind::Lt => BinOpKind::Gt,
153 BinOpKind::Gt => BinOpKind::Lt,
154 BinOpKind::Le => BinOpKind::Ge,
155 BinOpKind::Ge => BinOpKind::Le,
156 _ => BinOpKind::Or, // Dummy
161 fn check_compare(cx: &LateContext, bit_op: &Expr, cmp_op: BinOpKind, cmp_value: u128, span: Span) {
162 if let ExprKind::Binary(ref op, ref left, ref right) = bit_op.node {
163 if op.node != BinOpKind::BitAnd && op.node != BinOpKind::BitOr {
166 fetch_int_literal(cx, right)
167 .or_else(|| fetch_int_literal(cx, left))
168 .map_or((), |mask| check_bit_mask(cx, op.node, cmp_op, mask, cmp_value, span))
172 fn check_bit_mask(cx: &LateContext, bit_op: BinOpKind, cmp_op: BinOpKind, mask_value: u128, cmp_value: u128, span: Span) {
174 BinOpKind::Eq | BinOpKind::Ne => match bit_op {
175 BinOpKind::BitAnd => if mask_value & cmp_value != cmp_value {
182 "incompatible bit mask: `_ & {}` can never be equal to `{}`",
188 } else if mask_value == 0 {
189 span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
191 BinOpKind::BitOr => if mask_value | cmp_value != cmp_value {
197 "incompatible bit mask: `_ | {}` can never be equal to `{}`",
205 BinOpKind::Lt | BinOpKind::Ge => match bit_op {
206 BinOpKind::BitAnd => if mask_value < cmp_value {
212 "incompatible bit mask: `_ & {}` will always be lower than `{}`",
217 } else if mask_value == 0 {
218 span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
220 BinOpKind::BitOr => if mask_value >= cmp_value {
226 "incompatible bit mask: `_ | {}` will never be lower than `{}`",
232 check_ineffective_lt(cx, span, mask_value, cmp_value, "|");
234 BinOpKind::BitXor => check_ineffective_lt(cx, span, mask_value, cmp_value, "^"),
237 BinOpKind::Le | BinOpKind::Gt => match bit_op {
238 BinOpKind::BitAnd => if mask_value <= cmp_value {
244 "incompatible bit mask: `_ & {}` will never be higher than `{}`",
249 } else if mask_value == 0 {
250 span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
252 BinOpKind::BitOr => if mask_value > cmp_value {
258 "incompatible bit mask: `_ | {}` will always be higher than `{}`",
264 check_ineffective_gt(cx, span, mask_value, cmp_value, "|");
266 BinOpKind::BitXor => check_ineffective_gt(cx, span, mask_value, cmp_value, "^"),
273 fn check_ineffective_lt(cx: &LateContext, span: Span, m: u128, c: u128, op: &str) {
274 if c.is_power_of_two() && m < c {
277 INEFFECTIVE_BIT_MASK,
280 "ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
289 fn check_ineffective_gt(cx: &LateContext, span: Span, m: u128, c: u128, op: &str) {
290 if (c + 1).is_power_of_two() && m <= c {
293 INEFFECTIVE_BIT_MASK,
296 "ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
305 fn fetch_int_literal(cx: &LateContext, lit: &Expr) -> Option<u128> {
306 match constant(cx, cx.tables, lit)?.0 {
307 Constant::Int(n) => Some(n),