]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/bit_mask.rs
Various cosmetic improvements.
[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     /// ```ignore
41     /// if (x & 1 == 2) { … }
42     /// ```
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 declare_clippy_lint! {
49     /// **What it does:** Checks for bit masks in comparisons which can be removed
50     /// without changing the outcome. The basic structure can be seen in the
51     /// following table:
52     ///
53     /// |Comparison| Bit Op  |Example    |equals |
54     /// |----------|---------|-----------|-------|
55     /// |`>` / `<=`|`|` / `^`|`x | 2 > 3`|`x > 3`|
56     /// |`<` / `>=`|`|` / `^`|`x ^ 1 < 4`|`x < 4`|
57     ///
58     /// **Why is this bad?** Not equally evil as [`bad_bit_mask`](#bad_bit_mask),
59     /// but still a bit misleading, because the bit mask is ineffective.
60     ///
61     /// **Known problems:** False negatives: This lint will only match instances
62     /// where we have figured out the math (which is for a power-of-two compared
63     /// value). This means things like `x | 1 >= 7` (which would be better written
64     /// as `x >= 6`) will not be reported (but bit masks like this are fairly
65     /// uncommon).
66     ///
67     /// **Example:**
68     /// ```ignore
69     /// if (x | 1 > 3) { … }
70     /// ```
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 declare_clippy_lint! {
77     /// **What it does:** Checks for bit masks that can be replaced by a call
78     /// to `trailing_zeros`
79     ///
80     /// **Why is this bad?** `x.trailing_zeros() > 4` is much clearer than `x & 15
81     /// == 0`
82     ///
83     /// **Known problems:** llvm generates better code for `x & 15 == 0` on x86
84     ///
85     /// **Example:**
86     /// ```ignore
87     /// x & 0x1111 == 0
88     /// ```
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     fn name(&self) -> &'static str {
112         "BitMask"
113     }
114 }
115
116 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BitMask {
117     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
118         if let ExprKind::Binary(cmp, left, right) = &e.node {
119             if cmp.node.is_comparison() {
120                 if let Some(cmp_opt) = fetch_int_literal(cx, right) {
121                     check_compare(cx, left, cmp.node, cmp_opt, e.span)
122                 } else if let Some(cmp_val) = fetch_int_literal(cx, left) {
123                     check_compare(cx, right, invert_cmp(cmp.node), cmp_val, e.span)
124                 }
125             }
126         }
127         if_chain! {
128             if let ExprKind::Binary(op, left, right) = &e.node;
129             if BinOpKind::Eq == op.node;
130             if let ExprKind::Binary(op1, left1, right1) = &left.node;
131             if BinOpKind::BitAnd == op1.node;
132             if let ExprKind::Lit(lit) = &right1.node;
133             if let LitKind::Int(n, _) = lit.node;
134             if let ExprKind::Lit(lit1) = &right.node;
135             if let LitKind::Int(0, _) = lit1.node;
136             if n.leading_zeros() == n.count_zeros();
137             if n > u128::from(self.verbose_bit_mask_threshold);
138             then {
139                 span_lint_and_then(cx,
140                                    VERBOSE_BIT_MASK,
141                                    e.span,
142                                    "bit mask could be simplified with a call to `trailing_zeros`",
143                                    |db| {
144                     let sugg = Sugg::hir(cx, left1, "...").maybe_par();
145                     db.span_suggestion(
146                         e.span,
147                         "try",
148                         format!("{}.trailing_zeros() >= {}", sugg, n.count_ones()),
149                         Applicability::MaybeIncorrect,
150                     );
151                 });
152             }
153         }
154     }
155 }
156
157 fn invert_cmp(cmp: BinOpKind) -> BinOpKind {
158     match cmp {
159         BinOpKind::Eq => BinOpKind::Eq,
160         BinOpKind::Ne => BinOpKind::Ne,
161         BinOpKind::Lt => BinOpKind::Gt,
162         BinOpKind::Gt => BinOpKind::Lt,
163         BinOpKind::Le => BinOpKind::Ge,
164         BinOpKind::Ge => BinOpKind::Le,
165         _ => BinOpKind::Or, // Dummy
166     }
167 }
168
169 fn check_compare(cx: &LateContext<'_, '_>, bit_op: &Expr, cmp_op: BinOpKind, cmp_value: u128, span: Span) {
170     if let ExprKind::Binary(op, left, right) = &bit_op.node {
171         if op.node != BinOpKind::BitAnd && op.node != BinOpKind::BitOr {
172             return;
173         }
174         fetch_int_literal(cx, right)
175             .or_else(|| fetch_int_literal(cx, left))
176             .map_or((), |mask| check_bit_mask(cx, op.node, cmp_op, mask, cmp_value, span))
177     }
178 }
179
180 #[allow(clippy::too_many_lines)]
181 fn check_bit_mask(
182     cx: &LateContext<'_, '_>,
183     bit_op: BinOpKind,
184     cmp_op: BinOpKind,
185     mask_value: u128,
186     cmp_value: u128,
187     span: Span,
188 ) {
189     match cmp_op {
190         BinOpKind::Eq | BinOpKind::Ne => match bit_op {
191             BinOpKind::BitAnd => {
192                 if mask_value & cmp_value != cmp_value {
193                     if cmp_value != 0 {
194                         span_lint(
195                             cx,
196                             BAD_BIT_MASK,
197                             span,
198                             &format!(
199                                 "incompatible bit mask: `_ & {}` can never be equal to `{}`",
200                                 mask_value, cmp_value
201                             ),
202                         );
203                     }
204                 } else if mask_value == 0 {
205                     span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
206                 }
207             },
208             BinOpKind::BitOr => {
209                 if mask_value | cmp_value != cmp_value {
210                     span_lint(
211                         cx,
212                         BAD_BIT_MASK,
213                         span,
214                         &format!(
215                             "incompatible bit mask: `_ | {}` can never be equal to `{}`",
216                             mask_value, cmp_value
217                         ),
218                     );
219                 }
220             },
221             _ => (),
222         },
223         BinOpKind::Lt | BinOpKind::Ge => match bit_op {
224             BinOpKind::BitAnd => {
225                 if mask_value < cmp_value {
226                     span_lint(
227                         cx,
228                         BAD_BIT_MASK,
229                         span,
230                         &format!(
231                             "incompatible bit mask: `_ & {}` will always be lower than `{}`",
232                             mask_value, cmp_value
233                         ),
234                     );
235                 } else if mask_value == 0 {
236                     span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
237                 }
238             },
239             BinOpKind::BitOr => {
240                 if mask_value >= cmp_value {
241                     span_lint(
242                         cx,
243                         BAD_BIT_MASK,
244                         span,
245                         &format!(
246                             "incompatible bit mask: `_ | {}` will never be lower than `{}`",
247                             mask_value, cmp_value
248                         ),
249                     );
250                 } else {
251                     check_ineffective_lt(cx, span, mask_value, cmp_value, "|");
252                 }
253             },
254             BinOpKind::BitXor => check_ineffective_lt(cx, span, mask_value, cmp_value, "^"),
255             _ => (),
256         },
257         BinOpKind::Le | BinOpKind::Gt => match bit_op {
258             BinOpKind::BitAnd => {
259                 if mask_value <= cmp_value {
260                     span_lint(
261                         cx,
262                         BAD_BIT_MASK,
263                         span,
264                         &format!(
265                             "incompatible bit mask: `_ & {}` will never be higher than `{}`",
266                             mask_value, cmp_value
267                         ),
268                     );
269                 } else if mask_value == 0 {
270                     span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
271                 }
272             },
273             BinOpKind::BitOr => {
274                 if mask_value > cmp_value {
275                     span_lint(
276                         cx,
277                         BAD_BIT_MASK,
278                         span,
279                         &format!(
280                             "incompatible bit mask: `_ | {}` will always be higher than `{}`",
281                             mask_value, cmp_value
282                         ),
283                     );
284                 } else {
285                     check_ineffective_gt(cx, span, mask_value, cmp_value, "|");
286                 }
287             },
288             BinOpKind::BitXor => check_ineffective_gt(cx, span, mask_value, cmp_value, "^"),
289             _ => (),
290         },
291         _ => (),
292     }
293 }
294
295 fn check_ineffective_lt(cx: &LateContext<'_, '_>, span: Span, m: u128, c: u128, op: &str) {
296     if c.is_power_of_two() && m < c {
297         span_lint(
298             cx,
299             INEFFECTIVE_BIT_MASK,
300             span,
301             &format!(
302                 "ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
303                 op, m, c
304             ),
305         );
306     }
307 }
308
309 fn check_ineffective_gt(cx: &LateContext<'_, '_>, span: Span, m: u128, c: u128, op: &str) {
310     if (c + 1).is_power_of_two() && m <= c {
311         span_lint(
312             cx,
313             INEFFECTIVE_BIT_MASK,
314             span,
315             &format!(
316                 "ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
317                 op, m, c
318             ),
319         );
320     }
321 }
322
323 fn fetch_int_literal(cx: &LateContext<'_, '_>, lit: &Expr) -> Option<u128> {
324     match constant(cx, cx.tables, lit)?.0 {
325         Constant::Int(n) => Some(n),
326         _ => None,
327     }
328 }