Skip to content

Commit 92fa381

Browse files
authored
Warn if a switch case is unreachable because prior cases cover it. (#2811)
* Warn if a switch case is unreachable because prior cases cover it. The exhaustiveness algorithm defines when a case is unreachable, but the proposal didn't actually do anything with that information. This closes that gap. * Clarify that warning isn't spec'd.
1 parent b3836fc commit 92fa381

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

accepted/future-releases/0546-patterns/feature-specification.md

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2426,6 +2426,8 @@ patterns is complex, so the proposal to define how it works is in a [separate
24262426
document][exhaustiveness]. That tells us if the cases in a switch statement or
24272427
expression are exhaustive or not.
24282428

2429+
[exhaustiveness]: https://github.com/dart-lang/language/blob/master/accepted/future-releases/0546-patterns/exhaustiveness.md
2430+
24292431
We don't want to require *all* switches to be exhaustive. The language currently
24302432
does not require switch statements on, say, strings to be exhaustive, and
24312433
requiring that would likely lead to many pointless empty default cases for
@@ -2458,7 +2460,17 @@ All other types are not always-exhaustive. Then:
24582460
other option is to throw an error and most Dart users prefer to catch those
24592461
kinds of mistakes at compile time.*
24602462

2461-
[exhaustiveness]: https://github.com/dart-lang/language/blob/master/accepted/future-releases/0546-patterns/exhaustiveness.md
2463+
* The language doesn't specify or mandate this, but implementations are
2464+
encouraged to report a warning if a case in a switch statement, collection
2465+
element, or expression is unreachable because all values it can match are
2466+
also matched by preceding cases.
2467+
2468+
*We make this a warning and not an error because it's harmless dead code.
2469+
Also, in some cases the exhaustiveness analysis may not be very precise and
2470+
may require users to write a default case when it can't prove that the cases
2471+
cover all values. If we later make the exhaustiveness algorithm smarter,
2472+
that default case may become unreachable. If that happens, we don't want
2473+
this to be a breaking change.*
24622474

24632475
**Breaking change:** Currently, a non-exhaustive switch on an enum type is only
24642476
a warning. This promotes it to an error. Also, switches on `bool` do not
@@ -3429,6 +3441,8 @@ Here is one way it could be broken down into separate pieces:
34293441
- In list patterns, don't call `v[e]` if the corresponding subpattern is a
34303442
wildcard (#2671).
34313443
3444+
- Warn if a case is unreachable.
3445+
34323446
### 2.21
34333447
34343448
- Allow object pattern fields to tear off methods (#2561).

0 commit comments

Comments
 (0)