Skip to content

Commit

Permalink
MatchParentheses
Browse files Browse the repository at this point in the history
  • Loading branch information
xuwei-k committed Jan 3, 2025
1 parent 0c0e861 commit c334f2a
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
18 changes: 18 additions & 0 deletions input/src/main/scala-3/fix/MatchParenthesesTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
rule = MatchParentheses
*/
package fix

trait MatchParenthesesTest {
def f1(x: List[Int]): Int = (x match {
case Nil => ","
case _ => x.mkString(",")
}).length

def g(s: String): String

def f2(x: List[Int]): Int = g(x match {
case Nil => ","
case _ => x.mkString(",")
}).length
}
15 changes: 15 additions & 0 deletions output/src/main/scala-3/fix/MatchParenthesesTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package fix

trait MatchParenthesesTest {
def f1(x: List[Int]): Int = x .match {
case Nil => ","
case _ => x.mkString(",")
}.length

def g(s: String): String

def f2(x: List[Int]): Int = g(x match {
case Nil => ","
case _ => x.mkString(",")
}).length
}
34 changes: 34 additions & 0 deletions rules/src/main/scala/fix/MatchParentheses.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package fix

import scala.meta.Term
import scala.meta.XtensionClassifiable
import scala.meta.XtensionCollectionLikeUI
import scala.meta.tokens.Token
import scalafix.Patch
import scalafix.v1.SyntacticDocument
import scalafix.v1.SyntacticRule
import scalafix.v1.XtensionOptionPatch
import scalafix.v1.XtensionSeqPatch

class MatchParentheses extends SyntacticRule("MatchParentheses") {
override def fix(implicit doc: SyntacticDocument): Patch = {
doc.tree.collect { case t: Term.Match =>
PartialFunction
.condOpt(doc.tokens.filter(_.pos.start >= t.pos.end).take(2)) { case Seq(r: Token.RightParen, _: Token.Dot) =>
PartialFunction
.condOpt(doc.tokens.filter(_.pos.end <= t.pos.start).takeRight(2)) {
case Seq(n, l: Token.LeftParen) if !n.is[Token.Ident] =>
Seq(
Patch.removeToken(l),
t.tokens.collectFirst { case m: Token.KwMatch =>
Patch.addLeft(m, ".")
}.asPatch,
Patch.removeToken(r)
).asPatch
}
.asPatch
}
.asPatch
}.asPatch
}
}

0 comments on commit c334f2a

Please sign in to comment.