summaryrefslogtreecommitdiff
path: root/dice-lang/src/main/java/bjc/dicelang/ast/DiceASTReferenceSanitizer.java
blob: 08f84e358489ac95f9b7724e121e56eae38f627e (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package bjc.dicelang.ast;

import bjc.dicelang.ast.nodes.IDiceASTNode;
import bjc.dicelang.ast.nodes.OperatorDiceNode;
import bjc.dicelang.ast.nodes.VariableDiceNode;
import bjc.utils.funcdata.IFunctionalMap;
import bjc.utils.funcdata.ITree;
import bjc.utils.funcdata.TopDownTransformResult;
import bjc.utils.funcdata.Tree;

/**
 * Sanitize the references in an AST so that a variable that refers to
 * itself in its definition has the occurance of it replaced with its
 * previous definition
 * 
 * @author ben
 *
 */
public class DiceASTReferenceSanitizer {
	/**
	 * Sanitize the references in an AST
	 * 
	 * @param ast
	 * @param enviroment
	 * @return The sanitized AST
	 */
	public static ITree<IDiceASTNode> sanitize(ITree<IDiceASTNode> ast,
			IFunctionalMap<String, ITree<IDiceASTNode>> enviroment) {
		return ast.topDownTransform(
				DiceASTReferenceSanitizer::shouldSanitize, (subTree) -> {
					return doSanitize(subTree, enviroment);
				});
	}

	private static TopDownTransformResult
			shouldSanitize(IDiceASTNode node) {
		if (!node.isOperator()) {
			return TopDownTransformResult.SKIP;
		}

		switch (((OperatorDiceNode) node)) {
			case ASSIGN:
				return TopDownTransformResult.TRANSFORM;
			case ADD:
			case COMPOUND:
			case DIVIDE:
			case GROUP:
			case MULTIPLY:
			case SUBTRACT:
			default:
				return TopDownTransformResult.SKIP;
		}
	}

	private static ITree<IDiceASTNode> doSanitize(ITree<IDiceASTNode> ast,
			IFunctionalMap<String, ITree<IDiceASTNode>> enviroment) {
		if (ast.getChildrenCount() != 2) {
			throw new UnsupportedOperationException(
					"Assignment must have two arguments.");
		}

		ITree<IDiceASTNode> nameTree = ast.getChild(0);
		ITree<IDiceASTNode> valueTree = ast.getChild(1);

		if (!DiceASTUtils.containsSimpleVariable(nameTree)) {
			throw new UnsupportedOperationException(
					"Assignment must be between a variable and a expression");
		}

		String variableName = nameTree.transformHead(
				(node) -> ((VariableDiceNode) node).getVariable());

		if (enviroment.containsKey(variableName)) {
			// We should always inline out references to last, because it
			// will always change
			ITree<IDiceASTNode> inlinedValue =
					DiceASTInliner.selectiveInline(valueTree, enviroment,
							variableName, "last");

			return new Tree<>(ast.getHead(), nameTree, inlinedValue);
		}

		return ast;
	}
}