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