summaryrefslogtreecommitdiff
path: root/dice-lang/src/bjc/dicelang/v1/ast/DiceASTOptimizer.java
blob: a93de33c9772c721beaef089ac336f9af5d7b2be (plain)
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
53
54
55
package bjc.dicelang.v1.ast;

import bjc.dicelang.v1.ast.nodes.IDiceASTNode;
import bjc.dicelang.v1.ast.optimization.IOptimizationPass;
import bjc.utils.data.ITree;
import bjc.utils.funcdata.FunctionalList;
import bjc.utils.funcdata.IList;
import bjc.utils.funcdata.IMap;

/**
 * Contains optimizations appliable to a dice AST
 * 
 * @author ben
 *
 */
public class DiceASTOptimizer {
	private IList<IOptimizationPass> passes;

	/**
	 * Create a new optimizer
	 */
	public DiceASTOptimizer() {
		passes = new FunctionalList<>();
	}

	/**
	 * Add a pass to the list of optimization passes
	 * 
	 * @param pass
	 *                The pass to add
	 */
	public void addPass(IOptimizationPass pass) {
		passes.add(pass);
	}

	/**
	 * Optimize the passed in tree
	 * 
	 * @param ast
	 *                The tree to optimize
	 * @param enviroment
	 *                The enviroment for variable references
	 * @return The optimized tree
	 */
	public ITree<IDiceASTNode> optimizeTree(ITree<IDiceASTNode> ast, IMap<String, ITree<IDiceASTNode>> enviroment) {
		ITree<IDiceASTNode> optimizedTree = passes.reduceAux(ast, (currentPass, currentTree) -> {
			return currentTree.collapse(currentPass::optimizeLeaf, (operator) -> {
				return (nodes) -> {
					return currentPass.optimizeOperator(operator, nodes);
				};
			}, (tree) -> tree);
		}, (tree) -> tree);
		return optimizedTree;
	}
}