Skip to content

Fix #5402: Avoid duplicate labels in switches #5663

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala
Original file line number Diff line number Diff line change
Expand Up @@ -711,9 +711,14 @@ object PatternMatcher {
(tpe isRef defn.ShortClass) ||
(tpe isRef defn.CharClass)

def isIntConst(tree: Tree) = tree match {
case Literal(const) => const.isIntRange
case _ => false
val seen = mutable.Set[Int]()

def isNewIntConst(tree: Tree) = tree match {
case Literal(const) if const.isIntRange && !seen.contains(const.intValue) =>
seen += const.intValue
true
case _ =>
false
}

// An extractor to recover the shape of plans that can become alternatives
Expand All @@ -725,7 +730,7 @@ object PatternMatcher {
val alts = List.newBuilder[Tree]
def rec(innerPlan: Plan): Boolean = innerPlan match {
case SeqPlan(TestPlan(EqualTest(tree), scrut, _, ReturnPlan(`innerLabel`)), tail)
if scrut === scrutinee && isIntConst(tree) =>
if scrut === scrutinee && isNewIntConst(tree) =>
alts += tree
rec(tail)
case ReturnPlan(`outerLabel`) =>
Expand All @@ -746,7 +751,7 @@ object PatternMatcher {

def recur(plan: Plan): List[(List[Tree], Plan)] = plan match {
case SeqPlan(testPlan @ TestPlan(EqualTest(tree), scrut, _, ons), tail)
if scrut === scrutinee && isIntConst(tree) && !canFallThrough(ons) =>
if scrut === scrutinee && !canFallThrough(ons) && isNewIntConst(tree) =>
(tree :: Nil, ons) :: recur(tail)
case SeqPlan(AlternativesPlan(alts, ons), tail) =>
(alts, ons) :: recur(tail)
Expand Down
27 changes: 27 additions & 0 deletions tests/pos/i5402.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
object Main {
val a: Int = 4
a match {
case 1 => println("1")
case 1 | 2 => println("1 or 2")
}

a match {
case 1 => 1
case 0 | 0 => 0
case 2 | 2 | 2 | 3 | 2 | 3 => 0
case 4 | (_ @ 4) => 0
case _ => -1
}

a match {
case 1 => 1
case 0 | 0 => 0
case 2 | 2 | 2 | 3 | 2 | 3 => 0
case _ => -1
}

a match {
case 0 | 1 => 0
case 1 => 1
}
}