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;
12 declare_clippy_lint! {
14 /// Checks for incompatible bit masks in comparisons.
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
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` |
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).
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.
42 /// if (x & 1 == 2) { }
44 #[clippy::version = "pre 1.29.0"]
47 "expressions of the form `_ & mask == select` that will only ever return `true` or `false`"
50 declare_clippy_lint! {
52 /// Checks for bit masks in comparisons which can be removed
53 /// without changing the outcome. The basic structure can be seen in the
56 /// |Comparison| Bit Op |Example |equals |
57 /// |----------|---------|-----------|-------|
58 /// |`>` / `<=`|`|` / `^`|`x | 2 > 3`|`x > 3`|
59 /// |`<` / `>=`|`|` / `^`|`x ^ 1 < 4`|`x < 4`|
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.
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
75 /// if (x | 1 > 3) { }
77 #[clippy::version = "pre 1.29.0"]
78 pub INEFFECTIVE_BIT_MASK,
80 "expressions where a bit mask will be rendered useless by a comparison, e.g., `(x | 1) > 2`"
83 declare_clippy_lint! {
85 /// Checks for bit masks that can be replaced by a call
86 /// to `trailing_zeros`
88 /// ### Why is this bad?
89 /// `x.trailing_zeros() > 4` is much clearer than `x & 15
92 /// ### Known problems
93 /// llvm generates better code for `x & 15 == 0` on x86
98 /// if x & 0b1111 == 0 { }
100 #[clippy::version = "pre 1.29.0"]
101 pub VERBOSE_BIT_MASK,
103 "expressions where a bit mask is less readable than the corresponding method call"
106 #[derive(Copy, Clone)]
108 verbose_bit_mask_threshold: u64,
113 pub fn new(verbose_bit_mask_threshold: u64) -> Self {
115 verbose_bit_mask_threshold,
120 impl_lint_pass!(BitMask => [BAD_BIT_MASK, INEFFECTIVE_BIT_MASK, VERBOSE_BIT_MASK]);
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);
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);
145 span_lint_and_then(cx,
148 "bit mask could be simplified with a call to `trailing_zeros`",
150 let sugg = Sugg::hir(cx, left1, "...").maybe_par();
151 diag.span_suggestion(
154 format!("{}.trailing_zeros() >= {}", sugg, n.count_ones()),
155 Applicability::MaybeIncorrect,
164 fn invert_cmp(cmp: BinOpKind) -> BinOpKind {
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
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 {
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));
187 #[allow(clippy::too_many_lines)]
189 cx: &LateContext<'_>,
197 BinOpKind::Eq | BinOpKind::Ne => match bit_op {
198 BinOpKind::BitAnd => {
199 if mask_value & cmp_value != cmp_value {
206 "incompatible bit mask: `_ & {}` can never be equal to `{}`",
207 mask_value, cmp_value
211 } else if mask_value == 0 {
212 span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
215 BinOpKind::BitOr => {
216 if mask_value | cmp_value != cmp_value {
222 "incompatible bit mask: `_ | {}` can never be equal to `{}`",
223 mask_value, cmp_value
230 BinOpKind::Lt | BinOpKind::Ge => match bit_op {
231 BinOpKind::BitAnd => {
232 if mask_value < cmp_value {
238 "incompatible bit mask: `_ & {}` will always be lower than `{}`",
239 mask_value, cmp_value
242 } else if mask_value == 0 {
243 span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
246 BinOpKind::BitOr => {
247 if mask_value >= cmp_value {
253 "incompatible bit mask: `_ | {}` will never be lower than `{}`",
254 mask_value, cmp_value
258 check_ineffective_lt(cx, span, mask_value, cmp_value, "|");
261 BinOpKind::BitXor => check_ineffective_lt(cx, span, mask_value, cmp_value, "^"),
264 BinOpKind::Le | BinOpKind::Gt => match bit_op {
265 BinOpKind::BitAnd => {
266 if mask_value <= cmp_value {
272 "incompatible bit mask: `_ & {}` will never be higher than `{}`",
273 mask_value, cmp_value
276 } else if mask_value == 0 {
277 span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
280 BinOpKind::BitOr => {
281 if mask_value > cmp_value {
287 "incompatible bit mask: `_ | {}` will always be higher than `{}`",
288 mask_value, cmp_value
292 check_ineffective_gt(cx, span, mask_value, cmp_value, "|");
295 BinOpKind::BitXor => check_ineffective_gt(cx, span, mask_value, cmp_value, "^"),
302 fn check_ineffective_lt(cx: &LateContext<'_>, span: Span, m: u128, c: u128, op: &str) {
303 if c.is_power_of_two() && m < c {
306 INEFFECTIVE_BIT_MASK,
309 "ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
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 {
320 INEFFECTIVE_BIT_MASK,
323 "ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
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),