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