Skip to content

Commit a06ab12

Browse files
committed
Refine switch warning
The test code counted the number of different types in all patterns, but it needs to account for alternative patterns as well.
1 parent ba41139 commit a06ab12

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -969,11 +969,15 @@ object PatternMatcher {
969969
case Block(_, Match(_, cases)) => cases
970970
case _ => Nil
971971
}
972-
def numConsts(cdefs: List[CaseDef]): Int = {
973-
val tpes = cdefs.map(_.pat.tpe)
974-
tpes.toSet.size
972+
def numTypes(cdefs: List[CaseDef]): Int = {
973+
def patTypes(pat: Tree): List[Type] = pat match {
974+
case Alternative(pats) => pats.flatMap(patTypes)
975+
case _ => pat.tpe :: Nil
976+
}
977+
val tpes = cdefs.flatMap(patTypes)
978+
tpes.toSet.size: Int // without the type ascription, testPickling fails because of #2840.
975979
}
976-
if (numConsts(resultCases) < numConsts(original.cases))
980+
if (numTypes(resultCases) < numTypes(original.cases))
977981
ctx.warning(UnableToEmitSwitch(), original.pos)
978982
case _ =>
979983
}

tests/neg-custom-args/i3561.scala

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Test {
2+
val Constant = 'Q' // OK if final
3+
def tokenMe(ch: Char) = (ch: @annotation.switch) match { // error: could not emit switch
4+
case ' ' => 1
5+
case 'A' => 2
6+
case '5' | Constant => 3
7+
case '4' => 4
8+
}
9+
10+
def test2(x: Any) = (x: @annotation.switch) match { // error: could not emit switch
11+
case ' ' => 1
12+
case 'A' => 2
13+
case '5' | Constant => 3
14+
case '4' => 4
15+
}
16+
}

0 commit comments

Comments
 (0)