2003/11/18 10:47:26
[org.ibex.core.git] / src / org / xwt / js / Interpreter.java
index c9bcd73..f65a585 100644 (file)
@@ -5,144 +5,186 @@ import org.xwt.util.*;
 import java.util.*;
 import java.io.*;
 
+/** Encapsulates a single JS interpreter (ie call stack) */
 class Interpreter implements ByteCodes, Tokens {
 
-    static Object eval(final JSContext cx) throws JS.Exn {
-        final int initialPauseCount = cx.pausecount;
-        OUTER: for(;; cx.pc++) {
+
+    // Thread-Interpreter Mapping /////////////////////////////////////////////////////////////////////////
+
+    static Interpreter current() { return (Interpreter)threadToInterpreter.get(Thread.currentThread()); }
+    private static Hashtable threadToInterpreter = new Hashtable();
+
+    
+    // Instance members and methods //////////////////////////////////////////////////////////////////////
+    
+    int pausecount;               ///< the number of times pause() has been invoked; -1 indicates unpauseable
+    JSFunction f = null;          ///< the currently-executing JSFunction
+    JSScope scope;                ///< the current top-level scope (LIFO stack via NEWSCOPE/OLDSCOPE)
+    Vec stack = new Vec();        ///< the object stack
+    int pc = 0;                   ///< the program counter
+
+    Interpreter(JSFunction f, boolean pauseable, JSArray args) {
+        stack.push(new Interpreter.CallMarker(this));    // the "root function returned" marker -- f==null
+        this.f = f;
+        this.pausecount = pauseable ? 0 : -1;
+        this.scope = new JSScope(f.parentScope);
+        stack.push(args);
+    }
+    
+    /** this is the only synchronization point we need in order to be threadsafe */
+    synchronized Object resume() {
+        Thread t = Thread.currentThread();
+        Interpreter old = (Interpreter)threadToInterpreter.get(t);
+        threadToInterpreter.put(t, this);
+        try {
+            return run();
+        } finally {
+            if (old == null) threadToInterpreter.remove(t);
+            else threadToInterpreter.put(t, old);
+        }
+    }
+
+    private static JSExn je(String s) { return new JSExn(JS.getSourceName() + ":" + JS.getLine() + " " + s); }
+
+    // FIXME: double check the trap logic
+    private Object run() throws JSExn {
+
+        // if pausecount changes after a get/put/call, we know we've been paused
+        final int initialPauseCount = pausecount;
+
+        OUTER: for(;; pc++) {
         try {
-            if (cx.f == null || cx.pc >= cx.f.size) return cx.stack.pop();
-            int op = cx.f.op[cx.pc];
-            Object arg = cx.f.arg[cx.pc];
+            if (f == null) return stack.pop();
+            int op = f.op[pc];
+            Object arg = f.arg[pc];
             if(op == FINALLY_DONE) {
-                FinallyData fd = (FinallyData) cx.stack.pop();
+                FinallyData fd = (FinallyData) stack.pop();
                 if(fd == null) continue OUTER; // NOP
                 op = fd.op;
                 arg = fd.arg;
             }
             switch(op) {
-            case LITERAL: cx.stack.push(arg); break;
-            case OBJECT: cx.stack.push(new JS()); break;
-            case ARRAY: cx.stack.push(new JSArray(JS.toNumber(arg).intValue())); break;
-            case DECLARE: cx.scope.declare((String)(arg==null ? cx.stack.peek() : arg)); if(arg != null) cx.stack.push(arg); break;
-            case TOPSCOPE: cx.stack.push(cx.scope); break;
-            case JT: if (JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(arg).intValue() - 1; break;
-            case JF: if (!JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(arg).intValue() - 1; break;
-            case JMP: cx.pc += JS.toNumber(arg).intValue() - 1; break;
-            case POP: cx.stack.pop(); break;
+            case LITERAL: stack.push(arg); break;
+            case OBJECT: stack.push(new JS()); break;
+            case ARRAY: stack.push(new JSArray(JS.toNumber(arg).intValue())); break;
+            case DECLARE: scope.declare((String)(arg==null ? stack.peek() : arg)); if(arg != null) stack.push(arg); break;
+            case TOPSCOPE: stack.push(scope); break;
+            case JT: if (JS.toBoolean(stack.pop())) pc += JS.toNumber(arg).intValue() - 1; break;
+            case JF: if (!JS.toBoolean(stack.pop())) pc += JS.toNumber(arg).intValue() - 1; break;
+            case JMP: pc += JS.toNumber(arg).intValue() - 1; break;
+            case POP: stack.pop(); break;
             case SWAP: {
                 int depth = (arg == null ? 1 : JS.toInt(arg));
-                Object save = cx.stack.elementAt(cx.stack.size() - 1);
-                for(int i=cx.stack.size() - 1; i > cx.stack.size() - 1 - depth; i--)
-                    cx.stack.setElementAt(cx.stack.elementAt(i-1), i);
-                cx.stack.setElementAt(save, cx.stack.size() - depth - 1);
+                Object save = stack.elementAt(stack.size() - 1);
+                for(int i=stack.size() - 1; i > stack.size() - 1 - depth; i--)
+                    stack.setElementAt(stack.elementAt(i-1), i);
+                stack.setElementAt(save, stack.size() - depth - 1);
                 break; }
-            case DUP: cx.stack.push(cx.stack.peek()); break;
-            case NEWSCOPE: cx.scope = new JSScope(cx.scope); break;
-            case OLDSCOPE: cx.scope = cx.scope.getParentJSScope(); break;
-            case ASSERT: if (!JS.toBoolean(cx.stack.pop())) throw je("assertion failed"); break;
-            case BITNOT: cx.stack.push(new Long(~JS.toLong(cx.stack.pop()))); break;
-            case BANG: cx.stack.push(new Boolean(!JS.toBoolean(cx.stack.pop()))); break;
-            case NEWFUNCTION: cx.stack.push(((JSFunction)arg).cloneWithNewParentJSScope(cx.scope)); break;
+            case DUP: stack.push(stack.peek()); break;
+            case NEWSCOPE: scope = new JSScope(scope); break;
+            case OLDSCOPE: scope = scope.getParentScope(); break;
+            case ASSERT: if (!JS.toBoolean(stack.pop())) throw je("assertion failed"); break;
+            case BITNOT: stack.push(JS.N(~JS.toLong(stack.pop()))); break;
+            case BANG: stack.push(JS.B(!JS.toBoolean(stack.pop()))); break;
+            case NEWFUNCTION: stack.push(((JSFunction)arg).cloneWithNewParentScope(scope)); break;
             case LABEL: break;
 
             case TYPEOF: {
-                Object o = cx.stack.pop();
-                if (o == null) cx.stack.push(null);
-                else if (o instanceof JS) cx.stack.push(((JS)o).typeName());
-                else if (o instanceof String) cx.stack.push("string");
-                else if (o instanceof Number) cx.stack.push("number");
-                else if (o instanceof Boolean) cx.stack.push("boolean");
-                else cx.stack.push("unknown");
+                Object o = stack.pop();
+                if (o == null) stack.push(null);
+                else if (o instanceof JS) stack.push(((JS)o).typeName());
+                else if (o instanceof String) stack.push("string");
+                else if (o instanceof Number) stack.push("number");
+                else if (o instanceof Boolean) stack.push("boolean");
+                else stack.push("unknown");
                 break;
             }
 
             case PUSHKEYS: {
-                Object o = cx.stack.peek();
+                Object o = stack.peek();
                 Enumeration e = ((JS)o).keys();
                 JSArray a = new JSArray();
                 while(e.hasMoreElements()) a.addElement(e.nextElement());
-                cx.stack.push(a);
+                stack.push(a);
                 break;
             }
 
             case LOOP:
-                cx.stack.push(new LoopMarker(cx.pc, cx.pc > 0 && cx.f.op[cx.pc - 1] == LABEL ?
-                                             (String)cx.f.arg[cx.pc - 1] : (String)null, cx.scope));
-                cx.stack.push(Boolean.TRUE);
+                stack.push(new LoopMarker(pc, pc > 0 && f.op[pc - 1] == LABEL ? (String)f.arg[pc - 1] : (String)null, scope));
+                stack.push(Boolean.TRUE);
                 break;
 
             case BREAK:
             case CONTINUE:
-                while(cx.stack.size() > 0) {
-                    Object o = cx.stack.pop();
-                    if (o instanceof CallMarker) ee("break or continue not within a loop");
+                while(stack.size() > 0) {
+                    Object o = stack.pop();
+                    if (o instanceof CallMarker) je("break or continue not within a loop");
                     if (o instanceof TryMarker) {
                         if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
-                        cx.stack.push(new FinallyData(op, arg));
-                        cx.scope = ((TryMarker)o).scope;
-                        cx.pc = ((TryMarker)o).finallyLoc - 1;
+                        stack.push(new FinallyData(op, arg));
+                        scope = ((TryMarker)o).scope;
+                        pc = ((TryMarker)o).finallyLoc - 1;
                         continue OUTER;
                     }
                     if (o instanceof LoopMarker) {
                         if (arg == null || arg.equals(((LoopMarker)o).label)) {
                             int loopInstructionLocation = ((LoopMarker)o).location;
-                            int endOfLoop = ((Integer)cx.f.arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
-                            cx.scope = ((LoopMarker)o).scope;
-                            if (op == CONTINUE) { cx.stack.push(o); cx.stack.push(Boolean.FALSE); }
-                            cx.pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
+                            int endOfLoop = ((Integer)f.arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
+                            scope = ((LoopMarker)o).scope;
+                            if (op == CONTINUE) { stack.push(o); stack.push(Boolean.FALSE); }
+                            pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
                             continue OUTER;
                         }
                     }
                 }
                 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
-                                cx.getSourceName() + ":" + cx.getLine());
+                                JS.getSourceName() + ":" + JS.getLine());
 
             case TRY: {
                 int[] jmps = (int[]) arg;
                 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
                 // each can be < 0 if the specified block does not exist
-                cx.stack.push(new TryMarker(jmps[0] < 0 ? -1 : cx.pc + jmps[0], jmps[1] < 0 ? -1 : cx.pc + jmps[1], cx.scope));
+                stack.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1], scope));
                 break;
             }
 
             case RETURN: {
-                Object retval = cx.stack.pop();
-                while(cx.stack.size() > 0) {
-                    Object o = cx.stack.pop();
+                Object retval = stack.pop();
+                while(stack.size() > 0) {
+                    Object o = stack.pop();
                     if (o instanceof TryMarker) {
                         if(((TryMarker)o).finallyLoc < 0) continue;
-                        cx.stack.push(retval); 
-                        cx.stack.push(new FinallyData(RETURN));
-                        cx.scope = ((TryMarker)o).scope;
-                        cx.pc = ((TryMarker)o).finallyLoc - 1;
+                        stack.push(retval); 
+                        stack.push(new FinallyData(RETURN));
+                        scope = ((TryMarker)o).scope;
+                        pc = ((TryMarker)o).finallyLoc - 1;
                         continue OUTER;
                     } else if (o instanceof CallMarker) {
-                        if (cx.scope instanceof JSTrap.JSTrapScope) {
-                            JSTrap.JSTrapScope ts = (JSTrap.JSTrapScope)cx.scope;
+                        if (scope instanceof Trap.TrapScope) {
+                            Trap.TrapScope ts = (Trap.TrapScope)scope;
                             if (!ts.cascadeHappened) {
                                 ts.cascadeHappened = true;
-                                JSTrap t = ts.t.next;
+                                Trap t = ts.t.next;
                                 while (t != null && t.f.numFormalArgs == 0) t = t.next;
                                 if (t == null) {
                                     ((JS)ts.t.trapee).put(t.name, ts.val);
-                                    if (cx.pausecount > initialPauseCount) return null;   // we were paused
+                                    if (pausecount > initialPauseCount) { pc++; return null; }   // we were paused
                                 } else {
-                                    cx.stack.push(o);
+                                    stack.push(o);
                                     JSArray args = new JSArray();
                                     args.addElement(ts.val);
-                                    cx.stack.push(args);
-                                    cx.f = t.f;
-                                    cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, ts.val);
-                                    cx.pc = -1;
+                                    stack.push(args);
+                                    f = t.f;
+                                    scope = new Trap.TrapScope(f.parentScope, t, ts.val);
+                                    pc = -1;
                                     break;
                                 }
                             }
                         }
-                        cx.scope = ((CallMarker)o).scope;
-                        cx.pc = ((CallMarker)o).pc;
-                        cx.f = (JSFunction)((CallMarker)o).f;
-                        cx.stack.push(retval);
+                        scope = ((CallMarker)o).scope;
+                        pc = ((CallMarker)o).pc;
+                        f = (JSFunction)((CallMarker)o).f;
+                        stack.push(retval);
                         continue OUTER;
                     }
                 }
@@ -150,39 +192,39 @@ class Interpreter implements ByteCodes, Tokens {
             }
 
             case PUT: {
-                Object val = cx.stack.pop();
-                Object key = cx.stack.pop();
-                Object target = cx.stack.peek();
+                Object val = stack.pop();
+                Object key = stack.pop();
+                Object target = stack.peek();
                 if (target == null)
                     throw je("tried to put a value to the " + key + " property on the null value");
                 if (!(target instanceof JS))
                     throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
                 if (key == null)
                     throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
-                JSTrap t = null;
-                if (target instanceof JSTrap.JSTrappable) {
-                    t = ((JSTrap.JSTrappable)target).getTrap(val);
+                Trap t = null;
+                if (target instanceof JS) {
+                    t = ((JS)target).getTrap(val);
                     while (t != null && t.f.numFormalArgs == 0) t = t.next;
-                } else if (target instanceof JSTrap.JSTrapScope && key.equals("cascade")) {
-                    JSTrap.JSTrapScope ts = (JSTrap.JSTrapScope)target;
+                } else if (target instanceof Trap.TrapScope && key.equals("cascade")) {
+                    Trap.TrapScope ts = (Trap.TrapScope)target;
                     t = ts.t.next;
                     ts.cascadeHappened = true;
                     while (t != null && t.f.numFormalArgs == 0) t = t.next;
                     if (t == null) target = ts.t.trapee;
                 }
                 if (t != null) {
-                    cx.stack.push(new CallMarker(cx));
+                    stack.push(new CallMarker(this));
                     JSArray args = new JSArray();
                     args.addElement(val);
-                    cx.stack.push(args);
-                    cx.f = t.f;
-                    cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, val);
-                    cx.pc = -1;
+                    stack.push(args);
+                    f = t.f;
+                    scope = new Trap.TrapScope(f.parentScope, t, val);
+                    pc = -1;
                     break;
                 }
                 ((JS)target).put(key, val);
-                if (cx.pausecount > initialPauseCount) return null;   // we were paused
-                cx.stack.push(val);
+                if (pausecount > initialPauseCount) { pc++; return null; }   // we were paused
+                stack.push(val);
                 break;
             }
 
@@ -190,44 +232,44 @@ class Interpreter implements ByteCodes, Tokens {
             case GET_PRESERVE: {
                 Object o, v;
                 if (op == GET) {
-                    v = arg == null ? cx.stack.pop() : arg;
-                    o = cx.stack.pop();
+                    v = arg == null ? stack.pop() : arg;
+                    o = stack.pop();
                 } else {
-                    v = cx.stack.pop();
-                    o = cx.stack.peek();
-                    cx.stack.push(v);
+                    v = stack.pop();
+                    o = stack.peek();
+                    stack.push(v);
                 }
                 Object ret = null;
                 if (v == null) throw je("tried to get the null key from " + o);
-                if (o == null) throw je("tried to get property \"" + v + "\" from the null value @" + cx.pc + "\n" + cx.f.dump());
+                if (o == null) throw je("tried to get property \"" + v + "\" from the null value @" + pc + "\n" + f.dump());
                 if (o instanceof String || o instanceof Number || o instanceof Boolean) {
-                    ret = Internal.getFromPrimitive(o,v);
-                    cx.stack.push(ret);
+                    ret = getFromPrimitive(o,v);
+                    stack.push(ret);
                     break;
                 } else if (o instanceof JS) {
-                    JSTrap t = null;
-                    if (o instanceof JSTrap.JSTrappable) {
-                        t = ((JSTrap.JSTrappable)o).getTrap(v);
+                    Trap t = null;
+                    if (o instanceof JS) {
+                        t = ((JS)o).getTrap(v);
                         while (t != null && t.f.numFormalArgs != 0) t = t.next;
-                    } else if (o instanceof JSTrap.JSTrapScope && v.equals("cascade")) {
-                        t = ((JSTrap.JSTrapScope)o).t.next;
+                    } else if (o instanceof Trap.TrapScope && v.equals("cascade")) {
+                        t = ((Trap.TrapScope)o).t.next;
                         while (t != null && t.f.numFormalArgs != 0) t = t.next;
-                        if (t == null) o = ((JSTrap.JSTrapScope)o).t.trapee;
+                        if (t == null) o = ((Trap.TrapScope)o).t.trapee;
                     }
                     if (t != null) {
-                        cx.stack.push(new CallMarker(cx));
+                        stack.push(new CallMarker(this));
                         JSArray args = new JSArray();
-                        cx.stack.push(args);
-                        cx.f = t.f;
-                        cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, null);
-                        ((JSTrap.JSTrapScope)cx.scope).cascadeHappened = true;
-                        cx.pc = -1;
+                        stack.push(args);
+                        f = t.f;
+                        scope = new Trap.TrapScope(f.parentScope, t, null);
+                        ((Trap.TrapScope)scope).cascadeHappened = true;
+                        pc = -1;
                         break;
                     }
                     ret = ((JS)o).get(v);
-                    if (ret == JSCallable.METHOD) ret = new Internal.JSCallableStub((JS)o, v);
-                    if (cx.pausecount > initialPauseCount) return null;   // we were paused
-                    cx.stack.push(ret);
+                    if (ret == JS.METHOD) ret = new Stub((JS)o, v);
+                    if (pausecount > initialPauseCount) { pc++; return null; }   // we were paused
+                    stack.push(ret);
                     break;
                 }
                 throw je("tried to get property " + v + " from a " + o.getClass().getName());
@@ -237,81 +279,80 @@ class Interpreter implements ByteCodes, Tokens {
                 int numArgs = JS.toInt(arg);
                 Object method = null;
                 Object ret = null;
-                Object object = cx.stack.pop();
+                Object object = stack.pop();
 
-                if (op == CALL) {
-                    object = cx.stack.pop();
-                } else {
-                    if (object == JSCallable.METHOD) {
-                        method = cx.stack.pop();
-                        object = cx.stack.pop();
+                if (op == CALLMETHOD) {
+                    if (object == JS.METHOD) {
+                        method = stack.pop();
+                        object = stack.pop();
                     } else {
-                        cx.stack.pop();
-                        cx.stack.pop();
+                        stack.pop();
+                        stack.pop();
                     }
                 }
 
                 if (object instanceof String || object instanceof Number || object instanceof Boolean) {
-                    JSArray arguments = new JSArray();
-                    for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
-                    ret = Internal.callMethodOnPrimitive(object, method, arguments);
+                    if (numArgs > 2) throw new JSExn("too many arguments to primitive method");
+                    Object arg1 = numArgs >= 2 ? stack.pop() : null;
+                    Object arg0 = numArgs >= 1 ? stack.pop() : null;
+                    ret = callMethodOnPrimitive(object, method, arg0, arg1, numArgs);
 
                 } else if (object instanceof JSFunction) {
                     // FEATURE: use something similar to call0/call1/call2 here
                     JSArray arguments = new JSArray();
-                    for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
-                    cx.stack.push(new CallMarker(cx));
-                    cx.stack.push(arguments);
-                    cx.f = (JSFunction)object;
-                    cx.scope = new JSScope(cx.f.parentJSScope);
-                    cx.pc = -1;
+                    for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(stack.pop(), j);
+                    stack.push(new CallMarker(this));
+                    stack.push(arguments);
+                    f = (JSFunction)object;
+                    scope = new JSScope(f.parentScope);
+                    pc = -1;
                     break;
 
-                } else if (object instanceof JSCallable) {
-                    JSCallable c = (JSCallable)object;
+                } else if (object instanceof JS) {
+                    JS c = (JS)object;
                     Object[] rest = numArgs > 3 ? new Object[numArgs - 3] : null;
-                    for(int i=numArgs - 1; i>2; i--) rest[i-3] = cx.stack.pop();
-                    Object a2 = numArgs <= 2 ? null : cx.stack.pop();
-                    Object a1 = numArgs <= 1 ? null : cx.stack.pop();
-                    Object a0 = numArgs <= 0 ? null : cx.stack.pop();
+                    for(int i=numArgs - 1; i>2; i--) rest[i-3] = stack.pop();
+                    Object a2 = numArgs <= 2 ? null : stack.pop();
+                    Object a1 = numArgs <= 1 ? null : stack.pop();
+                    Object a0 = numArgs <= 0 ? null : stack.pop();
                     ret = method == null ? c.call(a0, a1, a2, rest, numArgs) : c.callMethod(method, a0, a1, a2, rest, numArgs);
 
                 } else {
-                    throw new JS.Exn("can't call a " + object.getClass().getName() + " @" + cx.pc + "\n" + cx.f.dump());
+                    throw new JSExn("can't call a " + object + " @" + pc + "\n" + f.dump());
 
                 }
-                if (cx.pausecount > initialPauseCount) return null;
-                cx.stack.push(ret);
+                if (pausecount > initialPauseCount) { pc++; return null; }
+                stack.push(ret);
                 break;
             }
 
             case THROW: {
-                Object o = cx.stack.pop();
-                if(o instanceof JS.Exn) throw (JS.Exn)o;
-                throw new JS.Exn(o);
+                Object o = stack.pop();
+                if(o instanceof JSExn) throw (JSExn)o;
+                throw new JSExn(o);
             }
 
             case ASSIGN_SUB: case ASSIGN_ADD: {
-                Object val = cx.stack.pop();
-                Object old = cx.stack.pop();
-                Object key = cx.stack.pop();
-                Object obj = cx.stack.peek();
+                Object val = stack.pop();
+                Object old = stack.pop();
+                Object key = stack.pop();
+                Object obj = stack.peek();
                 if (val instanceof JSFunction && obj instanceof JSScope) {
                     JSScope parent = (JSScope)obj;
-                    while(parent.getParentJSScope() != null) parent = parent.getParentJSScope();
-                    if (parent instanceof JSTrap.JSTrappable) {
-                        JSTrap.JSTrappable b = (JSTrap.JSTrappable)parent;
-                        if (op == ASSIGN_ADD) JSTrap.addTrap(b, key, (JSFunction)val);
-                        else JSTrap.delTrap(b, key, (JSFunction)val);
+                    while(parent.getParentScope() != null) parent = parent.getParentScope();
+                    if (parent instanceof JS) {
+                        JS b = (JS)parent;
+                        if (op == ASSIGN_ADD) b.addTrap(key, (JSFunction)val);
+                        else b.delTrap(key, (JSFunction)val);
                         // skip over the "normal" implementation of +=/-=
-                        cx.pc += ((Integer)arg).intValue() - 1;
+                        pc += ((Integer)arg).intValue() - 1;
                         break;
                     }
                 }
                 // use the "normal" implementation
-                cx.stack.push(key);
-                cx.stack.push(old);
-                cx.stack.push(val);
+                stack.push(key);
+                stack.push(old);
+                stack.push(val);
                 break;
             }
 
@@ -320,25 +361,25 @@ class Interpreter implements ByteCodes, Tokens {
                 if(count < 2) throw new Error("this should never happen");
                 if(count == 2) {
                     // common case
-                    Object right = cx.stack.pop();
-                    Object left = cx.stack.pop();
+                    Object right = stack.pop();
+                    Object left = stack.pop();
                     if(left instanceof String || right instanceof String)
-                        cx.stack.push(JS.toString(left).concat(JS.toString(right)));
-                    else cx.stack.push(new Double(JS.toDouble(left) + JS.toDouble(right)));
+                        stack.push(JS.toString(left).concat(JS.toString(right)));
+                    else stack.push(JS.N(JS.toDouble(left) + JS.toDouble(right)));
                 } else {
                     Object[] args = new Object[count];
-                    while(--count >= 0) args[count] = cx.stack.pop();
+                    while(--count >= 0) args[count] = stack.pop();
                     if(args[0] instanceof String) {
                         StringBuffer sb = new StringBuffer(64);
                         for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
-                        cx.stack.push(sb.toString());
+                        stack.push(sb.toString());
                     } else {
                         int numStrings = 0;
                         for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
                         if(numStrings == 0) {
                             double d = 0.0;
                             for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
-                            cx.stack.push(new Double(d));
+                            stack.push(JS.N(d));
                         } else {
                             int i=0;
                             StringBuffer sb = new StringBuffer(64);
@@ -347,10 +388,10 @@ class Interpreter implements ByteCodes, Tokens {
                                 do {
                                     d += JS.toDouble(args[i++]);
                                 } while(!(args[i] instanceof String));
-                                sb.append(JS.toString(new Double(d)));
+                                sb.append(JS.toString(JS.N(d)));
                             }
                             while(i < args.length) sb.append(JS.toString(args[i++]));
-                            cx.stack.push(sb.toString());
+                            stack.push(sb.toString());
                         }
                     }
                 }
@@ -358,34 +399,34 @@ class Interpreter implements ByteCodes, Tokens {
             }
 
             default: {
-                Object right = cx.stack.pop();
-                Object left = cx.stack.pop();
+                Object right = stack.pop();
+                Object left = stack.pop();
                 switch(op) {
                         
-                case BITOR: cx.stack.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
-                case BITXOR: cx.stack.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
-                case BITAND: cx.stack.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
-
-                case SUB: cx.stack.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
-                case MUL: cx.stack.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
-                case DIV: cx.stack.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
-                case MOD: cx.stack.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
+                case BITOR: stack.push(JS.N(JS.toLong(left) | JS.toLong(right))); break;
+                case BITXOR: stack.push(JS.N(JS.toLong(left) ^ JS.toLong(right))); break;
+                case BITAND: stack.push(JS.N(JS.toLong(left) & JS.toLong(right))); break;
+
+                case SUB: stack.push(JS.N(JS.toDouble(left) - JS.toDouble(right))); break;
+                case MUL: stack.push(JS.N(JS.toDouble(left) * JS.toDouble(right))); break;
+                case DIV: stack.push(JS.N(JS.toDouble(left) / JS.toDouble(right))); break;
+                case MOD: stack.push(JS.N(JS.toDouble(left) % JS.toDouble(right))); break;
                         
-                case LSH: cx.stack.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
-                case RSH: cx.stack.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
-                case URSH: cx.stack.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
+                case LSH: stack.push(JS.N(JS.toLong(left) << JS.toLong(right))); break;
+                case RSH: stack.push(JS.N(JS.toLong(left) >> JS.toLong(right))); break;
+                case URSH: stack.push(JS.N(JS.toLong(left) >>> JS.toLong(right))); break;
                         
                 case LT: case LE: case GT: case GE: {
-                    if (left == null) left = new Integer(0);
-                    if (right == null) right = new Integer(0);
+                    if (left == null) left = JS.N(0);
+                    if (right == null) right = JS.N(0);
                     int result = 0;
                     if (left instanceof String || right instanceof String) {
                         result = left.toString().compareTo(right.toString());
                     } else {
                         result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
                     }
-                    cx.stack.push(new Boolean((op == LT && result < 0) || (op == LE && result <= 0) ||
-                                       (op == GT && result > 0) || (op == GE && result >= 0)));
+                    stack.push(JS.B((op == LT && result < 0) || (op == LE && result <= 0) ||
+                               (op == GT && result > 0) || (op == GE && result >= 0)));
                     break;
                 }
                     
@@ -397,39 +438,39 @@ class Interpreter implements ByteCodes, Tokens {
                     if (l == null) { Object tmp = r; r = l; l = tmp; }
                     if (l == null && r == null) ret = true;
                     else if (r == null) ret = false; // l != null, so its false
-                    else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
+                    else if (l instanceof Boolean) ret = JS.B(JS.toBoolean(r)).equals(l);
                     else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
                     else if (l instanceof String) ret = r != null && l.equals(r.toString());
                     else ret = l.equals(r);
-                    cx.stack.push(new Boolean(op == EQ ? ret : !ret)); break;
+                    stack.push(JS.B(op == EQ ? ret : !ret)); break;
                 }
 
                 default: throw new Error("unknown opcode " + op);
                 } }
             }
 
-        } catch(JS.Exn e) {
-            while(cx.stack.size() > 0) {
-                Object o = cx.stack.pop();
+        } catch(JSExn e) {
+            while(stack.size() > 0) {
+                Object o = stack.pop();
                 if (o instanceof CatchMarker || o instanceof TryMarker) {
                     boolean inCatch = o instanceof CatchMarker;
                     if(inCatch) {
-                        o = cx.stack.pop();
+                        o = stack.pop();
                         if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
                     }
                     if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
                         // run the catch block, this will implicitly run the finally block, if it exists
-                        cx.stack.push(o);
-                        cx.stack.push(catchMarker);
-                        cx.stack.push(e.getObject());
-                        cx.scope = ((TryMarker)o).scope;
-                        cx.pc = ((TryMarker)o).catchLoc - 1;
+                        stack.push(o);
+                        stack.push(catchMarker);
+                        stack.push(e.getObject());
+                        scope = ((TryMarker)o).scope;
+                        pc = ((TryMarker)o).catchLoc - 1;
                         continue OUTER;
                     } else {
-                        cx.stack.push(e);
-                        cx.stack.push(new FinallyData(THROW));
-                        cx.scope = ((TryMarker)o).scope;
-                        cx.pc = ((TryMarker)o).finallyLoc - 1;
+                        stack.push(e);
+                        stack.push(new FinallyData(THROW));
+                        scope = ((TryMarker)o).scope;
+                        pc = ((TryMarker)o).finallyLoc - 1;
                         continue OUTER;
                     }
                 }
@@ -441,15 +482,6 @@ class Interpreter implements ByteCodes, Tokens {
         } // end for
     }
 
-    // Exception Stuff ////////////////////////////////////////////////////////////////
-
-    static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
-    static EvaluatorException ee(String s) {
-        throw new EvaluatorException(JSContext.getSourceName() + ":" + JSContext.getLine() + " " + s);
-    }
-    static JS.Exn je(String s) {
-        throw new JS.Exn(JSContext.getSourceName() + ":" + JSContext.getLine() + " " + s);
-    }
 
 
     // Markers //////////////////////////////////////////////////////////////////////
@@ -458,7 +490,7 @@ class Interpreter implements ByteCodes, Tokens {
         int pc;
         JSScope scope;
         JSFunction f;
-        public CallMarker(JSContext cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
+        public CallMarker(Interpreter cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
     }
     
     public static class CatchMarker { public CatchMarker() { } }
@@ -490,4 +522,155 @@ class Interpreter implements ByteCodes, Tokens {
         public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
         public FinallyData(int op) { this(op,null); }
     }
+
+
+    // Operations on Primitives //////////////////////////////////////////////////////////////////////
+
+    static Object callMethodOnPrimitive(Object o, Object method, Object arg0, Object arg1, int alength) {
+        if (o instanceof Number) {
+            //#switch(method)
+            case "toFixed": throw new JSExn("toFixed() not implemented");
+            case "toExponential": throw new JSExn("toExponential() not implemented");
+            case "toPrecision": throw new JSExn("toPrecision() not implemented");
+            case "toString": {
+                int radix = alength >= 1 ? JS.toInt(arg0) : 10;
+                return Long.toString(((Number)o).longValue(),radix);
+            }
+            //#end
+        } else if (o instanceof Boolean) {
+            // No methods for Booleans
+            throw new JSExn("attempt to call a method on a Boolean");
+        }
+
+        String s = JS.toString(o);
+        int slength = s.length();
+        //#switch(method)
+        case "substring": {
+            int a = alength >= 1 ? JS.toInt(arg0) : 0;
+            int b = alength >= 2 ? JS.toInt(arg1) : slength;
+            if (a > slength) a = slength;
+            if (b > slength) b = slength;
+            if (a < 0) a = 0;
+            if (b < 0) b = 0;
+            if (a > b) { int tmp = a; a = b; b = tmp; }
+            return s.substring(a,b);
+        }
+        case "substr": {
+            int start = alength >= 1 ? JS.toInt(arg0) : 0;
+            int len = alength >= 2 ? JS.toInt(arg1) : Integer.MAX_VALUE;
+            if (start < 0) start = slength + start;
+            if (start < 0) start = 0;
+            if (len < 0) len = 0;
+            if (len > slength - start) len = slength - start;
+            if (len <= 0) return "";
+            return s.substring(start,start+len);
+        }
+        case "charAt": {
+            int p = alength >= 1 ? JS.toInt(arg0) : 0;
+            if (p < 0 || p >= slength) return "";
+            return s.substring(p,p+1);
+        }
+        case "charCodeAt": {
+            int p = alength >= 1 ? JS.toInt(arg0) : 0;
+            if (p < 0 || p >= slength) return JS.N(Double.NaN);
+            return JS.N(s.charAt(p));
+        }
+        case "concat": {
+            // FIXME takes variable number of arguments...
+            /*
+            StringBuffer sb = new StringBuffer(slength*2).append(s);
+            for(int i=0;i<alength;i++) sb.append(args.elementAt(i));
+            return sb.toString();
+            */
+        }
+        case "indexOf": {
+            String search = alength >= 1 ? arg0.toString() : "null";
+            int start = alength >= 2 ? JS.toInt(arg1) : 0;
+            // Java's indexOf handles an out of bounds start index, it'll return -1
+            return JS.N(s.indexOf(search,start));
+        }
+        case "lastIndexOf": {
+            String search = alength >= 1 ? arg0.toString() : "null";
+            int start = alength >= 2 ? JS.toInt(arg1) : 0;
+            // Java's indexOf handles an out of bounds start index, it'll return -1
+            return JS.N(s.lastIndexOf(search,start));            
+        }
+        case "match": return JSRegexp.stringMatch(s,arg0);
+        case "replace": return JSRegexp.stringReplace(s,(String)arg0,arg1);
+        case "search": return JSRegexp.stringSearch(s,arg0);
+        case "split": return JSRegexp.stringSplit(s,(String)arg0,arg1);
+        case "toLowerCase": return s.toLowerCase();
+        case "toUpperCase": return s.toUpperCase();
+        case "toString": return s;
+        case "slice": {
+            int a = alength >= 1 ? JS.toInt(arg0) : 0;
+            int b = alength >= 2 ? JS.toInt(arg1) : slength;
+            if (a < 0) a = slength + a;
+            if (b < 0) b = slength + b;
+            if (a < 0) a = 0;
+            if (b < 0) b = 0;
+            if (a > slength) a = slength;
+            if (b > slength) b = slength;
+            if (a > b) return "";
+            return s.substring(a,b);
+        }
+        //#end
+        throw new JSExn("Attempted to call non-existent method: " + method);
+    }
+    
+    static Object getFromPrimitive(Object o, Object key) {
+        boolean returnJS = false;
+        if (o instanceof Boolean) {
+            throw new JSExn("cannot call methods on Booleans");
+        } else if (o instanceof Number) {
+            if (key.equals("toPrecision") || key.equals("toExponential") || key.equals("toFixed"))
+                returnJS = true;
+        }
+        if (!returnJS) {
+            // the string stuff applies to everything
+            String s = o.toString();
+            
+            // this is sort of ugly, but this list should never change
+            // These should provide a complete (enough) implementation of the ECMA-262 String object
+
+            //#switch(key)
+            case "length": return JS.N(s.length());
+            case "substring": returnJS = true; break; 
+            case "charAt": returnJS = true; break; 
+            case "charCodeAt": returnJS = true; break; 
+            case "concat": returnJS = true; break; 
+            case "indexOf": returnJS = true; break; 
+            case "lastIndexOf": returnJS = true; break; 
+            case "match": returnJS = true; break; 
+            case "replace": returnJS = true; break; 
+            case "seatch": returnJS = true; break; 
+            case "slice": returnJS = true; break; 
+            case "split": returnJS = true; break; 
+            case "toLowerCase": returnJS = true; break; 
+            case "toUpperCase": returnJS = true; break; 
+            case "toString": returnJS = true; break; 
+            case "substr": returnJS = true; break; 
+            //#end
+        }
+        if (returnJS) {
+            final Object target = o;
+            final String method = key.toString();
+            return new JS() {
+                    public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) {
+                        if (nargs > 2) throw new JSExn("cannot call that method with that many arguments");
+                        return callMethodOnPrimitive(target, method, a0, a1, nargs);
+                    }
+            };
+        }
+        return null;
+    }
+
+    private static class Stub extends JS {
+        private Object method;
+        JS obj;
+        public Stub(JS obj, Object method) { this.obj = obj; this.method = method; }
+        public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) {
+            return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs);
+        }
+    }
 }