Skip to content

clippy --fix removes necessary parens when changing 'len > 0' to '!.is_empty()' #10529

Closed
@ingomancer

Description

@ingomancer

I have the following minimized example:

fn main() {
    let a = [1, 2, 3];
    (a.len() > 0).then(|| println!("Hello, world!"));
}

running cargo clippy on this produces the following warning:

warning: length comparison to zero
 --> src/main.rs:3:5
  |
3 |     (a.len() > 0).then(|| println!("Hello, world!"));
  |     ^^^^^^^^^^^^^ help: using `!is_empty` is clearer and more explicit: `!a.is_empty()`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#len_zero
  = note: `#[warn(clippy::len_zero)]` on by default

which makes sense to me.

I expected to see this happen: running 'cargo clippy --fix' changes the condition to the one suggested

Instead, this happened:

cargo clippy --fix
    Checking minimal_example v0.1.0 (/home/ingo/minimal_example)
warning: failed to automatically apply fixes suggested by rustc to crate `minimal_example`

after fixes were automatically applied the compiler reported errors within these files:

  * src/main.rs

This likely indicates a bug in either rustc or cargo itself,
and we would appreciate a bug report! You're likely to see
a number of compiler warnings after this message which cargo
attempted to fix but failed. If you could open an issue at
https://github.com/rust-lang/rust/issues
quoting the full output of this command we'd be very appreciative!
Note that you may be able to make some more progress in the near-term
fixing code with the `--broken-code` flag

The following errors were reported:
error[E0600]: cannot apply unary operator `!` to type `std::option::Option<()>`
 --> src/main.rs:3:5
  |
3 |     !a.is_empty().then(|| println!("Hello, world!"));
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot apply unary operator `!`

error: aborting due to previous error

Reinserting parens around the condition makes it compile.

fn main() {
    let a = [1, 2, 3];
    (!a.is_empty()).then(|| println!("Hello, world!"));
}

Meta

rustc --version --verbose:

rustc 1.68.0 (2c8cc3432 2023-03-06)
binary: rustc
commit-hash: 2c8cc343237b8f7d5a3c3703e3a87f2eb2c54a74
commit-date: 2023-03-06
host: x86_64-unknown-linux-gnu
release: 1.68.0
LLVM version: 15.0.6

I get the same result on nightly, which is currently:
'rustc +nightly --version --verbose':

rustc 1.70.0-nightly (44f518058 2023-03-20)
binary: rustc
commit-hash: 44f5180584404d18058cbbf224c55255db4fdcbb
commit-date: 2023-03-20
host: x86_64-unknown-linux-gnu
release: 1.70.0-nightly
LLVM version: 15.0.7

Regards,
ingo

Backtrace

Metadata

Metadata

Assignees

Labels

C-bugCategory: Clippy is not doing the correct thing

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions