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
|
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 bjc.utils.funcutils.StringUtils;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Deque;
import java.util.List;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static bjc.dicelang.v2.Token.Type.*;
public class DiceLangEngine {
// Input rules for processing tokens
private List<IPair<String, String>> opExpansionList;
private List<IPair<String, String>> deaffixationList;
// ID for generation
private int nextLiteral;
private int nextSym;
// Debug indicator
private boolean debugMode;
// Should we do shunting?
private boolean postfixMode;
// Shunter for token postfixing
private Shunter shunt;
// Tables for symbols
private IMap<Integer, String> symTable;
private IMap<Integer, String> stringLits;
// Literal tokens for tokenization
private IMap<String, Token.Type> litTokens;
// Lists for preprocessing
private IList<Define> lineDefns;
private IList<Define> tokenDefns;
// Are defns sorted by priority
private boolean defnsSorted;
private StreamEngine streamEng;
private final int MATH_PREC = 20;
private final int DICE_PREC = 10;
private final int EXPR_PREC = 0;
public DiceLangEngine() {
lineDefns = new FunctionalList<>();
tokenDefns = new FunctionalList<>();
defnsSorted = true;
symTable = new FunctionalMap<>();
stringLits = new FunctionalMap<>();
opExpansionList = new LinkedList<>();
opExpansionList.add(new Pair<>("+", "\\+"));
opExpansionList.add(new Pair<>("-", "-"));
opExpansionList.add(new Pair<>("*", "\\*"));
opExpansionList.add(new Pair<>("//", "//"));
opExpansionList.add(new Pair<>("/", "/"));
opExpansionList.add(new Pair<>(":=", ":="));
opExpansionList.add(new Pair<>("=>", "=>"));
deaffixationList = new LinkedList<>();
deaffixationList.add(new Pair<>("(", "\\("));
deaffixationList.add(new Pair<>(")", "\\)"));
deaffixationList.add(new Pair<>("[", "\\["));
deaffixationList.add(new Pair<>("]", "\\]"));
litTokens = new FunctionalMap<>();
litTokens.put("+", ADD);
litTokens.put("-", SUBTRACT);
litTokens.put("*", MULTIPLY);
litTokens.put("/", DIVIDE);
litTokens.put("//", IDIVIDE);
litTokens.put("dg", DICEGROUP);
litTokens.put("dc", DICECONCAT);
litTokens.put("dl", DICELIST);
litTokens.put("=>", LET);
litTokens.put(":=", BIND);
shunt = new Shunter();
nextLiteral = 1;
debugMode = true;
postfixMode = false;
streamEng = new StreamEngine(this);
}
public void sortDefns() {
Comparator<Define> defnCmp = (dfn1, dfn2) -> dfn1.priority - dfn2.priority;
lineDefns.sort(defnCmp);
tokenDefns.sort(defnCmp);
defnsSorted = true;
}
public void addLineDefine(Define dfn) {
lineDefns.add(dfn);
defnsSorted = false;
}
public void addTokenDefine(Define dfn) {
tokenDefns.add(dfn);
defnsSorted = false;
}
public boolean toggleDebug() {
debugMode = !debugMode;
return debugMode;
}
public boolean togglePostfix() {
postfixMode = !postfixMode;
return postfixMode;
}
/*
* Matches quote-delimited strings
* (like "text" or "text\"text")
* Uses the "normal* (special normal*)*" pattern style
* recommended in 'Mastering regular expressions'
* Here, the normal is 'anything but a forward or backslash'
* (in regex, thats '[^\""]') and the special is 'an escaped forward slash'
* (in regex, thats '\\"')
*
* Then, we just follow the pattern, escape it for java strings, and
* add the enclosing quotes
*/
private Pattern quotePattern = Pattern.compile("\"([^\\\"]*(?:\\\"/(?:[^\\\"])*)*)\"");
public boolean runCommand(String command) {
// Sort the defines if they aren't sorted
if(!defnsSorted) sortDefns();
IList<String> streamToks = new FunctionalList<>();
boolean success = streamEng.doStreams(command.split(" "), streamToks);
if(!success) return false;
String newComm = ListUtils.collapseTokens(streamToks, " ");
if(debugMode)
System.out.println("\tCommand after stream commands: " + newComm);
for(Define dfn : lineDefns.toIterable()) {
newComm = dfn.apply(newComm);
}
if(debugMode)
System.out.println("\tCommand after line defines: " + newComm);
IMap<String, String> stringLiterals = new FunctionalMap<>();
Matcher quoteMatcher = quotePattern.matcher(newComm);
StringBuffer destringedCommand = new StringBuffer();
while(quoteMatcher.find()) {
String stringLit = quoteMatcher.group(1);
String litName = "stringLiteral" + nextLiteral++;
stringLiterals.put(litName, stringLit);
quoteMatcher.appendReplacement(destringedCommand, " " + litName + " ");
}
quoteMatcher.appendTail(destringedCommand);
// Split the command into tokens
IList<String> tokens = FunctionalStringTokenizer
.fromString(destringedCommand.toString())
.toList();
if(debugMode) {
System.out.println("\tCommand after destringing: " + tokens.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 = deaffixTokens(tokens, deaffixationList);
IList<String> fullyExpandedTokens = deaffixTokens(semiExpandedTokens, opExpansionList);
if(debugMode)
System.out.printf("\tCommand after token expansion: "
+ fullyExpandedTokens.toString() + "\n");
IList<Token> lexedTokens = new FunctionalList<>();
for(String token : fullyExpandedTokens.toIterable()) {
String newTok = token;
for(Define dfn : tokenDefns.toIterable()) {
newTok = dfn.apply(newTok);
}
Token tk = lexToken(token, stringLiterals);
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());
IList<Token> shuntedTokens = lexedTokens;
if(!postfixMode) {
shuntedTokens = new FunctionalList<>();
success = shunt.shuntTokens(lexedTokens, shuntedTokens);
if(!success) return false;
}
if(debugMode && !postfixMode)
System.out.printf("\tCommand after shunting: %s\n", shuntedTokens.toString());
return true;
}
private Token lexToken(String token, IMap<String, String> stringLts) {
if(token.equals("")) return null;
Token tk = Token.NIL_TOKEN;
if(litTokens.containsKey(token)) {
tk = new Token(litTokens.get(token));
} else {
switch(token) {
case "(":
case ")":
case "[":
case "]":
tk = tokenizeGrouping(token);
break;
default:
tk = tokenizeLiteral(token, stringLts);
}
}
return tk;
}
private Token tokenizeGrouping(String token) {
Token tk = Token.NIL_TOKEN;
if(StringUtils.containsOnly(token, "\\" + token.charAt(0))) {
switch(token) {
case "(":
tk = new Token(OPAREN, token.length());
break;
case ")":
tk = new Token(CPAREN, token.length());
break;
case "[":
tk = new Token(OBRACKET, token.length());
break;
case "]":
tk = new Token(CBRACKET, token.length());
break;
}
}
return tk;
}
private Pattern intMatcher = Pattern.compile("\\A[\\-\\+]?\\d+\\Z");
private Pattern hexadecimalMatcher = Pattern.compile("\\A[\\-\\+]?0x[0-9A-Fa-f]+\\Z");
private Pattern flexadecimalMatcher = Pattern.compile("\\A[\\-\\+]?[0-9][0-9A-Za-z]+B\\d{1,2}\\Z");
private Pattern stringLitMatcher = Pattern.compile("\\AstringLiteral(\\d+)\\Z");
private Token tokenizeLiteral(String token, IMap<String, String> stringLts) {
Token tk = Token.NIL_TOKEN;
if(intMatcher.matcher(token).matches()) {
tk = new Token(INT_LIT, Long.parseLong(token));
} else if(hexadecimalMatcher.matcher(token).matches()) {
String newToken = token.substring(0, 1) + token.substring(token.indexOf('x'));
tk = new Token(INT_LIT, Long.parseLong(newToken.substring(2).toUpperCase(), 16));
} else if(flexadecimalMatcher.matcher(token).matches()) {
tk = new Token(INT_LIT, Long.parseLong(token.substring(0, token.lastIndexOf('B')),
Integer.parseInt(token.substring(token.lastIndexOf('B') + 1))));
} else if(DoubleMatcher.floatingLiteral.matcher(token).matches()) {
tk = new Token(FLOAT_LIT, Double.parseDouble(token));
} else if(DiceBox.isValidExpression(token)) {
tk = new Token(DICE_LIT, DiceBox.parseExpression(token));
if(debugMode)
System.out.println("\tDEBUG: Parsed dice expression"
+ ", evaluated as: "
+ tk.diceValue.value());
} else {
Matcher stringLit = stringLitMatcher.matcher(token);
if(stringLit.matches()) {
int litNum = Integer.parseInt(stringLit.group(1));
stringLits.put(litNum, stringLts.get(token));
tk = new Token(STRING_LIT, litNum);
} else {
// @TODO define what a valid identifier is
symTable.put(nextSym++, token);
tk = new Token(VREF, nextSym - 1);
}
// @TODO uncomment when we have a defn. for var names
// System.out.printf("\tERROR: Unrecognized token:"
// + "%s\n", token);
}
return tk;
}
private IList<String> deaffixTokens(IList<String> tokens, List<IPair<String, String>> deaffixTokens) {
Deque<String> working = new LinkedList<>();
for(String tk : tokens.toIterable()) {
working.add(tk);
}
for(IPair<String, String> op : deaffixTokens) {
Deque<String> newWorking = new LinkedList<>();
String opName = op.getLeft();
String opRegex = op.getRight();
Pattern opRegexPattern = Pattern.compile(opRegex);
Pattern opRegexOnly = Pattern.compile("\\A(?:" + opRegex + ")+\\Z");
Pattern opRegexStarting = Pattern.compile("\\A" + opRegex);
Pattern opRegexEnding = Pattern.compile(opRegex + "\\Z");
for(String tk : working) {
// @Incomplete
if(opRegexOnly.matcher(tk).matches()) {
// The string contains only the operator
newWorking.add(tk);
} else {
Matcher medianMatcher = opRegexPattern.matcher(tk);
// Read the first match
boolean found = medianMatcher.find();
if(!found) {
newWorking.add(tk);
continue;
}
Matcher startMatcher = opRegexStarting.matcher(tk);
Matcher endMatcher = opRegexEnding.matcher(tk);
boolean startsWith = startMatcher.find();
boolean endsWith = endMatcher.find();
boolean doSplit = medianMatcher.find();
medianMatcher.reset();
if(doSplit || (!startsWith && !endsWith)) {
String[] pieces = opRegexPattern.split(tk);
if(startsWith) {
// Skip the starting operator
medianMatcher.find();
newWorking.add(tk.substring(0, startMatcher.end()));
}
for(int i = 0; i < pieces.length; i++) {
String piece = pieces[i];
// Find the next operator
boolean didFind = medianMatcher.find();
if(piece.equals("")) {
System.out.printf("\tWARNING: Empty token found during operator expansion"
+ "of token (%s). Weirdness may happen as a result\n", tk);
continue;
}
newWorking.add(piece);
if(didFind)
newWorking.add(tk.substring(medianMatcher.start(), medianMatcher.end()));
}
if(endsWith)
newWorking.add(tk.substring(endMatcher.start()));
} else if(startsWith && endsWith) {
newWorking.add(tk.substring(0, startMatcher.end()));
newWorking.add(tk.substring(startMatcher.end(), endMatcher.start()));
newWorking.add(tk.substring(endMatcher.start()));
} else if(startsWith) {
newWorking.add(tk.substring(0, startMatcher.end()));
newWorking.add(tk.substring(startMatcher.end()));
} else if(endsWith) {
newWorking.add(tk.substring(0, endMatcher.start()));
newWorking.add(tk.substring(endMatcher.end()));
} else {
newWorking.add(tk);
}
}
}
working = newWorking;
}
IList<String> returned = new FunctionalList<>();
for(String ent : working) {
returned.add(ent);
}
return returned;
}
}
|