]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/bit_mask.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[rust.git] / clippy_lints / src / bit_mask.rs
1 use crate::consts::{constant, Constant};
2 use crate::utils::sugg::Sugg;
3 use crate::utils::{span_lint, span_lint_and_then};
4 use if_chain::if_chain;
5 use rustc::hir::*;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{declare_tool_lint, lint_array};
8 use rustc_errors::Applicability;
9 use syntax::ast::LitKind;
10 use syntax::source_map::Span;
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for incompatible bit masks in comparisons.
14     ///
15     /// The formula for detecting if an expression of the type `_ <bit_op> m
16     /// <cmp_op> c` (where `<bit_op>` is one of {`&`, `|`} and `<cmp_op>` is one of
17     /// {`!=`, `>=`, `>`, `!=`, `>=`, `>`}) can be determined from the following
18     /// table:
19     ///
20     /// |Comparison  |Bit Op|Example     |is always|Formula               |
21     /// |------------|------|------------|---------|----------------------|
22     /// |`==` or `!=`| `&`  |`x & 2 == 3`|`false`  |`c & m != c`          |
23     /// |`<`  or `>=`| `&`  |`x & 2 < 3` |`true`   |`m < c`               |
24     /// |`>`  or `<=`| `&`  |`x & 1 > 1` |`false`  |`m <= c`              |
25     /// |`==` or `!=`| `|`  |`x | 1 == 0`|`false`  |`c | m != c`          |
26     /// |`<`  or `>=`| `|`  |`x | 1 < 1` |`false`  |`m >= c`              |
27     /// |`<=` or `>` | `|`  |`x | 1 > 0` |`true`   |`m > c`               |
28     ///
29     /// **Why is this bad?** If the bits that the comparison cares about are always
30     /// set to zero or one by the bit mask, the comparison is constant `true` or
31     /// `false` (depending on mask, compared value, and operators).
32     ///
33     /// So the code is actively misleading, and the only reason someone would write
34     /// this intentionally is to win an underhanded Rust contest or create a
35     /// test-case for this lint.
36     ///
37     /// **Known problems:** None.
38     ///
39     /// **Example:**
40     /// ```rust
41     /// # let x = 1;
42     /// if (x & 1 == 2) { }
43     /// ```
44     pub BAD_BIT_MASK,
45     correctness,
46     "expressions of the form `_ & mask == select` that will only ever return `true` or `false`"
47 }
48
49 declare_clippy_lint! {
50     /// **What it does:** Checks for bit masks in comparisons which can be removed
51     /// without changing the outcome. The basic structure can be seen in the
52     /// following table:
53     ///
54     /// |Comparison| Bit Op  |Example    |equals |
55     /// |----------|---------|-----------|-------|
56     /// |`>` / `<=`|`|` / `^`|`x | 2 > 3`|`x > 3`|
57     /// |`<` / `>=`|`|` / `^`|`x ^ 1 < 4`|`x < 4`|
58     ///
59     /// **Why is this bad?** Not equally evil as [`bad_bit_mask`](#bad_bit_mask),
60     /// but still a bit misleading, because the bit mask is ineffective.
61     ///
62     /// **Known problems:** False negatives: This lint will only match instances
63     /// where we have figured out the math (which is for a power-of-two compared
64     /// value). This means things like `x | 1 >= 7` (which would be better written
65     /// as `x >= 6`) will not be reported (but bit masks like this are fairly
66     /// uncommon).
67     ///
68     /// **Example:**
69     /// ```rust
70     /// # let x = 1;
71     /// if (x | 1 > 3) {  }
72     /// ```
73     pub INEFFECTIVE_BIT_MASK,
74     correctness,
75     "expressions where a bit mask will be rendered useless by a comparison, e.g., `(x | 1) > 2`"
76 }
77
78 declare_clippy_lint! {
79     /// **What it does:** Checks for bit masks that can be replaced by a call
80     /// to `trailing_zeros`
81     ///
82     /// **Why is this bad?** `x.trailing_zeros() > 4` is much clearer than `x & 15
83     /// == 0`
84     ///
85     /// **Known problems:** llvm generates better code for `x & 15 == 0` on x86
86     ///
87     /// **Example:**
88     /// ```rust
89     /// # let x = 1;
90     /// if x & 0x1111 == 0 { }
91     /// ```
92     pub VERBOSE_BIT_MASK,
93     style,
94     "expressions where a bit mask is less readable than the corresponding method call"
95 }
96
97 #[derive(Copy, Clone)]
98 pub struct BitMask {
99     verbose_bit_mask_threshold: u64,
100 }
101
102 impl BitMask {
103     pub fn new(verbose_bit_mask_threshold: u64) -> Self {
104         Self {
105             verbose_bit_mask_threshold,
106         }
107     }
108 }
109
110 impl LintPass for BitMask {
111     fn get_lints(&self) -> LintArray {
112         lint_array!(BAD_BIT_MASK, INEFFECTIVE_BIT_MASK, VERBOSE_BIT_MASK)
113     }
114     fn name(&self) -> &'static str {
115         "BitMask"
116     }
117 }
118
119 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BitMask {
120     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
121         if let ExprKind::Binary(cmp, left, right) = &e.node {
122             if cmp.node.is_comparison() {
123                 if let Some(cmp_opt) = fetch_int_literal(cx, right) {
124                     check_compare(cx, left, cmp.node, cmp_opt, e.span)
125                 } else if let Some(cmp_val) = fetch_int_literal(cx, left) {
126                     check_compare(cx, right, invert_cmp(cmp.node), cmp_val, e.span)
127                 }
128             }
129         }
130         if_chain! {
131             if let ExprKind::Binary(op, left, right) = &e.node;
132             if BinOpKind::Eq == op.node;
133             if let ExprKind::Binary(op1, left1, right1) = &left.node;
134             if BinOpKind::BitAnd == op1.node;
135             if let ExprKind::Lit(lit) = &right1.node;
136             if let LitKind::Int(n, _) = lit.node;
137             if let ExprKind::Lit(lit1) = &right.node;
138             if let LitKind::Int(0, _) = lit1.node;
139             if n.leading_zeros() == n.count_zeros();
140             if n > u128::from(self.verbose_bit_mask_threshold);
141             then {
142                 span_lint_and_then(cx,
143                                    VERBOSE_BIT_MASK,
144                                    e.span,
145                                    "bit mask could be simplified with a call to `trailing_zeros`",
146                                    |db| {
147                     let sugg = Sugg::hir(cx, left1, "...").maybe_par();
148                     db.span_suggestion(
149                         e.span,
150                         "try",
151                         format!("{}.trailing_zeros() >= {}", sugg, n.count_ones()),
152                         Applicability::MaybeIncorrect,
153                     );
154                 });
155             }
156         }
157     }
158 }
159
160 fn invert_cmp(cmp: BinOpKind) -> BinOpKind {
161     match cmp {
162         BinOpKind::Eq => BinOpKind::Eq,
163         BinOpKind::Ne => BinOpKind::Ne,
164         BinOpKind::Lt => BinOpKind::Gt,
165         BinOpKind::Gt => BinOpKind::Lt,
166         BinOpKind::Le => BinOpKind::Ge,
167         BinOpKind::Ge => BinOpKind::Le,
168         _ => BinOpKind::Or, // Dummy
169     }
170 }
171
172 fn check_compare(cx: &LateContext<'_, '_>, bit_op: &Expr, cmp_op: BinOpKind, cmp_value: u128, span: Span) {
173     if let ExprKind::Binary(op, left, right) = &bit_op.node {
174         if op.node != BinOpKind::BitAnd && op.node != BinOpKind::BitOr {
175             return;
176         }
177         fetch_int_literal(cx, right)
178             .or_else(|| fetch_int_literal(cx, left))
179             .map_or((), |mask| check_bit_mask(cx, op.node, cmp_op, mask, cmp_value, span))
180     }
181 }
182
183 #[allow(clippy::too_many_lines)]
184 fn check_bit_mask(
185     cx: &LateContext<'_, '_>,
186     bit_op: BinOpKind,
187     cmp_op: BinOpKind,
188     mask_value: u128,
189     cmp_value: u128,
190     span: Span,
191 ) {
192     match cmp_op {
193         BinOpKind::Eq | BinOpKind::Ne => match bit_op {
194             BinOpKind::BitAnd => {
195                 if mask_value & cmp_value != cmp_value {
196                     if cmp_value != 0 {
197                         span_lint(
198                             cx,
199                             BAD_BIT_MASK,
200                             span,
201                             &format!(
202                                 "incompatible bit mask: `_ & {}` can never be equal to `{}`",
203                                 mask_value, cmp_value
204                             ),
205                         );
206                     }
207                 } else if mask_value == 0 {
208                     span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
209                 }
210             },
211             BinOpKind::BitOr => {
212                 if mask_value | cmp_value != cmp_value {
213                     span_lint(
214                         cx,
215                         BAD_BIT_MASK,
216                         span,
217                         &format!(
218                             "incompatible bit mask: `_ | {}` can never be equal to `{}`",
219                             mask_value, cmp_value
220                         ),
221                     );
222                 }
223             },
224             _ => (),
225         },
226         BinOpKind::Lt | BinOpKind::Ge => match bit_op {
227             BinOpKind::BitAnd => {
228                 if mask_value < cmp_value {
229                     span_lint(
230                         cx,
231                         BAD_BIT_MASK,
232                         span,
233                         &format!(
234                             "incompatible bit mask: `_ & {}` will always be lower than `{}`",
235                             mask_value, cmp_value
236                         ),
237                     );
238                 } else if mask_value == 0 {
239                     span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
240                 }
241             },
242             BinOpKind::BitOr => {
243                 if mask_value >= cmp_value {
244                     span_lint(
245                         cx,
246                         BAD_BIT_MASK,
247                         span,
248                         &format!(
249                             "incompatible bit mask: `_ | {}` will never be lower than `{}`",
250                             mask_value, cmp_value
251                         ),
252                     );
253                 } else {
254                     check_ineffective_lt(cx, span, mask_value, cmp_value, "|");
255                 }
256             },
257             BinOpKind::BitXor => check_ineffective_lt(cx, span, mask_value, cmp_value, "^"),
258             _ => (),
259         },
260         BinOpKind::Le | BinOpKind::Gt => match bit_op {
261             BinOpKind::BitAnd => {
262                 if mask_value <= cmp_value {
263                     span_lint(
264                         cx,
265                         BAD_BIT_MASK,
266                         span,
267                         &format!(
268                             "incompatible bit mask: `_ & {}` will never be higher than `{}`",
269                             mask_value, cmp_value
270                         ),
271                     );
272                 } else if mask_value == 0 {
273                     span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
274                 }
275             },
276             BinOpKind::BitOr => {
277                 if mask_value > cmp_value {
278                     span_lint(
279                         cx,
280                         BAD_BIT_MASK,
281                         span,
282                         &format!(
283                             "incompatible bit mask: `_ | {}` will always be higher than `{}`",
284                             mask_value, cmp_value
285                         ),
286                     );
287                 } else {
288                     check_ineffective_gt(cx, span, mask_value, cmp_value, "|");
289                 }
290             },
291             BinOpKind::BitXor => check_ineffective_gt(cx, span, mask_value, cmp_value, "^"),
292             _ => (),
293         },
294         _ => (),
295     }
296 }
297
298 fn check_ineffective_lt(cx: &LateContext<'_, '_>, span: Span, m: u128, c: u128, op: &str) {
299     if c.is_power_of_two() && m < c {
300         span_lint(
301             cx,
302             INEFFECTIVE_BIT_MASK,
303             span,
304             &format!(
305                 "ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
306                 op, m, c
307             ),
308         );
309     }
310 }
311
312 fn check_ineffective_gt(cx: &LateContext<'_, '_>, span: Span, m: u128, c: u128, op: &str) {
313     if (c + 1).is_power_of_two() && m <= c {
314         span_lint(
315             cx,
316             INEFFECTIVE_BIT_MASK,
317             span,
318             &format!(
319                 "ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
320                 op, m, c
321             ),
322         );
323     }
324 }
325
326 fn fetch_int_literal(cx: &LateContext<'_, '_>, lit: &Expr) -> Option<u128> {
327     match constant(cx, cx.tables, lit)?.0 {
328         Constant::Int(n) => Some(n),
329         _ => None,
330     }
331 }