Lint significant drop on while let and if let

This commit is contained in:
Ruihan Li 2024-04-29 12:39:31 +08:00
parent a4bdab38f0
commit 378962f861
4 changed files with 149 additions and 30 deletions

View file

@ -801,4 +801,30 @@ fn should_not_trigger_lint_with_explicit_drop() {
}
}
fn should_trigger_lint_in_if_let() {
let mutex = Mutex::new(vec![1]);
if let Some(val) = mutex.lock().unwrap().first().copied() {
//~^ ERROR: temporary with significant `Drop` in `if let` scrutinee will live until the
//~| NOTE: this might lead to deadlocks or other unexpected behavior
println!("{}", val);
}
// Should not trigger lint without the final `copied()`, because we actually hold a reference
// (i.e., the `val`) to the locked data.
if let Some(val) = mutex.lock().unwrap().first() {
println!("{}", val);
};
}
fn should_trigger_lint_in_while_let() {
let mutex = Mutex::new(vec![1]);
while let Some(val) = mutex.lock().unwrap().pop() {
//~^ ERROR: temporary with significant `Drop` in `while let` scrutinee will live until the
//~| NOTE: this might lead to deadlocks or other unexpected behavior
println!("{}", val);
}
}
fn main() {}

View file

@ -541,5 +541,32 @@ LL ~ let value = mutex.lock().unwrap()[0];
LL ~ for val in [value, 2] {
|
error: aborting due to 27 previous errors
error: temporary with significant `Drop` in `if let` scrutinee will live until the end of the `if let` expression
--> tests/ui/significant_drop_in_scrutinee.rs:807:24
|
LL | if let Some(val) = mutex.lock().unwrap().first().copied() {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
LL | }
| - temporary lives until here
|
= note: this might lead to deadlocks or other unexpected behavior
help: try moving the temporary above the match
|
LL ~ let value = mutex.lock().unwrap().first().copied();
LL ~ if let Some(val) = value {
|
error: temporary with significant `Drop` in `while let` scrutinee will live until the end of the `while let` expression
--> tests/ui/significant_drop_in_scrutinee.rs:823:27
|
LL | while let Some(val) = mutex.lock().unwrap().pop() {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
LL | }
| - temporary lives until here
|
= note: this might lead to deadlocks or other unexpected behavior
error: aborting due to 29 previous errors