diff options
| author | bculkin2442 <bjculkin@mix.wvu.edu> | 2016-04-18 08:34:32 -0400 |
|---|---|---|
| committer | bculkin2442 <bjculkin@mix.wvu.edu> | 2016-04-18 08:34:32 -0400 |
| commit | 9ce39956fa1702f157c347dc4b8807d9b5dd2185 (patch) | |
| tree | d981c0010a92660a1f0501431c4a3bc02d94e56d /dice-lang/src/main/java/bjc/dicelang/ast/optimization/ArithmeticCollapser.java | |
| parent | 7c222f25d4b2d9f3b149d880f0e1acf8d673e4f5 (diff) | |
Reimplemented basic optimization.
Diffstat (limited to 'dice-lang/src/main/java/bjc/dicelang/ast/optimization/ArithmeticCollapser.java')
| -rw-r--r-- | dice-lang/src/main/java/bjc/dicelang/ast/optimization/ArithmeticCollapser.java | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/dice-lang/src/main/java/bjc/dicelang/ast/optimization/ArithmeticCollapser.java b/dice-lang/src/main/java/bjc/dicelang/ast/optimization/ArithmeticCollapser.java new file mode 100644 index 0000000..5318119 --- /dev/null +++ b/dice-lang/src/main/java/bjc/dicelang/ast/optimization/ArithmeticCollapser.java @@ -0,0 +1,49 @@ +package bjc.dicelang.ast.optimization; + +import java.util.function.BinaryOperator; + +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; +import bjc.utils.funcdata.IFunctionalList; +import bjc.utils.funcdata.ITree; +import bjc.utils.funcdata.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(IFunctionalList<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.toInt(children.first()); + + return children.tail().reduceAux(initState, + (currentNode, state) -> { + return reducer.apply(state, + DiceASTUtils.toInt(currentNode)); + }, (state) -> new Tree<>(new IntegerLiteralNode(state))); + } +} |
