Skip to content

Commit 9ec472c

Browse files
Rule for symbolic foldLeft(/:) and foldRight(:/) (fix #27)
1 parent a4c5413 commit 9ec472c

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/*
2+
rule = "scala:fix.Scalacollectioncompat_NewCollections"
3+
*/
4+
package fix
5+
6+
class FoldSrc(xs: List[Int]){
7+
val f: (Int, Int) => Int = (x, y) => x + y
8+
val g: (Int, Int) => Int = (x, y) => x * y
9+
10+
(0 /: xs)(f)
11+
(xs :\ 1)(g)
12+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
2+
3+
4+
package fix
5+
6+
class FoldSrc(xs: List[Int]){
7+
val f: (Int, Int) => Int = (x, y) => x + y
8+
val g: (Int, Int) => Int = (x, y) => x * y
9+
10+
xs.foldLeft(0)(f)
11+
xs.foldRight(1)(g)
12+
}

scalafix/rules/src/main/scala/fix/Scalacollectioncompat_NewCollections.scala

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,27 @@ case class Scalacollectioncompat_NewCollections(index: SemanticdbIndex)
3030
Symbol("_root_.scala.runtime.Tuple3Zipped.Ops.zipped.")
3131
)
3232

33+
def foldSymbol(isLeft: Boolean): SymbolMatcher = {
34+
val op =
35+
if (isLeft) "/:"
36+
else ":\\"
37+
38+
SymbolMatcher.normalized(Symbol(s"_root_.scala.collection.TraversableOnce.`$op`."))
39+
}
40+
41+
val foldLeftSymbol = foldSymbol(isLeft = true)
42+
val foldRightSymbol = foldSymbol(isLeft = false)
43+
44+
45+
def replaceSymbolicFold(ctx: RuleCtx) =
46+
ctx.tree.collect {
47+
case Term.Apply(ap @ Term.ApplyInfix(rhs, foldRightSymbol(_), _, List(lhs)), _) =>
48+
ctx.replaceTree(ap, s"$rhs.foldRight($lhs)")
49+
50+
case Term.Apply(ap @ Term.ApplyInfix(lhs, foldLeftSymbol(_), _, List(rhs)), _) =>
51+
ctx.replaceTree(ap, s"$rhs.foldLeft($lhs)")
52+
}.asPatch
53+
3354
def replaceToList(ctx: RuleCtx) =
3455
ctx.tree.collect {
3556
case iterator(t: Name) =>
@@ -110,6 +131,7 @@ case class Scalacollectioncompat_NewCollections(index: SemanticdbIndex)
110131
replaceSymbols(ctx) +
111132
replaceTupleZipped(ctx) +
112133
replaceCopyToBuffer(ctx) +
113-
replaceStreamAppend(ctx)
134+
replaceStreamAppend(ctx) +
135+
replaceSymbolicFold(ctx)
114136
}
115137
}

0 commit comments

Comments
 (0)