summaryrefslogtreecommitdiff
path: root/base/src/bjc/dicelang/Evaluator.java
blob: f3b2450eb6ea63a2e62666c2c694b2aa9e749709 (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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
package bjc.dicelang;

import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.function.Consumer;

import bjc.dicelang.dice.CompoundDie;
import bjc.dicelang.dice.Die;
import bjc.dicelang.dice.MathDie;
import bjc.dicelang.dice.ScalarDie;
import bjc.dicelang.dice.SimpleDie;
import bjc.dicelang.dice.SimpleDieList;

import bjc.utils.data.ITree;
import bjc.utils.data.SingleIterator;
import bjc.utils.data.TopDownTransformIterator;
import bjc.utils.data.TopDownTransformResult;
import bjc.utils.data.Tree;

import static bjc.dicelang.Errors.ErrorKey.*;
import static bjc.dicelang.EvaluatorResult.Type.DICE;
import static bjc.dicelang.EvaluatorResult.Type.FAILURE;
import static bjc.dicelang.EvaluatorResult.Type.FLOAT;
import static bjc.dicelang.EvaluatorResult.Type.INT;
import static bjc.dicelang.EvaluatorResult.Type.STRING;


/* @TODO 10/09/17 Ben Culkin :EvaluatorSplit
 * 	Type/sanity checking should be moved into a seperate stage, not part of
 * 	evaluation.
 */
/**
 * Evaluate DiceLang ASTs
 *
 * @author EVE
 *
 */
public class Evaluator {
	/* The steps of type coercion. */
	private static enum CoerceSteps {
		INTEGER, DOUBLE;
	}

	/* The context during iteration. */
	private static class Context {
		public Consumer<Iterator<ITree<Node>>> thunk;

		public boolean isDebug;

		public Context() {
			/* Empty block. */
		}
	}

	/* The engine we are connected to. */
	private final DiceLangEngine eng;

	/**
	 * Create a new evaluator.
	 *
	 * @param en
	 *                The engine.
	 */
	public Evaluator(final DiceLangEngine en) {
		eng = en;
	}

	/**
	 * Evaluate a AST.
	 *
	 * @param comm
	 *                The AST to evaluate.
	 *
	 * @return The result of the tree.
	 */
	public EvaluatorResult evaluate(final ITree<Node> comm) {
		final Context ctx = new Context();

		ctx.isDebug = false;
		ctx.thunk = itr -> {
			/*
			 * Deliberately finish the iterator, but ignore results.
			 * It's only for stepwise evaluation, but we don't know
			 * if stepping the iterator has side effects. 
			 */
			while (itr.hasNext()) {
				itr.next();
			}
		};

		/* The result. */
		final ITree<Node> res = comm.topDownTransform(
				this::pickEvaluationType,
				node -> this.evaluateNode(node, ctx));

		return res.getHead().resultVal;
	}

	/* @NOTE
	 * 	This is broken until stepwise top-down transforms are fixed. */
	public Iterator<ITree<Node>> stepDebug(final ITree<Node> comm) {
		final Context ctx = new Context();

		ctx.isDebug = true;

		return new TopDownTransformIterator<>(this::pickEvaluationType, (node, thnk) -> {
			ctx.thunk = thnk;

			return this.evaluateNode(node, ctx);
		}, comm);
	}

	/* Pick the way to evaluate a node. */
	private TopDownTransformResult pickEvaluationType(final Node nd) {
		switch (nd.type) {
		case UNARYOP:
			switch (nd.operatorType) {
			case COERCE:
				/* Coerce does special things to the tree. */
				return TopDownTransformResult.RTRANSFORM;
			default:
				return TopDownTransformResult.PUSHDOWN;
			}

		default:
			return TopDownTransformResult.PUSHDOWN;
		}
	}

	/* Evaluate a node. */
	private ITree<Node> evaluateNode(final ITree<Node> ast, final Context ctx) {
		switch (ast.getHead().type) {
		case UNARYOP:
			return evaluateUnaryOp(ast, ctx);
		case BINOP:
			return evaluateBinaryOp(ast, ctx);
		case TOKREF:
			return evaluateTokenRef(ast.getHead().tokenVal, ctx);
		case ROOT:
			return ast.getChild(ast.getChildrenCount() - 1);
		case RESULT:
			return ast;
		default:
			Errors.inst.printError(EK_EVAL_INVNODE, ast.getHead().type.toString());
			return new Tree<>(Node.FAIL(ast));
		}
	}

	/* Evaluate a unary operator. */
	private ITree<Node> evaluateUnaryOp(final ITree<Node> ast, final Context ctx) {
		/* Unary operators only take one operand. */
		if (ast.getChildrenCount() != 1) {
			Errors.inst.printError(EK_EVAL_UNUNARY, Integer.toString(ast.getChildrenCount()));
			return new Tree<>(Node.FAIL(ast));
		}

		switch (ast.getHead().operatorType) {
			/* 
			 * @TODO 10/09/17 Ben Culkin :CoerceRefactor :EvaluatorSplit
			 * 	Coercing should be moved to its own class, or at the
			 * 	very least its own method. When the evaluator splits,
			 * 	this node type'll be handled exclusively by the
			 * 	type-checker.
			 *
			 * 	Coerce also needs to be able to coerce things to
			 * 	dice and ratios (whenever they get added).
			 */
		case COERCE:
			final ITree<Node> toCoerce = ast.getChild(0);
			final ITree<Node> retVal = new Tree<>(toCoerce.getHead());
			final Deque<ITree<Node>> children = new LinkedList<>();

			/* The current type we are coercing to. */
			CoerceSteps curLevel = CoerceSteps.INTEGER;

			for (int i = 0; i < toCoerce.getChildrenCount(); i++) {
				final ITree<Node> child = toCoerce.getChild(i);
				ITree<Node> nChild = null;

				/* Tell our thunk we processed a node. */
				if (ctx.isDebug) {
					/* Evaluate each step of the child. */
					final Iterator<ITree<Node>> nd = stepDebug(child);

					for (; nd.hasNext(); nChild = nd.next()) {
						ctx.thunk.accept(new SingleIterator<>(child));
					}
				} else {
					/* Evaluate the child. */
					nChild = new Tree<>(new Node(Node.Type.RESULT, evaluate(child)));

					ctx.thunk.accept(new SingleIterator<>(nChild));
				}

				if (nChild == null) {
					Errors.inst.printError(EK_EVAL_INVNODE);
					return new Tree<>(Node.FAIL(ast));
				}

				final Node childNode = nChild.getHead();
				final EvaluatorResult res = childNode.resultVal;

				/* Move up to coercing to a float. */
				if (res.type == FLOAT) {
					curLevel = CoerceSteps.DOUBLE;
				}

				children.add(nChild);
			}

			for (final ITree<Node> child : children) {
				final Node nd = child.getHead();
				final EvaluatorResult res = nd.resultVal;

				switch (res.type) {
				case INT:
					/* Coerce ints to doubles if we need to. */
					if (curLevel == CoerceSteps.DOUBLE) {
						nd.resultVal = new EvaluatorResult(FLOAT, (double) res.intVal);
					}
				default:
					/* Do nothing */
					break;
				}

				retVal.addChild(child);
			}

			return retVal;
		case DICESCALAR:
			final EvaluatorResult opr = ast.getChild(0).getHead().resultVal;

			if (opr.type != INT) {
				Errors.inst.printError(EK_EVAL_INVDCREATE, opr.type.toString());
			}

			final EvaluatorResult sres = new EvaluatorResult(DICE, new ScalarDie(opr.intVal));
			return new Tree<>(new Node(Node.Type.RESULT, sres));
		case DICEFUDGE:
			final EvaluatorResult oprn = ast.getChild(0).getHead().resultVal;

			if (oprn.type != INT) {
				Errors.inst.printError(EK_EVAL_INVDCREATE, oprn.type.toString());
			}

			final EvaluatorResult fres = new EvaluatorResult(DICE, new ScalarDie(oprn.intVal));
			return new Tree<>(new Node(Node.Type.RESULT, fres));
		default:
			Errors.inst.printError(EK_EVAL_INVUNARY, ast.getHead().operatorType.toString());
			return new Tree<>(Node.FAIL(ast));
		}
	}

	/* Evaluate a binary operator. */
	private static ITree<Node> evaluateBinaryOp(final ITree<Node> ast, final Context ctx) {
		final Token.Type binOp = ast.getHead().operatorType;

		/* Binary operators always have two children. */
		if (ast.getChildrenCount() != 2) {
			Errors.inst.printError(EK_EVAL_INVBIN, Integer.toString(ast.getChildrenCount()),
					ast.toString());

			return new Tree<>(Node.FAIL(ast));
		}

		final ITree<Node> left  = ast.getChild(0);
		final ITree<Node> right = ast.getChild(1);

		final EvaluatorResult leftRes  = left.getHead().resultVal;
		final EvaluatorResult rightRes = right.getHead().resultVal;

		switch (binOp) {
		case ADD:
		case SUBTRACT:
		case MULTIPLY:
		case DIVIDE:
		case IDIVIDE:
			return evaluateMathBinary(binOp, leftRes, rightRes, ctx);
		case DICEGROUP:
		case DICECONCAT:
		case DICELIST:
			return evaluateDiceBinary(binOp, leftRes, rightRes, ctx);
		case STRCAT:
		case STRREP:
			return evaluateStringBinary(binOp, leftRes, rightRes, ctx);
		default:
			Errors.inst.printError(EK_EVAL_UNBIN, binOp.toString());
			return new Tree<>(Node.FAIL(ast));
		}
	}

	/* Evaluate a binary operator on strings. */
	private static ITree<Node> evaluateStringBinary(final Token.Type op,
			final EvaluatorResult left,
			final EvaluatorResult right, final Context ctx) {
		if (left.type != STRING) {
			Errors.inst.printError(EK_EVAL_INVSTRING, left.type.toString());
			return new Tree<>(Node.FAIL(left));
		}

		final String strang = left.stringVal;

		switch (op) {
		case STRCAT:
			if (right.type != STRING) {
				Errors.inst.printError(EK_EVAL_UNSTRING, right.type.toString());
				return new Tree<>(Node.FAIL(right));
			}

			final String strung = right.stringVal;
			final EvaluatorResult cres = new EvaluatorResult(STRING, strang + strung);

			return new Tree<>(new Node(Node.Type.RESULT, cres));
		case STRREP:
			if (right.type != INT) {
				Errors.inst.printError(EK_EVAL_INVSTRING, right.type.toString());
				return new Tree<>(Node.FAIL(right));
			}

			String res = strang;
			final long count = right.intVal;

			for (long i = 1; i < count; i++) {
				res += strang;
			}

			return new Tree<>(new Node(Node.Type.RESULT, new EvaluatorResult(STRING, res)));
		default:
			Errors.inst.printError(EK_EVAL_UNSTRING, op.toString());
			return new Tree<>(Node.FAIL());
		}
	}

	/* Evaluate dice binary operators. */
	private static ITree<Node> evaluateDiceBinary(final Token.Type op,
			final EvaluatorResult left,
			final EvaluatorResult right, final Context ctx) {
		EvaluatorResult res = null;

		switch (op) {
			/*
			 * @TODO 10/09/17 Ben Culkin :DiceSimplify
			 * 	Figure out some way to simplify this sort of
			 * 	thing.
			 */
		case DICEGROUP:
			if (left.type == DICE && !left.diceVal.isList) {
				if (right.type == DICE && !right.diceVal.isList) {
					Die simple = new SimpleDie(
							left.diceVal.scalar,
							right.diceVal.scalar);

					res = new EvaluatorResult(DICE, simple);
				} else if (right.type == INT) {
					res = new EvaluatorResult(DICE,
							new SimpleDie(left.diceVal.scalar, right.intVal));
				} else {
					Errors.inst.printError(EK_EVAL_INVDGROUP, right.type.toString());
					return new Tree<>(Node.FAIL(right));
				}
			} else if (left.type == INT) {
				if (right.type == DICE && !right.diceVal.isList) {
					res = new EvaluatorResult(DICE,
							new SimpleDie(left.intVal, right.diceVal.scalar));
				} else if (right.type == INT) {
					res = new EvaluatorResult(DICE, new SimpleDie(left.intVal, right.intVal));
				} else {
					Errors.inst.printError(EK_EVAL_INVDGROUP, right.type.toString());
					return new Tree<>(Node.FAIL(right));
				}
			} else {
				Errors.inst.printError(EK_EVAL_INVDGROUP, left.type.toString());
				return new Tree<>(Node.FAIL(left));
			}

		case DICECONCAT:
			if (left.type != DICE || left.diceVal.isList) {
				Errors.inst.printError(EK_EVAL_INVDICE, left.type.toString());
				return new Tree<>(Node.FAIL(left));
			} else if (right.type != DICE || right.diceVal.isList) {
				Errors.inst.printError(EK_EVAL_INVDICE, right.type.toString());
				return new Tree<>(Node.FAIL(right));
			} else {
				res = new EvaluatorResult(DICE,
						new CompoundDie(left.diceVal.scalar, right.diceVal.scalar));
			}

			break;

		case DICELIST:
			if (left.type != DICE || left.diceVal.isList) {
				Errors.inst.printError(EK_EVAL_INVDICE, left.type.toString());
				return new Tree<>(Node.FAIL(left));
			} else if (right.type != DICE || right.diceVal.isList) {
				Errors.inst.printError(EK_EVAL_INVDICE, right.type.toString());
				return new Tree<>(Node.FAIL(right));
			} else {
				res = new EvaluatorResult(DICE,
						new SimpleDieList(left.diceVal.scalar, right.diceVal.scalar));
			}

			break;

		default:
			Errors.inst.printError(EK_EVAL_UNDICE, op.toString());
			return new Tree<>(Node.FAIL());
		}

		return new Tree<>(new Node(Node.Type.RESULT, res));
	}

	/* Evaluate a binary math operator. */
	private static ITree<Node> evaluateMathBinary(final Token.Type op,
			final EvaluatorResult left,
			final EvaluatorResult right, final Context ctx) {
		if (left.type == STRING || right.type == STRING) {
			Errors.inst.printError(EK_EVAL_STRINGMATH);
			return new Tree<>(Node.FAIL());
		} else if (left.type == FAILURE || right.type == FAILURE) {
			return new Tree<>(Node.FAIL());
		} else if (left.type == INT && right.type != INT) {
			Errors.inst.printError(EK_EVAL_MISMATH);
			return new Tree<>(Node.FAIL(right));
		} else if (left.type == FLOAT && right.type != FLOAT) {
			Errors.inst.printError(EK_EVAL_MISMATH);
			return new Tree<>(Node.FAIL(right));
		} else if (left.type == DICE && right.type != DICE) {
			Errors.inst.printError(EK_EVAL_MISMATH);
			return new Tree<>(Node.FAIL(right));
		} else if (right.type == INT && left.type != INT) {
			Errors.inst.printError(EK_EVAL_MISMATH);
			return new Tree<>(Node.FAIL(left));
		} else if (right.type == FLOAT && left.type != FLOAT) {
			Errors.inst.printError(EK_EVAL_MISMATH);
			return new Tree<>(Node.FAIL(left));
		} else if (right.type == DICE && left.type != DICE) {
			Errors.inst.printError(EK_EVAL_MISMATH);
			return new Tree<>(Node.FAIL(left));
		}

		EvaluatorResult res = null;

		switch (op) {
		case ADD:
			if (left.type == INT) {
				res = new EvaluatorResult(INT, left.intVal + right.intVal);
			} else if (left.type == DICE) {
				if (left.diceVal.isList) {
					Errors.inst.printError(EK_EVAL_INVDICE, left.toString());
					return new Tree<>(Node.FAIL(left));
				} else if (right.diceVal.isList) {
					Errors.inst.printError(EK_EVAL_INVDICE, right.toString());
					return new Tree<>(Node.FAIL(right));
				}

				res = new EvaluatorResult(DICE, new MathDie(MathDie.MathOp.ADD, left.diceVal.scalar,
							right.diceVal.scalar));
			} else {
				res = new EvaluatorResult(FLOAT, left.floatVal + right.floatVal);
			}

			break;

		case SUBTRACT:
			if (left.type == INT) {
				res = new EvaluatorResult(INT, left.intVal - right.intVal);
			} else if (left.type == DICE) {
				if (left.diceVal.isList) {
					Errors.inst.printError(EK_EVAL_INVDICE, left.toString());
					return new Tree<>(Node.FAIL(left));
				} else if (right.diceVal.isList) {
					Errors.inst.printError(EK_EVAL_INVDICE, right.toString());
					return new Tree<>(Node.FAIL(right));
				}

				res = new EvaluatorResult(DICE, new MathDie(MathDie.MathOp.SUBTRACT,
							left.diceVal.scalar, right.diceVal.scalar));
			} else {
				res = new EvaluatorResult(FLOAT, left.floatVal - right.floatVal);
			}

			break;

		case MULTIPLY:
			if (left.type == INT) {
				res = new EvaluatorResult(INT, left.intVal * right.intVal);
			} else if (left.type == DICE) {
				if (left.diceVal.isList) {
					Errors.inst.printError(EK_EVAL_INVDICE, left.toString());
					return new Tree<>(Node.FAIL(left));
				} else if (right.diceVal.isList) {
					Errors.inst.printError(EK_EVAL_INVDICE, right.toString());
					return new Tree<>(Node.FAIL(right));
				}

				res = new EvaluatorResult(DICE, new MathDie(MathDie.MathOp.MULTIPLY,
							left.diceVal.scalar, right.diceVal.scalar));
			} else {
				res = new EvaluatorResult(FLOAT, left.floatVal * right.floatVal);
			}

			break;

		case DIVIDE:
			if (left.type == INT) {
				if (right.intVal == 0) {
					Errors.inst.printError(EK_EVAL_DIVZERO);
					res = new EvaluatorResult(FAILURE, right);
				} else {
					res = new EvaluatorResult(FLOAT, left.intVal / right.intVal);
				}
			} else if (left.type == FLOAT) {
				if (right.floatVal == 0) {
					Errors.inst.printError(EK_EVAL_DIVZERO);
					res = new EvaluatorResult(FAILURE, right);
				} else {
					res = new EvaluatorResult(FLOAT, left.floatVal / right.floatVal);
				}
			} else {
				Errors.inst.printError(EK_EVAL_DIVDICE);
				return new Tree<>(Node.FAIL());
			}

			break;

		case IDIVIDE:
			if (left.type == INT) {
				if (right.intVal == 0) {
					Errors.inst.printError(EK_EVAL_DIVZERO);
					res = new EvaluatorResult(FAILURE, right);
				} else {
					res = new EvaluatorResult(INT, (int) (left.intVal / right.intVal));
				}
			} else if (left.type == FLOAT) {
				if (right.floatVal == 0) {
					Errors.inst.printError(EK_EVAL_DIVZERO);
					res = new EvaluatorResult(FAILURE, right);
				} else {
					res = new EvaluatorResult(INT, (int) (left.floatVal / right.floatVal));
				}
			} else {
				Errors.inst.printError(EK_EVAL_DIVDICE);
				return new Tree<>(Node.FAIL());
			}

			break;

		default:
			Errors.inst.printError(EK_EVAL_UNMATH, op.toString());
			return new Tree<>(Node.FAIL());
		}

		return new Tree<>(new Node(Node.Type.RESULT, res));
	}

	/* Evaluate a token reference. */
	private ITree<Node> evaluateTokenRef(final Token tk, final Context ctx) {
		EvaluatorResult res = null;

		switch (tk.type) {
		case INT_LIT:
			res = new EvaluatorResult(INT, tk.intValue);
			break;
		case FLOAT_LIT:
			res = new EvaluatorResult(FLOAT, tk.floatValue);
			break;
		case DICE_LIT:
			res = new EvaluatorResult(DICE, tk.diceValue);
			break;
		case STRING_LIT:
			res = new EvaluatorResult(STRING, eng.getStringLiteral((int) tk.intValue));
			break;
		default:
			Errors.inst.printError(EK_EVAL_UNTOK, tk.type.toString());
			res = new EvaluatorResult(FAILURE);
		}

		return new Tree<>(new Node(Node.Type.RESULT, res));
	}
}