summaryrefslogtreecommitdiff
path: root/dice-lang/src/bjc/dicelang/ast/DiceASTEvaluator.java
blob: f4bfe798ca36318f78c69f5338c9923ef6951207 (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package bjc.dicelang.ast;

import java.util.function.Supplier;

import bjc.utils.data.IHolder;
import bjc.utils.data.IPair;
import bjc.utils.data.ITree;
import bjc.utils.data.Identity;
import bjc.utils.data.LazyPair;
import bjc.utils.data.Pair;
import bjc.utils.funcdata.FunctionalList;
import bjc.utils.funcdata.FunctionalMap;
import bjc.utils.funcdata.IList;
import bjc.utils.funcdata.IMap;
import bjc.utils.data.Tree;

import bjc.dicelang.ComplexDice;
import bjc.dicelang.ast.nodes.DiceASTType;
import bjc.dicelang.ast.nodes.DiceLiteralNode;
import bjc.dicelang.ast.nodes.DiceLiteralType;
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.dicelang.ast.nodes.VariableDiceNode;

/**
 * Evaluate a dice AST to an integer value
 * 
 * @author ben
 *
 */
public class DiceASTEvaluator {
	private static IResult bindLiteralValue(IDiceASTNode leafNode,
			IMap<String, ITree<IDiceASTNode>> enviroment) {
		String variableName = ((VariableDiceNode) leafNode).getVariable();

		if (enviroment.containsKey(variableName)) {
			IResult result = evaluateAST(enviroment.get(variableName),
					enviroment);

			return result;
		}

		// Return a DummyResult to handle lets properly
		return new DummyResult(
				"Attempted to deref unbound variable " + variableName);
	}

	/**
	 * Build the map of operations to use when collapsing the AST
	 * 
	 * @param enviroment
	 *            The enviroment to evaluate bindings and such against
	 * @return The operations to use when collapsing the AST
	 */
	private static IMap<IDiceASTNode, IOperatorCollapser> buildOperations(
			IMap<String, ITree<IDiceASTNode>> enviroment) {
		IMap<IDiceASTNode, IOperatorCollapser> operatorCollapsers = new FunctionalMap<>();

		operatorCollapsers.put(OperatorDiceNode.ADD,
				new ArithmeticCollapser(OperatorDiceNode.ADD,
						(left, right) -> left + right, 0));

		operatorCollapsers.put(OperatorDiceNode.SUBTRACT,
				new ArithmeticCollapser(OperatorDiceNode.SUBTRACT,
						(left, right) -> left - right, 0));

		operatorCollapsers.put(OperatorDiceNode.MULTIPLY,
				new ArithmeticCollapser(OperatorDiceNode.MULTIPLY,
						(left, right) -> left * right, 1));

		operatorCollapsers.put(OperatorDiceNode.DIVIDE,
				new ArithmeticCollapser(OperatorDiceNode.DIVIDE,
						(left, right) -> left / right, 1));

		operatorCollapsers.put(OperatorDiceNode.ASSIGN, (nodes) -> {
			return parseBinding(enviroment, nodes);
		});

		operatorCollapsers.put(OperatorDiceNode.COMPOUND,
				new ArithmeticCollapser(OperatorDiceNode.COMPOUND,
						(left, right) -> {
							return Integer.parseInt(Integer.toString(left)
									+ Integer.toString(right));
						}, 0));

		operatorCollapsers.put(OperatorDiceNode.GROUP,
				DiceASTEvaluator::parseGroup);

		operatorCollapsers.put(OperatorDiceNode.LET, (nodes) -> {
			// @TODO Fix lets prematurely evaluating things
			return parseLet(enviroment, nodes);
		});

		operatorCollapsers.put(OperatorDiceNode.ARRAY, (nodes) -> {

			// This is so that arrays respect lazy results properly
			Supplier<IResult> resultSupplier = () -> {
				IList<IResult> resultList = new FunctionalList<>();

				nodes.forEach((node) -> {
					resultList.add(node.getLeft());
				});

				return new ArrayResult(resultList);
			};

			Supplier<ITree<IDiceASTNode>> treeSupplier = () -> {
				ITree<IDiceASTNode> returnedTree = new Tree<>(
						OperatorDiceNode.ARRAY);

				nodes.forEach((element) -> {
					returnedTree.addChild(element.getRight());
				});

				return returnedTree;
			};

			return new LazyPair<>(resultSupplier, treeSupplier);
		});

		return operatorCollapsers;
	}

	private static void doArrayAssign(
			IMap<String, ITree<IDiceASTNode>> enviroment,
			IPair<IResult, ITree<IDiceASTNode>> nameNode,
			ITree<IDiceASTNode> nameTree, ITree<IDiceASTNode> valueTree,
			IHolder<Integer> childCount, ITree<IDiceASTNode> child) {
		if (nameTree.getHead().getType() != DiceASTType.VARIABLE) {
			throw new UnsupportedOperationException(
					"Assigning to complex variables isn't supported. Problem node is "
							+ nameNode.getRight());
		}

		String varName = child.transformHead((nameNod) -> {
			return ((VariableDiceNode) nameNod).getVariable();
		});

		enviroment.put(varName, valueTree.getChild(childCount.getValue()));

		childCount.transform(val -> val + 1);
	}

	/**
	 * Evaluate the provided AST to a numeric value
	 * 
	 * @param expression
	 *            The expression to evaluate
	 * @param enviroment
	 *            The enviroment to look up variables in
	 * @return The integer value of the expression
	 */
	public static IResult evaluateAST(ITree<IDiceASTNode> expression,
			IMap<String, ITree<IDiceASTNode>> enviroment) {
		IMap<IDiceASTNode, IOperatorCollapser> collapsers = buildOperations(
				enviroment);

		return expression.collapse(
				(node) -> evaluateLeaf(node, enviroment), collapsers::get,
				(pair) -> pair.getLeft());
	}

	private static IPair<IResult, ITree<IDiceASTNode>> evaluateLeaf(
			IDiceASTNode leafNode,
			IMap<String, ITree<IDiceASTNode>> enviroment) {
		ITree<IDiceASTNode> returnedAST = new Tree<>(leafNode);

		switch (leafNode.getType()) {
			case LITERAL:
				return new Pair<>(evaluateLiteral(leafNode), returnedAST);

			case VARIABLE:
				return new LazyPair<>(() -> {
					return bindLiteralValue(leafNode, enviroment);
				}, () -> returnedAST);

			case OPERATOR:
			default:
				throw new UnsupportedOperationException(
						"Node '" + leafNode + "' cannot be a leaf.");
		}
	}

	private static IResult evaluateLiteral(IDiceASTNode leafNode) {
		DiceLiteralType literalType = ((ILiteralDiceNode) leafNode)
				.getLiteralType();

		switch (literalType) {
			case DICE:
				int diceRoll = ((DiceLiteralNode) leafNode).getValue()
						.roll();

				return new IntegerResult(diceRoll);
			case INTEGER:
				int val = ((IntegerLiteralNode) leafNode).getValue();

				return new IntegerResult(val);
			default:
				throw new UnsupportedOperationException("Literal value '"
						+ leafNode + "' is of a type (" + literalType
						+ ") not currently supported.");
		}
	}

	private static IPair<IResult, ITree<IDiceASTNode>> parseBinding(
			IMap<String, ITree<IDiceASTNode>> enviroment,
			IList<IPair<IResult, ITree<IDiceASTNode>>> nodes) {
		if (nodes.getSize() != 2) {
			throw new UnsupportedOperationException(
					"Can only bind nodes with two children. Problem children are "
							+ nodes);
		}

		IPair<IResult, ITree<IDiceASTNode>> nameNode = nodes.getByIndex(0);
		IPair<IResult, ITree<IDiceASTNode>> valueNode = nodes
				.getByIndex(1);

		return nameNode.bindRight((nameTree) -> {
			return valueNode.bind((valueValue, valueTree) -> {
				if (DiceASTUtils.containsSimpleVariable(nameTree)) {
					String varName = nameTree.transformHead((nameNod) -> {
						return ((VariableDiceNode) nameNod).getVariable();
					});

					enviroment.put(varName, valueTree);

					return new Pair<>(valueValue, nameTree);
				} else if (nameTree.getHead() == OperatorDiceNode.ARRAY) {
					if (valueTree.getHead() == OperatorDiceNode.ARRAY) {
						if (nameTree.getChildrenCount() != valueTree
								.getChildrenCount()) {
							throw new UnsupportedOperationException(
									"Array assignment must be between two equal length arrays");
						}

						IHolder<Integer> childCount = new Identity<>(0);

						nameTree.doForChildren((child) -> {
							doArrayAssign(enviroment, nameNode, nameTree,
									valueTree, childCount, child);

							childCount.transform(val -> val + 1);
						});

						return new Pair<>(valueValue, nameTree);
					}

					nameTree.doForChildren((child) -> {
						String varName = child.transformHead((nameNod) -> {
							return ((VariableDiceNode) nameNod)
									.getVariable();
						});

						enviroment.put(varName, valueTree);
					});

					return new Pair<>(valueValue, nameTree);
				}

				throw new UnsupportedOperationException(
						"Assigning to complex variables isn't supported. Problem node is "
								+ nameNode.getRight());
			});
		});
	}

	private static IPair<IResult, ITree<IDiceASTNode>> parseGroup(
			IList<IPair<IResult, ITree<IDiceASTNode>>> nodes) {
		if (nodes.getSize() != 2) {
			throw new UnsupportedOperationException(
					"Can only form a group from two dice");
		}

		IPair<IResult, ITree<IDiceASTNode>> numberDiceNode = nodes
				.getByIndex(0);
		IPair<IResult, ITree<IDiceASTNode>> diceTypeNode = nodes
				.getByIndex(1);

		return numberDiceNode.bind((numberDiceValue, numberDiceTree) -> {
			return diceTypeNode.bind((diceTypeValue, diceTypeTree) -> {
				ComplexDice cDice = new ComplexDice(
						((IntegerResult) numberDiceValue).getValue(),
						((IntegerResult) diceTypeValue).getValue());

				return new Pair<>(new IntegerResult(cDice.roll()),
						new Tree<>(OperatorDiceNode.GROUP, numberDiceTree,
								diceTypeTree));
			});
		});
	}

	private static IPair<IResult, ITree<IDiceASTNode>> parseLet(
			IMap<String, ITree<IDiceASTNode>> enviroment,
			IList<IPair<IResult, ITree<IDiceASTNode>>> nodes) {
		if (nodes.getSize() != 2) {
			throw new UnsupportedOperationException(
					"Can only use let with two expressions.");
		}

		ITree<IDiceASTNode> bindTree = nodes.getByIndex(0).getRight();
		ITree<IDiceASTNode> expressionTree = nodes.getByIndex(1)
				.getRight();

		IMap<String, ITree<IDiceASTNode>> letEnviroment = enviroment
				.extend();

		System.out.println("Evaluating tree for bound values");

		evaluateAST(bindTree, letEnviroment);

		IResult exprResult = evaluateAST(expressionTree, letEnviroment);

		IList<ITree<IDiceASTNode>> childrn = nodes
				.map((pair) -> pair.getRight());

		return new Pair<>(exprResult,
				new Tree<>(OperatorDiceNode.LET, childrn));
	}
}