-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreproc.htm
596 lines (562 loc) · 18.7 KB
/
preproc.htm
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
<html>
<body>
<script language="javascript"><!--
var randomInteger = randomInteger || function(x){
return Math.floor(Math.random() * x) + 1;
};
BINARY_PRECEDENCE = {
'?': 1, ':': 2,
'||': 3, '&&': 4,
'|': 5, '^': 6, '&': 7,
'=': 8, '!=': 8,
'>=': 9, '>': 9, '<': 9, '<=': 9,
'<<': 10, '>>': 10,
'+': 11, '-': 11,
'*': 12, '/': 12, '%': 12,
'**': 14,
't': 98, 'd': 99
};
UNARY_PRECEDENCE = {'!': 13, '~': 13, '-': 13};
BINARY_FUNCTIONS = {
'||': function(x, y){ return x || y; },
'&&': function(x, y){ return x && y; },
'|': function(x, y){ return x | y; },
'^': function(x, y){ return x ^ y; },
'&': function(x, y){ return x & y; },
'=': function(x, y){ return x == y; },
'!=': function(x, y){ return x != y; },
'>=': function(x, y){ return x >= y; },
'>': function(x, y){ return x > y; },
'<': function(x, y){ return x < y; },
'<=': function(x, y){ return x <= y; },
'<<': function(x, y){ return x << y; },
'>>': function(x, y){ return x >> y; },
'+': function(x, y){ return x + y; },
'-': function(x, y){ return x - y; },
'*': function(x, y){ return x * y; },
'/': function(x, y){ return x / y; },
'%': function(x, y){ return x % y; },
'**': Math.pow,
'd': function(x, y){
var retval = 0;
for (var i = 0; i < x; i++){ retval += randomInteger(y); }
return retval;
}
};
UNARY_FUNCTIONS = {
'!': function(x){ return !x; },
'~': function(x){ return ~x; },
'-': function(x){ return -x; }
};
CLOSERS = {'(': ")", '{': "}"};
function getToken(s){
if (!s){ return s; }
var m;
function retVal(tokType, matchObj){
return {'type': tokType, 'text': matchObj[0], 'match': matchObj};
}
m = s.match(/^\s+/);
if (m){ return retVal("whitespace", m); }
m = s.match(/^[({]/);
if (m){ return retVal("opengroup", m); }
m = s.match(/^[)}]/);
if (m){ return retVal("closegroup", m); }
m = s.match(/^((\d+(\.\d+)?)|(\.\d+))/);
if (m){ return retVal("number", m); }
m = s.match(/^['"]/);
if (m){ return retVal("quote", m); }
m = s.match(/^((\|\|)|(&&)|(!=)|(>=)|(<=)|(<<)|(>>)|(\*\*)|[?:|^&=><%!~])/);
if (m){ return retVal("extoperator", m); }
m = s.match(/^[-+*/td]/);
if (m){ return retVal("baseoperator", m); }
m = s.match(/^\[([^\]]+)\]/);
if (m){ return retVal("label", m); }
m = s.match(/^\${([^'"($}][^}]*)}/);
if (m){ return retVal("variable", m); }
m = s.match(/^\${/);
if (m){ return retVal("openvariable", m); }
return {'type': "raw", 'text': s.charAt(0)};
}
function popToken(state){
state.tok = getToken(state.s);
if (state.tok){ state.s = state.s.substring(state.tok.text.length); }
return state;
}
function popString(state, delim){
var i = -1, j = i;
while (((i - j) & 1) == 0){
i = state.s.indexOf(delim, i + 1);
if (i < 0){ return; }
j = i - 1;
while ((j >= 0) && (state.s.charAt(j) == '\\')){ j--; }
}
function replaceEscapes(s){
return s.replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\t/g, "\t").replace(/\\/g, "");
}
var retval = state.s.substring(0, i).split("\\\\").map(replaceEscapes).join("\\");
state.s = state.s.substring(i);
popToken(state);
return retval;
}
function parseExpression(s, until){
if (typeof(s) == typeof("")){ s = {'s': s}; }
var operators = [{'precedence': 0}], operands = [];
function popOperator(){
var op = operators.pop();
var right = operands.pop();
if (op.unary){
operands.push({'type': (op.type == "baseoperator" ? "unop" : "unopex"),
'datatype': right.datatype,
'operator': op.text, 'operand': right});
return;
}
var left = operands.pop();
if (op.text != ":"){
var datatype;
if ((op.text == "d") || (op.text == "t")){ datatype = "number"; }
else if (left.datatype == right.datatype){ datatype = left.datatype; }
else if ((left.datatype == "string") || (right.datatype == "string")){ datatype = "string"; }
operands.push({'type': (op.type == "baseoperator" ? "binop" : "binopex"),
'datatype': datatype,
'operator': op.text, 'left': left, 'right': right,
'mods': op.mods, 'label': op.label});
return;
}
op = operators.pop();
if (op.text != "?"){ return "Error: Expected ? but got " + op.text; }
var cond = operands.pop();
operands.push({'type': "cond", 'cond': cond, 'left': left, 'right': right,
'datatype': (left.datatype == right.datatype ? left.datatype : undefined)});
}
function pushOperator(op){
var err;
op.precedence = (op.unary ? UNARY_PRECEDENCE[op.text] : BINARY_PRECEDENCE[op.text]) || 0;
while (operators[operators.length - 1].precedence >= op.precedence){
err = popOperator();
if (err){ return err; }
}
operators.push(op);
}
function parseHelper(){
var err;
popToken(s);
if (!s.tok){ return "Error: Unrecognized token: " + s.s.split(" ", 1)[0]; }
while (s.tok.type == "whitespace"){
popToken(s);
if (!s.tok){ return "Error: Unrecognized token: " + s.s.split(" ", 1)[0]; }
}
switch (s.tok.type){
case "number":
operands.push({'type': "number", 'datatype': "number", 'value': parseFloat(s.tok.text)});
return;
case "variable":
operands.push({'type': "variable", 'value': s.tok.match[1]});
return;
case "quote":
var str = popString(s, s.tok.text);
if (typeof(str) != typeof("")){
return "Error: Unterminated string";
}
operands.push({'type': "string", 'datatype': "string", 'value': str});
return;
case "opengroup":
var opener = s.tok.text, closer = CLOSERS[opener];
operands.push(parseExpression(s, closer));
if (s.tok.text != closer){
return "Error: Expected '" + closer + "' to close '" + opener + "', but got '" + s.tok.text + "'";
}
return;
case "openvariable":
var varExp = parseExpression(s, "}");
if (s.tok.text != "}"){
return "Error: Expected '}' to close '${', but got '" + s.tok.text + "'";
}
operands.push({'type': "variable", 'value': varExp});
return;
case "extoperator":
case "baseoperator":
if (!UNARY_PRECEDENCE[s.tok.text]){ return "Error: " + s.tok.text + " is not a unary operator"; }
s.tok.unary = true;
err = pushOperator(s.tok);
if (err){ return err; }
return parseHelper();
}
return "Error: Unrecognized token: " + s.tok.text;
}
var err = parseHelper();
if (err){ return err; }
for (popToken(s); (s.tok) && (s.tok.text != until); popToken(s)){
switch(s.tok.type){
case "extoperator":
case "baseoperator":
rollOperator = (s.tok.text == "d" ? s.tok : null);
err = pushOperator(s.tok);
if (err){ return err; }
if ((rollOperator) && (s.s.charAt(0) == 'F')){
operands.push({'type': "rollspec", 'value': "F"})
s.s = s.s.substring(1);
}
else if (s.tok.text == "t"){
if (s.s.charAt(0) != '['){ return "Error: 't' operator requires '[table]' argument"; }
var m = s.s.match(/^\[([^'"$(\]][^\]]*)\]/);
var tableExp;
if (m){
tableExp = m[1];
s.s = s.s.substring(m[0].length);
}
else{
s.s = s.s.substring(1);
tableExp = parseExpression(s, "]");
if (s.tok.text != "]"){
return "Error: Expected ']' to close 't[', but got '" + s.tok.text + "'";
}
}
operands.push({'type': "tablename", 'value': tableExp});
}
else{
err = parseHelper();
if (err){ return err; }
}
if (rollOperator){
var m = s.s.match(/^[acdfhkloprs0-9<=>!]+/);
if (m){
rollOperator.mods = m[0];
s.s = s.s.substring(m[0].length)
}
}
break;
case "label":
if ((operators.length > 0) && (operators[operators.length - 1].text == "d")){
// set label on "d" operator instead of operand (e.g. "1d6[foo]" is "(1d6)[foo]", not "1d(6[foo])")
operators[operators.length - 1].label = s.tok.match[1];
break;
}
var operand = operands.pop();
if (operand){
operand.label = s.tok.match[1];
operands.push(operand);
}
break;
}
}
while (operators.length > 1){
err = popOperator();
if (err){ return err; }
}
return operands.pop();
}
function buildCommand(chunks, asts, evalResults){
var labels = {}, references = {}, unevalRefs = [], evalReqs = [];
// substitute in results of base evaluation
for (var i = 0; i < evalResults.length; i++){
var t = evalResults[i][0];
delete t.operator;
delete t.left;
delete t.right;
t.type = "number";
t.datatype = "number";
t.value = evalResults[i][1];
t.baseValid = true;
}
function lazyEval(t, labels, references, unevalRefs, evalReqs, force){
var x, y;
if (t.label){ labels[t.label] = t; }
switch(t.type){
case "number":
case "rollspec":
t.baseValid = true;
// fall through
case "string":
return t;
case "tablename":
if (typeof(t.value) != typeof("")){
x = lazyEval(t.value, labels, references, unevalRefs, evalReqs, true);
if (typeof(x) == typeof("")){ return x; } // error
if (x.type == "number"){
// number node; coerce to string
x.value = "" + x.value;
x.type = "string"
}
if (x.type != "string"){
// unable to fully evaluate table name
if (t.baseValid){ t.baseValid = false; }
unevalRefs.push(t.value);
return t;
}
// successfully evaluated table name
t.value = x.value;
}
// if we got here, t.value is the name of a rollable table
t.baseValid = true;
return t;
case "unop":
case "unopex":
force = force || (t.type != "unop");
x = lazyEval(t.operand, labels, references, unevalRefs, evalReqs, force);
if (typeof(x) == typeof("")){ return x; } // error
if (force){
if (x.type != "number"){
// unable to fully evaluate operand
if (t.baseValid){ t.baseValid = false; }
return t;
}
// successfully evaluated operand
t.type = "number";
t.datatype = "number";
t.value = UNARY_FUNCTIONS[t.operator](x.value);
delete t.operator;
if (t.operand.label){ labels[t.operand.label] = x; }
delete t.operand;
t.baseValid = true;
}
else{ t.baseValid = x.baseValid; }
return t;
case "binop":
case "binopex":
force = force || (t.type != "binop") || (t.left.datatype == "string") || (t.right.datatype == "string");
var forceSubtrees = force || (t.operator == "d") || (t.operator == "t");
x = lazyEval(t.left, labels, references, unevalRefs, evalReqs, forceSubtrees);
if (typeof(x) == typeof("")){ return x; } // error
y = lazyEval(t.right, labels, references, unevalRefs, evalReqs, forceSubtrees);
if (typeof(y) == typeof("")){ return y; } // error
if (force){
if ((x.type != "number") && (x.type != "string")){
// unable to fully evaluate left operand
if (t.baseValid){ t.baseValid = false; }
return t;
}
if ((y.type != "number") && (y.type != "string") && (y.type != "rollspec") && (y.type != "tablename")){
// unable to fully evaluate right operand
if (t.baseValid){ t.baseValid = false; }
return t;
}
if ((y.type == "rollspec") && (t.operator != "d")){
return "Rollspec operand is only compatible with 'd' operator";
}
if ((t.operator == "t") && (y.type != "tablename")){
return "'t' operator requires tablename operand";
}
// successfully evaluated both operands
if ((t.operator == "t") || ((t.operator == "d") && (t.mods))){
// operator is rollable table or is roll with mods; must submit to base system for evaluation
evalReqs.push(t);
return t;
}
t.value = BINARY_FUNCTIONS[t.operator](x.value, y.value);
delete t.operator;
if (t.left.label){ labels[t.left.label] = x; }
delete t.left;
if (t.right.label){ labels[t.right.label] = y; }
delete t.right;
t.type = (typeof(t.value) == typeof("") ? "string" : "number");
t.datatype = t.type;
t.baseValid = (t.datatype == "number");
}
else if ((x.datatype == "number") && (y.datatype == "number")){
t.datatype = "number";
t.baseValid = true;
}
return t;
case "cond":
x = lazyEval(t.cond, labels, references, unevalRefs, evalReqs, true);
if (typeof(x) == typeof("")){ return x; } // error
if ((x.type != "number") && (x.type != "string")){
// unable to fully evaluate condition
t.baseValid = false;
return t;
}
// successfully evaluated condition; replace t with t.left or t.right as appropriate
y = (x.value ? t.left : t.right);
if (t.cond.label){ labels[t.cond.label] = x; }
delete t.cond;
delete t.left;
delete t.right;
for (var k in y){
t[k] = y[k];
}
return lazyEval(t, labels, references, unevalRefs, evalReqs, force);
case "variable":
if (typeof(t.value) != typeof("")){
x = lazyEval(t.value, labels, references, unevalRefs, evalReqs, true);
if (typeof(x) == typeof("")){ return x; } // error
if (x.type == "number"){
// number node; coerce to string
x.value = "" + x.value;
x.type = "string"
}
if (x.type != "string"){
// unable to fully evaluate variable name
if (t.baseValid){ t.baseValid = false; }
unevalRefs.push(t.value);
return t;
}
// successfully evaluated variable name
t.value = x.value;
}
// if we got here, t.value is the name of a variable
if ((labels[t.value]) && ((labels[t.value].type == "string") || (labels[t.value].type == "number"))){
// variable exists and has been fully evaluated
t.type = labels[t.value].type;
t.datatype = labels[t.value].datatype;
t.baseValid = labels[t.value].baseValid;
t.value = labels[t.value].value;
}
else{
// variable not yet defined or not yet fully evaluated
if (!references[t.value]){ references[t.value] = []; }
references[t.value].push(t);
if (t.baseValid){ t.baseValid = false; }
}
return t;
default:
return "Unknown node type: " + t.type;
}
}
// traverse ASTs, collapsing as much as possible
for (var i = 0; i < asts.length; i++){
if (asts[i].baseValid){ continue; } // can be handled by base expression evaluator
if ((asts[i].type == "string") || (asts[i].type == "number")){ continue; } // tree is fully evaluated
var err = lazyEval(asts[i], labels, references, unevalRefs, evalReqs, false);
if (typeof(err) == typeof("")){ return err; }
}
// do variable substitution; repeat until we don't make any more progress
var doSubstitution = true;
while (doSubstitution){
doSubstitution = false;
// substitute in values for variables for which we already have names
for (var label in references){
if (!labels[label]){
return "Variable '" + label + "' not defined";
}
if ((labels[label].type != "string") && (labels[label].type != "number")){
// variable exists but not yet evaluated; try to evaluate
var err = lazyEval(labels[label], labels, references, unevalRefs, evalReqs, true);
if (typeof(err) == typeof("")){ return err; }
}
if ((labels[label].type == "string") || (labels[label].type == "number")){
// variable fully evaluated; substitute it in
for (var i = 0; i < references[label].length; i++){
references[label][i].type = labels[label].type;
references[label][i].datatype = labels[label].datatype;
references[label][i].value = labels[label].value;
references[label][i].baseValid = labels[label].baseValid;
}
delete references[label];
doSubstitution = true;
}
}
// try to get names for variables and tables with unevaluated names
var newUneval = [];
while (unevalRefs.length > 0){
var r = lazyEval(unevalRefs.shift(), labels, references, unevalRefs, evalReqs, true);
if (typeof(r) == typeof("")){ return err; }
if ((r.type == "string") || (r.type == "number")){ doSubstitution = true; }
else{ newUneval.push(r); }
}
unevalRefs = newUneval;
}
function hasUnevaluatedLabels(t){
// base types: fully evaluated
if ((t.type == "number") || (t.type == "string") || (t.type == "rollspec")){ return false; }
// if we got here, node is unevaluated
if (t.label){ return true; }
// node has no label; check children
switch(t.type){
case "tablename":
case "variable":
if (typeof(t.value) == typeof("")){ return false; }
return hasUnevaluatedLabels(t.value);
case "unop":
case "unopex":
return hasUnevaluatedLabels(t.operand);
case "cond":
if (hasUnevaluatedLabels(t.cond)){ return true; }
// fall through
case "binop":
case "binopex":
if (hasUnevaluatedLabels(t.left)){ return true; }
return hasUnevaluatedLabels(t.right);
}
}
function flattenAST(t){
var retval;
switch(t.type){
case "number":
case "rollspec":
retval = t.value;
break;
case "tablename":
retval = "[" + t.value + "]";
break;
case "unop":
retval = "(" + t.operator + flattenAST(t.operand) + ")";
break;
case "binop":
retval = "(" + flattenAST(t.left) + t.operator + flattenAST(t.right) + (t.mods || "") + ")";
if ((t.label) && (t.operator == "d")){ retval += "[" + t.label + "]"; }
break;
default:
return "Unknown node type: " + t.type;
}
return retval;
}
function astToInline(t){
if (t.type == "string"){ return t.value; }
return "[[" + flattenAST(t) + "]]";
}
// flatten fully evaluated ASTs into strings and splice into chunks
for (var i = asts.length - 1; i >= 0; i--){
if ((!asts[i].baseValid) && (asts[i].type != "number") && (asts[i].type != "string")){ continue; }
if ((unevalRefs.length > 0) & (hasUnevaluatedLabels(asts[i]))){ continue; }
chunks.splice(i, 2, (chunks[i] || "") + astToInline(asts.splice(i, 1)[0]) + (chunks[i + 1] || ""));
}
if (evalReqs.length > 0){
// need to submit some expressions to the base evaluator; recurse via sendChat callback
var cmd = evalReqs.map(astToInline).join(" ");
var callback = function(msg){
var evalResults = [];
for (var i = 0; i < evalReqs.length; i++){
evalResults.push([evalReqs[i], msg.inlinerolls[i].results.total]);
}
buildCommand(chunks, asts, evalResults);
};
/////
//
//sendChat(speakingAs, cmd, callback);
return "<recursing with command "+cmd+">";
//
/////
}
if (asts.length > 0){
// need to finish evaluating some ASTs; recurse directly
return buildCommand(chunks, asts, [])
}
// if we got here, we're done evaluating everything; submit results via sendChat
/////
//
//sendChat(speakingAs, chunks.join(""));
return chunks.join("[[<incomplete>>]]");
//
/////
}
function processInput(){
var inBox = document.getElementById("inbox");
var outBox = document.getElementById("outbox");
var chunks = [];
var asts = [];
var s = {'s': inBox.value};
for (var i = s.s.indexOf('`'); i >= 0; i = s.s.indexOf('`')){
chunks.push(s.s.substring(0, i));
s.s = s.s.substring(i + 1);
asts.push(parseExpression(s, '`'));
}
chunks.push(s.s);
var output = buildCommand(chunks, asts, []);
outBox.value = output;
}
//--></script>
<input id="inbox">
<input type="button" onClick="processInput()" value="Do It"><br>
<textarea id="outbox"></textarea>
</body>
</html>