forked from NeilFraser/JS-Interpreter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interpreter.js
4826 lines (4576 loc) · 161 KB
/
interpreter.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
/**
* @license
* Copyright 2013 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Interpreting JavaScript in JavaScript.
* @author [email protected] (Neil Fraser)
*/
'use strict';
/**
* Create a new interpreter.
* @param {string|!Object} code Raw JavaScript text or AST.
* @param {Function=} opt_initFunc Optional initialization function. Used to
* define APIs. When called it is passed the interpreter object and the
* global scope object.
* @constructor
*/
var Interpreter = function(code, opt_initFunc) {
if (typeof code === 'string') {
code = this.parse_(code, 'code');
}
// Get a handle on Acorn's node_t object.
var nodeConstructor = code.constructor;
this.newNode = function() {
return new nodeConstructor({'options': {}});
};
// Clone the root 'Program' node so that the AST may be modified.
var ast = this.newNode();
for (var prop in code) {
ast[prop] = (prop === 'body') ? code[prop].slice() : code[prop];
}
this.ast = ast;
/**
* Sorted array of setTimeout/setInterval tasks waiting to execute.
*/
this.tasks = [];
this.initFunc_ = opt_initFunc;
/**
* True if the interpreter is paused while waiting for an async function.
*/
this.paused_ = false;
this.polyfills_ = [];
// Unique identifier for native functions. Used in serialization.
this.functionCounter_ = 0;
// Map node types to our step function names; a property lookup is faster
// than string concatenation with "step" prefix.
this.stepFunctions_ = Object.create(null);
var stepMatch = /^step([A-Z]\w*)$/;
var m;
for (var methodName in this) {
if ((typeof this[methodName] === 'function') &&
(m = methodName.match(stepMatch))) {
this.stepFunctions_[m[1]] = this[methodName].bind(this);
}
}
// Create and initialize the global scope.
this.globalScope = this.createScope(this.ast, null);
this.globalObject = this.globalScope.object;
// Run the polyfills.
this.ast = this.parse_(this.polyfills_.join('\n'), 'polyfills');
this.polyfills_ = undefined; // Allow polyfill strings to garbage collect.
Interpreter.stripLocations_(this.ast, undefined, undefined);
var state = new Interpreter.State(this.ast, this.globalScope);
state.done = false;
this.stateStack = [state];
this.run();
this.value = undefined;
// Point at the main program.
this.ast = ast;
state = new Interpreter.State(this.ast, this.globalScope);
state.done = false;
this.stateStack.length = 0;
this.stateStack[0] = state;
};
/**
* Completion Value Types.
* @enum {number}
*/
Interpreter.Completion = {
NORMAL: 0,
BREAK: 1,
CONTINUE: 2,
RETURN: 3,
THROW: 4,
};
/**
* Interpreter status values.
* @enum {number}
*/
Interpreter.Status = {
'DONE': 0,
'STEP': 1,
'TASK': 2,
'ASYNC': 3,
};
/**
* @const {!Object} Configuration used for all Acorn parsing.
*/
Interpreter.PARSE_OPTIONS = {
locations: true,
ecmaVersion: 5, // Needed in the event a version > 0.5.0 of Acorn is used.
};
/**
* Property descriptor of readonly properties.
*/
Interpreter.READONLY_DESCRIPTOR = {
'configurable': true,
'enumerable': true,
'writable': false,
};
/**
* Property descriptor of non-enumerable properties.
*/
Interpreter.NONENUMERABLE_DESCRIPTOR = {
'configurable': true,
'enumerable': false,
'writable': true,
};
/**
* Property descriptor of readonly, non-enumerable properties.
*/
Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR = {
'configurable': true,
'enumerable': false,
'writable': false,
};
/**
* Property descriptor of non-configurable, readonly, non-enumerable properties.
* E.g. NaN, Infinity.
*/
Interpreter.NONCONFIGURABLE_READONLY_NONENUMERABLE_DESCRIPTOR = {
'configurable': false,
'enumerable': false,
'writable': false,
};
/**
* Property descriptor of variables.
*/
Interpreter.VARIABLE_DESCRIPTOR = {
'configurable': false,
'enumerable': true,
'writable': true,
};
/**
* Unique symbol for indicating that a step has encountered an error, has
* added it to the stack, and will be thrown within the user's program.
* When STEP_ERROR is thrown in the JS-Interpreter, the error can be ignored.
*/
Interpreter.STEP_ERROR = {'STEP_ERROR': true};
/**
* Unique symbol for indicating that a reference is a variable on the scope,
* not an object property.
*/
Interpreter.SCOPE_REFERENCE = {'SCOPE_REFERENCE': true};
/**
* Unique symbol for indicating, when used as the value of the value
* parameter in calls to setProperty and friends, that the value
* should be taken from the property descriptor instead.
*/
Interpreter.VALUE_IN_DESCRIPTOR = /** @type {!Interpreter.Value} */({
'VALUE_IN_DESCRIPTOR': true
});
/**
* Unique symbol for indicating that a RegExp timeout has occurred in a VM.
*/
Interpreter.REGEXP_TIMEOUT = {'REGEXP_TIMEOUT': true};
/**
* For cycle detection in array to string and error conversion;
* see spec bug github.com/tc39/ecma262/issues/289
* Since this is for atomic actions only, it can be a class property.
*/
Interpreter.toStringCycles_ = [];
/**
* Node's vm module, if loaded and required.
* @type {Object}
*/
Interpreter.vm = null;
/**
* Currently executing interpreter. Needed so Interpreter.Object instances
* can know their environment.
* @type {Interpreter}
*/
Interpreter.currentInterpreter_ = null;
/**
* The global object. Ideally use `globalThis`. Failing that try `this` or
* `window`. Other options to consider are `self` and `global`.
* Same logic as in Acorn.
*/
Interpreter.nativeGlobal =
(typeof globalThis === 'undefined') ? this || window : globalThis;
/**
* Code for executing regular expressions in a thread.
*/
Interpreter.WORKER_CODE = [
"onmessage = function(e) {",
"var result;",
"var data = e.data;",
"switch (data[0]) {",
"case 'split':",
// ['split', string, separator, limit]
"result = data[1].split(data[2], data[3]);",
"break;",
"case 'match':",
// ['match', string, regexp]
"result = data[1].match(data[2]);",
"break;",
"case 'search':",
// ['search', string, regexp]
"result = data[1].search(data[2]);",
"break;",
"case 'replace':",
// ['replace', string, regexp, newSubstr]
"result = data[1].replace(data[2], data[3]);",
"break;",
"case 'exec':",
// ['exec', regexp, lastIndex, string]
"var regexp = data[1];",
"regexp.lastIndex = data[2];",
"result = [regexp.exec(data[3]), data[1].lastIndex];",
"break;",
"default:",
"throw Error('Unknown RegExp operation: ' + data[0]);",
"}",
"postMessage(result);",
"close();",
"};"];
/**
* Is a value a legal integer for an array length?
* @param {Interpreter.Value} x Value to check.
* @returns {number} Zero, or a positive integer if the value can be
* converted to such. NaN otherwise.
*/
Interpreter.legalArrayLength = function(x) {
var n = x >>> 0;
// Array length must be between 0 and 2^32-1 (inclusive).
return (n === Number(x)) ? n : NaN;
};
/**
* Is a value a legal integer for an array index?
* @param {Interpreter.Value} x Value to check.
* @returns {number} Zero, or a positive integer if the value can be
* converted to such. NaN otherwise.
*/
Interpreter.legalArrayIndex = function(x) {
var n = x >>> 0;
// Array index cannot be 2^32-1, otherwise length would be 2^32.
// 0xffffffff is 2^32-1.
return (String(n) === String(x) && n !== 0xffffffff) ? n : NaN;
};
/**
* Remove start and end values from AST, or set start and end values to a
* constant value. Used to remove highlighting from polyfills and to set
* highlighting in an eval to cover the entire eval expression.
* @param {!Object} node AST node.
* @param {number=} start Starting character of all nodes, or undefined.
* @param {number=} end Ending character of all nodes, or undefined.
* @private
*/
Interpreter.stripLocations_ = function(node, start, end) {
if (start) {
node.start = start;
} else {
delete node.start;
}
if (end) {
node.end = end;
} else {
delete node.end;
}
for (var name in node) {
if (name !== 'loc' && node.hasOwnProperty(name)) {
var prop = node[name];
if (prop && typeof prop === 'object') {
Interpreter.stripLocations_(/** @type {!Object} */(prop), start, end);
}
}
}
};
/**
* Some pathological regular expressions can take geometric time.
* Regular expressions are handled in one of three ways:
* 0 - throw as invalid.
* 1 - execute natively (risk of unresponsive program).
* 2 - execute in separate thread (not supported by IE 9).
*/
Interpreter.prototype['REGEXP_MODE'] = 2;
/**
* If REGEXP_MODE = 2, the length of time (in ms) to allow a RegExp
* thread to execute before terminating it.
*/
Interpreter.prototype['REGEXP_THREAD_TIMEOUT'] = 1000;
/**
* Length of time (in ms) to allow a polyfill to run before ending step.
* If set to 0, polyfills will execute step by step.
* If set to 1000, polyfills will run for up to a second per step
* (execution will resume in the polyfill in the next step).
* If set to Infinity, polyfills will run to completion in a single step.
*/
Interpreter.prototype['POLYFILL_TIMEOUT'] = 1000;
/**
* Flag indicating that a getter function needs to be called immediately.
* @private
*/
Interpreter.prototype.getterStep_ = false;
/**
* Flag indicating that a setter function needs to be called immediately.
* @private
*/
Interpreter.prototype.setterStep_ = false;
/**
* Number of code chunks appended to the interpreter.
* @private
*/
Interpreter.prototype.appendCodeNumber_ = 0;
/**
* Number of parsed tasks.
* @private
*/
Interpreter.prototype.taskCodeNumber_ = 0;
/**
* Parse JavaScript code into an AST using Acorn.
* @param {string} code Raw JavaScript text.
* @param {string} sourceFile Name of filename (for stack trace).
* @returns {!Object} AST.
* @private
*/
Interpreter.prototype.parse_ = function(code, sourceFile) {
// Create a new options object, since Acorn will modify this object.
// Inheritance can't be used since Acorn uses hasOwnProperty.
// Object.assign can't be used since that's ES6.
var options = {};
for (var name in Interpreter.PARSE_OPTIONS) {
options[name] = Interpreter.PARSE_OPTIONS[name];
}
options.sourceFile = sourceFile;
return Interpreter.nativeGlobal.acorn.parse(code, options);
};
/**
* Add more code to the interpreter.
* @param {string|!Object} code Raw JavaScript text or AST.
*/
Interpreter.prototype.appendCode = function(code) {
var state = this.stateStack[0];
if (!state || state.node.type !== 'Program') {
throw Error('Expecting original AST to start with a Program node');
}
if (typeof code === 'string') {
code = this.parse_(code, 'appendCode' + (this.appendCodeNumber_++));
}
if (!code || code.type !== 'Program') {
throw Error('Expecting new AST to start with a Program node');
}
this.populateScope_(code, state.scope);
// Append the new program to the old one.
Array.prototype.push.apply(state.node.body, code.body);
state.node.body.variableCache_ = null;
state.done = false;
};
/**
* Execute one step of the interpreter.
* @returns {boolean} True if a step was executed, false if no more instructions.
*/
Interpreter.prototype.step = function() {
var stack = this.stateStack;
var endTime;
do {
var state = stack[stack.length - 1];
if (this.paused_) {
// Blocked by an asynchronous function.
return true;
} else if (!state || (state.node.type === 'Program' && state.done)) {
if (!this.tasks.length) {
// Main program complete and no queued tasks. We're done!
return false;
}
state = this.nextTask_();
if (!state) {
// Main program complete, queued tasks, but nothing to run right now.
return true;
}
// Found a queued task, execute it.
}
var node = state.node;
// Record the interpreter in a global property so calls to toString/valueOf
// can execute in the proper context.
var oldInterpreterValue = Interpreter.currentInterpreter_;
Interpreter.currentInterpreter_ = this;
try {
var nextState = this.stepFunctions_[node.type](stack, state, node);
} catch (e) {
// Eat any step errors. They have been thrown on the stack.
if (e !== Interpreter.STEP_ERROR) {
// This is a real error, either in the JS-Interpreter, or an uncaught
// error in the interpreted code. Rethrow.
if (this.value !== e) {
// Uh oh. Internal error in the JS-Interpreter.
this.value = undefined;
}
throw e;
}
} finally {
// Restore to previous value (probably null, maybe nested toString calls).
Interpreter.currentInterpreter_ = oldInterpreterValue;
}
if (nextState) {
stack.push(nextState);
}
if (this.getterStep_) {
// Getter from this step was not handled.
this.value = undefined;
throw Error('Getter not supported in this context');
}
if (this.setterStep_) {
// Setter from this step was not handled.
this.value = undefined;
throw Error('Setter not supported in this context');
}
// This may be polyfill code. Keep executing until we arrive at user code.
if (!endTime && !node.end) {
// Ideally this would be defined at the top of the function, but that
// wastes time if the step isn't a polyfill.
endTime = Date.now() + this['POLYFILL_TIMEOUT'];
}
} while (!node.end && endTime > Date.now());
return true;
};
/**
* Execute the interpreter to program completion. Vulnerable to infinite loops.
* @returns {boolean} True if a execution is asynchronously blocked,
* false if no more instructions.
*/
Interpreter.prototype.run = function() {
while (!this.paused_ && this.step()) {}
return this.paused_;
};
/**
* Current status of the interpreter.
* @returns {Interpreter.Status} One of DONE, STEP, TASK, or ASYNC.
*/
Interpreter.prototype.getStatus = function() {
if (this.paused_) {
return Interpreter.Status['ASYNC'];
}
var stack = this.stateStack;
var state = stack[stack.length - 1];
if (state && (state.node.type !== 'Program' || !state.done)) {
// There's a step ready to execute.
return Interpreter.Status['STEP'];
}
var task = this.tasks[0];
if (task) {
if (task.time > Date.now()) {
// There's a pending task, but it's not ready.
return Interpreter.Status['TASK'];
}
// There's a task ready to execute.
return Interpreter.Status['STEP'];
}
return Interpreter.Status['DONE'];
};
/**
* Initialize the global object with built-in properties and functions.
* @param {!Interpreter.Object} globalObject Global object.
*/
Interpreter.prototype.initGlobal = function(globalObject) {
// Initialize uneditable global properties.
this.setProperty(globalObject, 'NaN', NaN,
Interpreter.NONCONFIGURABLE_READONLY_NONENUMERABLE_DESCRIPTOR);
this.setProperty(globalObject, 'Infinity', Infinity,
Interpreter.NONCONFIGURABLE_READONLY_NONENUMERABLE_DESCRIPTOR);
this.setProperty(globalObject, 'undefined', undefined,
Interpreter.NONCONFIGURABLE_READONLY_NONENUMERABLE_DESCRIPTOR);
this.setProperty(globalObject, 'window', globalObject,
Interpreter.READONLY_DESCRIPTOR);
this.setProperty(globalObject, 'this', globalObject,
Interpreter.NONCONFIGURABLE_READONLY_NONENUMERABLE_DESCRIPTOR);
this.setProperty(globalObject, 'self', globalObject); // Editable.
// Create the objects which will become Object.prototype and
// Function.prototype, which are needed to bootstrap everything else.
this.OBJECT_PROTO = new Interpreter.Object(null);
this.FUNCTION_PROTO = new Interpreter.Object(this.OBJECT_PROTO);
// Initialize global objects.
this.initFunction(globalObject);
this.initObject(globalObject);
// Unable to set globalObject's parent prior (OBJECT did not exist).
// Note that in a browser this would be `Window`, whereas in Node.js it would
// be `Object`. This interpreter is closer to Node in that it has no DOM.
globalObject.proto = this.OBJECT_PROTO;
this.setProperty(globalObject, 'constructor', this.OBJECT,
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.initArray(globalObject);
this.initString(globalObject);
this.initBoolean(globalObject);
this.initNumber(globalObject);
this.initDate(globalObject);
this.initRegExp(globalObject);
this.initError(globalObject);
this.initMath(globalObject);
this.initJSON(globalObject);
// Initialize global functions.
var thisInterpreter = this;
var wrapper;
var func = this.createNativeFunction(
function(_x) {throw EvalError("Can't happen");}, false);
func.eval = true;
this.setProperty(globalObject, 'eval', func,
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.setProperty(globalObject, 'parseInt',
this.createNativeFunction(parseInt, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.setProperty(globalObject, 'parseFloat',
this.createNativeFunction(parseFloat, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.setProperty(globalObject, 'isNaN',
this.createNativeFunction(isNaN, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.setProperty(globalObject, 'isFinite',
this.createNativeFunction(isFinite, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
var strFunctions = [
[escape, 'escape'], [unescape, 'unescape'],
[decodeURI, 'decodeURI'], [decodeURIComponent, 'decodeURIComponent'],
[encodeURI, 'encodeURI'], [encodeURIComponent, 'encodeURIComponent']
];
for (var i = 0; i < strFunctions.length; i++) {
wrapper = (function(nativeFunc) {
return function(str) {
try {
return nativeFunc(str);
} catch (e) {
// decodeURI('%xy') will throw an error. Catch and rethrow.
thisInterpreter.throwException(thisInterpreter.URI_ERROR, e.message);
}
};
})(strFunctions[i][0]);
this.setProperty(globalObject, strFunctions[i][1],
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
}
wrapper = function setTimeout(var_args) {
return thisInterpreter.createTask_(false, arguments);
};
this.setProperty(globalObject, 'setTimeout',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function setInterval(var_args) {
return thisInterpreter.createTask_(true, arguments);
};
this.setProperty(globalObject, 'setInterval',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function clearTimeout(pid) {
thisInterpreter.deleteTask_(pid);
};
this.setProperty(globalObject, 'clearTimeout',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function clearInterval(pid) {
thisInterpreter.deleteTask_(pid);
};
this.setProperty(globalObject, 'clearInterval',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
// Preserve public properties from being pruned/renamed by JS compilers.
// Add others as needed.
this['OBJECT'] = this.OBJECT; this['OBJECT_PROTO'] = this.OBJECT_PROTO;
this['FUNCTION'] = this.FUNCTION; this['FUNCTION_PROTO'] = this.FUNCTION_PROTO;
this['ARRAY'] = this.ARRAY; this['ARRAY_PROTO'] = this.ARRAY_PROTO;
this['REGEXP'] = this.REGEXP; this['REGEXP_PROTO'] = this.REGEXP_PROTO;
this['DATE'] = this.DATE; this['DATE_PROTO'] = this.DATE_PROTO;
// Run any user-provided initialization.
if (this.initFunc_) {
this.initFunc_(this, globalObject);
}
};
/**
* Number of functions created by the interpreter.
* @private
*/
Interpreter.prototype.functionCodeNumber_ = 0;
/**
* Initialize the Function class.
* @param {!Interpreter.Object} globalObject Global object.
*/
Interpreter.prototype.initFunction = function(globalObject) {
var thisInterpreter = this;
var wrapper;
var identifierRegexp = /^[A-Za-z_$][\w$]*$/;
// Function constructor.
wrapper = function Function(var_args) {
if (arguments.length) {
var code = String(arguments[arguments.length - 1]);
} else {
var code = '';
}
var argsStr = Array.prototype.slice.call(arguments, 0, -1).join(',').trim();
if (argsStr) {
var args = argsStr.split(/\s*,\s*/);
for (var i = 0; i < args.length; i++) {
var name = args[i];
if (!identifierRegexp.test(name)) {
thisInterpreter.throwException(thisInterpreter.SYNTAX_ERROR,
'Invalid function argument: ' + name);
}
}
argsStr = args.join(', ');
}
// Acorn needs to parse code in the context of a function or else `return`
// statements will be syntax errors.
try {
var ast = thisInterpreter.parse_('(function(' + argsStr + ') {' + code + '})',
'function' + (thisInterpreter.functionCodeNumber_++));
} catch (e) {
// Acorn threw a SyntaxError. Rethrow as a trappable error.
thisInterpreter.throwException(thisInterpreter.SYNTAX_ERROR,
'Invalid code: ' + e.message);
}
if (ast.body.length !== 1) {
// Function('a', 'return a + 6;}; {alert(1);');
thisInterpreter.throwException(thisInterpreter.SYNTAX_ERROR,
'Invalid code in function body');
}
var node = ast.body[0].expression;
// Note that if this constructor is called as `new Function()` the function
// object created by stepCallExpression and assigned to `this` is discarded.
// Interestingly, the scope for constructed functions is the global scope,
// even if they were constructed in some other scope.
return thisInterpreter.createFunction(node, thisInterpreter.globalScope,
'anonymous');
};
this.FUNCTION = this.createNativeFunction(wrapper, true);
this.setProperty(globalObject, 'Function', this.FUNCTION,
Interpreter.NONENUMERABLE_DESCRIPTOR);
// Throw away the created prototype and use the root prototype.
this.setProperty(this.FUNCTION, 'prototype', this.FUNCTION_PROTO,
Interpreter.NONENUMERABLE_DESCRIPTOR);
// Configure Function.prototype.
this.setProperty(this.FUNCTION_PROTO, 'constructor', this.FUNCTION,
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.FUNCTION_PROTO.nativeFunc = function() {};
this.FUNCTION_PROTO.nativeFunc.id = this.functionCounter_++;
this.FUNCTION_PROTO.illegalConstructor = true;
this.setProperty(this.FUNCTION_PROTO, 'length', 0,
Interpreter.READONLY_NONENUMERABLE_DESCRIPTOR);
this.FUNCTION_PROTO.class = 'Function';
wrapper = function apply_(func, thisArg, args) {
var state =
thisInterpreter.stateStack[thisInterpreter.stateStack.length - 1];
// Rewrite the current CallExpression state to apply a different function.
// Note: 'func' is provided by the polyfill as a non-standard argument.
state.func_ = func;
// Assign the `this` object.
state.funcThis_ = thisArg;
// Bind any provided arguments.
state.arguments_ = [];
if (args !== null && args !== undefined) {
if (args instanceof Interpreter.Object) {
// Convert the pseudo array of args into a native array.
// The pseudo array's properties object happens to be array-like.
state.arguments_ = Array.from(args.properties);
} else {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
'CreateListFromArrayLike called on non-object');
}
}
state.doneExec_ = false;
};
this.setNativeFunctionPrototype(this.FUNCTION, 'apply', wrapper);
this.polyfills_.push(
// Flatten the apply args list to remove any inheritance or getter functions.
"(function() {",
"var apply_ = Function.prototype.apply;",
"Function.prototype.apply = function apply(thisArg, args) {",
"var a2 = [];",
"for (var i = 0; i < args.length; i++) {",
"a2[i] = args[i];",
"}",
"return apply_(this, thisArg, a2);", // Note: Non-standard 'this' arg.
"};",
"})();");
wrapper = function call(thisArg /*, var_args */) {
var state =
thisInterpreter.stateStack[thisInterpreter.stateStack.length - 1];
// Rewrite the current CallExpression state to call a different function.
state.func_ = this;
// Assign the `this` object.
state.funcThis_ = thisArg;
// Bind any provided arguments.
state.arguments_ = [];
for (var i = 1; i < arguments.length; i++) {
state.arguments_.push(arguments[i]);
}
state.doneExec_ = false;
};
this.setNativeFunctionPrototype(this.FUNCTION, 'call', wrapper);
this.polyfills_.push(
// Polyfill copied from:
// developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
"Object.defineProperty(Function.prototype, 'bind',",
"{configurable: true, writable: true, value:",
"function bind(oThis) {",
"if (typeof this !== 'function') {",
"throw TypeError('What is trying to be bound is not callable');",
"}",
"var aArgs = Array.prototype.slice.call(arguments, 1),",
"fToBind = this,",
"fNOP = function() {},",
"fBound = function() {",
"return fToBind.apply(this instanceof fNOP",
"? this",
": oThis,",
"aArgs.concat(Array.prototype.slice.call(arguments)));",
"};",
"if (this.prototype) {",
"fNOP.prototype = this.prototype;",
"}",
"fBound.prototype = new fNOP();",
"return fBound;",
"}",
"});",
"");
// Function has no parent to inherit from, so it needs its own mandatory
// toString and valueOf functions.
wrapper = function toString() {
return String(this);
};
this.setNativeFunctionPrototype(this.FUNCTION, 'toString', wrapper);
this.setProperty(this.FUNCTION, 'toString',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function valueOf() {
return this.valueOf();
};
this.setNativeFunctionPrototype(this.FUNCTION, 'valueOf', wrapper);
this.setProperty(this.FUNCTION, 'valueOf',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
};
/**
* Initialize the Object class.
* @param {!Interpreter.Object} globalObject Global object.
*/
Interpreter.prototype.initObject = function(globalObject) {
var thisInterpreter = this;
var wrapper;
// Object constructor.
wrapper = function Object(value) {
if (value === undefined || value === null) {
// Create a new object.
if (thisInterpreter.calledWithNew()) {
// Called as `new Object()`.
return this;
} else {
// Called as `Object()`.
return thisInterpreter.createObjectProto(thisInterpreter.OBJECT_PROTO);
}
}
if (!(value instanceof Interpreter.Object)) {
// Wrap the value as an object.
var box = thisInterpreter.createObjectProto(
thisInterpreter.getPrototype(value));
box.data = value;
return box;
}
// Return the provided object.
return value;
};
this.OBJECT = this.createNativeFunction(wrapper, true);
// Throw away the created prototype and use the root prototype.
this.setProperty(this.OBJECT, 'prototype', this.OBJECT_PROTO,
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.setProperty(this.OBJECT_PROTO, 'constructor', this.OBJECT,
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.setProperty(globalObject, 'Object', this.OBJECT,
Interpreter.NONENUMERABLE_DESCRIPTOR);
/**
* Checks if the provided value is null or undefined.
* If so, then throw an error in the call stack.
* @param {Interpreter.Value} value Value to check.
*/
var throwIfNullUndefined = function(value) {
if (value === undefined || value === null) {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
"Cannot convert '" + value + "' to object");
}
};
// Static methods on Object.
wrapper = function getOwnPropertyNames(obj) {
throwIfNullUndefined(obj);
var props = (obj instanceof Interpreter.Object) ? obj.properties : obj;
return thisInterpreter.nativeToPseudo(Object.getOwnPropertyNames(props));
};
this.setProperty(this.OBJECT, 'getOwnPropertyNames',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function keys(obj) {
throwIfNullUndefined(obj);
if (obj instanceof Interpreter.Object) {
obj = obj.properties;
}
return thisInterpreter.nativeToPseudo(Object.keys(obj));
};
this.setProperty(this.OBJECT, 'keys',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function create_(proto) {
// Support for the second argument is the responsibility of a polyfill.
if (proto === null) {
return thisInterpreter.createObjectProto(null);
}
if (!(proto instanceof Interpreter.Object)) {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
'Object prototype may only be an Object or null, not ' + proto);
}
return thisInterpreter.createObjectProto(proto);
};
this.setProperty(this.OBJECT, 'create',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
// Add a polyfill to handle create's second argument.
this.polyfills_.push(
"(function() {",
"var create_ = Object.create;",
"Object.create = function create(proto, props) {",
"var obj = create_(proto);",
"props && Object.defineProperties(obj, props);",
"return obj;",
"};",
"})();",
"");
wrapper = function defineProperty(obj, prop, descriptor) {
prop = String(prop);
if (!(obj instanceof Interpreter.Object)) {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
'Object.defineProperty called on non-object: ' + obj);
}
if (!(descriptor instanceof Interpreter.Object)) {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
'Property description must be an object');
}
if (obj.preventExtensions && !(prop in obj.properties)) {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
"Can't define property '" + prop + "', object is not extensible");
}
// The polyfill guarantees no inheritance and no getter functions.
// Therefore the descriptor properties map is the native object needed.
thisInterpreter.setProperty(obj, prop, Interpreter.VALUE_IN_DESCRIPTOR,
descriptor.properties);
return obj;
};
this.setProperty(this.OBJECT, 'defineProperty',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
this.polyfills_.push(
// Flatten the descriptor to remove any inheritance or getter functions.
"(function() {",
"var defineProperty_ = Object.defineProperty;",
"Object.defineProperty = function defineProperty(obj, prop, d1) {",
"var d2 = {};",
"if ('configurable' in d1) d2.configurable = d1.configurable;",
"if ('enumerable' in d1) d2.enumerable = d1.enumerable;",
"if ('writable' in d1) d2.writable = d1.writable;",
"if ('value' in d1) d2.value = d1.value;",
"if ('get' in d1) d2.get = d1.get;",
"if ('set' in d1) d2.set = d1.set;",
"return defineProperty_(obj, prop, d2);",
"};",
"})();",
"Object.defineProperty(Object, 'defineProperties',",
"{configurable: true, writable: true, value:",
"function defineProperties(obj, props) {",
"var keys = Object.keys(props);",
"for (var i = 0; i < keys.length; i++) {",
"Object.defineProperty(obj, keys[i], props[keys[i]]);",
"}",
"return obj;",
"}",
"});",
"");
wrapper = function getOwnPropertyDescriptor(obj, prop) {
if (!(obj instanceof Interpreter.Object)) {
thisInterpreter.throwException(thisInterpreter.TYPE_ERROR,
'Object.getOwnPropertyDescriptor called on non-object: ' + obj);
}
prop = String(prop);
if (!(prop in obj.properties)) {
return undefined;
}
var descriptor = Object.getOwnPropertyDescriptor(obj.properties, prop);
var getter = obj.getter[prop];
var setter = obj.setter[prop];
var pseudoDescriptor =
thisInterpreter.createObjectProto(thisInterpreter.OBJECT_PROTO);
if (getter || setter) {
thisInterpreter.setProperty(pseudoDescriptor, 'get', getter);
thisInterpreter.setProperty(pseudoDescriptor, 'set', setter);
} else {
thisInterpreter.setProperty(pseudoDescriptor, 'value',
/** @type {!Interpreter.Value} */(descriptor['value']));
thisInterpreter.setProperty(pseudoDescriptor, 'writable',
descriptor['writable']);
}
thisInterpreter.setProperty(pseudoDescriptor, 'configurable',
descriptor['configurable']);
thisInterpreter.setProperty(pseudoDescriptor, 'enumerable',
descriptor['enumerable']);
return pseudoDescriptor;
};
this.setProperty(this.OBJECT, 'getOwnPropertyDescriptor',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function getPrototypeOf(obj) {
throwIfNullUndefined(obj);
return thisInterpreter.getPrototype(obj);
};
this.setProperty(this.OBJECT, 'getPrototypeOf',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function isExtensible(obj) {
return Boolean(obj) && !obj.preventExtensions;
};
this.setProperty(this.OBJECT, 'isExtensible',
this.createNativeFunction(wrapper, false),
Interpreter.NONENUMERABLE_DESCRIPTOR);
wrapper = function preventExtensions(obj) {
if (obj instanceof Interpreter.Object) {
obj.preventExtensions = true;
}
return obj;