summaryrefslogtreecommitdiff
path: root/dice-lang/src/bjc/dicelang/v1/ast/optimization/ArithmeticCollapser.java
diff options
context:
space:
mode:
authorbjculkin <bjculkin@WIT-136XG42.wvu-ad.wvu.edu>2017-02-27 10:08:50 -0500
committerbjculkin <bjculkin@WIT-136XG42.wvu-ad.wvu.edu>2017-02-27 10:08:50 -0500
commit79ee129fc0d36ad10bceb942262f2842419c030c (patch)
treed1298fdb8b81726f4b9012d7a29c3029a55a3aa7 /dice-lang/src/bjc/dicelang/v1/ast/optimization/ArithmeticCollapser.java
parentc50a0744269ce22604c0604cc69e6d5e5ce8a3fc (diff)
Pacakge reorganization
Diffstat (limited to 'dice-lang/src/bjc/dicelang/v1/ast/optimization/ArithmeticCollapser.java')
-rw-r--r--dice-lang/src/bjc/dicelang/v1/ast/optimization/ArithmeticCollapser.java49
1 files changed, 49 insertions, 0 deletions
diff --git a/dice-lang/src/bjc/dicelang/v1/ast/optimization/ArithmeticCollapser.java b/dice-lang/src/bjc/dicelang/v1/ast/optimization/ArithmeticCollapser.java
new file mode 100644
index 0000000..0d10a07
--- /dev/null
+++ b/dice-lang/src/bjc/dicelang/v1/ast/optimization/ArithmeticCollapser.java
@@ -0,0 +1,49 @@
+package bjc.dicelang.v1.ast.optimization;
+
+import java.util.function.BinaryOperator;
+
+import bjc.dicelang.v1.ast.DiceASTUtils;
+import bjc.dicelang.v1.ast.nodes.DiceASTType;
+import bjc.dicelang.v1.ast.nodes.IDiceASTNode;
+import bjc.dicelang.v1.ast.nodes.ILiteralDiceNode;
+import bjc.dicelang.v1.ast.nodes.IntegerLiteralNode;
+import bjc.dicelang.v1.ast.nodes.OperatorDiceNode;
+import bjc.utils.data.ITree;
+import bjc.utils.funcdata.IList;
+import bjc.utils.data.Tree;
+
+class ArithmeticCollapser {
+ private BinaryOperator<Integer> reducer;
+ private OperatorDiceNode type;
+
+ public ArithmeticCollapser(BinaryOperator<Integer> reducr,
+ OperatorDiceNode typ) {
+ reducer = reducr;
+ this.type = typ;
+ }
+
+ public ITree<IDiceASTNode> collapse(
+ IList<ITree<IDiceASTNode>> children) {
+ boolean allConstant = children.allMatch((subtree) -> {
+ return subtree.transformHead((node) -> {
+ if (node.getType() == DiceASTType.LITERAL) {
+ return ((ILiteralDiceNode) node).canOptimize();
+ }
+
+ return false;
+ });
+ });
+
+ if (!allConstant) {
+ return new Tree<>(type, children);
+ }
+
+ int initState = DiceASTUtils.literalToInteger(children.first());
+
+ return children.tail().reduceAux(initState,
+ (currentNode, state) -> {
+ return reducer.apply(state,
+ DiceASTUtils.literalToInteger(currentNode));
+ }, (state) -> new Tree<>(new IntegerLiteralNode(state)));
+ }
+}