Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't flag if_not_else when else block is longer than then block #5654

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions clippy_lints/src/if_not_else.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,12 @@ impl EarlyLintPass for IfNotElse {
if in_external_macro(cx.sess(), item.span) {
return;
}
if let ExprKind::If(ref cond, _, Some(ref els)) = item.kind {
if let ExprKind::Block(..) = els.kind {
if let ExprKind::If(ref cond, ref thn, Some(ref els)) = item.kind {
// Don't suggest rewriting if the result would be top-heavy.
if let ExprKind::Block(ref els_block, ..) = els.kind {
if thn.stmts.len() < els_block.stmts.len() {
Copy link
Member

@flip1995 flip1995 Jun 11, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because we already talked about cost-benefit:

The cost for this configuration option would be way higher, since this:

if !a {
    println!("xyz");
} else {
    let _ = if {
        // ...100 lines
    };
}

would still lint with this implementation. So we would need to implement a line counter. Or something that calculates complexity. But detecting complexity is a different story. Long story short: we can't do this (yet?, probably?, ...? #3793 (comment))

So what @sanmai-NL said, the cost for a working implementation for this would be too high for the benefit that it would give for a pedantic lint IMO.

return;
}
match cond.kind {
ExprKind::Unary(UnOp::Not, _) => {
span_lint_and_help(
Expand Down
17 changes: 17 additions & 0 deletions tests/ui/if_not_else.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,21 @@ fn main() {
} else {
println!("Bunny");
}

// These won't get flagged because the body of the `else` block is
// longer than the body of the then-block.
if !bla() {
println!("Bugs");
} else {
println!("Bunny");
println!("Daffy");
println!("Duck");
}
if 4 != 5 {
println!("Bugs");
} else {
println!("Bunny");
println!("Daffy");
println!("Duck");
}
}