Skip to content

Commit ebaae22

Browse files
committed
Fix missing unused_variables lint when using a match guard
Within a binding pattern match guard, only real reads of a bound local impact its liveness analysis - not the fake read that is injected.
1 parent a60d12c commit ebaae22

3 files changed

Lines changed: 31 additions & 3 deletions

File tree

compiler/rustc_mir_transform/src/liveness.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1243,9 +1243,12 @@ struct TransferFunction<'a, 'tcx> {
12431243
impl<'tcx> Visitor<'tcx> for TransferFunction<'_, 'tcx> {
12441244
fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
12451245
match statement.kind {
1246-
// `ForLet(None)` fake read erroneously marks the just-assigned local as live.
1247-
// This defeats the purpose of the analysis for `let` bindings.
1248-
StatementKind::FakeRead(box (FakeReadCause::ForLet(None), _)) => return,
1246+
// `ForLet(None)` and `ForGuardBinding` fake reads erroneously mark the just-assigned
1247+
// locals as live. This defeats the purpose of the analysis for such bindings.
1248+
StatementKind::FakeRead(box (
1249+
FakeReadCause::ForLet(None) | FakeReadCause::ForGuardBinding,
1250+
_,
1251+
)) => return,
12491252
// Handle self-assignment by restricting the read/write they do.
12501253
StatementKind::Assign(box (ref dest, ref rvalue))
12511254
if self.self_assignment.contains(&location) =>
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
//! The mere presence of a match guard should not deem bound variables "used".
2+
//! Regression test for https://github.com/rust-lang/rust/issues/151983
3+
//@ check-pass
4+
#![warn(unused)]
5+
fn main() {
6+
match Some(42) {
7+
Some(unused) if true => (), //~WARN unused variable: `unused`
8+
_ => (),
9+
}
10+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
warning: unused variable: `unused`
2+
--> $DIR/match_with_guard.rs:7:14
3+
|
4+
LL | Some(unused) if true => (),
5+
| ^^^^^^ help: if this is intentional, prefix it with an underscore: `_unused`
6+
|
7+
note: the lint level is defined here
8+
--> $DIR/match_with_guard.rs:4:9
9+
|
10+
LL | #![warn(unused)]
11+
| ^^^^^^
12+
= note: `#[warn(unused_variables)]` implied by `#[warn(unused)]`
13+
14+
warning: 1 warning emitted
15+

0 commit comments

Comments
 (0)