Skip to content

Fix #3561: Correctly handle switches followed by other tests in matches #3724

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 6 commits into from
Jan 14, 2018
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
Original file line number Diff line number Diff line change
Expand Up @@ -2030,10 +2030,11 @@ object messages {
}
}

case class UnableToEmitSwitch()(implicit ctx: Context)
case class UnableToEmitSwitch(tooFewCases: Boolean)(implicit ctx: Context)
extends Message(UnableToEmitSwitchID) {
val kind = "Syntax"
val msg = hl"Could not emit switch for ${"@switch"} annotated match"
val tooFewStr = if (tooFewCases) " since there are not enough cases" else ""
val msg = hl"Could not emit switch for ${"@switch"} annotated match$tooFewStr"
val explanation = {
val codeExample =
"""val ConstantB = 'B'
Expand Down
28 changes: 20 additions & 8 deletions compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ object PatternMatcher {

final val selfCheck = false // debug option, if on we check that no case gets generated twice

/** Minimal number of cases to emit a switch */
final val MinSwitchCases = 4

/** Was symbol generated by pattern matcher? */
def isPatmatGenerated(sym: Symbol)(implicit ctx: Context): Boolean =
sym.is(Synthetic) &&
Expand Down Expand Up @@ -845,10 +848,10 @@ object PatternMatcher {

/** Emit cases of a switch */
private def emitSwitchCases(cases: List[Plan]): List[CaseDef] = (cases: @unchecked) match {
case TestPlan(EqualTest(tree), _, _, ons, _) :: cases1 =>
CaseDef(tree, EmptyTree, emit(ons)) :: emitSwitchCases(cases1)
case (default: Plan) :: Nil =>
CaseDef(Underscore(defn.IntType), EmptyTree, emit(default)) :: Nil
case TestPlan(EqualTest(tree), _, _, ons, _) :: cases1 =>
CaseDef(tree, EmptyTree, emit(ons)) :: emitSwitchCases(cases1)
}

/** If selfCheck is `true`, used to check whether a tree gets generated twice */
Expand All @@ -863,7 +866,7 @@ object PatternMatcher {
plan match {
case plan: TestPlan =>
val switchCases = collectSwitchCases(plan)
if (switchCases.lengthCompare(4) >= 0) // at least 3 cases + default
if (switchCases.lengthCompare(MinSwitchCases) >= 0) // at least 3 cases + default
Match(plan.scrutinee, emitSwitchCases(switchCases))
else {
/** Merge nested `if`s that have the same `else` branch into a single `if`.
Expand Down Expand Up @@ -969,12 +972,21 @@ object PatternMatcher {
case Block(_, Match(_, cases)) => cases
case _ => Nil
}
def numConsts(cdefs: List[CaseDef]): Int = {
val tpes = cdefs.map(_.pat.tpe)
tpes.toSet.size
def typesInPattern(pat: Tree): List[Type] = pat match {
case Alternative(pats) => pats.flatMap(typesInPattern)
case _ => pat.tpe :: Nil
}
def typesInCases(cdefs: List[CaseDef]): List[Type] =
cdefs.flatMap(cdef => typesInPattern(cdef.pat))
def numTypes(cdefs: List[CaseDef]): Int =
typesInCases(cdefs).toSet.size: Int // without the type ascription, testPickling fails because of #2840.
if (numTypes(resultCases) < numTypes(original.cases)) {
patmatch.println(i"switch warning for ${ctx.compilationUnit}")
patmatch.println(i"original types: ${typesInCases(original.cases)}%, %")
patmatch.println(i"switch types : ${typesInCases(resultCases)}%, %")
patmatch.println(i"tree = $result")
ctx.warning(UnableToEmitSwitch(numTypes(original.cases) < MinSwitchCases), original.pos)
}
if (numConsts(resultCases) < numConsts(original.cases))
ctx.warning(UnableToEmitSwitch(), original.pos)
case _ =>
}

Expand Down
1 change: 1 addition & 0 deletions compiler/test/dotty/tools/dotc/CompilationTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ class CompilationTests extends ParallelTesting {
compileFile("../tests/neg-custom-args/noimports2.scala", defaultOptions.and("-Yno-imports")) +
compileFile("../tests/neg-custom-args/overloadsOnAbstractTypes.scala", allowDoubleBindings) +
compileFile("../tests/neg-custom-args/xfatalWarnings.scala", defaultOptions.and("-Xfatal-warnings")) +
compileFile("../tests/neg-custom-args/i3561.scala", defaultOptions.and("-Xfatal-warnings")) +
compileFile("../tests/neg-custom-args/pureStatement.scala", defaultOptions.and("-Xfatal-warnings")) +
compileFile("../tests/neg-custom-args/i3589-a.scala", defaultOptions.and("-Xfatal-warnings")) +
compileFile("../tests/neg-custom-args/i2333.scala", defaultOptions.and("-Xfatal-warnings")) +
Expand Down
22 changes: 22 additions & 0 deletions tests/neg-custom-args/i3561.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Test {
val Constant = 'Q' // OK if final
def tokenMe(ch: Char) = (ch: @annotation.switch) match { // error: could not emit switch
case ' ' => 1
case 'A' => 2
case '5' | Constant => 3
case '4' => 4
}

def test2(x: Any) = (x: @annotation.switch) match { // error: could not emit switch
case ' ' => 1
case 'A' => 2
case '5' | Constant => 3
case '4' => 4
}

def test3(x: Any) = (x: @annotation.switch) match { // error: could not emit switch - too few cases
case 1 => 1
case 2 => 2
case x: String => 4
}
}
15 changes: 15 additions & 0 deletions tests/pos/i3561.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class Test {
val Constant = 'Q' // OK if final
def tokenMe(ch: Char) = (ch: @annotation.switch) match {
case ' ' => 1
case 'A' => 2
case '5' | Constant => 3
}

def test2(x: Any) = x match {
case 1 => 1
case 2 => 2
case 3 => 3
case x: String => 4
}
}
2 changes: 1 addition & 1 deletion tests/pos/typers.scala
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ object typers {

class C {

@tailrec final def factorial(acc: Int, n: Int): Int = (n: @switch) match {
@tailrec final def factorial(acc: Int, n: Int): Int = n match {
case 0 => acc
case _ => factorial(acc * n, n - 1)
}
Expand Down
2 changes: 1 addition & 1 deletion tests/run/switches.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ object Test extends App {
case _ => 4
}

val x3 = (x: @switch) match {
val x3 = x match {
case '0' if x > 0 => 0
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

scalac supports emitting switch when cases contain conditions, it translates something like:

  def foo(x: Int, cond: Boolean) = x match {
    case 1 if cond =>
      println("1")
    case 2 =>
      println("2")
    case 3 =>
      println("3")
    case _ =>
      println("4")
  }

to

      x1 match {
        case 1 => if (cond)
          scala.Predef.println("1")
        else
          default5()
        case 2 => scala.Predef.println("2")
        case 3 => scala.Predef.println("3")
        case _ => default5(){
          scala.Predef.println("4")
        }
      }

Is this an intended limitation of Dotty @switch, or something that still needs to be implemented?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was supposed to go in the local optimizations. I made an implementation of this a while ago but I do not know if it went into Dotty or just stayed in the linker.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would make sense to have it by default. Could you open an issue so we keep track of it?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you open an issue so we keep track of it?

Turns out there's already one: #1313

case '1' => 1
case '2' => 2
Expand Down
4 changes: 2 additions & 2 deletions tests/run/t5830.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ object Test extends dotty.runtime.LegacyApp {
case 'c' =>
}

def ifThenElse(ch: Char, eof: Boolean) = (ch: @switch) match {
def ifThenElse(ch: Char, eof: Boolean) = ch match {
case 'a' if eof => println("a with oef") // then branch
case 'a' if eof => println("a with oef2") // unreachable, but the analysis is not that sophisticated
case 'a' => println("a") // else-branch
Expand All @@ -22,7 +22,7 @@ object Test extends dotty.runtime.LegacyApp {
case _ => println("default")
}

def defaults(ch: Char, eof: Boolean) = (ch: @switch) match {
def defaults(ch: Char, eof: Boolean) = ch match {
case _ if eof => println("def with oef") // then branch
case _ if eof => println("def with oef2") // unreachable, but the analysis is not that sophisticated
case _ => println("def") // else-branch
Expand Down