]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/bit_mask.rs
Rollup merge of #97277 - jyn514:no-unstable-for-bootstrap, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / clippy_lints / src / bit_mask.rs
1 use clippy_utils::consts::{constant, Constant};
2 use clippy_utils::diagnostics::{span_lint, span_lint_and_then};
3 use clippy_utils::sugg::Sugg;
4 use rustc_ast::ast::LitKind;
5 use rustc_errors::Applicability;
6 use rustc_hir::{BinOpKind, Expr, ExprKind};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
9 use rustc_span::source_map::Span;
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// 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?
30     /// 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     /// ### Example
39     /// ```rust
40     /// # let x = 1;
41     /// if (x & 1 == 2) { }
42     /// ```
43     #[clippy::version = "pre 1.29.0"]
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
51     /// 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?
61     /// Not equally evil as [`bad_bit_mask`](#bad_bit_mask),
62     /// but still a bit misleading, because the bit mask is ineffective.
63     ///
64     /// ### Known problems
65     /// False negatives: This lint will only match instances
66     /// where we have figured out the math (which is for a power-of-two compared
67     /// value). This means things like `x | 1 >= 7` (which would be better written
68     /// as `x >= 6`) will not be reported (but bit masks like this are fairly
69     /// uncommon).
70     ///
71     /// ### Example
72     /// ```rust
73     /// # let x = 1;
74     /// if (x | 1 > 3) {  }
75     /// ```
76     #[clippy::version = "pre 1.29.0"]
77     pub INEFFECTIVE_BIT_MASK,
78     correctness,
79     "expressions where a bit mask will be rendered useless by a comparison, e.g., `(x | 1) > 2`"
80 }
81
82 declare_clippy_lint! {
83     /// ### What it does
84     /// Checks for bit masks that can be replaced by a call
85     /// to `trailing_zeros`
86     ///
87     /// ### Why is this bad?
88     /// `x.trailing_zeros() > 4` is much clearer than `x & 15
89     /// == 0`
90     ///
91     /// ### Known problems
92     /// llvm generates better code for `x & 15 == 0` on x86
93     ///
94     /// ### Example
95     /// ```rust
96     /// # let x = 1;
97     /// if x & 0b1111 == 0 { }
98     /// ```
99     #[clippy::version = "pre 1.29.0"]
100     pub VERBOSE_BIT_MASK,
101     pedantic,
102     "expressions where a bit mask is less readable than the corresponding method call"
103 }
104
105 #[derive(Copy, Clone)]
106 pub struct BitMask {
107     verbose_bit_mask_threshold: u64,
108 }
109
110 impl BitMask {
111     #[must_use]
112     pub fn new(verbose_bit_mask_threshold: u64) -> Self {
113         Self {
114             verbose_bit_mask_threshold,
115         }
116     }
117 }
118
119 impl_lint_pass!(BitMask => [BAD_BIT_MASK, INEFFECTIVE_BIT_MASK, VERBOSE_BIT_MASK]);
120
121 impl<'tcx> LateLintPass<'tcx> for BitMask {
122     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
123         if let ExprKind::Binary(cmp, left, right) = &e.kind {
124             if cmp.node.is_comparison() {
125                 if let Some(cmp_opt) = fetch_int_literal(cx, right) {
126                     check_compare(cx, left, cmp.node, cmp_opt, e.span);
127                 } else if let Some(cmp_val) = fetch_int_literal(cx, left) {
128                     check_compare(cx, right, invert_cmp(cmp.node), cmp_val, e.span);
129                 }
130             }
131         }
132
133         if let ExprKind::Binary(op, left, right) = &e.kind
134             && BinOpKind::Eq == op.node
135             && let ExprKind::Binary(op1, left1, right1) = &left.kind
136             && BinOpKind::BitAnd == op1.node
137             && let ExprKind::Lit(lit) = &right1.kind
138             && let LitKind::Int(n, _) = lit.node
139             && let ExprKind::Lit(lit1) = &right.kind
140             && let LitKind::Int(0, _) = lit1.node
141             && n.leading_zeros() == n.count_zeros()
142             && n > u128::from(self.verbose_bit_mask_threshold)
143         {
144             span_lint_and_then(
145                 cx,
146                 VERBOSE_BIT_MASK,
147                 e.span,
148                 "bit mask could be simplified with a call to `trailing_zeros`",
149                 |diag| {
150                     let sugg = Sugg::hir(cx, left1, "...").maybe_par();
151                     diag.span_suggestion(
152                         e.span,
153                         "try",
154                         format!("{}.trailing_zeros() >= {}", sugg, n.count_ones()),
155                         Applicability::MaybeIncorrect,
156                     );
157                 },
158             );
159         }
160     }
161 }
162
163 #[must_use]
164 fn invert_cmp(cmp: BinOpKind) -> BinOpKind {
165     match cmp {
166         BinOpKind::Eq => BinOpKind::Eq,
167         BinOpKind::Ne => BinOpKind::Ne,
168         BinOpKind::Lt => BinOpKind::Gt,
169         BinOpKind::Gt => BinOpKind::Lt,
170         BinOpKind::Le => BinOpKind::Ge,
171         BinOpKind::Ge => BinOpKind::Le,
172         _ => BinOpKind::Or, // Dummy
173     }
174 }
175
176 fn check_compare(cx: &LateContext<'_>, bit_op: &Expr<'_>, cmp_op: BinOpKind, cmp_value: u128, span: Span) {
177     if let ExprKind::Binary(op, left, right) = &bit_op.kind {
178         if op.node != BinOpKind::BitAnd && op.node != BinOpKind::BitOr {
179             return;
180         }
181         fetch_int_literal(cx, right)
182             .or_else(|| fetch_int_literal(cx, left))
183             .map_or((), |mask| check_bit_mask(cx, op.node, cmp_op, mask, cmp_value, span));
184     }
185 }
186
187 #[allow(clippy::too_many_lines)]
188 fn check_bit_mask(
189     cx: &LateContext<'_>,
190     bit_op: BinOpKind,
191     cmp_op: BinOpKind,
192     mask_value: u128,
193     cmp_value: u128,
194     span: Span,
195 ) {
196     match cmp_op {
197         BinOpKind::Eq | BinOpKind::Ne => match bit_op {
198             BinOpKind::BitAnd => {
199                 if mask_value & cmp_value != cmp_value {
200                     if cmp_value != 0 {
201                         span_lint(
202                             cx,
203                             BAD_BIT_MASK,
204                             span,
205                             &format!(
206                                 "incompatible bit mask: `_ & {}` can never be equal to `{}`",
207                                 mask_value, cmp_value
208                             ),
209                         );
210                     }
211                 } else if mask_value == 0 {
212                     span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
213                 }
214             },
215             BinOpKind::BitOr => {
216                 if mask_value | cmp_value != cmp_value {
217                     span_lint(
218                         cx,
219                         BAD_BIT_MASK,
220                         span,
221                         &format!(
222                             "incompatible bit mask: `_ | {}` can never be equal to `{}`",
223                             mask_value, cmp_value
224                         ),
225                     );
226                 }
227             },
228             _ => (),
229         },
230         BinOpKind::Lt | BinOpKind::Ge => match bit_op {
231             BinOpKind::BitAnd => {
232                 if mask_value < cmp_value {
233                     span_lint(
234                         cx,
235                         BAD_BIT_MASK,
236                         span,
237                         &format!(
238                             "incompatible bit mask: `_ & {}` will always be lower than `{}`",
239                             mask_value, cmp_value
240                         ),
241                     );
242                 } else if mask_value == 0 {
243                     span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
244                 }
245             },
246             BinOpKind::BitOr => {
247                 if mask_value >= cmp_value {
248                     span_lint(
249                         cx,
250                         BAD_BIT_MASK,
251                         span,
252                         &format!(
253                             "incompatible bit mask: `_ | {}` will never be lower than `{}`",
254                             mask_value, cmp_value
255                         ),
256                     );
257                 } else {
258                     check_ineffective_lt(cx, span, mask_value, cmp_value, "|");
259                 }
260             },
261             BinOpKind::BitXor => check_ineffective_lt(cx, span, mask_value, cmp_value, "^"),
262             _ => (),
263         },
264         BinOpKind::Le | BinOpKind::Gt => match bit_op {
265             BinOpKind::BitAnd => {
266                 if mask_value <= cmp_value {
267                     span_lint(
268                         cx,
269                         BAD_BIT_MASK,
270                         span,
271                         &format!(
272                             "incompatible bit mask: `_ & {}` will never be higher than `{}`",
273                             mask_value, cmp_value
274                         ),
275                     );
276                 } else if mask_value == 0 {
277                     span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
278                 }
279             },
280             BinOpKind::BitOr => {
281                 if mask_value > cmp_value {
282                     span_lint(
283                         cx,
284                         BAD_BIT_MASK,
285                         span,
286                         &format!(
287                             "incompatible bit mask: `_ | {}` will always be higher than `{}`",
288                             mask_value, cmp_value
289                         ),
290                     );
291                 } else {
292                     check_ineffective_gt(cx, span, mask_value, cmp_value, "|");
293                 }
294             },
295             BinOpKind::BitXor => check_ineffective_gt(cx, span, mask_value, cmp_value, "^"),
296             _ => (),
297         },
298         _ => (),
299     }
300 }
301
302 fn check_ineffective_lt(cx: &LateContext<'_>, span: Span, m: u128, c: u128, op: &str) {
303     if c.is_power_of_two() && m < c {
304         span_lint(
305             cx,
306             INEFFECTIVE_BIT_MASK,
307             span,
308             &format!(
309                 "ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
310                 op, m, c
311             ),
312         );
313     }
314 }
315
316 fn check_ineffective_gt(cx: &LateContext<'_>, span: Span, m: u128, c: u128, op: &str) {
317     if (c + 1).is_power_of_two() && m <= c {
318         span_lint(
319             cx,
320             INEFFECTIVE_BIT_MASK,
321             span,
322             &format!(
323                 "ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
324                 op, m, c
325             ),
326         );
327     }
328 }
329
330 fn fetch_int_literal(cx: &LateContext<'_>, lit: &Expr<'_>) -> Option<u128> {
331     match constant(cx, cx.typeck_results(), lit)?.0 {
332         Constant::Int(n) => Some(n),
333         _ => None,
334     }
335 }