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

import java.util.Deque;
import java.util.InputMismatchException;
import java.util.function.Function;
import java.util.function.Predicate;

import bjc.utils.data.ITree;
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.utils.funcutils.StringUtils;
import bjc.utils.parserutils.TreeConstructor;

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;

/**
 * Parse a string expression into AST form. Doesn't do anything else
 * 
 * @author ben
 *
 */
public class DiceASTParser {
		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.");
						}
				}

				if (leafNode.matches("[+-]?\\d*\\.\\d+")) {
						throw new InputMismatchException(
										"Floating point literals are not supported");
				}

				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;
				}
		}

		/**
		 * 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(
						IList<String> tokens) {
				// Mark arrays as special operators
				Predicate<String> specialPicker = (operator) -> {
						if (StringUtils.containsOnly(operator, "\\[") ||
										StringUtils.containsOnly(operator, "\\]")) {
								return true;
										}

						return false;
				};

				// Here is the map for holding special operators
				IMap<String, Function<Deque<ITree<String>>, ITree<String>>> operators = new FunctionalMap<>();

				// Handle open [
				operators.put("[", (queuedTrees) -> {
						// Just put in a [
						Tree<String> openArray = new Tree<>("[");

						return openArray;
				});

				operators.put("]", (queuedTrees) -> {
						// Parse closing an array
						return parseCloseArray(queuedTrees);
				});

				ITree<String> rawTokens = TreeConstructor.constructTree(tokens,
								(token) -> {
										return isOperatorNode(token);
								}, specialPicker, operators::get);

				ITree<IDiceASTNode> tokenizedTree = rawTokens.rebuildTree(
								DiceASTParser::convertLeafNode,
								DiceASTParser::convertOperatorNode);

				return tokenizedTree;
						}

		private static boolean isOperatorNode(String token) {
				if (StringUtils.containsOnly(token, "\\[")) {
						return true;
				} else if (StringUtils.containsOnly(token, "\\]")) {
						return true;
				}

				if (token.equals("[]")) {
						// This is a synthetic operator, constructed by [ and ]
						return true;
				}

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

		private static ITree<String> parseCloseArray(
						Deque<ITree<String>> queuedTrees) {
				IList<ITree<String>> children = new FunctionalList<>();

				while (shouldContinuePopping(queuedTrees)) {
						children.add(queuedTrees.pop());
				}

				queuedTrees.pop();

				children.reverse();

				ITree<String> arrayTree = new Tree<>("[]", children);

				return arrayTree;
						}

		private static boolean shouldContinuePopping(
						Deque<ITree<String>> queuedTrees) {
				String peekToken = queuedTrees.peek().getHead();

				return !peekToken.equals("[");
						}
}