// Copyright 2000-2005 the Contributors, as shown in the revision logs. // Licensed under the Apache Public Source License 2.0 ("the License"). // You may not use this file except in compliance with the License. package org.ibex.js; import org.ibex.util.*; import java.util.*; /** Encapsulates a single JS interpreter (ie call stack) */ class Interpreter implements ByteCodes, Tokens, Pausable { // 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) final Stack stack = new Stack(); ///< the object stack int pc = 0; ///< the program counter Interpreter(JSFunction f, boolean pauseable, JS[] args) { this.f = f; this.pausecount = pauseable ? 0 : -1; this.scope = f.parentScope; try { stack.push(new CallMarker(null)); // the "root function returned" marker -- f==null stack.push(new JSArgs(args, f)); // FIXME: temprorary bug fix } catch(JSExn e) { throw new Error("should never happen"); } } Interpreter(JS.Trap t, JS val, boolean pauseOnPut) { this.pausecount = -1; try { setupTrap(t,val,new TrapMarker(null,t,val,pauseOnPut)); } catch(JSExn e) { throw new Error("should never happen"); } } private boolean get = false; // FIXME: split this stuff out into a Script instance control object // so it's possible to make JS either single or multi threaded. /** this is the only synchronization point we need in order to be threadsafe */ public synchronized Object run(Object o) throws JSExn { if (f == null) throw new AlreadyRunningException("function already finished"); if (scope == null) throw new RuntimeException("scope is null"); Thread t = Thread.currentThread(); Interpreter old = (Interpreter)threadToInterpreter.get(t); threadToInterpreter.put(t, this); if (get) stack.push(o); try { return run(); } finally { if (old == null) threadToInterpreter.remove(t); else threadToInterpreter.put(t, old); } } public void pause() throws NotPausableException { if (pausecount == -1 || f == null) throw new NotPausableException(); pausecount++; switch(f.op[pc]) { case Tokens.RETURN: case ByteCodes.PUT: get = false; break; case ByteCodes.GET: case ByteCodes.GET_PRESERVE: case ByteCodes.CALLMETHOD: case ByteCodes.CALL: get = true; break; default: throw new Error("paused on unexpected bytecode: " + f.op[pc]); } } static int getLine() { Interpreter c = Interpreter.current(); return c == null || c.f == null || c.pc < 0 || c.pc >= c.f.size ? -1 : c.f.line[c.pc]; } static String getSourceName() { Interpreter c = Interpreter.current(); return c == null || c.f == null ? null : c.f.sourceName; } private static JSExn je(String s) { return new JSExn(getSourceName() + ":" + getLine() + " " + s); } private JS 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 { int op = f.op[pc]; Object arg = f.arg[pc]; if(op == FINALLY_DONE) { FinallyData fd = (FinallyData) stack.pop(); if(fd == null) continue OUTER; // NOP if(fd.exn != null) throw fd.exn; op = fd.op; arg = fd.arg; } switch(op) { case LITERAL: stack.push((JS)arg); break; case OBJECT: stack.push(new JS.Obj()); break; case ARRAY: stack.push(new JSArray(JSU.toInt((JS)arg))); break; //case DECLARE: scope.declare((JS)(arg==null ? stack.peek() : arg)); if(arg != null) stack.push((JS)arg); break; case JT: if (JSU.toBoolean((JS)stack.pop())) pc += JSU.toInt((JS)arg) - 1; break; case JF: if (!JSU.toBoolean((JS)stack.pop())) pc += JSU.toInt((JS)arg) - 1; break; case JMP: pc += JSU.toInt((JS)arg) - 1; break; case POP: stack.pop(); break; case SWAP: stack.swap(); break; case DUP: stack.push(stack.peek()); break; case NEWSCOPE: { int n = JSU.toInt((JS)arg); scope = new JSScope(scope,(n>>>16)&0xffff,(n>>>0)&0xffff); break; } case OLDSCOPE: scope = scope.parent; break; case GLOBALSCOPE: stack.push(scope.getGlobal()); break; case SCOPEGET: stack.push(scope.get((JS)arg)); break; case SCOPEPUT: { // FIXME: HACK: share this around more and find the callee. Object val = stack.peek(); if (val != null && val instanceof JS[]) val = new JSArgs((JS[])val, null); scope.put((JS)arg, (JS)val); break; } case ASSERT: if (!JSU.toBoolean((JS)stack.pop())) throw je("ibex.assertion.failed"); break; case BITNOT: stack.push(JSU.N(~JSU.toLong((JS)stack.pop()))); break; case BANG: stack.push(JSU.B(!JSU.toBoolean((JS)stack.pop()))); break; case NEWFUNCTION: stack.push(((JSFunction)arg)._cloneWithNewParentScope(scope)); break; case LABEL: break; case TYPEOF: { Object o = stack.pop(); if (o == null) stack.push(null); else if (o instanceof JSString) stack.push(JSU.S("string")); else if (o instanceof JSNumber.B) stack.push(JSU.S("boolean")); else if (o instanceof JSNumber) stack.push(JSU.S("number")); else stack.push(JSU.S("object")); break; } case PUSHKEYS: { JS o = (JS)stack.peek(); stack.push(o == null ? null : o.keys()); break; } case LOOP: stack.push(new LoopMarker(pc, (String)(pc > 0 && f.op[pc - 1] == LABEL ? f.arg[pc - 1] : null), scope)); stack.push(JSU.T); break; case BREAK: case CONTINUE: while(!stack.empty()) { 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 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 = JSU.toInt((JS)f.arg[loopInstructionLocation]) + loopInstructionLocation; scope = ((LoopMarker)o).scope; if (op == CONTINUE) { stack.push(o); stack.push(JSU.F); } pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation; continue OUTER; } } } throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " + getSourceName() + ":" + 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 stack.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1], this)); break; } case RETURN: { JS retval = (JS)stack.pop(); while(!stack.empty()) { Object o = stack.pop(); if (o instanceof TryMarker) { if(((TryMarker)o).finallyLoc < 0) continue; stack.push(retval); stack.push(new FinallyData(RETURN)); scope = ((TryMarker)o).scope; pc = ((TryMarker)o).finallyLoc - 1; continue OUTER; } else if (o instanceof CallMarker) { boolean didTrapPut = false; if (o instanceof TrapMarker) { // handles return component of a write trap TrapMarker tm = (TrapMarker) o; boolean cascade = tm.t.isWriteTrap() && !tm.cascadeHappened && !JSU.toBoolean(retval); if(cascade) { JS.Trap t = tm.t.nextWrite(); if(t == null && tm.t.target() instanceof JS.Clone) { t = ((JS.Clone)tm.t.target()).clonee.getTrap(tm.t.key()); if(t != null && !t.isWriteTrap()) t = t.nextWrite(); } if(t != null) { tm.t = t; // we reuse the old trap marker setupTrap(t, tm.val, tm); pc--; // we increment it on the next iter continue OUTER; } else { didTrapPut = true; if(!tm.pauseOnPut) tm.t.target().put(tm.t.key(), tm.val); } } } CallMarker cm = (CallMarker) o; scope = cm.scope; pc = cm.pc - 1; f = cm.f; if (didTrapPut) { if (((TrapMarker)cm).pauseOnPut) { pc++; return ((TrapMarker)cm).val; } if (pausecount > initialPauseCount) { pc++; return null; } // we were paused } else { stack.push(retval); } if (f == null) return retval; continue OUTER; } } throw new Error("error: RETURN invoked but couldn't find a CallMarker!"); } case CASCADE: { boolean write = JSU.toBoolean((JS)arg); JS val = write ? (JS)stack.pop() : null; CallMarker o = stack.findCall(); if(!(o instanceof TrapMarker)) throw new JSExn("tried to CASCADE while not in a trap"); TrapMarker tm = (TrapMarker) o; JS key = tm.t.key(); JS target = tm.t.target(); if(tm.t.isWriteTrap() != write) throw new JSExn("tried to do a "+(write?"write":"read") + " cascade in a " + (write?"read":"write") + " trap"); JS.Trap t = write ? tm.t.nextWrite() : tm.t.nextRead(); while (t == null && target instanceof JS.Clone) { target = ((JS.Clone)target).clonee; t = target.getTrap(key); if(t != null) t = write ? t.write() : t.read(); } if(write) { tm.cascadeHappened = true; stack.push(val); } if(t != null) { setupTrap(t,val,new TrapMarker(this,t,val,tm.pauseOnPut)); pc--; // we increment later } else { if(write) { if (tm.pauseOnPut) { pc++; return val; } target.put(key,val); } else { JS ret = target.get(key); if (ret != null && ret instanceof JS.Method) ret = new Stub(target, key); stack.push(ret); } if (pausecount > initialPauseCount) { pc++; return null; } // we were paused } break; } case PUT: { JS val = (JS)stack.pop(); JS key = (JS)stack.pop(); JS target = (JS)stack.peek(); if (target == null) throw je("tried to put " + JSU.str(val) + " to the " + JSU.str(key) + " property on the null value"); if (key == null) throw je("tried to assign \"" + JSU.str(val) + "\" to the null key"); JS.Trap t = target.getTrap(key); if(t != null) t = t.write(); if(t == null && target instanceof JS.Clone) { target = ((JS.Clone)target).clonee; t = target.getTrap(key); if(t != null) t = t.nextWrite(); } stack.push(val); if(t != null) { setupTrap(t,val,new TrapMarker(this,t,val)); pc--; // we increment later } else { target.put(key,val); if (pausecount > initialPauseCount) { pc++; return null; } // we were paused } break; } case GET: case GET_PRESERVE: { JS target, key; if (op == GET) { key = arg == null ? (JS)stack.pop() : (JS)arg; target = (JS)stack.pop(); } else { key = (JS)stack.pop(); target = (JS)stack.peek(); stack.push(key); } JS ret = null; if (key == null) throw je("tried to get the null key from " + JSU.str(target)); if (target == null) throw je("tried to get property \"" + JSU.str(key) + "\" from the null object"); JS.Trap t = null; try { t = target.getTrap(key); } catch (JSExn e) {} if(t != null) t = t.read(); if(t == null && target instanceof JS.Clone) { target = ((JS.Clone)target).clonee; t = target.getTrap(key); if(t != null) t = t.nextRead(); } if(t != null) { setupTrap(t,null,new TrapMarker(this,t,null)); pc--; // we increment later } else { ret = target.get(key); if (pausecount > initialPauseCount) { pc++; return null; } // we were paused if (ret != null && ret instanceof JS.Method) ret = new Stub(target, key); stack.push(ret); } break; } case CALL: case CALLMETHOD: { JS[] jsargs; if (arg instanceof JSNumber.I) { // FIXME: we should be able to recycle JS[]'s here jsargs = new JS[((JSNumber.I)arg).toInt()]; for (int i=0; i < jsargs.length; i++) jsargs[i] = (JS)stack.pop(); } else jsargs = (JS[])arg; JS method = null; JS ret = null; JS object = (JS)stack.pop(); if (op == CALLMETHOD) { if (object == null) { method = (JS)stack.pop(); object = (JS)stack.pop(); throw new JSExn("function '"+JSU.str(method)+"' not found in " + object.getClass().getName()); } else if (object instanceof JS.Method) { method = (JS)stack.pop(); object = (JS)stack.pop(); } else { stack.pop(); stack.pop(); } } if (object instanceof JSFunction) { stack.push(new CallMarker(this)); f = (JSFunction)object; stack.push(new JSArgs(jsargs, f)); scope = f.parentScope; pc = -1; break; } else { JS c = (JS)object; ret = c.call(method, jsargs); } if (pausecount > initialPauseCount) { pc++; return null; } stack.push(ret); break; } case THROW: throw new JSExn((JS)stack.pop(), this); case ADD_TRAP: case DEL_TRAP: { JS val = (JS)stack.pop(); JS key = (JS)stack.pop(); JS js = (JS)stack.peek(); // A trap addition/removal if(!(val instanceof JSFunction)) throw new JSExn("tried to add/remove a non-function trap"); if(op == ADD_TRAP) js.addTrap(key, val); else js.delTrap(key, val); break; } case ADD: { int count = ((JSNumber)arg).toInt(); if(count < 2) throw new Error("this should never happen"); if(count == 2) { // common case JS right = (JS)stack.pop(); JS left = (JS)stack.pop(); JS ret; if(left instanceof JSString || right instanceof JSString) ret = JSU.S(JSU.toString(left).concat(JSU.toString(right))); else if(left instanceof JSNumber.D || right instanceof JSNumber.D) ret = JSU.N(JSU.toDouble(left) + JSU.toDouble(right)); else { long l = JSU.toLong(left) + JSU.toLong(right); if(l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) ret = JSU.N(l); ret = JSU.N((int)l); } stack.push(ret); } else { JS[] args = new JS[count]; while(--count >= 0) args[count] = (JS)stack.pop(); if(args[0] instanceof JSString) { StringBuffer sb = new StringBuffer(64); for(int i=0;i> JSU.toLong(right))); break; case URSH: stack.push(JSU.N(JSU.toLong(left) >>> JSU.toLong(right))); break; case LT: case LE: case GT: case GE: { int cmp = 0; if(left instanceof JSString && right instanceof JSString) cmp = JSU.toString(left).compareTo(JSU.toString(right)); else cmp = (int)(100 * (JSU.toDouble(left) - JSU.toDouble(right))); switch(op) { case LE: stack.push(JSU.B(cmp <= 0)); break; case LT: stack.push(JSU.B(cmp < 0)); break; case GE: stack.push(JSU.B(cmp >= 0)); break; case GT: stack.push(JSU.B(cmp > 0)); break; default: throw new RuntimeException("impossible"); } break; } case EQ: case NE: { boolean ret; if(left == null && right == null) ret = true; else if(left == null || right == null) ret = false; else ret = left.equals(right); stack.push(JSU.B(op == EQ ? ret : !ret)); break; } default: throw new Error("unknown opcode " + op); } } } } catch(JSExn e) { catchException(e); pc--; // it'll get incremented on the next iteration } // end try/catch } // end for } /** tries to find a handler withing the call chain for this exception if a handler is found the interpreter is setup to call the exception handler if a handler is not found the exception is thrown */ void catchException(JSExn e) throws JSExn { while(!stack.empty()) { Object o = stack.pop(); if (o instanceof CatchMarker || o instanceof TryMarker) { boolean inCatch = o instanceof CatchMarker; if(inCatch) { o = (JS)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 stack.push(o); stack.push(catchMarker); stack.push(e.getObject()); f = ((TryMarker)o).f; scope = ((TryMarker)o).scope; pc = ((TryMarker)o).catchLoc; return; } else { stack.push(new FinallyData(e)); f = ((TryMarker)o).f; scope = ((TryMarker)o).scope; pc = ((TryMarker)o).finallyLoc; return; } } } throw e; } void setupTrap(JS.Trap t, JS val, CallMarker cm) throws JSExn { stack.push(cm); stack.push(new TrapArgs(t, val)); f = (JSFunction)t.function(); scope = f.parentScope; pc = 0; } // Markers ////////////////////////////////////////////////////////////////////// static class Marker {} static class CallMarker extends Marker { final int pc; final JSScope scope; final JSFunction f; public CallMarker(Interpreter cx) { pc = cx == null ? -1 : cx.pc + 1; scope = cx == null ? null : cx.scope; f = cx == null ? null : cx.f; } } static class TrapMarker extends CallMarker { JS.Trap t; JS val; boolean cascadeHappened; final boolean pauseOnPut; public TrapMarker(Interpreter cx, JS.Trap t, JS val) { this(cx,t,val,false); } public TrapMarker(Interpreter cx, JS.Trap t, JS val, boolean pauseOnPut) { super(cx); this.t = t; this.val = val; this.pauseOnPut = pauseOnPut; } } static class CatchMarker extends Marker { } private static final CatchMarker catchMarker = new CatchMarker(); static class LoopMarker extends Marker { final public int location; final public String label; final public JSScope scope; public LoopMarker(int location, String label, JSScope scope) { this.location = location; this.label = label; this.scope = scope; } } static class TryMarker extends Marker { final public int catchLoc; final public int finallyLoc; final public JSScope scope; final public JSFunction f; public TryMarker(int catchLoc, int finallyLoc, Interpreter cx) { this.catchLoc = catchLoc; this.finallyLoc = finallyLoc; this.scope = cx.scope; this.f = cx.f; } } static class FinallyData extends Marker { final public int op; final public Object arg; final public JSExn exn; public FinallyData(int op) { this(op,null); } public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; this.exn = null; } public FinallyData(JSExn exn) { this.exn = exn; this.op = -1; this.arg = null; } // Just throw this exn } static class JSArgs extends JS.Immutable { private final JS[] args; private final JS callee; public JSArgs(JS[] args, JS callee) { this.args = args; this.callee = callee; } public JS get(JS key) throws JSExn { if(JSU.isInt(key)) { int i = JSU.toInt(key); return i>=args.length ? null : args[i]; } //#switch(JSU.toString(key)) case "callee": return callee; case "length": return JSU.N(args.length); //#end return super.get(key); } } static class TrapArgs extends JS.Immutable { private Trap t; private JS val; public TrapArgs(Trap t, JS val) { this.t = t; this.val = val; } public JS get(JS key) throws JSExn { if(JSU.isInt(key) && JSU.toInt(key) == 0) return val; //#switch(JSU.str(key)) case "trapee": return t.target(); case "callee": return t.function(); case "trapname": return t.key(); case "length": return t.isWriteTrap() ? JSU.ONE : JSU.ZERO; //#end return super.get(key); } } static class Stub extends JS.Immutable { private JS method; JS obj; public Stub(JS obj, JS method) { this.obj = obj; this.method = method; } public JS call(JS method, JS[] args) throws JSExn { if (method==null) return obj.call(this.method, args); return super.call(method, args); } } static final class Stack { private static final int MAX_STACK_SIZE = 512; private Object[] stack = new Object[8]; private int sp = 0; boolean empty() { return sp == 0; } void push(Object o) throws JSExn { if(sp == stack.length) grow(); stack[sp++] = o; } Object peek() { if(sp == 0) throw new RuntimeException("stack underflow"); return stack[sp-1]; } final Object pop() { if(sp == 0) throw new RuntimeException("stack underflow"); return stack[--sp]; } void swap() throws JSExn { if(sp < 2) throw new JSExn("stack overflow"); Object tmp = stack[sp-2]; stack[sp-2] = stack[sp-1]; stack[sp-1] = tmp; } CallMarker findCall() { for(int i=sp-1;i>=0;i--) if(stack[i] instanceof CallMarker) return (CallMarker) stack[i]; return null; } void grow() throws JSExn { if(stack.length >= MAX_STACK_SIZE) throw new JSExn("stack overflow"); Object[] stack2 = new Object[stack.length * 2]; System.arraycopy(stack,0,stack2,0,stack.length); stack = stack2; } void backtrace(JSExn e) { for(int i=sp-1;i>=0;i--) { if (stack[i] instanceof CallMarker) { CallMarker cm = (CallMarker)stack[i]; if(cm.f == null) break; String s = cm.f.sourceName + ":" + cm.f.line[cm.pc-1]; if(cm instanceof Interpreter.TrapMarker) s += " (trap on " + JSU.str(((Interpreter.TrapMarker)cm).t.key()) + ")"; e.addBacktrace(s); } } } } }