From 9ce39956fa1702f157c347dc4b8807d9b5dd2185 Mon Sep 17 00:00:00 2001 From: bculkin2442 Date: Mon, 18 Apr 2016 08:34:32 -0400 Subject: Reimplemented basic optimization. --- .../ast/optimization/ArithmeticCollapser.java | 49 ++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 dice-lang/src/main/java/bjc/dicelang/ast/optimization/ArithmeticCollapser.java (limited to 'dice-lang/src/main/java/bjc/dicelang/ast/optimization/ArithmeticCollapser.java') 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 reducer; + private OperatorDiceNode type; + + public ArithmeticCollapser(BinaryOperator reducr, + OperatorDiceNode typ) { + reducer = reducr; + this.type = typ; + } + + public ITree + collapse(IFunctionalList> 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))); + } +} -- cgit v1.2.3