Skip to content

PatMat:(add support guards in switches) implement common subexpression elimination #1313

Closed
@DarkDimius

Description

@DarkDimius

In Scalac pattern matcher is able to support guards inside switches by generating arbitrary GOTOs.

Unlike this, in Dotty I propose to implement more general optimization outside of pattern-matcher, that would also give us support for guards.

I propose to add a phase, that would follow the structure of matches, match common prefixes of pattern match, and restructure that pattern.

See following examples for illustration:

x match {
  case List(1, 2, 3) => // 1
  case List(3, 4, 5) => // 2
  case 6 if pred     => // 3 
  case 6 =>             // 4
  case _ =>             // 5
}

should be rewritten as(a simplified version):

x match {
  case t: List[Int] => 
    t match {
      case List(1, 2, 3) => // 1
      case List(3, 4, 5) => // 2
      case _ => fallback
    }
  case x @ 6 => 
      x match {
        case _ if pred =>     // 3 
        case _ =>             // 4
        case _ => fallback
     }
  case _ => 
    fallback
   }
}
<label> def fallback = // 5

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions