summaryrefslogtreecommitdiff
path: root/dice-lang/src/bjc/dicelang/ast/optimization/ArithmeticCollapser.java
diff options
context:
space:
mode:
authorbculkin2442 <bjculkin@mix.wvu.edu>2016-10-27 21:56:18 -0400
committerbculkin2442 <bjculkin@mix.wvu.edu>2016-10-27 22:12:47 -0400
commite7413128ff4e376997de6e94e4bea5eca14811ef (patch)
tree0749e270fdb754d04dc223abd95d47436508047f /dice-lang/src/bjc/dicelang/ast/optimization/ArithmeticCollapser.java
parente13a6981bd278c2cfc3b5ecb2517367b117f7a52 (diff)
Moved examples
Diffstat (limited to 'dice-lang/src/bjc/dicelang/ast/optimization/ArithmeticCollapser.java')
-rw-r--r--dice-lang/src/bjc/dicelang/ast/optimization/ArithmeticCollapser.java50
1 files changed, 50 insertions, 0 deletions
diff --git a/dice-lang/src/bjc/dicelang/ast/optimization/ArithmeticCollapser.java b/dice-lang/src/bjc/dicelang/ast/optimization/ArithmeticCollapser.java
new file mode 100644
index 0000000..960fbf7
--- /dev/null
+++ b/dice-lang/src/bjc/dicelang/ast/optimization/ArithmeticCollapser.java
@@ -0,0 +1,50 @@
+package bjc.dicelang.ast.optimization;
+
+import java.util.function.BinaryOperator;
+
+import bjc.utils.funcdata.IList;
+import bjc.utils.funcdata.ITree;
+import bjc.utils.funcdata.Tree;
+
+import bjc.dicelang.ast.DiceASTUtils;
+import bjc.dicelang.ast.nodes.DiceASTType;
+import bjc.dicelang.ast.nodes.IDiceASTNode;
+import bjc.dicelang.ast.nodes.ILiteralDiceNode;
+import bjc.dicelang.ast.nodes.IntegerLiteralNode;
+import bjc.dicelang.ast.nodes.OperatorDiceNode;
+
+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)));
+ }
+}