1
/* ***** BEGIN LICENSE BLOCK *****
2
* vim: set ts=4 sw=4 et tw=80:
4
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
6
* The contents of this file are subject to the Mozilla Public License Version
7
* 1.1 (the "License"); you may not use this file except in compliance with
8
* the License. You may obtain a copy of the License at
9
* http://www.mozilla.org/MPL/
11
* Software distributed under the License is distributed on an "AS IS" basis,
12
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13
* for the specific language governing rights and limitations under the
16
* The Original Code is the Narcissus JavaScript engine.
18
* The Initial Developer of the Original Code is
19
* Brendan Eich <brendan@mozilla.org>.
20
* Portions created by the Initial Developer are Copyright (C) 2004
21
* the Initial Developer. All Rights Reserved.
25
* Alternatively, the contents of this file may be used under the terms of
26
* either the GNU General Public License Version 2 or later (the "GPL"), or
27
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28
* in which case the provisions of the GPL or the LGPL are applicable instead
29
* of those above. If you wish to allow use of your version of this file only
30
* under the terms of either the GPL or the LGPL, and not to allow others to
31
* use your version of this file under the terms of the MPL, indicate your
32
* decision by deleting the provisions above and replace them with the notice
33
* and other provisions required by the GPL or the LGPL. If you do not delete
34
* the provisions above, a recipient may use your version of this file under
35
* the terms of any one of the MPL, the GPL or the LGPL.
37
* ***** END LICENSE BLOCK ***** */
40
* Narcissus - JS implemented in JS.
42
* Execution of parse trees.
44
* Standard classes except for eval, Function, Array, and String are borrowed
45
* from the host JS environment. Function is metacircular. Array and String
46
* are reflected via wrapping the corresponding native constructor and adding
47
* an extra level of prototype-based delegation.
54
GLOBAL_CODE = 0; EVAL_CODE = 1; FUNCTION_CODE = 2;
56
function ExecutionContext(type) {
61
var agenda = new Array();
67
NaN: NaN, Infinity: Infinity, undefined: undefined,
68
alert : function(msg) { alert(msg) },
69
confirm : function(msg) { return confirm(msg) },
73
//debug: window.open('','debugwindow','width=600,height=400,scrollbars=yes,resizable=yes'),
75
navigator : navigator,
76
XMLHttpRequest : function() { return new XMLHttpRequest() },
77
// Function properties.
79
if (typeof s != "string") {
83
var x = ExecutionContext.current;
84
var x2 = new ExecutionContext(EVAL_CODE);
85
x2.thisObject = x.thisObject;
89
ExecutionContext.current = x2;
91
execute(parse(s), x2);
96
ExecutionContext.current = x;
100
parseInt: parseInt, parseFloat: parseFloat,
101
isNaN: isNaN, isFinite: isFinite,
102
decodeURI: decodeURI, encodeURI: encodeURI,
103
decodeURIComponent: decodeURIComponent,
104
encodeURIComponent: encodeURIComponent,
106
// Class constructors. Where ECMA-262 requires C.length == 1, we declare
107
// a dummy formal parameter.
109
Function: function(dummy) {
110
var p = "", b = "", n = arguments.length;
115
for (var k = 1; k < m; k++)
116
p += "," + arguments[k];
121
// XXX We want to pass a good file and line to the tokenizer.
122
// Note the anonymous name to maintain parity with Spidermonkey.
123
var t = new Tokenizer("anonymous(" + p + ") {" + b + "}");
125
// NB: Use the STATEMENT_FORM constant since we don't want to push this
126
// function onto the null compilation context.
127
var f = FunctionDefinition(t, null, false, STATEMENT_FORM);
128
var s = {object: global, parent: null};
129
return new FunctionObject(f, s);
131
Array: function(dummy) {
132
// Array when called as a function acts as a constructor.
133
return GLOBAL.Array.apply(this, arguments);
135
String: function(s) {
136
// Called as function or constructor: convert argument to string type.
137
s = arguments.length ? "" + s : "";
138
if (this instanceof String) {
139
// Called as constructor: save the argument as the string value
140
// of this String object and return this object.
146
Boolean: Boolean, Number: Number, Date: Date, RegExp: RegExp,
147
Error: Error, EvalError: EvalError, RangeError: RangeError,
148
ReferenceError: ReferenceError, SyntaxError: SyntaxError,
149
TypeError: TypeError, URIError: URIError,
154
// Extensions to ECMA.
158
if (typeof s != "string")
160
var req = new XMLHttpRequest();
161
req.open('GET', s, false);
164
evaluate(req.responseText, s, 1)
166
print: print, version: null
170
//global.debug.document.body.innerHTML = ''
173
// Helper to avoid Object.prototype.hasOwnProperty polluting scope objects.
174
function hasDirectProperty(o, p) {
175
return Object.prototype.hasOwnProperty.call(o, p);
178
// Reflect a host class into the target global environment by delegation.
179
function reflectClass(name, proto) {
180
var gctor = global[name];
181
gctor.prototype = proto;
182
proto.constructor = gctor;
186
// Reflect Array -- note that all Array methods are generic.
187
reflectClass('Array', new Array);
189
// Reflect String, overriding non-generic methods.
190
var gSp = reflectClass('String', new String);
191
gSp.toSource = function () { return this.value.toSource(); };
192
gSp.toString = function () { return this.value; };
193
gSp.valueOf = function () { return this.value; };
194
global.String.fromCharCode = String.fromCharCode;
196
var XCp = ExecutionContext.prototype;
197
ExecutionContext.current = XCp.caller = XCp.callee = null;
198
XCp.scope = {object: global, parent: null};
199
XCp.thisObject = global;
200
XCp.result = undefined;
202
XCp.ecmaStrictMode = false;
204
function Reference(base, propertyName, node) {
206
this.propertyName = propertyName;
210
Reference.prototype.toString = function () { return this.node.getSource(); }
212
function getValue(v) {
213
if (v instanceof Reference) {
215
throw new ReferenceError(v.propertyName + " is not defined",
216
v.node.filename(), v.node.lineno);
218
return v.base[v.propertyName];
223
function putValue(v, w, vn) {
224
if (v instanceof Reference)
225
return (v.base || global)[v.propertyName] = w;
226
throw new ReferenceError("Invalid assignment left-hand side",
227
vn.filename(), vn.lineno);
230
function isPrimitive(v) {
232
return (t == "object") ? v === null : t != "function";
235
function isObject(v) {
237
return (t == "object") ? v !== null : t == "function";
240
// If r instanceof Reference, v == getValue(r); else v === r. If passed, rn
241
// is the node whose execute result was r.
242
function toObject(v, r, rn) {
245
return new global.Boolean(v);
247
return new global.Number(v);
249
return new global.String(v);
256
var message = r + " (type " + (typeof v) + ") has no properties";
257
throw rn ? new TypeError(message, rn.filename(), rn.lineno)
258
: new TypeError(message);
261
function execute(n, x) {
263
new_block = new Array();
265
var a, f, i, j, r, s, t, u, v;
268
if (n.functionForm != DECLARED_FORM) {
269
if (!n.name || n.functionForm == STATEMENT_FORM) {
270
v = new FunctionObject(n, x.scope);
271
if (n.functionForm == STATEMENT_FORM)
272
x.scope.object[n.name] = v;
275
x.scope = {object: t, parent: x.scope};
277
v = new FunctionObject(n, x.scope);
280
x.scope = x.scope.parent;
289
for (i = 0, j = a.length; i < j; i++) {
291
f = new FunctionObject(a[i], x.scope);
295
for (i = 0, j = a.length; i < j; i++) {
298
if (u.readOnly && hasDirectProperty(t, s)) {
299
throw new TypeError("Redeclaration of const " + s,
300
u.filename(), u.lineno);
302
if (u.readOnly || !hasDirectProperty(t, s)) {
309
for (i = 0, j = n.$length; i < j; i++) {
312
//new_block.unshift([n[i], x]);
313
new_block.push([n[i], x]);
316
agenda = agenda.concat(new_block);
317
//agenda = new_block.concat(agenda)
322
if (getValue(execute(n.condition, x)))
323
execute(n.thenPart, x);
325
execute(n.elsePart, x);
329
s = getValue(execute(n.discriminant, x));
331
var matchDefault = false;
333
for (i = 0, j = a.length; ; i++) {
335
if (n.defaultIndex >= 0) {
336
i = n.defaultIndex - 1; // no case matched, do default
340
break; // no default, exit switch_loop
342
t = a[i]; // next case (might be default!)
343
if (t.type == CASE) {
344
u = getValue(execute(t.caseLabel, x));
346
if (!matchDefault) // not defaulting, skip for now
348
u = s; // force match to do default
351
for (;;) { // this loop exits switch_loop
352
if (t.statements.length) {
354
execute(t.statements, x);
356
if (!(e == BREAK && x.target == n)) { throw e }
371
// added "skip_setup" so initialization doesn't get called
374
n.setup && getValue(execute(n.setup, x));
378
//while (!n.condition || getValue(execute(n.condition, x))) {
379
if (!n.condition || getValue(execute(n.condition, x))) {
382
//execute(n.body, x);
383
new_block.push([n.body, x]);
384
agenda.push([n.body, x])
385
//agenda.unshift([n.body, x])
388
if (e == BREAK && x.target == n) {
390
} else if (e == CONTINUE && x.target == n) {
392
// 'continue' is invalid inside an 'if' clause
393
// I don't know what commenting this out will break!
401
n.update && getValue(execute(n.update, x));
403
new_block.unshift([n, x])
404
agenda.splice(agenda.length-1,0,[n, x])
405
//agenda.splice(1,0,[n, x])
419
s = execute(n.object, x);
422
// ECMA deviation to track extant browser JS implementation behavior.
423
t = (v == null && !x.ecmaStrictMode) ? v : toObject(v, s, n.object);
427
for (i = 0, j = a.length; i < j; i++) {
428
putValue(execute(r, x), a[i], r);
432
if (e == BREAK && x.target == n) {
434
} else if (e == CONTINUE && x.target == n) {
448
if (e == BREAK && x.target == n) {
450
} else if (e == CONTINUE && x.target == n) {
456
} while (getValue(execute(n.condition, x)));
466
execute(n.tryBlock, x);
468
if (!(e == THROW && (j = n.catchClauses.length))) {
472
x.result = undefined;
478
t = n.catchClauses[i];
479
x.scope = {object: {}, parent: x.scope};
480
x.scope.object[t.varName] = e;
482
if (t.guard && !getValue(execute(t.guard, x)))
487
x.scope = x.scope.parent;
492
execute(n.finallyBlock, x);
497
x.result = getValue(execute(n.exception, x));
501
x.result = getValue(execute(n.value, x));
505
r = execute(n.object, x);
506
t = toObject(getValue(r), r, n.object);
507
x.scope = {object: t, parent: x.scope};
511
x.scope = x.scope.parent;
517
for (i = 0, j = n.$length; i < j; i++) {
518
u = n[i].initializer;
522
for (s = x.scope; s; s = s.parent) {
523
if (hasDirectProperty(s.object, t))
526
u = getValue(execute(u, x));
535
throw "NYI: " + tokens[n.type];
538
var req = new XMLHttpRequest();
539
req.open('GET', n.filename, 'false');
543
// print debugging statements
545
var the_start = n.start
547
var the_statement = parse_result.tokenizer.source.slice(the_start,the_end)
548
//global.debug.document.body.innerHTML += ('<pre>>>> <b>' + the_statement + '</b></pre>')
549
LOG.info('>>>' + the_statement)
550
x.result = getValue(execute(n.expression, x));
552
//global.debug.document.body.innerHTML += ( '<pre>>>> ' + x.result + '</pre>')
558
execute(n.statement, x);
560
if (!(e == BREAK && x.target == n)) { throw e }
565
for (i = 0, j = n.$length; i < j; i++)
566
v = getValue(execute(n[i], x));
570
r = execute(n[0], x);
574
v = getValue(execute(n[1], x));
577
case BITWISE_OR: v = u | v; break;
578
case BITWISE_XOR: v = u ^ v; break;
579
case BITWISE_AND: v = u & v; break;
580
case LSH: v = u << v; break;
581
case RSH: v = u >> v; break;
582
case URSH: v = u >>> v; break;
583
case PLUS: v = u + v; break;
584
case MINUS: v = u - v; break;
585
case MUL: v = u * v; break;
586
case DIV: v = u / v; break;
587
case MOD: v = u % v; break;
590
putValue(r, v, n[0]);
594
v = getValue(execute(n[0], x)) ? getValue(execute(n[1], x))
595
: getValue(execute(n[2], x));
599
v = getValue(execute(n[0], x)) || getValue(execute(n[1], x));
603
v = getValue(execute(n[0], x)) && getValue(execute(n[1], x));
607
v = getValue(execute(n[0], x)) | getValue(execute(n[1], x));
611
v = getValue(execute(n[0], x)) ^ getValue(execute(n[1], x));
615
v = getValue(execute(n[0], x)) & getValue(execute(n[1], x));
619
v = getValue(execute(n[0], x)) == getValue(execute(n[1], x));
623
v = getValue(execute(n[0], x)) != getValue(execute(n[1], x));
627
v = getValue(execute(n[0], x)) === getValue(execute(n[1], x));
631
v = getValue(execute(n[0], x)) !== getValue(execute(n[1], x));
635
v = getValue(execute(n[0], x)) < getValue(execute(n[1], x));
639
v = getValue(execute(n[0], x)) <= getValue(execute(n[1], x));
643
v = getValue(execute(n[0], x)) >= getValue(execute(n[1], x));
647
v = getValue(execute(n[0], x)) > getValue(execute(n[1], x));
651
v = getValue(execute(n[0], x)) in getValue(execute(n[1], x));
655
t = getValue(execute(n[0], x));
656
u = getValue(execute(n[1], x));
657
if (isObject(u) && typeof u.__hasInstance__ == "function")
658
v = u.__hasInstance__(t);
664
v = getValue(execute(n[0], x)) << getValue(execute(n[1], x));
668
v = getValue(execute(n[0], x)) >> getValue(execute(n[1], x));
672
v = getValue(execute(n[0], x)) >>> getValue(execute(n[1], x));
676
v = getValue(execute(n[0], x)) + getValue(execute(n[1], x));
680
v = getValue(execute(n[0], x)) - getValue(execute(n[1], x));
684
v = getValue(execute(n[0], x)) * getValue(execute(n[1], x));
688
v = getValue(execute(n[0], x)) / getValue(execute(n[1], x));
692
v = getValue(execute(n[0], x)) % getValue(execute(n[1], x));
696
t = execute(n[0], x);
697
v = !(t instanceof Reference) || delete t.base[t.propertyName];
701
getValue(execute(n[0], x));
705
t = execute(n[0], x);
706
if (t instanceof Reference)
707
t = t.base ? t.base[t.propertyName] : undefined;
712
v = !getValue(execute(n[0], x));
716
v = ~getValue(execute(n[0], x));
720
v = +getValue(execute(n[0], x));
724
v = -getValue(execute(n[0], x));
729
t = execute(n[0], x);
730
u = Number(getValue(t));
733
putValue(t, (n.type == INCREMENT) ? ++u : --u, n[0]);
739
r = execute(n[0], x);
742
v = new Reference(toObject(t, r, n[0]), u, n);
746
r = execute(n[0], x);
748
u = getValue(execute(n[1], x));
749
v = new Reference(toObject(t, r, n[0]), String(u), n);
753
// Curse ECMA for specifying that arguments is not an Array object!
755
for (i = 0, j = n.$length; i < j; i++) {
756
u = getValue(execute(n[i], x));
763
r = execute(n[0], x);
764
a = execute(n[1], x);
766
if (isPrimitive(f) || typeof f.__call__ != "function") {
767
throw new TypeError(r + " is not callable",
768
n[0].filename(), n[0].lineno);
770
t = (r instanceof Reference) ? r.base : null;
771
if (t instanceof Activation)
773
v = f.__call__(t, a, x);
778
r = execute(n[0], x);
784
a = execute(n[1], x);
786
if (isPrimitive(f) || typeof f.__construct__ != "function") {
787
throw new TypeError(r + " is not a constructor",
788
n[0].filename(), n[0].lineno);
790
v = f.__construct__(a, x);
795
for (i = 0, j = n.$length; i < j; i++) {
797
v[i] = getValue(execute(n[i], x));
804
for (i = 0, j = n.$length; i < j; i++) {
806
if (t.type == PROPERTY_INIT) {
807
v[t[0].value] = getValue(execute(t[1], x));
809
f = new FunctionObject(t, x.scope);
811
u = (t.type == GETTER) ? '__defineGetter__'
812
: '__defineSetter__';
813
v[u](t.name, thunk(f, x));
836
for (s = x.scope; s; s = s.parent) {
837
if (n.value in s.object)
840
v = new Reference(s && s.object, n.value, n);
850
v = execute(n[0], x);
854
throw "PANIC: unknown operation " + n.type + ": " + uneval(n);
859
function Activation(f, a) {
860
for (var i = 0, j = f.params.length; i < j; i++)
861
this[f.params[i]] = a[i];
865
// Null Activation.prototype's proto slot so that Object.prototype.* does not
866
// pollute the scope of heavyweight functions. Also delete its 'constructor'
867
// property so that it doesn't pollute function scopes.
869
Activation.prototype.__proto__ = null;
870
delete Activation.prototype.constructor;
872
function FunctionObject(node, scope) {
875
this.length = node.params.length;
877
this.prototype = proto;
878
proto.constructor = this;
881
var FOp = FunctionObject.prototype = {
883
__call__: function (t, a, x) {
884
var x2 = new ExecutionContext(FUNCTION_CODE);
885
x2.thisObject = t || global;
890
x2.scope = {object: new Activation(f, a), parent: this.scope};
892
ExecutionContext.current = x2;
896
if (!(e == RETURN)) { throw e } else if (e == RETURN) {
899
if (e != THROW) { throw e }
900
x.result = x2.result;
903
ExecutionContext.current = x;
908
__construct__: function (a, x) {
910
var p = this.prototype;
913
// else o.__proto__ defaulted to Object.prototype
915
var v = this.__call__(o, a, x);
921
__hasInstance__: function (v) {
924
var p = this.prototype;
925
if (isPrimitive(p)) {
926
throw new TypeError("'prototype' property is not an object",
927
this.node.filename(), this.node.lineno);
930
while ((o = v.__proto__)) {
939
toString: function () {
940
return this.node.getSource();
943
apply: function (t, a) {
945
if (typeof this.__call__ != "function") {
946
throw new TypeError("Function.prototype.apply called on" +
947
" uncallable object");
950
if (t === undefined || t === null)
952
else if (typeof t != "object")
955
if (a === undefined || a === null) {
958
} else if (a instanceof Array) {
960
for (var i = 0, j = a.length; i < j; i++)
964
} else if (!(a instanceof Object)) {
965
// XXX check for a non-arguments object
966
throw new TypeError("Second argument to Function.prototype.apply" +
967
" must be an array or arguments object",
968
this.node.filename(), this.node.lineno);
971
return this.__call__(t, a, ExecutionContext.current);
975
// Curse ECMA a third time!
976
var a = Array.prototype.splice.call(arguments, 1);
977
return this.apply(t, a);
981
// Connect Function.prototype and Function.prototype.constructor in global.
982
reflectClass('Function', FOp);
984
// Help native and host-scripted functions be like FunctionObjects.
985
var Fp = Function.prototype;
986
var REp = RegExp.prototype;
988
if (!('__call__' in Fp)) {
989
Fp.__call__ = function (t, a, x) {
990
// Curse ECMA yet again!
991
a = Array.prototype.splice.call(a, 0, a.length);
992
return this.apply(t, a);
995
REp.__call__ = function (t, a, x) {
996
a = Array.prototype.splice.call(a, 0, a.length);
997
return this.exec.apply(this, a);
1000
Fp.__construct__ = function (a, x) {
1005
return new this(a[0]);
1007
return new this(a[0], a[1]);
1009
return new this(a[0], a[1], a[2]);
1011
return new this(a[0], a[1], a[2], a[3]);
1013
return new this(a[0], a[1], a[2], a[3], a[4]);
1015
return new this(a[0], a[1], a[2], a[3], a[4], a[5]);
1017
return new this(a[0], a[1], a[2], a[3], a[4], a[5], a[6]);
1019
throw "PANIC: too many arguments to constructor";
1022
// Since we use native functions such as Date along with host ones such
1023
// as global.eval, we want both to be considered instances of the native
1024
// Function constructor.
1025
Fp.__hasInstance__ = function (v) {
1026
return v instanceof Function || v instanceof global.Function;
1030
function thunk(f, x) {
1031
return function () { return f.__call__(this, arguments, x); };
1034
function evaluate(s, f, l) {
1035
if (typeof s != "string")
1038
var x = ExecutionContext.current;
1039
var x2 = new ExecutionContext(GLOBAL_CODE);
1040
ExecutionContext.current = x2;
1042
execute(parse(s, f, l), x2);
1044
if (e != THROW) { throw e }
1046
x.result = x2.result;
1051
ExecutionContext.current = x;