rust/clippy_lints/src/bit_mask.rs

336 lines
12 KiB
Rust
Raw Normal View History

2021-05-27 08:49:37 -05:00
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::{span_lint, span_lint_and_then};
2021-03-16 11:06:34 -05:00
use clippy_utils::sugg::Sugg;
2018-11-27 14:14:15 -06:00
use if_chain::if_chain;
2020-02-29 21:23:33 -06:00
use rustc_ast::ast::LitKind;
use rustc_errors::Applicability;
2020-02-21 02:39:38 -06:00
use rustc_hir::{BinOpKind, Expr, ExprKind};
2020-01-12 00:08:41 -06:00
use rustc_lint::{LateContext, LateLintPass};
2020-01-11 05:37:08 -06:00
use rustc_session::{declare_tool_lint, impl_lint_pass};
use rustc_span::source_map::Span;
2018-03-28 08:24:26 -05:00
declare_clippy_lint! {
/// ### What it does
/// Checks for incompatible bit masks in comparisons.
///
/// The formula for detecting if an expression of the type `_ <bit_op> m
/// <cmp_op> c` (where `<bit_op>` is one of {`&`, `|`} and `<cmp_op>` is one of
/// {`!=`, `>=`, `>`, `!=`, `>=`, `>`}) can be determined from the following
/// table:
///
2022-01-13 14:20:30 -06:00
/// |Comparison |Bit Op|Example |is always|Formula |
/// |------------|------|-------------|---------|----------------------|
/// |`==` or `!=`| `&` |`x & 2 == 3` |`false` |`c & m != c` |
/// |`<` or `>=`| `&` |`x & 2 < 3` |`true` |`m < c` |
/// |`>` or `<=`| `&` |`x & 1 > 1` |`false` |`m <= c` |
/// |`==` or `!=`| `\|` |`x \| 1 == 0`|`false` |`c \| m != c` |
/// |`<` or `>=`| `\|` |`x \| 1 < 1` |`false` |`m >= c` |
/// |`<=` or `>` | `\|` |`x \| 1 > 0` |`true` |`m > c` |
///
/// ### Why is this bad?
/// If the bits that the comparison cares about are always
/// set to zero or one by the bit mask, the comparison is constant `true` or
/// `false` (depending on mask, compared value, and operators).
///
/// So the code is actively misleading, and the only reason someone would write
/// this intentionally is to win an underhanded Rust contest or create a
/// test-case for this lint.
///
/// ### Example
/// ```rust
/// # let x = 1;
/// if (x & 1 == 2) { }
/// ```
Added `clippy::version` attribute to all normal lints So, some context for this, well, more a story. I'm not used to scripting, I've never really scripted anything, even if it's a valuable skill. I just never really needed it. Now, `@flip1995` correctly suggested using a script for this in `rust-clippy#7813`... And I decided to write a script using nushell because why not? This was a mistake... I spend way more time on this than I would like to admit. It has definitely been more than 4 hours. It shouldn't take that long, but me being new to scripting and nushell just wasn't a good mixture... Anyway, here is the script that creates another script which adds the versions. Fun... Just execute this on the `gh-pages` branch and the resulting `replacer.sh` in `clippy_lints` and it should all work. ```nu mv v0.0.212 rust-1.00.0; mv beta rust-1.57.0; mv master rust-1.58.0; let paths = (open ./rust-1.58.0/lints.json | select id id_span | flatten | select id path); let versions = ( ls | where name =~ "rust-" | select name | format {name}/lints.json | each { open $it | select id | insert version $it | str substring "5,11" version} | group-by id | rotate counter-clockwise id version | update version {get version | first 1} | flatten | select id version); $paths | each { |row| let version = ($versions | where id == ($row.id) | format {version}) let idu = ($row.id | str upcase) $"sed -i '0,/($idu),/{s/pub ($idu),/#[clippy::version = "($version)"]\n pub ($idu),/}' ($row.path)" } | str collect ";" | str find-replace --all '1.00.0' 'pre 1.29.0' | save "replacer.sh"; ``` And this still has some problems, but at this point I just want to be done -.-
2021-10-21 14:06:26 -05:00
#[clippy::version = "pre 1.29.0"]
pub BAD_BIT_MASK,
2018-03-28 08:24:26 -05:00
correctness,
"expressions of the form `_ & mask == select` that will only ever return `true` or `false`"
}
2018-03-28 08:24:26 -05:00
declare_clippy_lint! {
/// ### What it does
/// Checks for bit masks in comparisons which can be removed
/// without changing the outcome. The basic structure can be seen in the
/// following table:
///
2022-01-13 14:20:30 -06:00
/// |Comparison| Bit Op |Example |equals |
/// |----------|----------|------------|-------|
/// |`>` / `<=`|`\|` / `^`|`x \| 2 > 3`|`x > 3`|
/// |`<` / `>=`|`\|` / `^`|`x ^ 1 < 4` |`x < 4`|
///
/// ### Why is this bad?
/// Not equally evil as [`bad_bit_mask`](#bad_bit_mask),
/// but still a bit misleading, because the bit mask is ineffective.
///
/// ### Known problems
/// False negatives: This lint will only match instances
/// where we have figured out the math (which is for a power-of-two compared
/// value). This means things like `x | 1 >= 7` (which would be better written
/// as `x >= 6`) will not be reported (but bit masks like this are fairly
/// uncommon).
///
/// ### Example
/// ```rust
/// # let x = 1;
/// if (x | 1 > 3) { }
/// ```
Added `clippy::version` attribute to all normal lints So, some context for this, well, more a story. I'm not used to scripting, I've never really scripted anything, even if it's a valuable skill. I just never really needed it. Now, `@flip1995` correctly suggested using a script for this in `rust-clippy#7813`... And I decided to write a script using nushell because why not? This was a mistake... I spend way more time on this than I would like to admit. It has definitely been more than 4 hours. It shouldn't take that long, but me being new to scripting and nushell just wasn't a good mixture... Anyway, here is the script that creates another script which adds the versions. Fun... Just execute this on the `gh-pages` branch and the resulting `replacer.sh` in `clippy_lints` and it should all work. ```nu mv v0.0.212 rust-1.00.0; mv beta rust-1.57.0; mv master rust-1.58.0; let paths = (open ./rust-1.58.0/lints.json | select id id_span | flatten | select id path); let versions = ( ls | where name =~ "rust-" | select name | format {name}/lints.json | each { open $it | select id | insert version $it | str substring "5,11" version} | group-by id | rotate counter-clockwise id version | update version {get version | first 1} | flatten | select id version); $paths | each { |row| let version = ($versions | where id == ($row.id) | format {version}) let idu = ($row.id | str upcase) $"sed -i '0,/($idu),/{s/pub ($idu),/#[clippy::version = "($version)"]\n pub ($idu),/}' ($row.path)" } | str collect ";" | str find-replace --all '1.00.0' 'pre 1.29.0' | save "replacer.sh"; ``` And this still has some problems, but at this point I just want to be done -.-
2021-10-21 14:06:26 -05:00
#[clippy::version = "pre 1.29.0"]
pub INEFFECTIVE_BIT_MASK,
2018-03-28 08:24:26 -05:00
correctness,
2019-01-30 19:15:29 -06:00
"expressions where a bit mask will be rendered useless by a comparison, e.g., `(x | 1) > 2`"
2015-05-15 07:09:29 -05:00
}
2018-03-28 08:24:26 -05:00
declare_clippy_lint! {
/// ### What it does
/// Checks for bit masks that can be replaced by a call
/// to `trailing_zeros`
///
/// ### Why is this bad?
/// `x.trailing_zeros() > 4` is much clearer than `x & 15
/// == 0`
///
/// ### Known problems
/// llvm generates better code for `x & 15 == 0` on x86
///
/// ### Example
/// ```rust
/// # let x = 1;
/// if x & 0b1111 == 0 { }
/// ```
Added `clippy::version` attribute to all normal lints So, some context for this, well, more a story. I'm not used to scripting, I've never really scripted anything, even if it's a valuable skill. I just never really needed it. Now, `@flip1995` correctly suggested using a script for this in `rust-clippy#7813`... And I decided to write a script using nushell because why not? This was a mistake... I spend way more time on this than I would like to admit. It has definitely been more than 4 hours. It shouldn't take that long, but me being new to scripting and nushell just wasn't a good mixture... Anyway, here is the script that creates another script which adds the versions. Fun... Just execute this on the `gh-pages` branch and the resulting `replacer.sh` in `clippy_lints` and it should all work. ```nu mv v0.0.212 rust-1.00.0; mv beta rust-1.57.0; mv master rust-1.58.0; let paths = (open ./rust-1.58.0/lints.json | select id id_span | flatten | select id path); let versions = ( ls | where name =~ "rust-" | select name | format {name}/lints.json | each { open $it | select id | insert version $it | str substring "5,11" version} | group-by id | rotate counter-clockwise id version | update version {get version | first 1} | flatten | select id version); $paths | each { |row| let version = ($versions | where id == ($row.id) | format {version}) let idu = ($row.id | str upcase) $"sed -i '0,/($idu),/{s/pub ($idu),/#[clippy::version = "($version)"]\n pub ($idu),/}' ($row.path)" } | str collect ";" | str find-replace --all '1.00.0' 'pre 1.29.0' | save "replacer.sh"; ``` And this still has some problems, but at this point I just want to be done -.-
2021-10-21 14:06:26 -05:00
#[clippy::version = "pre 1.29.0"]
pub VERBOSE_BIT_MASK,
pedantic,
"expressions where a bit mask is less readable than the corresponding method call"
}
2017-08-09 02:30:56 -05:00
#[derive(Copy, Clone)]
pub struct BitMask {
verbose_bit_mask_threshold: u64,
}
impl BitMask {
#[must_use]
pub fn new(verbose_bit_mask_threshold: u64) -> Self {
Self {
verbose_bit_mask_threshold,
}
}
}
2019-04-08 15:43:55 -05:00
impl_lint_pass!(BitMask => [BAD_BIT_MASK, INEFFECTIVE_BIT_MASK, VERBOSE_BIT_MASK]);
impl<'tcx> LateLintPass<'tcx> for BitMask {
fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
2019-09-27 10:16:06 -05:00
if let ExprKind::Binary(cmp, left, right) = &e.kind {
if cmp.node.is_comparison() {
2016-06-05 18:16:16 -05:00
if let Some(cmp_opt) = fetch_int_literal(cx, right) {
check_compare(cx, left, cmp.node, cmp_opt, e.span);
2016-06-05 18:16:16 -05:00
} else if let Some(cmp_val) = fetch_int_literal(cx, left) {
check_compare(cx, right, invert_cmp(cmp.node), cmp_val, e.span);
2016-06-05 18:16:16 -05:00
}
}
}
if_chain! {
2019-09-27 10:16:06 -05:00
if let ExprKind::Binary(op, left, right) = &e.kind;
2018-07-12 02:50:09 -05:00
if BinOpKind::Eq == op.node;
2019-09-27 10:16:06 -05:00
if let ExprKind::Binary(op1, left1, right1) = &left.kind;
2018-07-12 02:50:09 -05:00
if BinOpKind::BitAnd == op1.node;
2019-09-27 10:16:06 -05:00
if let ExprKind::Lit(lit) = &right1.kind;
if let LitKind::Int(n, _) = lit.node;
2019-09-27 10:16:06 -05:00
if let ExprKind::Lit(lit1) = &right.kind;
if let LitKind::Int(0, _) = lit1.node;
if n.leading_zeros() == n.count_zeros();
if n > u128::from(self.verbose_bit_mask_threshold);
then {
span_lint_and_then(cx,
VERBOSE_BIT_MASK,
e.span,
"bit mask could be simplified with a call to `trailing_zeros`",
|diag| {
let sugg = Sugg::hir(cx, left1, "...").maybe_par();
diag.span_suggestion(
e.span,
"try",
format!("{}.trailing_zeros() >= {}", sugg, n.count_ones()),
Applicability::MaybeIncorrect,
2018-09-18 10:07:54 -05:00
);
});
}
}
}
}
#[must_use]
2018-07-12 02:50:09 -05:00
fn invert_cmp(cmp: BinOpKind) -> BinOpKind {
match cmp {
2018-07-12 02:50:09 -05:00
BinOpKind::Eq => BinOpKind::Eq,
BinOpKind::Ne => BinOpKind::Ne,
BinOpKind::Lt => BinOpKind::Gt,
BinOpKind::Gt => BinOpKind::Lt,
BinOpKind::Le => BinOpKind::Ge,
BinOpKind::Ge => BinOpKind::Le,
_ => BinOpKind::Or, // Dummy
}
}
fn check_compare(cx: &LateContext<'_>, bit_op: &Expr<'_>, cmp_op: BinOpKind, cmp_value: u128, span: Span) {
2019-09-27 10:16:06 -05:00
if let ExprKind::Binary(op, left, right) = &bit_op.kind {
2018-07-12 02:50:09 -05:00
if op.node != BinOpKind::BitAnd && op.node != BinOpKind::BitOr {
2015-09-18 22:02:56 -05:00
return;
}
2016-01-03 22:26:12 -06:00
fetch_int_literal(cx, right)
.or_else(|| fetch_int_literal(cx, left))
.map_or((), |mask| check_bit_mask(cx, op.node, cmp_op, mask, cmp_value, span));
}
}
2019-01-13 09:19:02 -06:00
#[allow(clippy::too_many_lines)]
2018-11-27 14:14:15 -06:00
fn check_bit_mask(
cx: &LateContext<'_>,
2018-11-27 14:14:15 -06:00
bit_op: BinOpKind,
cmp_op: BinOpKind,
mask_value: u128,
cmp_value: u128,
span: Span,
) {
match cmp_op {
2018-07-12 02:50:09 -05:00
BinOpKind::Eq | BinOpKind::Ne => match bit_op {
2018-11-27 14:14:15 -06:00
BinOpKind::BitAnd => {
if mask_value & cmp_value != cmp_value {
if cmp_value != 0 {
span_lint(
cx,
BAD_BIT_MASK,
span,
&format!(
"incompatible bit mask: `_ & {}` can never be equal to `{}`",
mask_value, cmp_value
),
);
}
} else if mask_value == 0 {
span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
}
},
BinOpKind::BitOr => {
if mask_value | cmp_value != cmp_value {
2017-09-05 04:33:04 -05:00
span_lint(
cx,
BAD_BIT_MASK,
span,
2017-09-05 04:33:04 -05:00
&format!(
2018-11-27 14:14:15 -06:00
"incompatible bit mask: `_ | {}` can never be equal to `{}`",
mask_value, cmp_value
2017-09-05 04:33:04 -05:00
),
);
}
},
_ => (),
2016-12-20 11:21:30 -06:00
},
2018-07-12 02:50:09 -05:00
BinOpKind::Lt | BinOpKind::Ge => match bit_op {
2018-11-27 14:14:15 -06:00
BinOpKind::BitAnd => {
if mask_value < cmp_value {
span_lint(
cx,
BAD_BIT_MASK,
span,
&format!(
"incompatible bit mask: `_ & {}` will always be lower than `{}`",
mask_value, cmp_value
),
);
} else if mask_value == 0 {
span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
}
2017-09-05 04:33:04 -05:00
},
2018-11-27 14:14:15 -06:00
BinOpKind::BitOr => {
if mask_value >= cmp_value {
span_lint(
cx,
BAD_BIT_MASK,
span,
&format!(
"incompatible bit mask: `_ | {}` will never be lower than `{}`",
mask_value, cmp_value
),
);
} else {
check_ineffective_lt(cx, span, mask_value, cmp_value, "|");
}
2017-09-05 04:33:04 -05:00
},
2018-07-12 02:50:09 -05:00
BinOpKind::BitXor => check_ineffective_lt(cx, span, mask_value, cmp_value, "^"),
2017-09-05 04:33:04 -05:00
_ => (),
2016-12-20 11:21:30 -06:00
},
2018-07-12 02:50:09 -05:00
BinOpKind::Le | BinOpKind::Gt => match bit_op {
2018-11-27 14:14:15 -06:00
BinOpKind::BitAnd => {
if mask_value <= cmp_value {
span_lint(
cx,
BAD_BIT_MASK,
span,
&format!(
"incompatible bit mask: `_ & {}` will never be higher than `{}`",
mask_value, cmp_value
),
);
} else if mask_value == 0 {
span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero");
}
2017-09-05 04:33:04 -05:00
},
2018-11-27 14:14:15 -06:00
BinOpKind::BitOr => {
if mask_value > cmp_value {
span_lint(
cx,
BAD_BIT_MASK,
span,
&format!(
"incompatible bit mask: `_ | {}` will always be higher than `{}`",
mask_value, cmp_value
),
);
} else {
check_ineffective_gt(cx, span, mask_value, cmp_value, "|");
}
2017-09-05 04:33:04 -05:00
},
2018-07-12 02:50:09 -05:00
BinOpKind::BitXor => check_ineffective_gt(cx, span, mask_value, cmp_value, "^"),
2017-09-05 04:33:04 -05:00
_ => (),
2016-12-20 11:21:30 -06:00
},
2016-01-03 22:26:12 -06:00
_ => (),
}
}
fn check_ineffective_lt(cx: &LateContext<'_>, span: Span, m: u128, c: u128, op: &str) {
2015-08-19 02:07:50 -05:00
if c.is_power_of_two() && m < c {
2017-08-09 02:30:56 -05:00
span_lint(
cx,
INEFFECTIVE_BIT_MASK,
span,
&format!(
"ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
2018-11-27 14:14:15 -06:00
op, m, c
2017-08-09 02:30:56 -05:00
),
);
2015-08-19 02:07:50 -05:00
}
}
fn check_ineffective_gt(cx: &LateContext<'_>, span: Span, m: u128, c: u128, op: &str) {
2015-08-19 02:07:50 -05:00
if (c + 1).is_power_of_two() && m <= c {
2017-08-09 02:30:56 -05:00
span_lint(
cx,
INEFFECTIVE_BIT_MASK,
span,
&format!(
"ineffective bit mask: `x {} {}` compared to `{}`, is the same as x compared directly",
2018-11-27 14:14:15 -06:00
op, m, c
2017-08-09 02:30:56 -05:00
),
);
2015-08-19 02:07:50 -05:00
}
}
fn fetch_int_literal(cx: &LateContext<'_>, lit: &Expr<'_>) -> Option<u128> {
2020-07-17 03:47:04 -05:00
match constant(cx, cx.typeck_results(), lit)?.0 {
2018-03-13 05:38:11 -05:00
Constant::Int(n) => Some(n),
2016-01-03 22:26:12 -06:00
_ => None,
}
}