rust-clippy/tests/ui/needless_bool/fixable.fixed
Andre Bogus 4a39707795 Parenthesize blocks in needless_bool suggestion
Because the `if .. {}` statement already puts the condition in
expression scope, contained blocks would be parsed as complete
statements, so any `&` binary expression whose left operand ended in a
block would lead to a non-compiling suggestion.

This adds a visitor to identify such expressions and add parentheses.

This fixes #8052.
2021-12-06 13:15:31 +01:00

117 lines
2.2 KiB
Rust

// run-rustfix
#![warn(clippy::needless_bool)]
#![allow(
unused,
dead_code,
clippy::no_effect,
clippy::if_same_then_else,
clippy::equatable_if_let,
clippy::needless_return,
clippy::self_named_constructors
)]
use std::cell::Cell;
macro_rules! bool_comparison_trigger {
($($i:ident: $def:expr, $stb:expr );+ $(;)*) => (
#[derive(Clone)]
pub struct Trigger {
$($i: (Cell<bool>, bool, bool)),+
}
#[allow(dead_code)]
impl Trigger {
pub fn trigger(&self, key: &str) -> bool {
$(
if let stringify!($i) = key {
return self.$i.1 && self.$i.2 == $def;
}
)+
false
}
}
)
}
fn main() {
let x = true;
let y = false;
x;
!x;
!(x && y);
if x {
x
} else {
false
}; // would also be questionable, but we don't catch this yet
bool_ret3(x);
bool_ret4(x);
bool_ret5(x, x);
bool_ret6(x, x);
needless_bool(x);
needless_bool2(x);
needless_bool3(x);
needless_bool_condition();
}
fn bool_ret3(x: bool) -> bool {
return x;
}
fn bool_ret4(x: bool) -> bool {
return !x;
}
fn bool_ret5(x: bool, y: bool) -> bool {
return x && y;
}
fn bool_ret6(x: bool, y: bool) -> bool {
return !(x && y);
}
fn needless_bool(x: bool) {
if x {};
}
fn needless_bool2(x: bool) {
if !x {};
}
fn needless_bool3(x: bool) {
bool_comparison_trigger! {
test_one: false, false;
test_three: false, false;
test_two: true, true;
}
if x {};
if !x {};
}
fn needless_bool_in_the_suggestion_wraps_the_predicate_of_if_else_statement_in_brackets() {
let b = false;
let returns_bool = || false;
let x = if b {
true
} else { !returns_bool() };
}
unsafe fn no(v: u8) -> u8 {
v
}
#[allow(clippy::unnecessary_operation)]
fn needless_bool_condition() -> bool {
(unsafe { no(4) } & 1 != 0);
let _brackets_unneeded = unsafe { no(4) } & 1 != 0;
fn foo() -> bool {
// parentheses are needed here
(unsafe { no(4) } & 1 != 0)
}
foo()
}