]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/bit_mask.rs
Rollup merge of #94113 - Mizobrook-kan:issue-94025, r=estebank
[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 if_chain::if_chain;
5 use rustc_ast::ast::LitKind;
6 use rustc_errors::Applicability;
7 use rustc_hir::{BinOpKind, Expr, ExprKind};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 use rustc_span::source_map::Span;
11
12 declare_clippy_lint! {
13     /// ### What it does
14     /// 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?
31     /// If the bits that the comparison cares about are always
32     /// set to zero or one by the bit mask, the comparison is constant `true` or
33     /// `false` (depending on mask, compared value, and operators).
34     ///
35     /// So the code is actively misleading, and the only reason someone would write
36     /// this intentionally is to win an underhanded Rust contest or create a
37     /// test-case for this lint.
38     ///
39     /// ### Example
40     /// ```rust
41     /// # let x = 1;
42     /// if (x & 1 == 2) { }
43     /// ```
44     #[clippy::version = "pre 1.29.0"]
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
52     /// Checks for bit masks in comparisons which can be removed
53     /// without changing the outcome. The basic structure can be seen in the
54     /// following table:
55     ///
56     /// |Comparison| Bit Op   |Example     |equals |
57     /// |----------|----------|------------|-------|
58     /// |`>` / `<=`|`\|` / `^`|`x \| 2 > 3`|`x > 3`|
59     /// |`<` / `>=`|`\|` / `^`|`x ^ 1 < 4` |`x < 4`|
60     ///
61     /// ### Why is this bad?
62     /// Not equally evil as [`bad_bit_mask`](#bad_bit_mask),
63     /// but still a bit misleading, because the bit mask is ineffective.
64     ///
65     /// ### Known problems
66     /// False negatives: This lint will only match instances
67     /// where we have figured out the math (which is for a power-of-two compared
68     /// value). This means things like `x | 1 >= 7` (which would be better written
69     /// as `x >= 6`) will not be reported (but bit masks like this are fairly
70     /// uncommon).
71     ///
72     /// ### Example
73     /// ```rust
74     /// # let x = 1;
75     /// if (x | 1 > 3) {  }
76     /// ```
77     #[clippy::version = "pre 1.29.0"]
78     pub INEFFECTIVE_BIT_MASK,
79     correctness,
80     "expressions where a bit mask will be rendered useless by a comparison, e.g., `(x | 1) > 2`"
81 }
82
83 declare_clippy_lint! {
84     /// ### What it does
85     /// Checks for bit masks that can be replaced by a call
86     /// to `trailing_zeros`
87     ///
88     /// ### Why is this bad?
89     /// `x.trailing_zeros() > 4` is much clearer than `x & 15
90     /// == 0`
91     ///
92     /// ### Known problems
93     /// llvm generates better code for `x & 15 == 0` on x86
94     ///
95     /// ### Example
96     /// ```rust
97     /// # let x = 1;
98     /// if x & 0b1111 == 0 { }
99     /// ```
100     #[clippy::version = "pre 1.29.0"]
101     pub VERBOSE_BIT_MASK,
102     pedantic,
103     "expressions where a bit mask is less readable than the corresponding method call"
104 }
105
106 #[derive(Copy, Clone)]
107 pub struct BitMask {
108     verbose_bit_mask_threshold: u64,
109 }
110
111 impl BitMask {
112     #[must_use]
113     pub fn new(verbose_bit_mask_threshold: u64) -> Self {
114         Self {
115             verbose_bit_mask_threshold,
116         }
117     }
118 }
119
120 impl_lint_pass!(BitMask => [BAD_BIT_MASK, INEFFECTIVE_BIT_MASK, VERBOSE_BIT_MASK]);
121
122 impl<'tcx> LateLintPass<'tcx> for BitMask {
123     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
124         if let ExprKind::Binary(cmp, left, right) = &e.kind {
125             if cmp.node.is_comparison() {
126                 if let Some(cmp_opt) = fetch_int_literal(cx, right) {
127                     check_compare(cx, left, cmp.node, cmp_opt, e.span);
128                 } else if let Some(cmp_val) = fetch_int_literal(cx, left) {
129                     check_compare(cx, right, invert_cmp(cmp.node), cmp_val, e.span);
130                 }
131             }
132         }
133         if_chain! {
134             if let ExprKind::Binary(op, left, right) = &e.kind;
135             if BinOpKind::Eq == op.node;
136             if let ExprKind::Binary(op1, left1, right1) = &left.kind;
137             if BinOpKind::BitAnd == op1.node;
138             if let ExprKind::Lit(lit) = &right1.kind;
139             if let LitKind::Int(n, _) = lit.node;
140             if let ExprKind::Lit(lit1) = &right.kind;
141             if let LitKind::Int(0, _) = lit1.node;
142             if n.leading_zeros() == n.count_zeros();
143             if n > u128::from(self.verbose_bit_mask_threshold);
144             then {
145                 span_lint_and_then(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 }