-
Notifications
You must be signed in to change notification settings - Fork 0
/
xex.js
959 lines (819 loc) · 32.6 KB
/
xex.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
// xex.js <https://github.com/jsstuff/xex>
(function($export, $as) {
"use strict";
$export[$as] = (function() {
const hasOwn = Object.prototype.hasOwnProperty;
const freeze = Object.freeze;
const isArray = Array.isArray;
const NoObject = freeze(Object.create(null));
/**
* Version in "major.minor.patch" form.
*
* @alias xex.VERSION
*/
const VERSION = "0.1.0";
// ----------------------------------------------------------------------------
// [ExpressionError]
// ----------------------------------------------------------------------------
/**
* Error class used by xex.
*
* Contains `message` and `position` members. If the `position` is not `-1`
* then it is a zero-based index, which points to a first character of the
* token near the error.
*/
class ExpressionError extends Error {
constructor(message, position) {
super(message);
this.name = "ExpressionError";
this.message = message;
this.position = position != null ? position : -1;
}
}
function throwExpressionError(message, position) {
throw new ExpressionError(message, position);
}
// ----------------------------------------------------------------------------
// [Expression & Utilities]
// ----------------------------------------------------------------------------
const LanguageFeatures = freeze({
"ternary-if" : true,
"ternary-else": true
});
function isNode(node) { return node !== null && typeof node === "object"; }
function isBinary(node) { return node !== null && node.type === "Binary"; }
function isNumber(node) { return typeof node === "number"; }
function newVar(name) {
return { type: "Var", name: name };
}
function newUnary(name, info, value) {
return { type: "Unary", name: name, info: info, value: value };
}
function newBinary(name, info, left, right) {
return { type: "Binary", name: name, info: info, left: left, right: right };
}
function newCall(name, info, args) {
return { type: "Call", name: name, info: info, args: args };
}
function cloneNode(node) {
if (!isNode(node)) return node;
switch (node.type) {
case "Var" : return node; // Variable nodes are immutable.
case "Unary" : return newUnary(node.name, node.info, cloneNode(node.value));
case "Binary": return newBinary(node.name, node.info, cloneNode(node.left), cloneNode(node.right));
case "Call" : return newCall(node.name, node.info, node.args.map(cloneNode));
default:
throwExpressionError(`Node '${node.type}' not recognized`);
}
}
function mustEnclose(node) {
if (typeof node !== "object")
return false;
const type = node.type;
return type === "Operator" && type.lang !== "ternary-else";
}
function numberToString(x) {
return Object.is(x, -0) ? "-0" : String(x);
}
function propertyAccess(name) {
return /^[A-Za-z_\$][\w\$]*$/.test(name) ? `.${name}` : `[${JSON.stringify(name)}]`;
}
/**
* Parsed expression.
*
* Expression contains the whole expression tree and provides API to perform
* basic manipulation and to compile the expression into a native JS function.
*
* @alias xex.Expression
*/
class Expression {
constructor(env, root) {
this.env = env;
this.root = root != null ? root : null;
this.dirty = false;
this.$eval = null;
this.$vars = null;
}
clone() {
return new Expression(this.env, cloneNode(this.root));
}
fold(cmap) {
this.root = this.$onNodeFold(this.root, cmap);
this._checkDirty();
return this;
}
compile(args) {
// Build `varr` and `vmap` based on the source argument.
if (!isArray(args))
throwExpressionError(`Argument 'args' must be an array, not '${typeof args}'`);
const varr = [];
const vmap = Object.create(null);
for (var i = 0; i < args.length; i++) {
const name = args[i];
if (hasOwn.call(vmap, name))
throwExpressionError(`Variable '${name}' provided multiple times`);
const ident = "_" + String(i + 1);
varr.push(ident);
vmap[name] = ident;
}
return this.$onFuncCompile(this.root, vmap, varr);
}
compileBody(vmap) {
if (typeof vmap !== "string" && typeof vmap !== "object")
throwExpressionError(`Argument 'vmap' must be a string or object, not '${typeof vmap}'`);
return this.$onNodeCompile(this.root, vmap);
}
get eval() {
if (this.$eval === null)
this.$eval = this.$onFuncCompile(this.root, "v", null);
return this.$eval;
}
get vars() {
if (this.$vars === null) {
this.$vars = Object.create(null);
this.$onNodeInfo(this.root);
}
return this.$vars;
}
_checkDirty() {
if (this.dirty) {
this.dirty = false;
this.$eval = null;
this.$vars = null;
}
}
$onNodeInfo(node) {
if (node === null || typeof node !== "object")
return;
switch (node.type) {
case "Var":
this.$vars[node.name] = node;
break;
case "Unary":
this.$onNodeInfo(node.value);
break;
case "Binary":
this.$onNodeInfo(node.left);
this.$onNodeInfo(node.right);
break;
case "Call":
const args = node.args;
for (var i = 0; i < args.length; i++)
this.$onNodeInfo(args[i]);
break;
default:
throwExpressionError(`Node '${node.type}' not recognized`);
}
}
$onNodeFold(node, cmap) {
if (node === null || typeof node !== "object")
return node;
const info = node.info;
switch (node.type) {
case "Var": {
if (cmap && hasOwn.call(cmap, node.name)) {
this.dirty = true;
return cmap[node.name];
}
return node;
}
case "Unary": {
const child = node.value = this.$onNodeFold(node.value, cmap);
if (info.safe && isNumber(child)) {
this.dirty = true;
return info.eval(child);
}
return node;
}
case "Binary": {
const left = node.left = this.$onNodeFold(node.left, cmap);
const right = node.right = this.$onNodeFold(node.right, cmap);
const feature = info.lang;
if (feature === null) {
if (info.safe && isNumber(left) && isNumber(right)) {
this.dirty = true;
return info.eval(left, right);
}
return node;
}
if (feature === "ternary-if") {
// The "ternary-if" operator must have "ternary-else" on right side.
if (!isBinary(right) || right.info.lang !== "ternary-else")
throwExpressionError(`Invalid AST - Ternary if '${info.name}' requires ternary-else on right side`);
if (isNumber(left))
return left ? right.left : right.right;
}
return node;
}
case "Call": {
const args = node.args;
for (var i = 0; i < args.length; i++)
args[i] = this.$onNodeFold(args[i], cmap);
if (info.safe && args.every(isNumber)) {
this.dirty = true;
return info.eval.apply(info, args);
}
return node;
}
default:
throwExpressionError(`Node '${node.type}' not recognized`);
}
}
$onFuncCompile(node, vmap, varr) {
const decl = [];
const args = [];
decl.push("$");
args.push(this.env.func);
const signature = varr ? varr.join(", ") : vmap;
const body = this.$onNodeCompile(node, vmap);
decl.push(`"use strict"\n` +
`return function(${signature}) {\n` +
` return ${body};\n` +
`}\n`);
try {
return Function.apply(null, decl).apply(null, args);
}
catch (ex) {
throw new ExpressionError(`${ex.message}: ${body}`);
}
}
$onNodeCompile(node, vmap) {
if (isNumber(node))
return numberToString(node);
const info = node.info;
switch (node.type) {
case "Var": {
const name = node.name;
if (typeof vmap === "string")
return vmap + propertyAccess(name);
if (!hasOwn.call(vmap, name))
throwExpressionError(`Variable '${name}' used, but no mapping provided`);
return vmap[node.name];
}
case "Unary": {
return info.emit.replace(/@1/g, () => {
const child = node.value;
const code = this.$onNodeCompile(child, vmap);
return mustEnclose(child) ? `(${code})` : code;
});
}
case "Binary": {
return info.emit.replace(/@[1-2]/g, (p) => {
const child = p === "@1" ? node.left : node.right;
const code = this.$onNodeCompile(child, vmap);
return mustEnclose(child) ? `(${code})` : code;
});
}
case "Call": {
return info.emit.replace(/(?:@args|@[1-2])/g, (p) => {
const args = node.args;
if (p !== "@args") {
const index = parseInt(p.substr(1), 10) - 1;
if (index >= args.length)
throwExpressionError(`Invalid index '@${index}' in '${info.emit}'`);
return this.$onNodeCompile(args[index], vmap);
}
var s = "";
for (var i = 0; i < args.length; i++) {
if (s) s += ", ";
s += this.$onNodeCompile(args[i], vmap);
}
return s;
});
}
default:
throwExpressionError(`Node '${node.type}' not recognized`);
}
}
}
// ----------------------------------------------------------------------------
// [Tokenization & Parsing]
// ----------------------------------------------------------------------------
const kCharNone = 0; // '_' - Character category - Invalid or <end>.
const kCharSpace = 1; // 'S' - Character category - Space.
const kCharAlpha = 2; // 'A' - Character category - Alpha [A-Za-z_].
const kCharDigit = 3; // 'D' - Character category - Digit [0-9].
const kCharPunct = 4; // '$' - Character category - Punctuation.
const Category = (function(_, S, A, D, $) {
const Table = freeze([
_,_,_,_,_,_,_,_,_,S,S,S,S,S,_,_, // 000-015 |......... ..|
_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_, // 016-031 |................|
S,$,$,$,$,$,$,$,$,$,$,$,$,$,$,$, // 032-047 | !"#$%&'()*+,-./|
D,D,D,D,D,D,D,D,D,D,$,$,$,$,$,$, // 048-063 |0123456789:;<=>?|
$,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A, // 064-079 |@ABCDEFGHIJKLMNO|
A,A,A,A,A,A,A,A,A,A,A,$,$,$,$,A, // 080-095 |PQRSTUVWXYZ[\]^_|
$,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A, // 096-111 |`abcdefghijklmno|
A,A,A,A,A,A,A,A,A,A,A,$,$,$,$,_, // 112-127 |pqrstuvwxyz{|}~ |
_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_, // 128-143 |................|
_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_ // 144-159 |................|
]);
const kTableLength = Table.length;
return function(c) {
if (c < kTableLength)
return Table[c];
return kCharNone;
};
})(kCharNone, kCharSpace, kCharAlpha, kCharDigit, kCharPunct);
const kTokenNone = 0; // Invalid token, should be only used with `NoToken`.
const kTokenPunct = 1; // Token is a punctuation, used to recognize operators.
const kTokenIdent = 2; // Token is an identifier name (variable or function).
const kTokenValue = 3; // Token is a value.
const kMaxOperatorLen = 4; // Maximum length of a single operator.
function newToken(type, position, data, value) {
return {
type : type, // Token type, see `kToken...`.
position: position, // Token position in expression's source.
data : data, // Token data (content) as string.
value : value // Token value (only if the token is a value).
};
}
const NoToken = freeze(newToken(kTokenNone, -1, "<end>", null));
// Must be reset before it can be used, use `RegExp.lastIndex`.
const reValue = /(?:(?:\d*\.\d+|\d+)(?:[E|e][+|-]?\d+)?)/g;
function rightAssociate(info, bPrec) {
return info.prec > bPrec || (info.prec === bPrec && info.rtl);
}
function throwTokenError(token) {
throw new ExpressionError(`Unexpected token '${token.data}'`, token.position);
}
class Parser {
constructor(env, options) {
this.env = env; // Expression environment (features).
this.exp = null; // Expression instance, created in `parse()`.
this.options = options; // Expression options.
this.vars = Object.create(null); // Parsed variables name to node mapping.
this.tIndex = 0; // Current token index, used during parsing.
this.tokens = []; // Tokens array.
}
tokenize(source) {
const tokens = this.tokens; // Tokens array.
const env = this.env; // Expression environment.
const len = source.length; // Source length.
var i = 0, j = 0; // Current index in `source` and temporary.
var start = 0; // Current token start position.
var data = ""; // Current token data (content) as string.
var c, cat; // Current character code and category.
while (i < len) {
cat = Category(c = source.charCodeAt(i));
if (cat === kCharSpace) {
i++;
}
else if (cat === kCharDigit) {
const n = tokens.length - 1;
if (n >= 0 && tokens[n].data === "." && source[i - 1] === ".") {
tokens.length = n;
i--;
}
reValue.lastIndex = i;
data = reValue.exec(source)[0];
tokens.push(newToken(kTokenValue, i, data, parseFloat(data)));
i += data.length;
}
else if (cat === kCharAlpha) {
start = i;
while (++i < len && ((cat = Category(source.charCodeAt(i))) === kCharAlpha || cat === kCharDigit))
continue;
data = source.substring(start, i);
tokens.push(newToken(kTokenIdent, start, data, null));
}
else if (cat === kCharPunct) {
start = i;
while (++i < len && Category(source.charCodeAt(i)) === kCharPunct)
continue;
data = source.substring(start, i);
do {
for (j = Math.min(i - start, kMaxOperatorLen); j > 0; j--) {
const part = source.substr(start, j);
if (env.get(part) || j === 1) {
tokens.push(newToken(kTokenPunct, start, part, null));
start += j;
break;
}
}
} while (start < i);
}
else {
throwExpressionError(`Unrecognized character '0x${c.toString(16)}'`, i);
}
}
return this;
}
skip() { this.tIndex++ ; return this; }
back(t) { this.tIndex -= +(t !== NoToken); return this; }
peek() { return this.tIndex < this.tokens.length ? this.tokens[this.tIndex ] : NoToken; }
next() { return this.tIndex < this.tokens.length ? this.tokens[this.tIndex++] : NoToken; }
parse() {
// The root expression cannot be empty.
var token = this.peek();
if (token === NoToken)
throwExpressionError("Expression cannot be empty", 0);
this.exp = new Expression(this.env, null);
this.exp.root = this.parseExpression();
// The root expression must reach the end of the input.
token = this.peek();
if (token !== NoToken) throwTokenError(token);
return this.exp;
}
parseExpression() {
const stack = [];
const env = this.env;
const options = this.options;
const whitelist = options.varsWhitelist;
var value = null;
var info = null;
for (;;) {
// The only case of value not being `null` is after ternary-if. In that
// case the value was already parsed so we want to skip this section.
// In C/C++ I would have used the evil goto, here I did it this way.
if (value === null) {
var token = this.next();
var unaryFirst = null;
var unaryLast = null;
// Parse a possible unary operator(s).
value = null;
if (token.type === kTokenPunct) {
do {
const name = "unary" + token.data;
if (!(info = env.get(name))) break;
const node = newUnary(name, info, value);
if (unaryLast)
unaryLast.value = node;
else
unaryFirst = node;
unaryLast = node;
token = this.next();
} while (token.type === kTokenPunct);
}
// Parse a value, variable, function call, or nested expression.
if (token.type === kTokenValue) {
value = token.value;
}
else if (token.type === kTokenIdent) {
const name = token.data;
info = env.get(name);
if (this.peek().data === "(") {
if (!info)
throwExpressionError(`Function '${name}' not defined`, token.position);
if (info.type !== "Function")
throwExpressionError(`Variable '${name}' cannot be used as function`, token.position);
value = this.parseCall(token, info);
}
else {
if (info && info.type === "Function")
throwExpressionError(`Function '${name}' cannot be used as variable`, token.position);
if (info && info.type === "Constant") {
value = info.value;
}
else {
if (whitelist && !hasOwn.call(whitelist, name))
throwExpressionError(`Variable '${name}' is not defined`, token.position);
value = this.vars[name] || (this.vars[name] = newVar(name));
}
}
}
else if (token.data === "(") {
value = this.parseExpression();
token = this.next();
if (token.data !== ")")
throwTokenError(token);
}
else {
throwTokenError(token);
}
// Replace the value with the top-level unary operator, if parsed.
if (unaryFirst) {
unaryLast.value = value;
value = unaryFirst;
}
}
// Parse a possible binary operator - the loop must repeat if present.
token = this.peek();
if (token.type === kTokenPunct && (info = env.get(token.data))) {
const langConstruct = info.lang;
const name = token.data;
const bNode = newBinary(name, info, null, null);
// Handle "ternary-else" construct - it must return now as the
// token is checked by the caller of `parseExpression()`.
if (langConstruct === "ternary-else") break;
// Consume the token.
this.skip();
if (!stack.length) {
bNode.left = value;
stack.push(bNode);
}
else {
var aNode = stack.pop();
var aPrec = aNode.info.prec;
var bPrec = bNode.info.prec;
if (aPrec > bPrec) {
aNode.right = bNode;
bNode.left = value;
stack.push(aNode, bNode);
}
else {
aNode.right = value;
// Advance to the top-most op that has less/equal precedence than `bPrec`.
while (stack.length) {
if (rightAssociate(aNode.info, bPrec))
break;
aNode = stack.pop();
}
if (!stack.length && !rightAssociate(aNode.info, bPrec)) {
bNode.left = aNode;
stack.push(bNode);
}
else {
const tmp = aNode.right;
aNode.right = bNode;
bNode.left = tmp;
stack.push(aNode, bNode);
}
}
}
// Parse "<cond> {ternary-if} <taken> {ternary-else} <not-taken>".
if (langConstruct === "ternary-if") {
const ternLeft = this.parseExpression();
const ternTok = this.next();
if (ternTok.type !== kTokenPunct || (info = env.get(ternTok.data)) == null || info.lang !== "ternary-else")
throwExpressionError(`Unterminated ternary-if '${token.data}'`, token.position);
const ternRight = this.parseExpression();
value = newBinary(info.name, info, ternLeft, ternRight);
}
else {
value = null;
}
continue;
}
break;
}
if (value === null)
throwExpressionError("Invalid state");
if (stack.length !== 0) {
stack[stack.length - 1].right = value;
value = stack[0];
}
return value;
}
parseCall(func, info) {
const name = func.data;
const args = [];
var token = this.next();
if (token.data !== "(") throwTokenError(token);
for (;;) {
token = this.peek();
if (token.data === ")") break;
if (args.length !== 0) {
if (token.data !== ",")
throwTokenError(token);
this.skip();
}
args.push(this.parseExpression());
}
this.skip();
if (args.length < info.args || args.length > info.amax) {
if (info.args === info.amax)
throwExpressionError(`Function '${name}' accepts ${info.args} argument(s), ${args.length} provided`);
else
throwExpressionError(`Function '${name}' accepts ${info.args} to ${info.amax} argument(s), ${args.length} provided`);
}
return newCall(name, info, args);
}
}
// ----------------------------------------------------------------------------
// [Environment]
// ----------------------------------------------------------------------------
/**
* Environment - defines operators, functions, and constants.
*/
class Environment {
constructor() {
this.lang = Object.create(null);
this.func = Object.create(null);
this.frozen = false;
this.VERSION = VERSION;
this.Expression = Expression;
this.ExpressionError = ExpressionError;
}
/**
* Creates a new `Expression` from `source`.
*
* Options:
* - `noFolding` {boolean} If true the `Expression` returned won't be
* simplified - it disables constant folding
*
* - `varsWhitelist` {object} If passed, the parser will recognize only
* variables, which are whitelisted (by using `hasOwnProperty` call).
*
* @param {string} source Expression source.
* @param {object} [options]
*
* @return {Expression} A new `Expression` instance.
* @throws {ExpresionError} If tokenizer, parser, or analysis failed.
*/
exp(source, options) {
if (typeof source !== "string")
throwExpressionError(`Argument 'source' must be a string, not '${typeof source}'`);
if (options == null) options = NoObject;
const exp = new Parser(this, options).tokenize(source).parse();
if (options.noFolding !== true) exp.fold();
return exp;
}
clone() {
const cloned = new Environment();
Object.assign(cloned.lang, this.lang);
Object.assign(cloned.func, this.func);
return cloned;
}
freeze() {
freeze(this.lang);
freeze(this.func);
this.frozen = true;
return freeze(this);
}
get(name) {
return this.lang[name] || null;
}
add(def) {
if (this.frozen)
throwExpressionError(`Environment is frozen`);
const type = def.type;
const name = def.name;
const lang = def.lang;
if (typeof name !== "string")
throwExpressionError(`Identifier name be string, not '${typeof name}'`);
if (hasOwn.call(this.lang, name))
throwExpressionError(`Identifier '${name}' already defined`);
switch (type) {
case "Constant":
if (typeof def.value !== "number")
throwExpressionError(`Constant '${name}' must be a number, not '${typeof value}'`);
break;
case "Operator":
if (typeof def.prec !== "number") throwExpressionError(`${type} '${name}' must provide 'prec' property`);
if (typeof def.rtl !== "boolean") throwExpressionError(`${type} '${name}' must provide 'rtl' property`);
/* [[fallthrough]] */
case "Function":
if (lang != null && !hasOwn.call(LanguageFeatures, lang))
throwExpressionError(`Language feature '${lang}' not recognized`);
if (typeof def.args !== "number") throwExpressionError(`${type} '${name}' must provide 'args' property`);
if (typeof def.amax !== "number") throwExpressionError(`${type} '${name}' must provide 'amax' property`);
if (typeof def.emit !== "string") throwExpressionError(`${type} '${name}' must provide 'emit' property`);
if (typeof def.eval !== "function" && !lang)
throwExpressionError(`${type} '${name}' must provide 'eval' property`);
this.func[name] = def.eval;
break;
default:
throwExpressionError(`Type '${type}' not recognized`);
}
this.lang[name] = freeze(def);
return this;
}
addConstant(def) {
const name = typeof def === "object" ? def.name : def;
const value = typeof def === "object" ? def.value : arguments[1];
return this.add({
type: "Constant",
name: name,
value: value
});
}
addUnary(def) {
return this.add({
type: "Operator",
name: "unary" + def.name,
args: 1,
amax: 1,
prec: def.prec || 0,
rtl : Boolean(def.rtl),
safe: def.safe !== false,
lang: def.lang || null,
eval: def.eval || null,
emit: def.emit || `$${propertyAccess(def.name)}(@1)`
});
}
addBinary(def) {
return this.add({
type: "Operator",
name: def.name,
args: 2,
amax: 2,
prec: def.prec || 0,
rtl : Boolean(def.rtl),
safe: def.safe !== false,
lang: def.lang || null,
eval: def.eval || null,
emit: def.emit || `$${propertyAccess(def.name)}(@1, @2)`
});
}
addFunction(def) {
return this.add({
type: "Function",
name: def.name,
args: def.args,
amax: typeof def.amax === "number" ? def.amax : def.args,
prec: 0,
rtl : false,
safe: def.safe !== false,
lang: def.lang || null,
eval: def.eval || null,
emit: def.emit || `$${propertyAccess(def.name)}(@args)`
});
}
del(name) {
if (this.frozen)
throwExpressionError(`Environment is frozen`);
delete this.lang[name];
delete this.func[name];
return this;
}
}
// Use "+" to coerce booleans to numbers where required as `xex` works with numbers only.
function frac(x) { return x - Math.floor(x); }
function isnan(x) { return +Number.isNaN(x); }
function isinf(x) { return +(x === Infinity || x === -Infinity); }
function isfinite(x) { return +Number.isFinite(x); }
function isint(x) { return +Number.isInteger(x); }
function issafeint(x) { return +Number.isSafeInteger(x); }
function isequal(x, y) { return +Object.is(x, y); }
function clamp(x, a, b) { return x < a ? a : x > b ? b : x; }
function isbetween(x, a, b) { return +(x >= a && x <= b); }
function minmaxval(op) {
return function() {
var i = 0, len = arguments.length;
var x = NaN, y = 0;
while (i < len && Number.isNaN(x = arguments[i++]))
continue;
while (i < len)
if (!Number.isNaN(y = arguments[i++]))
x = op(x, y);
return x;
};
}
const N = Infinity;
return new Environment()
.addConstant({ name: "Infinity" , value: Infinity })
.addConstant({ name: "NaN" , value: NaN })
.addConstant({ name: "PI" , value: Math.PI })
.addUnary ({ name: "-" , prec: 3, rtl : 1, safe: true, eval: function(val) { return -val; }, emit: "-(@1)" })
.addUnary ({ name: "!" , prec: 3, rtl : 1, safe: true, eval: function(val) { return +!val; }, emit: "+!(@1)" })
.addBinary ({ name: "+" , prec: 6, rtl : 0, safe: true, eval: function(x,y) { return x + y; }, emit: "@1 + @2" })
.addBinary ({ name: "-" , prec: 6, rtl : 0, safe: true, eval: function(x,y) { return x - y; }, emit: "@1 - @2" })
.addBinary ({ name: "*" , prec: 5, rtl : 0, safe: true, eval: function(x,y) { return x * y; }, emit: "@1 * @2" })
.addBinary ({ name: "/" , prec: 5, rtl : 0, safe: true, eval: function(x,y) { return x / y; }, emit: "@1 / @2" })
.addBinary ({ name: "%" , prec: 5, rtl : 0, safe: true, eval: function(x,y) { return x % y; }, emit: "@1 % @2" })
.addBinary ({ name: "&&" , prec:13, rtl : 0, safe: true, eval: function(x,y) { return +(x && y); }, emit: "+(@1 && @2)" })
.addBinary ({ name: "||" , prec:14, rtl : 0, safe: true, eval: function(x,y) { return +(x || y); }, emit: "+(@1 || @2)" })
.addBinary ({ name: "==" , prec: 9, rtl : 0, safe: true, eval: function(x,y) { return +(x === y); }, emit: "+(@1 === @2)" })
.addBinary ({ name: "!=" , prec: 9, rtl : 0, safe: true, eval: function(x,y) { return +(x !== y); }, emit: "+(@1 !== @2)" })
.addBinary ({ name: "<" , prec: 8, rtl : 0, safe: true, eval: function(x,y) { return +(x < y); }, emit: "+(@1 < @2)" })
.addBinary ({ name: "<=" , prec: 8, rtl : 0, safe: true, eval: function(x,y) { return +(x <= y); }, emit: "+(@1 <= @2)" })
.addBinary ({ name: ">" , prec: 8, rtl : 0, safe: true, eval: function(x,y) { return +(x > y); }, emit: "+(@1 > @2)" })
.addBinary ({ name: ">=" , prec: 8, rtl : 0, safe: true, eval: function(x,y) { return +(x >= y); }, emit: "+(@1 >= @2)" })
.addBinary ({ name: "?" , prec:20, rtl : 0, safe: true, lang: "ternary-if" , emit: "@1 ? @2" })
.addBinary ({ name: ":" , prec:20, rtl : 0, safe: true, lang: "ternary-else", emit: "@1 : @2" })
.addFunction({ name: "isinf" , args: 1, amax: 1, safe: true, eval: isinf })
.addFunction({ name: "isint" , args: 1, amax: 1, safe: true, eval: isint , emit: "+Number.isInteger(@1)"})
.addFunction({ name: "issafeint", args: 1, amax: 1, safe: true, eval: issafeint, emit: "+Number.isSafeInteger(@1)"})
.addFunction({ name: "isnan" , args: 1, amax: 1, safe: true, eval: isnan , emit: "+Number.isNaN(@1)"})
.addFunction({ name: "isfinite" , args: 1, amax: 1, safe: true, eval: isfinite , emit: "+Number.isFinite(@1)" })
.addFunction({ name: "isequal" , args: 2, amax: 2, safe: true, eval: isequal , emit: "+Object.is(@1, @2)" })
.addFunction({ name: "abs" , args: 1, amax: 1, safe: true, eval: Math.abs })
.addFunction({ name: "sign" , args: 1, amax: 1, safe: true, eval: Math.sign })
.addFunction({ name: "round" , args: 1, amax: 1, safe: true, eval: Math.round })
.addFunction({ name: "trunc" , args: 1, amax: 1, safe: true, eval: Math.trunc })
.addFunction({ name: "floor" , args: 1, amax: 1, safe: true, eval: Math.floor })
.addFunction({ name: "ceil" , args: 1, amax: 1, safe: true, eval: Math.ceil })
.addFunction({ name: "frac" , args: 1, amax: 1, safe: true, eval: frac })
.addFunction({ name: "sqrt" , args: 1, amax: 1, safe: true, eval: Math.sqrt })
.addFunction({ name: "cbrt" , args: 1, amax: 1, safe: true, eval: Math.cbrt })
.addFunction({ name: "exp" , args: 1, amax: 1, safe: true, eval: Math.exp })
.addFunction({ name: "expm1" , args: 1, amax: 1, safe: true, eval: Math.expm1 })
.addFunction({ name: "log" , args: 1, amax: 1, safe: true, eval: Math.log })
.addFunction({ name: "log10" , args: 1, amax: 1, safe: true, eval: Math.log10 })
.addFunction({ name: "log1p" , args: 1, amax: 1, safe: true, eval: Math.log1p })
.addFunction({ name: "log2" , args: 1, amax: 1, safe: true, eval: Math.log2 })
.addFunction({ name: "sin" , args: 1, amax: 1, safe: true, eval: Math.sin })
.addFunction({ name: "sinh" , args: 1, amax: 1, safe: true, eval: Math.sinh })
.addFunction({ name: "cos" , args: 1, amax: 1, safe: true, eval: Math.cos })
.addFunction({ name: "cosh" , args: 1, amax: 1, safe: true, eval: Math.cosh })
.addFunction({ name: "tan" , args: 1, amax: 1, safe: true, eval: Math.tan })
.addFunction({ name: "tanh" , args: 1, amax: 1, safe: true, eval: Math.tanh })
.addFunction({ name: "asin" , args: 1, amax: 1, safe: true, eval: Math.asin })
.addFunction({ name: "asinh" , args: 1, amax: 1, safe: true, eval: Math.asinh })
.addFunction({ name: "acos" , args: 1, amax: 1, safe: true, eval: Math.acos })
.addFunction({ name: "acosh" , args: 1, amax: 1, safe: true, eval: Math.acosh })
.addFunction({ name: "atan" , args: 1, amax: 1, safe: true, eval: Math.atan })
.addFunction({ name: "atanh" , args: 1, amax: 1, safe: true, eval: Math.atanh })
.addFunction({ name: "min" , args: 2, amax: N, safe: true, eval: Math.min })
.addFunction({ name: "minval" , args: 2, amax: N, safe: true, eval: minmaxval(Math.min) })
.addFunction({ name: "max" , args: 2, amax: N, safe: true, eval: Math.max })
.addFunction({ name: "maxval" , args: 2, amax: N, safe: true, eval: minmaxval(Math.max) })
.addFunction({ name: "pow" , args: 2, amax: 2, safe: true, eval: Math.pow })
.addFunction({ name: "atan2" , args: 2, amax: 2, safe: true, eval: Math.atan2 })
.addFunction({ name: "hypot" , args: 2, amax: 2, safe: true, eval: Math.hypot })
.addFunction({ name: "clamp" , args: 3, amax: 3, safe: true, eval: clamp })
.addFunction({ name: "isbetween", args: 3, amax: 3, safe: true, eval: isbetween })
.freeze();
})();
}).apply(this, typeof module === "object" && module && module.exports
? [module, "exports"] : [this, "xex"]);