rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
11.52k stars 1.55k forks source link

Remove unnecessary `if` statement when results can be determined at compile time #11378

Open poopsicles opened 1 year ago

poopsicles commented 1 year ago

What it does

If an if else expression only contains static types, such as i8s and u32s, not variables, then it's likely that one branch can be totally removed without the "correctness" of the code changing.

A Reddit thread (Archive.org link) demonstrated this by putting an if else inside another if, which was evaluated correctly.

I'm not exactly sure whether this lint should capture:

Advantage

Drawbacks

Someone might intend to later "fill out" the other branches, which is why this is limiting it to if-else expressions in another if statement, as opposed to freestanding if statements might make more sense, the former is usually an unintended, while the latter could be intended to be added to.

Example

let a = 13;
if if a == 13 { 10 } else { 0 } > 5 { // <- nested if-else
    println!("This will be printed");
}

Could be written as this (if we're just looking for nested ones):

let a = 13;
if 10 > 5 { // <- inner if-else removed, however the outer if-statement, which *could* be removed, isn't
    println!("This will be printed");
}

Or

let a = 13;
println!("This will be printed"); // <- if removed, but most likely more "annoying"
poopsicles commented 1 year ago

Another example would be

if 1 > 0 {
    println!("hi");
}

This example just deals with static ints, and not any variables since that might require the compiler probably?

poopsicles commented 1 year ago

Perhaps simply lifting the inner if-else is more achieveable?

Going from:

let a = 13;
if if a == 13 { 10 } else { 0 } > 5 { // <- nested if-else
    println!("This will be printed");
}

To:

let a = 13;
let thing = if a == 13 { 10 } else { 0 };

if thing > 5 {
    println!("This will be printed");
}