summaryrefslogtreecommitdiff
path: root/dice-lang/src/bjc/dicelang/v2/DiceLangEngine.java
blob: d8a43c58812362f5ecd4cef591aec39959f21497 (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
package bjc.dicelang.v2;

import bjc.utils.data.IPair;
import bjc.utils.data.Pair;
import bjc.utils.funcdata.FunctionalList;
import bjc.utils.funcdata.FunctionalMap;
import bjc.utils.funcdata.FunctionalStringTokenizer;
import bjc.utils.funcdata.IList;
import bjc.utils.funcdata.IMap;
import bjc.utils.funcutils.ListUtils;

import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.regex.Pattern;

import static bjc.dicelang.v2.Token.Type.*;

public class DiceLangEngine {
	// Input rules for processing tokens
	private Deque<IPair<String, String>> opExpansionTokens;
	private Deque<IPair<String, String>> deaffixationTokens;

	// ID for generation of string literal variables
	private int nextLiteral;

	// Debug indicator
	private boolean debugMode;

	private final int MATH_PREC = 20;
	private final int DICE_PREC = 10;
	private final int EXPR_PREC = 0;

	public DiceLangEngine() {
		opExpansionTokens = new LinkedList<>();

		opExpansionTokens.add(new Pair<>("+", "\\+"));
		opExpansionTokens.add(new Pair<>("-", "-"));
		opExpansionTokens.add(new Pair<>("*", "\\*"));
		opExpansionTokens.add(new Pair<>("//", "//"));
		opExpansionTokens.add(new Pair<>("/", "/"));
		opExpansionTokens.add(new Pair<>(":=", ":="));
		opExpansionTokens.add(new Pair<>("=>", "=>"));

		deaffixationTokens = new LinkedList<>();

		deaffixationTokens.add(new Pair<>("(", "\\("));
		deaffixationTokens.add(new Pair<>(")", "\\)"));
		deaffixationTokens.add(new Pair<>("[", "\\["));
		deaffixationTokens.add(new Pair<>("]", "\\]"));

		nextLiteral = 1;

		// @TODO make configurable
		debugMode = true;
	}

	public boolean runCommand(String command) {
		// Split the command into tokens
		IList<String> tokens = FunctionalStringTokenizer
			.fromString(command)
			.toList();

		// Will hold tokens with string literals removed
		IList<String> destringed = new FunctionalList<>();

		// Where we keep the string literals
		// @TODO put these in the sym-table early instead
		// 		 once there is a sym-table
		IMap<String, String> stringLiterals = new FunctionalMap<>();

		boolean success = destringTokens(tokens, stringLiterals,
				destringed);

		if(!success) return success;

		if(debugMode) {
			System.out.println("\tCommand after destringing: "
					+ destringed.toString());

			System.out.println("\tString literals in table");
			stringLiterals.forEach((key, val) -> {
				System.out.printf("\t\tName: (%s)\tValue: (%s)\n",
					key, val);
			});
		}

		IList<String> semiExpandedTokens = 
			ListUtils.deAffixTokens(
					destringed, deaffixationTokens);

		IList<String> fullyExpandedTokens = 
			ListUtils.splitTokens(
					semiExpandedTokens, opExpansionTokens);

		if(debugMode)
			System.out.printf("\tCommand after token"
					+ " expansion: " 
					+ fullyExpandedTokens.toString()
					+ "\n");

		IList<Token> lexedTokens = new FunctionalList<>();

		for(String token : fullyExpandedTokens.toIterable()) {
			Token tk = lexToken(token);

			if(tk == null) continue;
			else if(tk == Token.NIL_TOKEN) return false;
			else lexedTokens.add(tk);
		}

		if(debugMode)
			System.out.printf("\tCommand after tokenization: %s\n", lexedTokens.toString());

		return true;
	}

	private Token lexToken(String token) {
		if(token.equals("")) return null;

		Token tk = Token.NIL_TOKEN;

		switch(token) {
			case "+":
				tk = new Token(ADD);
				break;
			case "-":
				tk = new Token(SUBTRACT);
				break;
			case "*":
				tk = new Token(MULTIPLY);
				break;
			case "/":
				tk = new Token(DIVIDE);
				break;
			case "//":
				tk = new Token(IDIVIDE);
				break;
			case "(":
				tk = new Token(OPAREN);
				break;
			case ")":
				tk = new Token(CPAREN);
				break;
			case "[":
				tk = new Token(OBRACKET);
				break;
			case "]":
				tk = new Token(CBRACKET);
				break;
			default:

				tk = tokenizeLiteral(token);
		}

		return tk;
	}

	private Pattern intMatcher = Pattern.compile(
			"[\\-\\+]?\\d+");

	private Token tokenizeLiteral(String token) {
		Token tk = Token.NIL_TOKEN;

		if(DoubleMatcher.floatingLiteral.matcher(token).matches()) {
			tk = new Token(FLOAT_LIT, Double.parseDouble(token));
		} else if(intMatcher.matcher(token).matches()) {
			tk = new Token(INT_LIT, Integer.parseInt(token));
		} else if(DiceBox.isValidExpression(token)) {
			tk = new Token(DICE_LIT, DiceBox.parseExpression(token));
		} else {
			System.out.printf("\tERROR: Unrecognized token:"
					+ "%s\n", token);

			return tk;
		}

		return tk;
	}

	private boolean destringTokens(IList<String> tokens,
			IMap<String, String> stringLiterals,
			IList<String> destringed) {
		// Are we parsing a string literal?
		boolean stringMode = false;

		// The current string literal
		StringBuilder currentLiteral = new StringBuilder();
		String literalName = "stringLiteral";

		for(String token : tokens.toIterable()) {
			if(token.startsWith("\"")) {
				if(token.endsWith("\"")) {
					String litName = literalName + nextLiteral++;

					stringLiterals.put(litName,
							token.substring(1, token.length() - 1));
					destringed.add(litName);

					continue;
				}

				if(stringMode) {
					// @TODO make this not an error
					System.out.printf("\tPARSER ERROR: Initial" 
							+" quotes can only start strings\n");
				} else {
					currentLiteral.append(token.substring(1) + " ");

					stringMode = true;
				}
			} else if (token.endsWith("\"")) {
				if(!stringMode) {
					// @TODO make this not an error
					System.out.printf("\tPARSER ERROR: Terminal" 
							+" quotes can only end strings\n"); 
					return false;
				} else {
					currentLiteral.append(
							token.substring(0, token.length() - 1));

					String litName = literalName + nextLiteral++;

					stringLiterals.put(litName,
							currentLiteral.toString());
					destringed.add(litName);

					currentLiteral = new StringBuilder();

					stringMode = false;
				}
			} else if (token.contains("\"")) {
				if(token.contains("\\\"")) {
					if(stringMode) {
						currentLiteral.append(token + " ");
					} else {
						System.out.printf("\tERROR: Escaped quote "
								+ " outside of string literal\n");
						return false;
					}
				} else {
					// @TODO make this not an error
					System.out.printf("\tPARSER ERROR: A string"
							+ " literal must be delimited by spaces"
							+ " for now.\n");
					return false;
				}
			} else {
				if(stringMode) {
					currentLiteral.append(token + " ");
				} else {
					destringed.add(token);
				}
			}
		}

		if(stringMode) {
			System.out.printf("\tERROR: Unclosed string literal (%s"
					+ ").\n", currentLiteral.toString());

			return false;
		}

		return true;
	}
}