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.46k stars 1.54k forks source link

False positive with `expect(clippy::collapsible_else_if)` inside the `else` block #13365

Open schuetzm opened 2 months ago

schuetzm commented 2 months ago

Summary

expect(clippy::collapsible_else_if) falsely reports "this lint expectation is unfulfilled" when used inside the else block:

Lint Name

clippy::collapsible_else_if

Reproducer

fn main() {
    // Correctly detected as collapsible:
    if true {
    } else {
        if false {}
    }

    // Allowing the lint silences it both inside the `else` block:
    if true {
    } else {
        #[allow(clippy::collapsible_else_if)]
        if false {}
    }

    // ... and before the entire `if`:
    #[allow(clippy::collapsible_else_if)]
    if true {
    } else {
        if false {}
    }

    // Using `expect` inside the `else` block says "this lint expectation is unfulfilled":
    if true {
    } else {
        #[expect(clippy::collapsible_else_if)]
        if false {}
    }

    // This works correctly, however:
    #[expect(clippy::collapsible_else_if)]
    if true {
    } else {
        if false {}
    }
}

Version

rustc 1.81.0 (eeb90cda1 2024-09-04)
binary: rustc
commit-hash: eeb90cda1969383f56a2637cbd3037bdf598841c
commit-date: 2024-09-04
host: x86_64-unknown-linux-gnu
release: 1.81.0
LLVM version: 18.1.7

Additional Labels

No response

Jarcho commented 2 months ago

This will require the same workaround as needless_return. The lint doesn't fire if the inner if has an attribute on it which the causes the lint expectation to be unfulfilled.