Skip to content

Commit 9d057f3

Browse files
committed
gccrs: add unreachable pattern lint
gcc/rust/ChangeLog: * checks/lints/unused/rust-unused-checker.cc (UnusedChecker::visit): New. * checks/lints/unused/rust-unused-checker.h (UnusedChecker::visit): New. gcc/testsuite/ChangeLog: * rust/compile/unreachable-patterns_0.rs: New test. Signed-off-by: Lucas Ly Ba <lucas.ly-ba@outlook.com>
1 parent 206d052 commit 9d057f3

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

gcc/rust/checks/lints/unused/rust-unused-checker.cc

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,29 @@ UnusedChecker::visit (HIR::MatchExpr &expr)
320320
"multiple ranges are one apart");
321321
}
322322

323+
// Every arm after an irrefutable one (a bare wildcard or binding without a
324+
// guard) can never match.
325+
bool seen_irrefutable = false;
326+
for (auto &match_case : expr.get_match_cases ())
327+
{
328+
auto &arm = match_case.get_arm ();
329+
if (seen_irrefutable)
330+
{
331+
rust_warning_at (arm.get_pattern ()->get_locus (),
332+
OPT_Wunused_variable, "unreachable pattern");
333+
continue;
334+
}
335+
336+
auto type = arm.get_pattern ()->get_pattern_type ();
337+
if (!arm.has_match_arm_guard ()
338+
&& (type == HIR::Pattern::PatternType::WILDCARD
339+
|| (type == HIR::Pattern::PatternType::IDENTIFIER
340+
&& !static_cast<HIR::IdentifierPattern &> (
341+
*arm.get_pattern ())
342+
.has_subpattern ())))
343+
seen_irrefutable = true;
344+
}
345+
323346
walk (expr);
324347
}
325348

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// { dg-additional-options "-frust-unused-check-2.0" }
2+
#![feature(no_core)]
3+
#![no_core]
4+
5+
pub fn foo() {
6+
match 1 {
7+
_ => {}
8+
1 => {}
9+
// { dg-warning "unreachable pattern" "" { target *-*-* } .-1 }
10+
}
11+
}

0 commit comments

Comments
 (0)