rust-lang / rust-lang/rust-clippy
`unnecessary_unwrap`: false positive with disjunctive `if`-condition
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
I think I get a false positive when having an if-else where the condition is a disjunction where the tested Option may be None or have some specific value.
Lint Name
unnecessary_unwrap
Reproducer
I tried this code:
fn main() {
let opt: Option<i32> = None;
if opt.is_none() || opt.unwrap().is_positive() {
println!("None or positive")
} else {
foo(opt.unwrap())
}
}
fn foo(x: i32) {
println!("foo: {}", x)
}
I saw this happen:
/home/horn/.cargo/bin/cargo clippy --manifest-path /home/horn/tmp/playground-rs/Cargo.toml
Checking playground-rs v0.1.0 (/home/horn/tmp/playground-rs)
warning: called `unwrap` on `opt` after checking its variant with `is_none`
--> src/main.rs:6:13
|
3 | if opt.is_none() || opt.unwrap().is_positive() {
| ------------- the check is happening here
...
6 | foo(opt.unwrap())
| ^^^^^^^^^^^^
|
= note: `#[warn(clippy::unnecessary_unwrap)]` on by default
= help: try using `if let` or `match`
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_unwrap
warning: `playground-rs` (bin "playground-rs") generated 1 warning
Finished dev [unoptimized + debuginfo] target(s) in 0.04s
Cargo-Process finished at Mon Mar 14 15:56:21
I expected to see this happen:
There should be no warning as there is no good way to rewrite this code using if let or match. Feel free to prove me wrong, though. :-)
Version
rustc 1.59.0 (9d1b2106e 2022-02-23)
binary: rustc
commit-hash: 9d1b2106e23b1abd32fce1f17267604a5102f57a
commit-date: 2022-02-23
host: x86_64-unknown-linux-gnu
release: 1.59.0
LLVM version: 13.0.0
$ cargo clippy --version
clippy 0.1.59 (9d1b210 2022-02-23)
Additional Labels
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the unnecessary_unwrap lint and the Rust reproducer in this issue, then inspect how its disjunctive if condition is analyzed. Confirm the warning behavior with the shown example and add or update coverage so the false positive is no longer reported while valid cases remain checked.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100