summaryrefslogtreecommitdiff
path: root/dice-lang/src/main/java/bjc/dicelang/ast/DiceASTParser.java
blob: 95495bda43b7a3cdb155d259a13eb3161a2b6901 (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
package bjc.dicelang.ast;

import java.util.InputMismatchException;

import bjc.dicelang.IDiceExpression;
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;
import bjc.utils.funcdata.IFunctionalList;
import bjc.utils.funcdata.ITree;
import bjc.utils.parserutils.TreeConstructor;

/**
 * Parse a string expression into AST form. Doesn't do anything else
 * 
 * @author ben
 *
 */
public class DiceASTParser {
	/**
	 * Create an AST from a list of tokens
	 * 
	 * @param tokens
	 *            The list of tokens to convert
	 * @return An AST built from the tokens
	 */
	public static ITree<IDiceASTNode> createFromString(
			IFunctionalList<String> tokens) {
		ITree<String> rawTokens = TreeConstructor.constructTree(tokens,
				(token) -> {
					return isOperatorNode(token);
				}, (operator) -> false, null);
		// The last argument is valid because there are no special
		// operators yet, so it'll never get called

		return rawTokens.rebuildTree(DiceASTParser::convertLeafNode,
				DiceASTParser::convertOperatorNode);
	}

	private static boolean isOperatorNode(String token) {
		try {
			OperatorDiceNode.fromString(token);
			return true;
		} catch (@SuppressWarnings("unused") IllegalArgumentException iaex) {
			// We don't care about details
			return false;
		}
	}

	private static IDiceASTNode convertLeafNode(String leafNode) {
		DiceLiteralType literalType = ILiteralDiceNode
				.getLiteralType(leafNode);

		if (literalType != null) {
			switch (literalType) {
				case DICE:
					return new DiceLiteralNode(
							IDiceExpression.toExpression(leafNode));
				case INTEGER:
					return new IntegerLiteralNode(
							Integer.parseInt(leafNode));
				default:
					throw new InputMismatchException(
							"Cannot convert string '" + leafNode
									+ "' into a literal.");
			}
		}

		return new VariableDiceNode(leafNode);
	}

	private static IDiceASTNode convertOperatorNode(String operatorNode) {
		try {
			return OperatorDiceNode.fromString(operatorNode);
		} catch (IllegalArgumentException iaex) {
			InputMismatchException imex = new InputMismatchException(
					"Attempted to parse invalid operator " + operatorNode);

			imex.initCause(iaex);

			throw imex;
		}
	}
}