X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=src%2Forg%2Fxwt%2Fjs%2FInterpreter.java;h=b5becd03287aaae0e251f84adfed5ae96930c688;hb=de378041d5ca2aca1a2b5a31ef15ae90a86c977f;hp=a9ea8a3f284d63ff9fd7ce36d49b309454ecbf85;hpb=cba642c3dd58d20b4ecebe4ea96232cdd983b17e;p=org.ibex.core.git diff --git a/src/org/xwt/js/Interpreter.java b/src/org/xwt/js/Interpreter.java index a9ea8a3..b5becd0 100644 --- a/src/org/xwt/js/Interpreter.java +++ b/src/org/xwt/js/Interpreter.java @@ -1,148 +1,203 @@ -// Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL] +// Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL] package org.xwt.js; 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() throws JSExn { + Thread t = Thread.currentThread(); + Interpreter old = (Interpreter)threadToInterpreter.get(t); + threadToInterpreter.put(t, this); 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]; + return run(); + } finally { + if (old == null) threadToInterpreter.remove(t); + else threadToInterpreter.put(t, old); + } + } + + 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); } + + // 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 (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 + if(fd.exn != null) throw fd.exn; 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("xwt.assertion.failed" /*FEATURE: line number*/); 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("object"); + 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 throw new Error("this should not happen"); 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()); + 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 - 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], this)); 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) { // handles return component of a read trap + Trap.TrapScope ts = (Trap.TrapScope)scope; + if (retval != null && retval instanceof Boolean && ((Boolean)retval).booleanValue()) + ts.cascadeHappened = true; 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 + ((JS)ts.t.trapee).put(ts.t.name, ts.val); + 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; - break; + stack.push(args); + f = t.f; + scope = new Trap.TrapScope(f.parentScope, t, ts.val); + pc = -1; + continue OUTER; } } } - 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 - 1; + f = (JSFunction)((CallMarker)o).f; + stack.push(retval); continue OUTER; } } @@ -150,39 +205,53 @@ 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); - 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; + + Trap t = null; + 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) { target = ts.t.trapee; key = ts.t.name; } + + } else if (target instanceof Trap.TrapScope && key.equals(((Trap.TrapScope)target).t.name)) { + throw je("tried to put to " + key + " inside a trap it owns; use cascade instead"); + + } else if (target instanceof JS) { + if (target instanceof JSScope) { + JSScope p = (JSScope)target; // search the scope-path for the trap + t = p.getTrap(key); + while (t == null && p.getParentScope() != null) { p = p.getParentScope(); t = p.getTrap(key); } + } else { + t = ((JS)target).getTrap(key); + } + + while (t != null && t.f.numFormalArgs == 0) t = t.next; // find the first write trap + if (t != null) { + stack.push(new CallMarker(this)); + JSArray args = new JSArray(); + args.addElement(val); + stack.push(args); + } } if (t != null) { - cx.stack.push(new CallMarker(cx)); - 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; + 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 +259,54 @@ 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 object"); 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); - 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; + Trap t = null; + 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) { v = ((Trap.TrapScope)o).t.name; o = ((Trap.TrapScope)o).t.trapee; } + + } else if (o instanceof JS) { + if (o instanceof JSScope) { + JSScope p = (JSScope)o; // search the scope-path for the trap + t = p.getTrap(v); + while (t == null && p.getParentScope() != null) { p = p.getParentScope(); t = p.getTrap(v); } + } else { + t = ((JS)o).getTrap(v); + } + + while (t != null && t.f.numFormalArgs != 0) t = t.next; // get first read trap + if (t != null) { + stack.push(new CallMarker(this)); + JSArray args = new JSArray(); + stack.push(args); + } } if (t != null) { - cx.stack.push(new CallMarker(cx)); - 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; + 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,76 +316,100 @@ 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 if (object == null) { + Object name = stack.pop(); + stack.pop(); + throw new JSExn("function '"+name+"' not found"); + } else { + stack.pop(); + stack.pop(); + } } + Object[] rest = numArgs > 3 ? new Object[numArgs - 3] : null; + 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(); 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); + ret = callMethodOnPrimitive(object, method, a0, a1, a2, null, numArgs); } else if (object instanceof JSFunction) { - // FEATURE: use something similar to call0/call1/call2 here + // FIXME: 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 i=0; i 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(); - ret = c.callMethod(method, a0, a1, a2, rest, numArgs); + } else if (object instanceof JS) { + JS c = (JS)object; + 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: + throw new JSExn(stack.pop()); + + case MAKE_GRAMMAR: { + final Grammar r = (Grammar)arg; + final JSScope final_scope = scope; + Grammar r2 = new Grammar() { + public int match(String s, int start, Hash v, JSScope scope) throws JSExn { + return r.match(s, start, v, final_scope); + } + public int matchAndWrite(String s, int start, Hash v, JSScope scope, String key) throws JSExn { + return r.matchAndWrite(s, start, v, final_scope, key); + } + public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn { + Hash v = new Hash(); + r.matchAndWrite((String)a0, 0, v, final_scope, "foo"); + return v.get("foo"); + } + }; + Object obj = stack.pop(); + if (obj != null && obj instanceof Grammar) r2 = new Grammar.Alternative((Grammar)obj, r2); + stack.push(r2); break; } - case THROW: { - Object o = cx.stack.pop(); - if(o instanceof JS.Exn) throw (JS.Exn)o; - throw new JS.Exn(o); + case ADD_TRAP: case DEL_TRAP: { + Object val = stack.pop(); + Object key = stack.pop(); + Object obj = stack.peek(); + // A trap addition/removal + JS js = obj instanceof JSScope ? ((JSScope)obj).top() : (JS) obj; + if(op == ADD_TRAP) js.addTrap(key, (JSFunction)val); + else js.delTrap(key, (JSFunction)val); + break; } 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(); - 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); - // skip over the "normal" implementation of +=/-= - cx.pc += ((Integer)arg).intValue() - 1; - break; - } - } - // use the "normal" implementation - cx.stack.push(key); - cx.stack.push(old); - cx.stack.push(val); + Object val = stack.pop(); + Object key = stack.pop(); + Object obj = stack.peek(); + // The following setup is VERY important. The generated bytecode depends on the stack + // being setup like this (top to bottom) KEY, OBJ, VAL, KEY, OBJ + stack.push(key); + stack.push(val); + stack.push(obj); + stack.push(key); break; } @@ -315,25 +418,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> 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; } @@ -392,59 +495,56 @@ 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) { + if(f.op[pc] != FINALLY_DONE) e.addBacktrace(f.sourceName,f.line[pc]); + 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()); + f = ((TryMarker)o).f; + 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(new FinallyData(e)); + f = ((TryMarker)o).f; + scope = ((TryMarker)o).scope; + pc = ((TryMarker)o).finallyLoc - 1; continue OUTER; } + } else if(o instanceof CallMarker) { + CallMarker cm = (CallMarker) o; + if(cm.f == null) + e.addBacktrace("",0); // This might not even be worth mentioning + else + e.addBacktrace(cm.f.sourceName,cm.f.line[cm.pc-1]); } - // no handler found within this func - if(o instanceof CallMarker) throw e; } throw e; } // end try/catch } // 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 ////////////////////////////////////////////////////////////////////// @@ -453,7 +553,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() { } } @@ -473,16 +573,171 @@ class Interpreter implements ByteCodes, Tokens { public int catchLoc; public int finallyLoc; public JSScope scope; - public TryMarker(int catchLoc, int finallyLoc, JSScope scope) { + public JSFunction f; + public TryMarker(int catchLoc, int finallyLoc, Interpreter cx) { this.catchLoc = catchLoc; this.finallyLoc = finallyLoc; - this.scope = scope; + this.scope = cx.scope; + this.f = cx.f; } } public static class FinallyData { public int op; public Object arg; - public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; } + public JSExn exn; public FinallyData(int op) { this(op,null); } + public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; } + public FinallyData(JSExn exn) { this.exn = exn; } // Just throw this exn + } + + + // Operations on Primitives ////////////////////////////////////////////////////////////////////// + + static Object callMethodOnPrimitive(Object o, Object method, Object arg0, Object arg1, Object arg2, Object[] rest, int alength) throws JSExn { + if (method == null || !(method instanceof String) || "".equals(method)) + throw new JSExn("attempt to call a non-existant method on a primitive"); + + 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": { + StringBuffer sb = new StringBuffer(slength*2).append(s); + for(int i=0;i= 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,arg0,arg1); + case "search": return JSRegexp.stringSearch(s,arg0); + case "split": return JSRegexp.stringSplit(s,arg0,arg1,alength); + 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) throws JSExn { + 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) throws JSExn { + if (nargs > 2) throw new JSExn("cannot call that method with that many arguments"); + return callMethodOnPrimitive(target, method, a0, a1, a2, rest, 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) throws JSExn { + return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs); + } } }