Skip to content

Commit bdb2197

Browse files
authored
Merge pull request #35 from MasseGuillaume/symbolic-fold
Rule for symbolic foldLeft(/:) and foldRight(:/) (fix #27)
2 parents 2351d86 + b3262ce commit bdb2197

File tree

3 files changed

+45
-2
lines changed

3 files changed

+45
-2
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: 21 additions & 2 deletions
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 retainMap =
3443
SymbolMatcher.normalized(
@@ -60,7 +69,16 @@ case class Scalacollectioncompat_NewCollections(index: SemanticdbIndex)
6069
ctx.replaceToken(open, "{case ") +
6170
ctx.replaceToken(close, "}") +
6271
ctx.replaceTree(n, "filterInPlace")
63-
).asPatch
72+
).asPatch
73+
}.asPatch
74+
75+
def replaceSymbolicFold(ctx: RuleCtx) =
76+
ctx.tree.collect {
77+
case Term.Apply(ap @ Term.ApplyInfix(rhs, foldRightSymbol(_), _, List(lhs)), _) =>
78+
ctx.replaceTree(ap, s"$rhs.foldRight($lhs)")
79+
80+
case Term.Apply(ap @ Term.ApplyInfix(lhs, foldLeftSymbol(_), _, List(rhs)), _) =>
81+
ctx.replaceTree(ap, s"$rhs.foldLeft($lhs)")
6482
}.asPatch
6583

6684
def replaceToList(ctx: RuleCtx) =
@@ -147,6 +165,7 @@ case class Scalacollectioncompat_NewCollections(index: SemanticdbIndex)
147165
replaceCopyToBuffer(ctx) +
148166
replaceStreamAppend(ctx) +
149167
replaceMutableMap(ctx) +
150-
replaceMutableSet(ctx)
168+
replaceMutableSet(ctx) +
169+
replaceSymbolicFold(ctx)
151170
}
152171
}

0 commit comments

Comments
 (0)