-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcore.js
1484 lines (1379 loc) · 49.1 KB
/
core.js
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const seedrandom = require('seedrandom');
function rand(min, max) {
return min + Math.random() * (max - min);
}
function choice(l) {
const index = Math.floor(Math.random() * l.length);
return l[index];
}
function randomChar(min, max) {
min = min.charCodeAt(0);
max = max.charCodeAt(0);
charCode = Math.round(rand(min, max));
return String.fromCharCode(charCode);
}
String.prototype.toTitleCase = function() {
return this.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
};
/**
* Function for applying Seed specific filters to a string s.
* @param {*} s - String that will be modified according to filters.
* @param {*} filters - An array of filters to use on the string.
*/
function applyFilters(s, filters) {
for (f of filters) {
if (f === 'upper') {
s = s.toUpperCase();
} else if (f === 'lower') {
s = s.toLowerCase();
} else if (f === 'title') {
s = s.toTitleCase();
} else if (f === 'sentence') {
s = s.substring(0, 1).toUpperCase() + s.substring(1);
} else {
throw new Error(`Unknown filter "${f}".`);
}
}
return s;
}
RegExp.escape = function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
function getURLParameter(name, url) {
if (typeof window === 'undefined') {
return false;
}
if (!url) {
url = window.location.search;
}
const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) {
return null;
}
if (!results[2]) {
return '';
}
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
/**
* Async method wrapper for asynchronously execute eval with a callback.
* @param {*} code The code to be evaluated
* @param {*} callback The callback with result of evaluation.
*/
async function asyncEval(code, callback) {
let result = eval(code);
callback(result);
}
const VARIABLE_TAG_START = '{{';
const VARIABLE_TAG_END = '}}';
const CONDITION_TAG_START = '([';
const CONDITION_TAG_END = '])';
const REF_START = 'ref_start';
const REF_END = 'ref_end';
const TEXT = 'text';
const REF = 'ref';
const EOF = 'eof';
const KEY = 'key';
const STRING = 'string';
const REAL_CONST = 'real_const';
const INTEGER_CONST = 'integer_const';
const RANGE = 'range';
const ANIMATION_RANGE = 'anim_range';
const FILTER = 'filter';
const VAR_GLOBAL = 'var_g';
const PLUS = '+';
const MINUS = '-';
const MUL = '*';
const DIV = '/';
const LPAREN = '(';
const RPAREN = ')';
const LBRACK = '[';
const RBRACK = ']';
const COMMA = ',';
const COLON = ':';
// Token symbols for conditional expressions. No longer needed
// becasue of the change in the way that conditional expressions
// are handled.
// const LESS_THAN = '<';
// const LESS_OR_EQUAL = '<=';
// const GREATER_THAN = '>';
// const GREATER_OR_EQUAL = '>=';
// const EQUAL_TO = '==';
// const EQUAL_TO_TYPED = '===';
// const UNEQUAL_TO = '!=';
// const UNEQUAL_TO_TYPED = '!==';
// const AND = '&&';
// const OR = '||';
// const NOT = '!';
const WILDCARD_SIGN = '_';
const DIGITS = '0123456789';
const ALPHA = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const ALPHANUM = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._';
// const LOGICAL_OPS = [LESS_THAN, LESS_OR_EQUAL, GREATER_THAN, GREATER_OR_EQUAL, EQUAL_TO,
// EQUAL_TO_TYPED, UNEQUAL_TO, UNEQUAL_TO_TYPED, AND, OR, NOT]
const WHITESPACE = ' \t'; // todo: add more to these
const PREAMBLE_RE = /^\s*(\w+)\s*:\s*(.+)*$/;
const POS_INTEGER_RE = /^\d+$/;
const DURATION_RE = /^(\d+(\.\d+)?)\s*(s|ms)?$/;
const IMPORT_RE = /^\s*import\s+(.+)\s+as\s+(([a-zA-Z]|\_)([a-zA-Z0-9]|\_|\.(?!\.))*)\s*$/;
const PREAMBLE_KEYS = ['depth', 'duration', 'animation', 'script'];
const ANIMATION_TYPES = ['once', 'linear', 'bounce'];
const MAX_LEVEL = 50;
const TIMEOUT_MILLIS = 1000;
const TIMEOUT = getURLParameter('timeout') !== 'false';
function bounce(t) {
const a = t * Math.PI * 2;
return 0.5 - Math.cos(a) * 0.5;
}
function lerp(min, max, t, animType) {
switch (animType) {
case 'linear':
break;
case 'bounce':
default:
t = bounce(t);
break;
}
return min + t * (max - min);
}
class Token {
constructor(type, value) {
this.type = type;
this.value = value;
}
toString() {
return `Token(${this.type}, ${this.value})`;
}
}
class Lexer {
constructor(text) {
this.text = text;
this.pos = 0;
this.currentChar = text.length > 0 ? text[this.pos] : null;
}
error(char) {
const s = char.length > 1 ? 's' : '';
throw new Error(
`Invalid character${s} ${char} at position ${this.pos} in phrase '${this.text}'.`
);
}
advance() {
this.pos += 1;
if (this.pos > this.text.length - 1) {
this.currentChar = null;
} else {
this.currentChar = this.text[this.pos];
}
}
peek() {
const peekPos = this.pos + 1;
if (peekPos > this.text.length - 1) {
return null;
} else {
return this.text[peekPos];
}
}
skipWhitespace() {
while (WHITESPACE.indexOf(this.currentChar) !== -1) {
this.advance();
}
}
checkCurrentNextChars(chars) {
return this.currentChar === chars[0] && this.peek() === chars[1];
}
checkEscapeChar(char) {
return this.currentChar === '\\' && this.peek() === char;
}
nextToken() {
throw new Error('Cannot call Lexer this way. Did you forget to subclass it?');
}
}
class PhraseLexer extends Lexer {
constructor(text) {
super(text);
this.insideRef = false;
}
_string(terminator) {
let result = '';
while (this.currentChar !== null) {
if (this.checkEscapeChar(terminator)) {
result += terminator;
this.advance();
this.advance();
} else if (this.currentChar === terminator) {
this.advance();
break;
} else {
result += this.currentChar;
this.advance();
}
}
return new Token(STRING, result);
}
_number() {
let result = '';
while (this.currentChar !== null && DIGITS.indexOf(this.currentChar) !== -1) {
result += this.currentChar;
this.advance();
}
if (this.currentChar === '.' && this.peek() !== '.') {
result += this.currentChar;
this.advance();
while (this.currentChar !== null && DIGITS.indexOf(this.currentChar) !== -1) {
result += this.currentChar;
this.advance();
}
return new Token(REAL_CONST, parseFloat(result));
} else {
return new Token(INTEGER_CONST, parseInt(result));
}
}
_key() {
let result = '';
if (DIGITS.indexOf(this.currentChar) !== -1) {
this.error(this.currentChar);
}
while (this.currentChar !== null && ALPHANUM.indexOf(this.currentChar) !== -1) {
if (this.checkCurrentNextChars('..')) {
break;
}
result += this.currentChar;
this.advance();
}
return new Token(KEY, result);
}
_filter() {
let result = '';
while (this.currentChar !== null && WHITESPACE.indexOf(this.currentChar) !== -1) {
this.skipWhitespace();
continue;
}
while (this.currentChar !== null && ALPHANUM.indexOf(this.currentChar) !== -1) {
if (this.checkCurrentNextChars('..')) {
break;
}
result += this.currentChar;
this.advance();
}
return new Token(FILTER, result);
}
_varg() {
let result = '';
while (this.currentChar !== null && WHITESPACE.indexOf(this.currentChar) !== -1) {
this.skipWhitespace();
continue;
}
while (this.currentChar !== null && ALPHANUM.indexOf(this.currentChar) !== -1) {
result += this.currentChar;
this.advance();
}
return new Token(VAR_GLOBAL, result);
}
_animRange() {
while (this.currentChar !== null) {
this.skipWhitespace();
let start, end;
let negate = false;
if (this.currentChar === '-') {
negate = true;
this.advance();
}
if (DIGITS.indexOf(this.currentChar) !== -1) {
start = this._number().value;
if (negate) {
start = -start;
}
} else {
this.error(this.currentChar);
}
negate = false;
this.skipWhitespace();
if (this.currentChar !== ',') {
this.error(this.currentChar);
} else {
this.advance();
}
this.skipWhitespace();
if (this.currentChar === '-') {
negate = true;
this.advance();
}
if (DIGITS.indexOf(this.currentChar) !== -1) {
end = this._number().value;
if (negate) {
end = -end;
}
} else {
this.error(this.currentChar);
}
this.skipWhitespace();
if (this.currentChar !== ']') {
this.error(this.currentChar);
} else {
this.advance();
}
return new Token(ANIMATION_RANGE, { start, end });
}
}
_ref() {
let result = '';
while (this.currentChar !== null) {
if (WHITESPACE.indexOf(this.currentChar) !== -1) {
this.skipWhitespace();
continue;
} else if (this.checkCurrentNextChars(VARIABLE_TAG_START)) {
this.error(VARIABLE_TAG_START);
} else if (this.checkCurrentNextChars(VARIABLE_TAG_END)) {
this.advance();
this.advance();
this.insideRef = false;
return new Token(REF_END, VARIABLE_TAG_END);
} else if (this.currentChar === '"') {
this.advance();
return this._string('"');
} else if (this.currentChar === "'") {
this.advance();
return this._string("'");
} else if (this.checkCurrentNextChars('..')) {
this.advance();
this.advance();
return new Token(RANGE, '..');
} else if (this.currentChar === '[') {
this.advance();
return this._animRange();
} else if (this.currentChar === '|') {
this.advance();
return this._filter();
} else if (this.currentChar === ':') {
this.advance();
return this._varg();
} else if (DIGITS.indexOf(this.currentChar) !== -1) {
return this._number();
} else if (this.currentChar === ',') {
this.advance();
return new Token(COMMA, ',');
} else if (this.currentChar === '+') {
this.advance();
return new Token(PLUS, '+');
} else if (this.currentChar === '-') {
this.advance();
return new Token(MINUS, '-');
} else if (this.currentChar === '*') {
this.advance();
return new Token(MUL, '*');
} else if (this.currentChar === '/') {
this.advance();
return new Token(DIV, '/');
} else if (this.currentChar === '(') {
this.advance();
return new Token(LPAREN, '(');
} else if (this.currentChar === ')') {
this.advance();
return new Token(RPAREN, ')');
} else if (ALPHANUM.indexOf(this.currentChar) !== -1) {
return this._key();
}
result += this.currentChar;
if (result) {
this.error(result);
}
}
}
_text() {
if (this.checkCurrentNextChars(VARIABLE_TAG_START)) {
this.advance();
this.advance();
this.insideRef = true;
return new Token(REF_START, VARIABLE_TAG_START);
}
let result = '';
while (this.currentChar !== null) {
if (this.checkCurrentNextChars(VARIABLE_TAG_END)) {
this.error(VARIABLE_TAG_END);
} else if (this.checkCurrentNextChars(VARIABLE_TAG_START)) {
break;
} else if (this.checkEscapeChar('{')) {
result += '{';
this.advance();
this.advance();
} else if (this.checkEscapeChar('}')) {
result += '}';
this.advance();
this.advance();
} else {
result += this.currentChar;
this.advance();
}
}
return new Token(TEXT, result);
}
nextToken() {
while (this.currentChar !== null) {
return this.insideRef ? this._ref() : this._text();
}
return new Token(EOF, null);
}
}
class DefLexer extends Lexer {
_key() {
let result = '';
if (DIGITS.indexOf(this.currentChar) !== -1) {
this.error(this.currentChar);
}
while (this.currentChar !== null && ALPHANUM.indexOf(this.currentChar) !== -1) {
if (this.checkCurrentNextChars('..')) {
break;
}
result += this.currentChar;
this.advance();
}
return new Token(KEY, result);
}
nextToken() {
let result = '';
while (this.currentChar !== null) {
if (WHITESPACE.indexOf(this.currentChar) !== -1) {
this.skipWhitespace();
continue;
} else if (this.currentChar === ':') {
this.advance();
return new Token(COLON, ':');
} else if (this.currentChar === ',') {
this.advance();
return new Token(COMMA, ',');
} else if (this.currentChar === '(') {
this.advance();
return new Token(LPAREN, '(');
} else if (this.currentChar === ')') {
this.advance();
return new Token(RPAREN, ')');
} else if (ALPHANUM.indexOf(this.currentChar) !== -1) {
return this._key();
}
result += this.currentChar;
if (result) {
this.error(result);
}
}
return new Token(EOF, null);
}
}
const NODE_CONCAT = 'Concat';
const NODE_TEXT = 'Text';
const NODE_REF = 'Ref';
const NODE_INTEGER = 'Integer';
const NODE_REAL = 'Real';
const NODE_STRING = 'String';
const NODE_RANGE = 'Range';
const NODE_KEY = 'Key';
const NODE_NAMED_KEY = 'NamedKey';
const NODE_CHAR = 'Char';
const NODE_FILTER = 'Filter';
const NODE_ANIMATION_RANGE = 'AnimRange';
const NODE_UNARY_OP = 'UnaryOp';
const NODE_BINARY_OP = 'BinaryOp';
const NODE_NO_OP = 'NoOp';
class Node {
constructor(type, data) {
this.type = type;
if (data) {
Object.assign(this, data);
}
}
}
class Parser {
constructor(lexer, lineno) {
this.lexer = lexer;
this.lineno = lineno;
this.currentToken = this.lexer.nextToken();
}
error() {
throw new Error('Cannot call Parser this way. Did you forget to subclass it?');
}
consume(tokenType) {
if (this.currentToken.type === tokenType) {
this.currentToken = this.lexer.nextToken();
} else {
this.error(tokenType);
}
}
parse() {
throw new Error('Cannot call Parser this way. Did you forget to subclass it?');
}
}
class PhraseParser extends Parser {
error(tokenType) {
throw new Error(
`Invalid syntax: expected a symbol of type ${tokenType} at position ${this.lexer.pos}, but encountered ${this.currentToken.type} instead.`
);
}
_filters(node) {
while (this.currentToken.type === FILTER) {
if (this.currentToken.value === '') {
throw new Error(
`Naming Error. Encountered a filter token (|) at position ${this.lexer.pos} without a filter name.`
);
}
node = new Node(NODE_FILTER, { node, name: this.currentToken.value });
this.consume(FILTER);
node = this._parameters(node);
}
return node;
}
_range(node) {
if (this.currentToken.type === RANGE) {
if (node.type === NODE_STRING && node.value.length !== 1) {
throw new Error(
`Range Error: Only single character strings can be part of a range. The encountered string '${node.value}' at position ${this.lexer.pos} has a length of ${node.value.length}.`
);
}
this.consume(RANGE);
let start = node;
let end = this.factor(false);
if (end.type === NODE_STRING && end.value.length !== 1) {
throw new Error(
`Range Error: Only single character strings can be part of a range. The encountered string '${end.value}' at position ${this.lexer.pos} has a length of ${end.value.length}.`
);
}
if (start.type === NODE_KEY && start.key.length === 1 && !start.parameters) {
start = new Node(NODE_CHAR, { value: start.key });
}
if (end.type === NODE_KEY && end.key.length === 1 && !end.parameters) {
end = new Node(NODE_CHAR, { value: end.key });
}
node = new Node(NODE_RANGE, { start, end });
node = this._filters(node);
}
return node;
}
_name(node) {
let token = this.currentToken;
if (this.currentToken.type === VAR_GLOBAL) {
this.consume(VAR_GLOBAL);
node = new Node(NODE_NAMED_KEY, { key: node.key, name: token.value });
}
return node;
}
_parameters(node) {
const parameters = [];
if (this.currentToken.type === LPAREN) {
this.consume(LPAREN);
if (this.currentToken.type === RPAREN) {
node.parameters = parameters;
this.consume(RPAREN);
return node;
}
parameters.push(this.expr());
while (this.currentToken.type === COMMA) {
this.consume(COMMA);
parameters.push(this.expr());
}
if (this.currentToken.type === RPAREN) {
this.consume(RPAREN);
node.parameters = parameters;
return node;
} else {
this.error(RPAREN);
}
}
return node;
}
factor(parseFiltersRange = true) {
const token = this.currentToken;
let node;
if (token.type === PLUS) {
this.consume(PLUS);
node = new Node(NODE_UNARY_OP, { op: token.type, expression: this.factor(false) });
} else if (token.type === MINUS) {
this.consume(MINUS);
node = new Node(NODE_UNARY_OP, { op: token.type, expression: this.factor(false) });
} else if (token.type === INTEGER_CONST) {
this.consume(INTEGER_CONST);
node = new Node(NODE_INTEGER, { value: token.value });
} else if (token.type === REAL_CONST) {
this.consume(REAL_CONST);
node = new Node(NODE_REAL, { value: token.value });
} else if (token.type === ANIMATION_RANGE) {
this.consume(ANIMATION_RANGE);
node = new Node(NODE_ANIMATION_RANGE, {
start: token.value.start,
end: token.value.end
});
} else if (token.type === STRING) {
this.consume(STRING);
node = new Node(NODE_STRING, { value: token.value });
} else if (token.type === KEY) {
this.consume(KEY);
if (this.currentToken.type === KEY) {
throw new Error(
`Invalid syntax at position ${this.lexer.pos}: Spaces are not allowed as part of identifiers. You could write '${token.value}_${this.currentToken.value}' instead.`
);
}
node = new Node(NODE_KEY, { key: token.value });
node = this._name(node);
node = this._parameters(node);
} else if (token.type === LPAREN) {
this.consume(LPAREN);
try {
node = this.expr();
} catch (e) {
throw new Error(`Error. Empty expression at position ${this.lexer.pos}.`);
}
this.consume(RPAREN);
} else {
throw new Error(
`Invalid syntax: expected a symbol (an integer, float, string, ...) at position ${this.lexer.pos}, but encountered ${this.currentToken.type} instead.`
);
}
if (parseFiltersRange) {
node = this._filters(node);
node = this._range(node);
}
return node;
}
term() {
let node = this.factor();
while (this.currentToken.type === MUL || this.currentToken.type === DIV) {
let token = this.currentToken;
if (token.type === MUL) {
this.consume(MUL);
} else if (token.type === DIV) {
this.consume(DIV);
}
node = new Node(NODE_BINARY_OP, { left: node, op: token.type, right: this.factor() });
}
return node;
}
expr() {
if (this.currentToken.type === REF_END) {
return new Node(NODE_NO_OP);
} else if (this.currentToken.type === RPAREN) {
throw new Error(
`Invalid syntax: Encountered ) symbol at position ${this.lexer.pos} but no ( was seen.`
);
}
let node = this.term();
while (this.currentToken.type === PLUS || this.currentToken.type === MINUS) {
let token = this.currentToken;
if (token.type === PLUS) {
this.consume(PLUS);
} else if (token.type === MINUS) {
this.consume(MINUS);
}
node = new Node(NODE_BINARY_OP, { left: node, op: token.type, right: this.term() });
}
return node;
}
ref() {
let node = this.expr();
if (this.currentToken.type !== REF_END) {
throw new Error(
`Invalid syntax: expected end of reference at position ${this.lexer.pos}, but encountered ${this.currentToken.type} instead.`
);
}
return new Node(NODE_REF, { node });
}
part() {
const token = this.currentToken;
let node;
if (token.type === TEXT) {
this.consume(TEXT);
return new Node(NODE_TEXT, { text: token.value });
} else if (token.type === REF_START) {
this.consume(REF_START);
node = this.ref();
this.consume(REF_END);
return node;
}
}
phrase() {
let node = this.part();
while (this.currentToken.type === TEXT || this.currentToken.type === REF_START) {
node = new Node(NODE_CONCAT, { left: node, right: this.part() });
}
return node;
}
parse() {
try {
const node = this.phrase();
if (this.currentToken.type !== EOF) {
this.error(EOF);
}
return node;
} catch (e) {
throw new Error(`Line ${this.lineno}: ${e.message}`);
}
}
}
class DefParser extends Parser {
error(tokenType) {
throw new Error(
`Invalid syntax: expected a symbol of type ${tokenType} at position ${this.lexer.pos}, but encountered ${this.currentToken.type} instead.`
);
}
_key() {
let key = this.currentToken.value;
this.consume(KEY);
if (this.currentToken.type === KEY) {
throw new Error(
`Invalid syntax at position ${this.lexer.pos}: Spaces are not allowed as part of identifiers. You could write '${key}_${this.currentToken.value}' instead.`
);
}
return key;
}
_parameters() {
const parameters = [];
if (this.currentToken.type === LPAREN) {
this.consume(LPAREN);
if (this.currentToken.type === RPAREN) {
this.consume(RPAREN);
return parameters;
}
parameters.push(this._key());
while (this.currentToken.type === COMMA) {
this.consume(COMMA);
parameters.push(this._key());
}
if (this.currentToken.type === RPAREN) {
this.consume(RPAREN);
return parameters;
} else {
this.error(RPAREN);
}
}
return parameters;
}
parse() {
try {
const key = this._key();
const parameters = this._parameters();
this.consume(COLON);
if (this.currentToken.type !== EOF) {
this.error(EOF);
}
if (parameters.length === 0) {
return { key };
} else {
return { key, parameters };
}
} catch (e) {
throw new Error(`Line ${this.lineno}: ${e.message}`);
}
}
}
class Interpreter {
constructor(data) {
if (data) {
Object.assign(this, data);
}
this.globalScope = {};
}
async visit(node) {
const methodName = 'visit' + node.type;
if (this[methodName]) {
return await this[methodName](node);
}
this.genericVisit(node);
}
genericVisit(node) {
throw new Error(`No visit${node.type} method available for node ${node}.`);
}
visitNoOp(node) {
return '';
}
async visitUnaryOp(node) {
const op = node.op;
if (op === PLUS) {
return +(await this.visit(node.expression));
} else if (op === MINUS) {
return -(await this.visit(node.expression));
}
}
async visitBinaryOp(node) {
const op = node.op;
if (op === PLUS) {
return (await this.visit(node.left)) + (await this.visit(node.right));
} else if (op === MINUS) {
return (await this.visit(node.left)) - (await this.visit(node.right));
} else if (op === MUL) {
return (await this.visit(node.left)) * (await this.visit(node.right));
} else if (op === DIV) {
return (await this.visit(node.left)) / (await this.visit(node.right));
}
}
async visitConcat(node) {
return (await this.visit(node.left)) + (await this.visit(node.right));
}
visitText(node) {
return node.text;
}
async visitRef(node) {
return String(await this.visit(node.node));
}
visitString(node) {
return node.value;
}
visitInteger(node) {
return node.value;
}
visitReal(node) {
return node.value;
}
visitChar(node) {
return node.value;
}
async visitRange(node) {
let start, end;
let startError, endError;
if (node.start.type === NODE_CHAR) {
start = node.start.value;
if (this.localMemory[start] !== undefined) {
start = this.localMemory[start];
} else if (this.phraseBook[start] !== undefined) {
start = await this.visitKey(new Node(NODE_KEY, { key: start }));
}
} else {
start = await this.visit(node.start);
}
if (typeof start === 'string' && String(parseFloat(start)) === start) {
start = parseFloat(start);
}
if (node.end.type === NODE_CHAR) {
end = node.end.value;
if (this.localMemory[end] !== undefined) {
end = this.localMemory[end];
} else if (this.phraseBook[end] !== undefined) {
end = await this.visitKey(new Node(NODE_KEY, { key: end }));
}
} else {
end = await this.visit(node.end);
}
if (typeof end === 'string' && end.length === 1 && String(parseFloat(end)) === end) {
end = parseFloat(end);
}
if (typeof start === 'number' && typeof end === 'number') {
return Math.floor(rand(start, end));
}
let min, max, charCode;
if (
typeof start === 'string' &&
start.length === 1 &&
typeof end === 'string' &&
end.length === 1
) {
return randomChar(start, end);
} else if (
typeof start === 'string' &&
start.length === 1 &&
typeof end === 'number' &&
String(end).length === 1
) {
return randomChar(start, String(end));
} else if (
typeof start === 'number' &&
String(start).length === 1 &&
typeof end === 'string' &&
end.length === 1
) {
return randomChar(String(start), end);
} else {
if (typeof start === 'string') {
start = `"${start}"`;
}
if (typeof end === 'string') {
end = `"${end}"`;
}
throw new Error(`Range Error: ${start}..${end}`);
}
}
async visitKey(node, searchLocal = true) {
if (searchLocal && this.localMemory[node.key] !== undefined) {
return this.localMemory[node.key];
}
let key, phraseBook, globalMemory;
if (this.phraseBook['%imports'][node.key] !== undefined) {
phraseBook = this.phraseBook['%imports'][node.key];
key = 'root';
globalMemory = {};
} else {
phraseBook = this.phraseBook;
key = node.key;
globalMemory = this.globalMemory;
}
const phrase = lookupPhrase(phraseBook, key);
const localMemory = {};
const parameters = phraseBook[key].parameters;
if (parameters) {
for (let i = 0; i < parameters.length; i += 1) {
let name = parameters[i];
if (node.parameters && node.parameters[i]) {
localMemory[name] = await this.visit(node.parameters[i]);
} else {
localMemory[name] = '';
}
}
}
return evalPhrase(
phraseBook,