Skip to content

Commit 80905f3

Browse files
Rule for symbolic foldLeft(/:) and foldRight(:/) (fix #27)
1 parent 431d2fa commit 80905f3

File tree

3 files changed

+43
-1
lines changed

3 files changed

+43
-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: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,15 @@ case class Scalacollectioncompat_NewCollections(index: SemanticdbIndex)
2929
Symbol("_root_.scala.runtime.Tuple2Zipped.Ops.zipped."),
3030
Symbol("_root_.scala.runtime.Tuple3Zipped.Ops.zipped.")
3131
)
32+
def foldSymbol(isLeft: Boolean): SymbolMatcher = {
33+
val op =
34+
if (isLeft) "/:"
35+
else ":\\"
36+
37+
SymbolMatcher.normalized(Symbol(s"_root_.scala.collection.TraversableOnce.`$op`."))
38+
}
39+
val foldLeftSymbol = foldSymbol(isLeft = true)
40+
val foldRightSymbol = foldSymbol(isLeft = false)
3241

3342
val retain =
3443
SymbolMatcher.normalized(
@@ -50,6 +59,14 @@ case class Scalacollectioncompat_NewCollections(index: SemanticdbIndex)
5059
ctx.replaceToken(close, "}") +
5160
ctx.replaceTree(n, "filterInPlace")
5261
).asPatch
62+
63+
def replaceSymbolicFold(ctx: RuleCtx) =
64+
ctx.tree.collect {
65+
case Term.Apply(ap @ Term.ApplyInfix(rhs, foldRightSymbol(_), _, List(lhs)), _) =>
66+
ctx.replaceTree(ap, s"$rhs.foldRight($lhs)")
67+
68+
case Term.Apply(ap @ Term.ApplyInfix(lhs, foldLeftSymbol(_), _, List(rhs)), _) =>
69+
ctx.replaceTree(ap, s"$rhs.foldLeft($lhs)")
5370
}.asPatch
5471

5572
def replaceToList(ctx: RuleCtx) =
@@ -133,6 +150,7 @@ case class Scalacollectioncompat_NewCollections(index: SemanticdbIndex)
133150
replaceTupleZipped(ctx) +
134151
replaceCopyToBuffer(ctx) +
135152
replaceStreamAppend(ctx) +
136-
replaceMutableMap(ctx)
153+
replaceMutableMap(ctx) +
154+
replaceSymbolicFold(ctx)
137155
}
138156
}

0 commit comments

Comments
 (0)