-
Notifications
You must be signed in to change notification settings - Fork 0
/
ASTNormalizer.scala
52 lines (46 loc) · 1.2 KB
/
ASTNormalizer.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// ASTNormalizer.scala
package backend
import scala.annotation.tailrec
object ASTNormalizer:
private def expandComposite(
exprs: List[AwkMapExpr]
): List[AwkMapExpr] =
exprs match {
case h :: tail =>
h match {
case CompositeMap(innerExpr) =>
innerExpr ::: exprs
case _ =>
h :: expandComposite(tail)
}
case Nil =>
Nil
}
private def mergeProjections(
exprs: List[AwkMapExpr]
): List[AwkMapExpr] =
exprs match {
case MapExpr(l1) :: MapExpr(l2) :: tail =>
val m1 = Map(l1.idx.zipWithIndex.map(x => ((x._2 + 1) -> x._1)): _*)
MapExpr(
Projection(l2.idx.map(prj => m1(prj)): _*)
) :: tail
case h :: tail =>
h :: mergeProjections(tail)
case Nil =>
Nil
}
@tailrec
private def normalizeList(
exprs: List[AwkMapExpr]
): List[AwkMapExpr] =
val result =
expandComposite.andThen(mergeProjections)(exprs)
if (result != exprs)
normalizeList(result)
else
result
def normalize(awkRootExpr: AwkQueryAST) = AwkQueryAST(
awkRootExpr.fileNameOrPath,
normalizeList(awkRootExpr.mapFilterExpr.toList): _*
)