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.
50 const GLOBAL_CODE = 0, EVAL_CODE = 1, FUNCTION_CODE = 2;
52 function ExecutionContext(type) {
58 NaN: NaN, Infinity: Infinity, undefined: undefined,
60 // Function properties.
61 eval: function eval(s) {
62 if (typeof s != "string")
65 var x = ExecutionContext.current;
66 var x2 = new ExecutionContext(EVAL_CODE);
67 x2.thisObject = x.thisObject;
71 ExecutionContext.current = x2;
73 execute(parse(s), x2);
74 } catch (e if e == THROW) {
78 ExecutionContext.current = x;
82 parseInt: parseInt, parseFloat: parseFloat,
83 isNaN: isNaN, isFinite: isFinite,
84 decodeURI: decodeURI, encodeURI: encodeURI,
85 decodeURIComponent: decodeURIComponent,
86 encodeURIComponent: encodeURIComponent,
88 // Class constructors. Where ECMA-262 requires C.length == 1, we declare
89 // a dummy formal parameter.
91 Function: function Function(dummy) {
92 var p = "", b = "", n = arguments.length;
97 for (var k = 1; k < m; k++)
98 p += "," + arguments[k];
103 // XXX We want to pass a good file and line to the tokenizer.
104 // Note the anonymous name to maintain parity with Spidermonkey.
105 var t = new Tokenizer("anonymous(" + p + ") {" + b + "}");
107 // NB: Use the STATEMENT_FORM constant since we don't want to push this
108 // function onto the null compilation context.
109 var f = FunctionDefinition(t, null, false, STATEMENT_FORM);
110 var s = {object: global, parent: null};
111 return new FunctionObject(f, s);
113 Array: function Array(dummy) {
114 // Array when called as a function acts as a constructor.
115 return GLOBAL.Array.apply(this, arguments);
117 String: function String(s) {
118 // Called as function or constructor: convert argument to string type.
119 s = arguments.length ? "" + s : "";
120 if (this instanceof String) {
121 // Called as constructor: save the argument as the string value
122 // of this String object and return this object.
128 Boolean: Boolean, Number: Number, Date: Date, RegExp: RegExp,
129 Error: Error, EvalError: EvalError, RangeError: RangeError,
130 ReferenceError: ReferenceError, SyntaxError: SyntaxError,
131 TypeError: TypeError, URIError: URIError,
136 // Extensions to ECMA.
137 snarf: snarf, evaluate: evaluate,
138 load: function load(s) {
139 if (typeof s != "string")
142 evaluate(snarf(s), s, 1)
144 print: print, version: null
147 // Helper to avoid Object.prototype.hasOwnProperty polluting scope objects.
148 function hasDirectProperty(o, p) {
149 return Object.prototype.hasOwnProperty.call(o, p);
152 // Reflect a host class into the target global environment by delegation.
153 function reflectClass(name, proto) {
154 var gctor = global[name];
155 gctor.__defineProperty__('prototype', proto, true, true, true);
156 proto.__defineProperty__('constructor', gctor, false, false, true);
160 // Reflect Array -- note that all Array methods are generic.
161 reflectClass('Array', new Array);
163 // Reflect String, overriding non-generic methods.
164 var gSp = reflectClass('String', new String);
165 gSp.toSource = function () { return this.value.toSource(); };
166 gSp.toString = function () { return this.value; };
167 gSp.valueOf = function () { return this.value; };
168 global.String.fromCharCode = String.fromCharCode;
170 ExecutionContext.current = null;
172 ExecutionContext.prototype = {
175 scope: {object: global, parent: null},
182 function Reference(base, propertyName, node) {
184 this.propertyName = propertyName;
188 Reference.prototype.toString = function () { return this.node.getSource(); }
190 function getValue(v) {
191 if (v instanceof Reference) {
193 throw new ReferenceError(v.propertyName + " is not defined",
194 v.node.filename, v.node.lineno);
196 return v.base[v.propertyName];
201 function putValue(v, w, vn) {
202 if (v instanceof Reference)
203 return (v.base || global)[v.propertyName] = w;
204 throw new ReferenceError("Invalid assignment left-hand side",
205 vn.filename, vn.lineno);
208 function isPrimitive(v) {
210 return (t == "object") ? v === null : t != "function";
213 function isObject(v) {
215 return (t == "object") ? v !== null : t == "function";
218 // If r instanceof Reference, v == getValue(r); else v === r. If passed, rn
219 // is the node whose execute result was r.
220 function toObject(v, r, rn) {
223 return new global.Boolean(v);
225 return new global.Number(v);
227 return new global.String(v);
234 var message = r + " (type " + (typeof v) + ") has no properties";
235 throw rn ? new TypeError(message, rn.filename, rn.lineno)
236 : new TypeError(message);
239 function execute(n, x) {
240 var a, f, i, j, r, s, t, u, v;
244 if (n.functionForm != DECLARED_FORM) {
245 if (!n.name || n.functionForm == STATEMENT_FORM) {
246 v = new FunctionObject(n, x.scope);
247 if (n.functionForm == STATEMENT_FORM)
248 x.scope.object.__defineProperty__(n.name, v, true);
251 x.scope = {object: t, parent: x.scope};
253 v = new FunctionObject(n, x.scope);
254 t.__defineProperty__(n.name, v, true, true);
256 x.scope = x.scope.parent;
265 for (i = 0, j = a.length; i < j; i++) {
267 f = new FunctionObject(a[i], x.scope);
268 t.__defineProperty__(s, f, x.type != EVAL_CODE);
271 for (i = 0, j = a.length; i < j; i++) {
274 if (u.readOnly && hasDirectProperty(t, s)) {
275 throw new TypeError("Redeclaration of const " + s,
276 u.filename, u.lineno);
278 if (u.readOnly || !hasDirectProperty(t, s)) {
279 t.__defineProperty__(s, undefined, x.type != EVAL_CODE,
286 for (i = 0, j = n.length; i < j; i++)
291 if (getValue(execute(n.condition, x)))
292 execute(n.thenPart, x);
294 execute(n.elsePart, x);
298 s = getValue(execute(n.discriminant, x));
300 var matchDefault = false;
302 for (i = 0, j = a.length; ; i++) {
304 if (n.defaultIndex >= 0) {
305 i = n.defaultIndex - 1; // no case matched, do default
309 break; // no default, exit switch_loop
311 t = a[i]; // next case (might be default!)
312 if (t.type == CASE) {
313 u = getValue(execute(t.caseLabel, x));
315 if (!matchDefault) // not defaulting, skip for now
317 u = s; // force match to do default
320 for (;;) { // this loop exits switch_loop
321 if (t.statements.length) {
323 execute(t.statements, x);
324 } catch (e if e == BREAK && x.target == n) {
338 n.setup && getValue(execute(n.setup, x));
341 while (!n.condition || getValue(execute(n.condition, x))) {
344 } catch (e if e == BREAK && x.target == n) {
346 } catch (e if e == CONTINUE && x.target == n) {
347 // Must run the update expression.
349 n.update && getValue(execute(n.update, x));
358 s = execute(n.object, x);
361 // ECMA deviation to track extant browser JS implementation behavior.
362 t = (v == null && !x.ecma3OnlyMode) ? v : toObject(v, s, n.object);
366 for (i = 0, j = a.length; i < j; i++) {
367 putValue(execute(r, x), a[i], r);
370 } catch (e if e == BREAK && x.target == n) {
372 } catch (e if e == CONTINUE && x.target == n) {
382 } catch (e if e == BREAK && x.target == n) {
384 } catch (e if e == CONTINUE && x.target == n) {
387 } while (getValue(execute(n.condition, x)));
397 execute(n.tryBlock, x);
398 } catch (e if e == THROW && (j = n.catchClauses.length)) {
400 x.result = undefined;
406 t = n.catchClauses[i];
407 x.scope = {object: {}, parent: x.scope};
408 x.scope.object.__defineProperty__(t.varName, e, true);
410 if (t.guard && !getValue(execute(t.guard, x)))
415 x.scope = x.scope.parent;
420 execute(n.finallyBlock, x);
425 x.result = getValue(execute(n.exception, x));
429 x.result = getValue(execute(n.value, x));
433 r = execute(n.object, x);
434 t = toObject(getValue(r), r, n.object);
435 x.scope = {object: t, parent: x.scope};
439 x.scope = x.scope.parent;
445 for (i = 0, j = n.length; i < j; i++) {
446 u = n[i].initializer;
450 for (s = x.scope; s; s = s.parent) {
451 if (hasDirectProperty(s.object, t))
454 u = getValue(execute(u, x));
456 s.object.__defineProperty__(t, u, x.type != EVAL_CODE, true);
463 throw "NYI: " + tokens[n.type];
467 x.result = getValue(execute(n.expression, x));
472 execute(n.statement, x);
473 } catch (e if e == BREAK && x.target == n) {
478 for (i = 0, j = n.length; i < j; i++)
479 v = getValue(execute(n[i], x));
483 r = execute(n[0], x);
487 v = getValue(execute(n[1], x));
490 case BITWISE_OR: v = u | v; break;
491 case BITWISE_XOR: v = u ^ v; break;
492 case BITWISE_AND: v = u & v; break;
493 case LSH: v = u << v; break;
494 case RSH: v = u >> v; break;
495 case URSH: v = u >>> v; break;
496 case PLUS: v = u + v; break;
497 case MINUS: v = u - v; break;
498 case MUL: v = u * v; break;
499 case DIV: v = u / v; break;
500 case MOD: v = u % v; break;
503 putValue(r, v, n[0]);
507 v = getValue(execute(n[0], x)) ? getValue(execute(n[1], x))
508 : getValue(execute(n[2], x));
512 v = getValue(execute(n[0], x)) || getValue(execute(n[1], x));
516 v = getValue(execute(n[0], x)) && getValue(execute(n[1], x));
520 v = getValue(execute(n[0], x)) | getValue(execute(n[1], x));
524 v = getValue(execute(n[0], x)) ^ getValue(execute(n[1], x));
528 v = getValue(execute(n[0], x)) & getValue(execute(n[1], x));
532 v = getValue(execute(n[0], x)) == getValue(execute(n[1], x));
536 v = getValue(execute(n[0], x)) != getValue(execute(n[1], x));
540 v = getValue(execute(n[0], x)) === getValue(execute(n[1], x));
544 v = getValue(execute(n[0], x)) !== getValue(execute(n[1], x));
548 v = getValue(execute(n[0], x)) < getValue(execute(n[1], x));
552 v = getValue(execute(n[0], x)) <= getValue(execute(n[1], x));
556 v = getValue(execute(n[0], x)) >= getValue(execute(n[1], x));
560 v = getValue(execute(n[0], x)) > getValue(execute(n[1], x));
564 v = getValue(execute(n[0], x)) in getValue(execute(n[1], x));
568 t = getValue(execute(n[0], x));
569 u = getValue(execute(n[1], x));
570 if (isObject(u) && typeof u.__hasInstance__ == "function")
571 v = u.__hasInstance__(t);
577 v = getValue(execute(n[0], x)) << getValue(execute(n[1], x));
581 v = getValue(execute(n[0], x)) >> getValue(execute(n[1], x));
585 v = getValue(execute(n[0], x)) >>> getValue(execute(n[1], x));
589 v = getValue(execute(n[0], x)) + getValue(execute(n[1], x));
593 v = getValue(execute(n[0], x)) - getValue(execute(n[1], x));
597 v = getValue(execute(n[0], x)) * getValue(execute(n[1], x));
601 v = getValue(execute(n[0], x)) / getValue(execute(n[1], x));
605 v = getValue(execute(n[0], x)) % getValue(execute(n[1], x));
609 t = execute(n[0], x);
610 v = !(t instanceof Reference) || delete t.base[t.propertyName];
614 getValue(execute(n[0], x));
618 t = execute(n[0], x);
619 if (t instanceof Reference)
620 t = t.base ? t.base[t.propertyName] : undefined;
625 v = !getValue(execute(n[0], x));
629 v = ~getValue(execute(n[0], x));
633 v = +getValue(execute(n[0], x));
637 v = -getValue(execute(n[0], x));
642 t = execute(n[0], x);
643 u = Number(getValue(t));
646 putValue(t, (n.type == INCREMENT) ? ++u : --u, n[0]);
652 r = execute(n[0], x);
655 v = new Reference(toObject(t, r, n[0]), u, n);
659 r = execute(n[0], x);
661 u = getValue(execute(n[1], x));
662 v = new Reference(toObject(t, r, n[0]), String(u), n);
666 // Curse ECMA for specifying that arguments is not an Array object!
668 for (i = 0, j = n.length; i < j; i++) {
669 u = getValue(execute(n[i], x));
670 v.__defineProperty__(i, u, false, false, true);
672 v.__defineProperty__('length', i, false, false, true);
676 r = execute(n[0], x);
677 a = execute(n[1], x);
679 if (isPrimitive(f) || typeof f.__call__ != "function") {
680 throw new TypeError(r + " is not callable",
681 n[0].filename, n[0].lineno);
683 t = (r instanceof Reference) ? r.base : null;
684 if (t instanceof Activation)
686 v = f.__call__(t, a, x);
691 r = execute(n[0], x);
695 a.__defineProperty__('length', 0, false, false, true);
697 a = execute(n[1], x);
699 if (isPrimitive(f) || typeof f.__construct__ != "function") {
700 throw new TypeError(r + " is not a constructor",
701 n[0].filename, n[0].lineno);
703 v = f.__construct__(a, x);
708 for (i = 0, j = n.length; i < j; i++) {
710 v[i] = getValue(execute(n[i], x));
717 for (i = 0, j = n.length; i < j; i++) {
719 if (t.type == PROPERTY_INIT) {
720 v[t[0].value] = getValue(execute(t[1], x));
722 f = new FunctionObject(t, x.scope);
723 u = (t.type == GETTER) ? '__defineGetter__'
724 : '__defineSetter__';
725 v[u](t.name, thunk(f, x));
747 for (s = x.scope; s; s = s.parent) {
748 if (n.value in s.object)
751 v = new Reference(s && s.object, n.value, n);
761 v = execute(n[0], x);
765 throw "PANIC: unknown operation " + n.type + ": " + uneval(n);
771 function Activation(f, a) {
772 for (var i = 0, j = f.params.length; i < j; i++)
773 this.__defineProperty__(f.params[i], a[i], true);
774 this.__defineProperty__('arguments', a, true);
777 // Null Activation.prototype's proto slot so that Object.prototype.* does not
778 // pollute the scope of heavyweight functions. Also delete its 'constructor'
779 // property so that it doesn't pollute function scopes. But first, we must
780 // copy __defineProperty__ down from Object.prototype.
782 Activation.prototype.__defineProperty__ = Object.prototype.__defineProperty__;
783 Activation.prototype.__proto__ = null;
784 delete Activation.prototype.constructor;
786 function FunctionObject(node, scope) {
789 this.__defineProperty__('length', node.params.length, true, true, true);
791 this.__defineProperty__('prototype', proto, true);
792 proto.__defineProperty__('constructor', this, false, false, true);
795 var FOp = FunctionObject.prototype = {
797 __call__: function (t, a, x) {
798 var x2 = new ExecutionContext(FUNCTION_CODE);
799 x2.thisObject = t || global;
802 a.__defineProperty__('callee', this, false, false, true);
804 x2.scope = {object: new Activation(f, a), parent: this.scope};
806 ExecutionContext.current = x2;
809 } catch (e if e == RETURN) {
811 } catch (e if e == THROW) {
812 x.result = x2.result;
815 ExecutionContext.current = x;
820 __construct__: function (a, x) {
822 var p = this.prototype;
825 // else o.__proto__ defaulted to Object.prototype
827 var v = this.__call__(o, a, x);
833 __hasInstance__: function (v) {
836 var p = this.prototype;
837 if (isPrimitive(p)) {
838 throw new TypeError("'prototype' property is not an object",
839 this.node.filename, this.node.lineno);
842 while ((o = v.__proto__)) {
851 toString: function () {
852 return this.node.getSource();
855 apply: function (t, a) {
857 if (typeof this.__call__ != "function") {
858 throw new TypeError("Function.prototype.apply called on" +
859 " uncallable object");
862 if (t === undefined || t === null)
864 else if (typeof t != "object")
867 if (a === undefined || a === null) {
869 a.__defineProperty__('length', 0, false, false, true);
870 } else if (a instanceof Array) {
872 for (var i = 0, j = a.length; i < j; i++)
873 v.__defineProperty__(i, a[i], false, false, true);
874 v.__defineProperty__('length', i, false, false, true);
876 } else if (!(a instanceof Object)) {
877 // XXX check for a non-arguments object
878 throw new TypeError("Second argument to Function.prototype.apply" +
879 " must be an array or arguments object",
880 this.node.filename, this.node.lineno);
883 return this.__call__(t, a, ExecutionContext.current);
887 // Curse ECMA a third time!
888 var a = Array.prototype.splice.call(arguments, 1);
889 return this.apply(t, a);
893 // Connect Function.prototype and Function.prototype.constructor in global.
894 reflectClass('Function', FOp);
896 // Help native and host-scripted functions be like FunctionObjects.
897 var Fp = Function.prototype;
898 var REp = RegExp.prototype;
900 if (!('__call__' in Fp)) {
901 Fp.__defineProperty__('__call__', function (t, a, x) {
902 // Curse ECMA yet again!
903 a = Array.prototype.splice.call(a, 0, a.length);
904 return this.apply(t, a);
905 }, true, true, true);
907 REp.__defineProperty__('__call__', function (t, a, x) {
908 a = Array.prototype.splice.call(a, 0, a.length);
909 return this.exec.apply(this, a);
910 }, true, true, true);
912 Fp.__defineProperty__('__construct__', function (a, x) {
913 a = Array.prototype.splice.call(a, 0, a.length);
914 return this.__applyConstructor__(a);
915 }, true, true, true);
917 // Since we use native functions such as Date along with host ones such
918 // as global.eval, we want both to be considered instances of the native
919 // Function constructor.
920 Fp.__defineProperty__('__hasInstance__', function (v) {
921 return v instanceof Function || v instanceof global.Function;
922 }, true, true, true);
925 function thunk(f, x) {
926 return function () { return f.__call__(this, arguments, x); };
929 function evaluate(s, f, l) {
930 if (typeof s != "string")
933 var x = ExecutionContext.current;
934 var x2 = new ExecutionContext(GLOBAL_CODE);
935 ExecutionContext.current = x2;
937 execute(parse(s, f, l), x2);
938 } catch (e if e == THROW) {
940 x.result = x2.result;
945 ExecutionContext.current = x;