-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmodel.js
2575 lines (2449 loc) · 77.1 KB
/
model.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
/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
* Copyright 2013 Art Compiler LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
/*
Backward.js defines lexically scoped functions to support backward
compatibility with IE8.
Derived from https://github.com/kriskowal/es5-shim
*/
// ES5 15.4.4.18
// http://es5.github.com/#x15.4.4.18
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach
// Check failure of by-index access of string characters (IE < 9)
// and failure of `0 in boxedString` (Rhino)
var boxedString = Object("a"),
splitString = boxedString[0] != "a" || !(0 in boxedString);
var forEach = function forEach(array, fun) {
var thisp = arguments[2];
if (Array.prototype.forEach) {
return array.forEach(fun);
}
var object = toObject(array),
self = splitString && _toString(object) == "[object String]" ? object.split("") : object,
i = -1,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
while (++i < length) {
if (i in self) {
// Invoke the callback function with call, passing arguments:
// context, property value, property key, thisArg object
// context
fun.call(thisp, self[i], i, object);
}
}
};
// ES5 15.4.4.20
// http://es5.github.com/#x15.4.4.20
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter
var filter = function filter(array, fun /*, thisp */) {
var thisp = arguments[2];
if (Array.prototype.filter) {
return array.filter(fun);
}
var object = toObject(array),
self = splitString && _toString(array) == "[object String]" ? array.split("") : object,
length = self.length >>> 0,
result = [],
value;
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self) {
value = self[i];
if (fun.call(thisp, value, i, object)) {
result.push(value);
}
}
}
return result;
};
// ES5 15.4.4.16
// http://es5.github.com/#x15.4.4.16
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every
var every = function every(array, fun /*, thisp */) {
var thisp = arguments[2];
if (Array.prototype.every) {
return array.every(fun, thisp);
}
var object = toObject(array),
self = splitString && _toString(array) == "[object String]" ? array.split("") : object,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
// ES5 15.4.4.17
// http://es5.github.com/#x15.4.4.17
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
var some = function some(array, fun /*, thisp */) {
var thisp = arguments[2];
if (Array.prototype.some) {
return array.some(fun, thisp);
}
var object = toObject(array),
self = splitString && _toString(array) == "[object String]" ? array.split("") : object,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && fun.call(thisp, self[i], i, object)) {
return true;
}
}
return false;
};
// ES5 15.4.4.14
// http://es5.github.com/#x15.4.4.14
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
var indexOf = function indexOf(array, sought /*, fromIndex */ ) {
var fromIndex = arguments[2];
if (Array.prototype.indexOf || typeof array === "string") {
return array.indexOf(sought, fromIndex);
}
var self = splitString && _toString(array) == "[object String]" ? array.split("") : toObject(array),
length = self.length >>> 0;
if (!length) {
return -1;
}
var i = 0;
if (arguments.length > 2) {
i = toInteger(fromIndex);
}
// handle negative indices
i = i >= 0 ? i : Math.max(0, length + i);
for (; i < length; i++) {
if (i in self && self[i] === sought) {
return i;
}
}
return -1;
};
// ES5 15.2.3.14
// http://es5.github.com/#x15.2.3.14
var keys = function keys(object) {
if (Object.keys) {
return Object.keys(object);
}
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
var hasDontEnumBug = true,
dontEnums = [
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
],
dontEnumsLength = dontEnums.length;
for (var key in {"toString": null}) {
hasDontEnumBug = false;
}
if ((typeof object != "object" && typeof object != "function") ||
object === null) {
throw new TypeError("Object.keys called on a non-object");
}
var keys = [];
for (var name in object) {
if (owns(object, name)) {
keys.push(name);
}
}
if (hasDontEnumBug) {
for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
var dontEnum = dontEnums[i];
if (owns(object, dontEnum)) {
keys.push(dontEnum);
}
}
}
return keys;
};
// ES5 9.9
// http://es5.github.com/#x9.9
var toObject = function (o) {
if (o == null) { // this matches both null and undefined
throw new TypeError("can't convert "+o+" to object");
}
return Object(o);
};
//var call = Function.prototype.call;
//var prototypeOfArray = Array.prototype;
var prototypeOfObject = Object.prototype;
//var _Array_slice_ = prototypeOfArray.slice;
// Having a toString local variable name breaks in Opera so use _toString.
var _toString = function (val) { return prototypeOfObject.toString.apply(val); }; //call.bind(prototypeOfObject.toString);
var owns = function (object, name) { return prototypeOfObject.hasOwnProperty.call(object, name); }; //call.bind(prototypeOfObject.hasOwnProperty);
var create = function create(o) {
if(Object.create) {
return Object.create(o)
}
var F = function () {};
if (arguments.length != 1) {
throw new Error('Object.create implementation only accepts one parameter.');
}
F.prototype = o;
return new F();
};
// From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
if (typeof window === "object" && !window.JSON) {
window.JSON = {
parse: function(sJSON) { return eval('(' + sJSON + ')'); },
stringify: (function () {
var toString = Object.prototype.toString;
var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; };
var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'};
var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); };
var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g;
return function stringify(value) {
if (value == null) {
return 'null';
} else if (typeof value === 'number') {
return isFinite(value) ? value.toString() : 'null';
} else if (typeof value === 'boolean') {
return value.toString();
} else if (typeof value === 'object') {
if (typeof value.toJSON === 'function') {
return stringify(value.toJSON());
} else if (isArray(value)) {
var res = '[';
for (var i = 0; i < value.length; i++)
res += (i ? ', ' : '') + stringify(value[i]);
return res + ']';
} else if (toString.call(value) === '[object Object]') {
var tmp = [];
for (var k in value) {
if (value.hasOwnProperty(k))
tmp.push(stringify(k) + ': ' + stringify(value[k]));
}
return '{' + tmp.join(', ') + '}';
}
}
return '"' + value.toString().replace(escRE, escFunc) + '"';
};
})()
};
}
/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
* Copyright 2013 Art Compiler LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
/*
ASSERTS AND MESSAGES
We use the 'assert()' function to trap invalid states of all kinds. External
messages are distinguished from internal messages by a numeric prefix that
indicates the error code associated with the message. For example, the
following two asserts implement an internal and external assert, respectively.
assert(false, "This code is broken.");
assert(false, "1001: Invalid user input.");
To aid in the writing of external messages, we keep them in a single global
table named 'Assert.messages'. Each module adds to this table its own messages
with an expression such as
messages[1001] = "Invalid user input.";
These messages are accessed with the 'message' function as such
message(1001);
Calling 'assert' with 'message' looks like
assert(x != y, message(1001));
ALLOCATING ERROR CODES
In order to avoid error code conflicts, each module claims a range of values
that is not already taken by the modules in the same system. A module claims
a range of codes by calling the function reserveCodeRange() like this:
reserveCodeRange(1000, 1999, "mymodule");
If the requested code range has any values that are already reserved, then
an assertion is raised.
USAGE
In general, only allocate message codes for external asserts. For internal
asserts, it is sufficient to simply inline the message text in the assert
expression.
It is good to write an assert for every undefined state, regardless of whether
it is the result of external input or not. Asserts can then be externalized if
and when they it is clear that they are the result of external input.
A client module can override the messages provided by the libraries it uses by
simply redefining those messages after the defining library is loaded. That is,
the client can copy and past the statements of the form
messages[1001] = "Invalid user input.";
and provide new text for the message.
messages[1001] = "Syntax error.";
In the same way different sets of messages can be overridden for the purpose
of localization.
*/
var ASSERT = true;
var assert = (function () {
return !ASSERT ?
function () { } :
function (val, str, location) {
if ( str === void 0 ) {
str = "failed!";
}
if ( !val ) {
var err = new Error(str);
err.location = location ? location : Assert.location;
throw err;
}
}
})();
var message = function (errorCode, args) {
var str = Assert.messages[errorCode];
var location = Assert.location;
if (args) {
forEach(args, function (arg, i) {
str = str.replace("%" + (i + 1), arg);
});
}
return errorCode + ": " + str;
};
var reserveCodeRange = function (first, last, moduleName) {
assert(first <= last, "Invalid code range");
var noConflict = every(Assert.reservedCodes, function (range) {
return last < range.first || first > range.last;
});
assert(noConflict, "Conflicting request for error code range");
Assert.reservedCodes.push({first: first, last: last, name: moduleName});
}
var setLocation = function (location) {
//assert(location, "Empty location");
Assert.location = location;
}
var clearLocation = function () {
Assert.location = null;
}
var setCounter = function (count, message) {
Assert.count = count;
Assert.countMessage = message ? message : "ERROR count exceeded";
}
var checkCounter = function () {
var count = Assert.count;
if (typeof count !== "number" || isNaN(count)) {
assert(false, "ERROR counter not set");
return;
}
assert(Assert.count--, Assert.countMessage);
}
// Namespace functions for safe keeping.
var Assert = {
assert: assert,
message: message,
messages: {},
reserveCodeRange: reserveCodeRange,
reservedCodes: [],
setLocation: setLocation,
clearLocation: clearLocation,
setCounter: setCounter,
checkCounter: checkCounter,
};
/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
* Copyright 2013 Art Compiler LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
var TRACE = false;
var global = this;
var trace = (function () {
return !TRACE ?
function () { } :
function trace(str) {
if (global.console && global.console.log) {
console.log(str);
} else if (global.print) {
print(str);
} else {
throw "No trace function defined!";
}
}
})();
/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
* Copyright 2013 Art Compiler LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
/*
This module implements the node factory for abstract syntax trees (AST).
Each node inherits an Ast instance as it prototype.
All Ast instances share the same node pool and therefore intern trees of
identical structure to the same node id.
Construct new nodes using the following forms:
ast.create("+").arg(10).arg(20);
ast.create("+", [10, 20]);
ast.create({op: "+", args: [10, 20]});
Node manipulation functions are chainable.
*/
var Ast = (function () {
// Pool of nodes. Shared between all Ast instances.
var nodePool = [ "unused" ]; // nodePool[0] is reserved
// Maps for fast lookup of nodes. Shared betwen all Ast instances.
var numberMap = {};
var stringMap = {};
var nodeMap = {};
function Ast() {
}
Ast.clearPool = function () {
nodePool = ["unused"];
numberMap = {};
stringMap = {};
nodeMap = {};
}
// Create a node for operation 'op'
Ast.prototype.create = function create(op, args) {
// Create a node that inherits from Ast
var node = create(this);
if (typeof op === "string") {
node.op = op;
if (args instanceof Array) {
node.args = args;
} else {
node.args = [];
}
} else if (op !== null && typeof op === "object") {
var obj = op;
forEach(keys(obj), function (v, i) {
node[v] = obj[v];
});
}
return node;
}
// Append node to this node's args.
Ast.prototype.arg = function arg(node) {
if (!isNode(this)) {
throw "Malformed node";
}
this.args.push(node);
return this;
}
// Get or set the Nth arg of this node.
Ast.prototype.argN = function argN(i, node) {
if (!isNode(this)) {
throw "Malformed node";
}
if (node === undefined) {
return this.args[i];
}
this.args[i] = node;
return this;
}
// Get or set the args of this node.
Ast.prototype.args = function args(a) {
if (!isNode(this)) {
throw "Malformed node";
}
if (a === undefined) {
return this.args;
}
this.args = a;
return this;
}
// Check if obj is a value node object [private]
Ast.prototype.isNode = isNode;
function isNode(obj) {
if (obj === undefined) {
obj = this;
}
return obj.op && obj.args;
}
// Intern an AST into the node pool and return its node id.
Ast.intern = Ast.prototype.intern = function intern(node) {
if (this instanceof Ast &&
node === undefined &&
isNode(this)) {
// We have an Ast that look like a node
node = this;
}
assert(typeof node === "object", "node not an object");
var op = node.op;
var count = node.args.length;
var args = "";
var args_nids = [ ];
for (var i=0; i < count; i++) {
if (typeof node.args[i] === "string") {
args += args_nids[i] = node.args[i];
} else {
args += args_nids[i] = intern(node.args[i]);
}
}
var key = op + count + args;
var nid = nodeMap[key];
if (nid === void 0) {
nodePool.push({
op: op,
args: args_nids,
});
nid = nodePool.length - 1 ;
nodeMap[key] = nid;
}
return nid;
};
// Get a node from the node pool.
Ast.node = Ast.prototype.node = function node(nid) {
var n = JSON.parse(JSON.stringify(nodePool[nid]));
for (var i=0; i < n.args.length; i++) {
// If string, then not a nid.
if (typeof n.args[i] !== "string") {
n.args[i] = this.node(n.args[i]);
}
}
return n;
};
// Dump the contents of the node pool.
Ast.dumpAll = Ast.prototype.dumpAll = function dumpAll() {
var s = "";
var ast = this;
forEach(nodePool, function (n, i) {
s += "\n" + i + ": " + Ast.dump(n);
});
return s;
};
// Dump the contents of a node.
Ast.dump = Ast.prototype.dump = function dump(n) {
if (typeof n === "string") {
var s = "\""+n+"\"";
} else if (typeof n === "number") {
var s = n;
} else {
var s = "{ op: \"" + n.op + "\", args: [ ";
for (var i=0; i < n.args.length; i++) {
if (i > 0) {
s += " , ";
}
s += dump(n.args[i]);
}
s += " ] }";
}
return s;
};
// Self tests
var RUN_SELF_TESTS = false;
function test() {
(function () {
trace("Ast self testing");
var ast = new Ast();
var node1 = {op: "+", args: [10, 20]};
var node2 = {op: "+", args: [10, 30]};
var node3 = {op: "num", args: [10]};
var node4 = ast.create("+").arg(10).arg(30);
var node5 = ast.create("+", [10, 20]);
var node6 = ast.create({op: "+", args: [10, 20]});
var nid1 = ast.intern(node1);
var nid2 = ast.intern(node2);
var nid3 = ast.intern(node3);
var nid4 = node4.intern();
var nid5 = node5.intern();
var nid6 = node6.intern();
var result = nid2 === nid4 ? "PASS" : "FAIL";
trace(result + ": " + "nid2 === nid4");
var result = nid1 === nid5 ? "PASS" : "FAIL";
trace(result + ": " + "nid1 === nid5");
var result = nid5 === nid6 ? "PASS" : "FAIL";
trace(result + ": " + "nid5 === nid6");
})();
}
if (RUN_SELF_TESTS) {
test();
}
return Ast;
})();
/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
* Copyright 2013 Art Compiler LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
This module defines an object model for evaluating and comparing LaTex
strings. The primary data structure is the Model class. Instances of the
Model class contain an AST (Ast instance) and zero or more plugins that
provide functions for evaluating, transforming and comparing models.
Basic Terms
Node - a node is a raw JavaScript object that consists of an 'op' property
that is a string indicating the node type, an 'args' property that is an array
that holds the operands of the operation, and any other "attribute" properties
used by plugins to elaborate the mean meaning of the node.
AST - an AST is an a Node that is an instance of the Ast class. The Ast class
provides methods for constructing and managing nodes.
Model - a model is a Node that is an instance of the Model class, which
inherits from the Ast class. The model class adds methods for creating nodes
from LaTex strings and rendering them to LaTex strings. Model values are
configured by Model plugins that implement operations for evaluating,
transforming and comparing nodes.
Overview
Every model object is also a factory for other model objects that share
the same set of plugins.
Model.fn.isEquivalent; // register plugin function
var model = new Model;
var expected = model.create("1 + 2");
var actual = model.create(response);
model.isEquivalent(expected, actual);
expected.isEquivalent(actual);
When all models in a particular JavaScript sandbox (global scope) use the same
plugins, those plugins can be registered with the Model class as default
plugins, as follows:
*/
"use strict";
var Model = (function () {
function error(str) {
trace("error: " + str);
}
function Model() {
}
Model.fn = {};
Model.env = env = {};
var envStack = [];
var env = {};
Model.pushEnv = function pushEnv(e) {
envStack.push(env);
Model.env = env = e;
}
Model.popEnv = function popEnv() {
assert(envStack.length > 0, "Empty envStack");
Model.env = env = envStack.pop();
}
function isChemCore() {
// Has chem symbols so in chem mode
return !!Model.env["Au"];
}
var Mp = Model.prototype = new Ast();
// Add messages here
Assert.reserveCodeRange(1000, 1999, "model");
Assert.messages[1001] = "Invalid syntax. '%1' expected, '%2' found.";
Assert.messages[1002] = "Only one decimal separator can be specified.";
Assert.messages[1003] = "Extra characters in input at position: %1, lexeme: %2.";
Assert.messages[1004] = "Invalid character '%1' (%2) in input.";
Assert.messages[1005] = "Misplaced thousands separator.";
Assert.messages[1006] = "Unexpected expression: %1";
Assert.messages[1007] = "Unexpected character: '%1' in '%2'.";
Assert.messages[1008] = "The same character '%1' is being used as a thousands and decimal separators.";
Assert.messages[1009] = "Missing argument for '%1' command.";
var message = Assert.message;
// Create a model from a node object or expression string
Model.create = Mp.create = function create(node, location) {
assert(node != undefined, "Model.create() called with invalid argument " + node);
// If we already have a model, then just return it.
if (node instanceof Model) {
if (location) {
node.location = location;
}
return node;
}
var model;
if (node instanceof Array) {
model = [];
forEach(node, function (n) {
model.push(create(n, location));
});
return model;
}
if (!(this instanceof Model)) {
return new Model().create(node, location);
}
// Create a node that inherits from Ast
model = create(this);
model.location = location;
if (typeof node === "string") {
// Got a string, so parse it into a node
node = parse(node, Model.env).expr();
} else {
// Make a deep copy of the node
node = JSON.parse(JSON.stringify(node));
}
// Add missing plugin functions to the Model prototype
forEach(keys(Model.fn), function (v, i) {
if (!Mp.hasOwnProperty(v)) {
Mp[v] = function () {
var fn = Model.fn[v];
if (arguments.length > 1 &&
arguments[1] instanceof Model) {
return fn.apply(this, arguments);
} else {
var args = [this];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
return fn.apply(this, args);
}
}
}
});
// Now copy the node's properties into the model object
forEach(keys(node), function (v, i) {
model[v] = node[v];
});
return model;
};
// Create a Model node from LaTex source.
Model.fromLaTex = Mp.fromLaTex = function fromLaTex(src) {
assert(typeof src === "string", "Model.prototype.fromLaTex");
if (!this) {
return Model.create(src);
}
return this.create(src);
}
// Render LaTex from the model node.
Mp.toLaTex = function toLaTex(node) {
return render(node);
}
var OpStr = {
ADD: "+",
SUB: "-",
MUL: "times",
DIV: "div",
FRAC: "frac",
EQL: "=",
ATAN2: "atan2",
SQRT: "sqrt",
VEC: "vec",
PM: "pm",
SIN: "sin",
COS: "cos",
TAN: "tan",
SEC: "sec",
COT: "cot",
CSC: "csc",
ARCSIN: "arcsin",
ARCCOS: "arccos",
ARCTAN: "arctan",
LOG: "log",
LN: "ln",
LG: "lg",
VAR: "var",
NUM: "num",
CST: "cst",
COMMA: ",",
POW: "^",
SUBSCRIPT: "_",
ABS: "abs",
PAREN: "()",
HIGHLIGHT: "hi",
LT: "lt",
LE: "le",
GT: "gt",
GE: "ge",
NE: "ne",
APPROX: "approx",
INTERVAL: "interval",
LIST: "list",
EXISTS: "exists",
IN: "in",
FORALL: "forall",
LIM: "lim",
EXP: "exp",
TO: "to",
SUM: "sum",
INT: "int",
PROD: "prod",
PERCENT: "%",
M: "M",
RIGHTARROW: "->",
FACT: "fact",
BINOM: "binom",
ROW: "row",
COL: "col",
COLON: "colon",
MATRIX: "matrix",
FORMAT: "format",
OVERSET: "overset",
UNDERSET: "underset",
OVERLINE: "overline",
DEGREE: "degree",
BACKSLASH: "backslash",
MATHBF: "mathbf",
NONE: "none"
};
forEach(keys(OpStr), function (v, i) {
Model[v] = OpStr[v];
});
var OpToLaTeX = {};
OpToLaTeX[OpStr.ADD] = "+";
OpToLaTeX[OpStr.SUB] = "-";
OpToLaTeX[OpStr.MUL] = "\\times";
OpToLaTeX[OpStr.DIV] = "\\div";
OpToLaTeX[OpStr.FRAC] = "\\frac";
OpToLaTeX[OpStr.EQL] = "=";
OpToLaTeX[OpStr.ATAN2] = "\\atan2";
OpToLaTeX[OpStr.POW] = "^";
OpToLaTeX[OpStr.SUBSCRIPT] = "_";
OpToLaTeX[OpStr.PM] = "\\pm";
OpToLaTeX[OpStr.SIN] = "\\sin";
OpToLaTeX[OpStr.COS] = "\\cos";
OpToLaTeX[OpStr.TAN] = "\\tan";
OpToLaTeX[OpStr.ARCSIN] = "\\arcsin";
OpToLaTeX[OpStr.ARCCOS] = "\\arccos";
OpToLaTeX[OpStr.ARCTAN] = "\\arctan";
OpToLaTeX[OpStr.SEC] = "\\sec";
OpToLaTeX[OpStr.COT] = "\\cot";
OpToLaTeX[OpStr.CSC] = "\\csc";
OpToLaTeX[OpStr.LN] = "\\ln";
OpToLaTeX[OpStr.COMMA] = ",";
OpToLaTeX[OpStr.M] = "\\M";
OpToLaTeX[OpStr.BINOM] = "\\binom";
OpToLaTeX[OpStr.COLON] = "\\colon";
Model.fold = function fold(node, env) {
var args = [], val;
forEach(node.args, function (n) {
args.push(fold(n, env));
});
node.args = args;
switch (node.op) {
case OpStr.VAR:
if ((val = env[node.args[0]])) {
node = val; // Replace var node with its value.
}
break;
default:
// Nothing to fold.
break;
}
return node;
}
// Render an AST to LaTex
var render = function render(n) {
var text = "";
if (typeof n === "string") {
text = n;
} else if (typeof n === "number") {
text = n;
} else if (typeof n === "object") {
// render sub-expressions
var args = [];
for (var i = 0; i < n.args.length; i++) {
args[i] = render(n.args[i]);
}
// render operator