1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
4 import org.ibex.util.*;
7 /** Encapsulates a single JS interpreter (ie call stack) */
8 class Interpreter implements ByteCodes, Tokens {
9 private static final JS CASCADE = JSString.intern("cascade");
11 // Thread-Interpreter Mapping /////////////////////////////////////////////////////////////////////////
13 static Interpreter current() { return (Interpreter)threadToInterpreter.get(Thread.currentThread()); }
14 private static Hashtable threadToInterpreter = new Hashtable();
17 // Instance members and methods //////////////////////////////////////////////////////////////////////
19 int pausecount; ///< the number of times pause() has been invoked; -1 indicates unpauseable
20 JSFunction f = null; ///< the currently-executing JSFunction
21 JSScope scope; ///< the current top-level scope (LIFO stack via NEWSCOPE/OLDSCOPE)
22 final Stack stack = new Stack(); ///< the object stack
23 int pc = 0; ///< the program counter
25 Interpreter(JSFunction f, boolean pauseable, JSArgs args) {
27 this.pausecount = pauseable ? 0 : -1;
28 this.scope = new JSScope(f.parentScope);
30 stack.push(new CallMarker(null)); // the "root function returned" marker -- f==null
33 throw new Error("should never happen");
37 Interpreter(Trap t, JS val, boolean pauseOnPut) {
40 setupTrap(t,val,new TrapMarker(null,t,val,pauseOnPut));
42 throw new Error("should never happen");
46 /** this is the only synchronization point we need in order to be threadsafe */
47 synchronized JS resume() throws JSExn {
48 if(f == null) throw new RuntimeException("function already finished");
49 Thread t = Thread.currentThread();
50 Interpreter old = (Interpreter)threadToInterpreter.get(t);
51 threadToInterpreter.put(t, this);
55 if (old == null) threadToInterpreter.remove(t);
56 else threadToInterpreter.put(t, old);
60 static int getLine() {
61 Interpreter c = Interpreter.current();
62 return c == null || c.f == null || c.pc < 0 || c.pc >= c.f.size ? -1 : c.f.line[c.pc];
65 static String getSourceName() {
66 Interpreter c = Interpreter.current();
67 return c == null || c.f == null ? null : c.f.sourceName;
70 private static JSExn je(String s) { return new JSExn(getSourceName() + ":" + getLine() + " " + s); }
72 private JS run() throws JSExn {
74 // if pausecount changes after a get/put/call, we know we've been paused
75 final int initialPauseCount = pausecount;
80 Object arg = f.arg[pc];
81 if(op == FINALLY_DONE) {
82 FinallyData fd = (FinallyData) stack.pop();
83 if(fd == null) continue OUTER; // NOP
84 if(fd.exn != null) throw fd.exn;
89 case LITERAL: stack.push((JS)arg); break;
90 case OBJECT: stack.push(new JS.O()); break;
91 case ARRAY: stack.push(new JSArray(JS.toInt((JS)arg))); break;
92 case DECLARE: scope.declare((JS)(arg==null ? stack.peek() : arg)); if(arg != null) stack.push((JS)arg); break;
93 case TOPSCOPE: stack.push(scope); break;
94 case JT: if (JS.toBoolean(stack.pop())) pc += JS.toInt((JS)arg) - 1; break;
95 case JF: if (!JS.toBoolean(stack.pop())) pc += JS.toInt((JS)arg) - 1; break;
96 case JMP: pc += JS.toInt((JS)arg) - 1; break;
97 case POP: stack.pop(); break;
98 case SWAP: stack.swap(); break;
99 case DUP: stack.push(stack.peek()); break;
100 case NEWSCOPE: scope = new JSScope(scope); break;
101 case OLDSCOPE: scope = scope.getParentScope(); break;
102 case ASSERT: if (!JS.toBoolean(stack.pop())) throw je("ibex.assertion.failed"); break;
103 case BITNOT: stack.push(JS.N(~JS.toLong(stack.pop()))); break;
104 case BANG: stack.push(JS.B(!JS.toBoolean(stack.pop()))); break;
105 case NEWFUNCTION: stack.push(((JSFunction)arg)._cloneWithNewParentScope(scope)); break;
109 Object o = stack.pop();
110 if (o == null) stack.push(null);
111 else if (o instanceof JSString) stack.push(JS.S("string"));
112 else if (o instanceof JSNumber.B) stack.push(JS.S("boolean"));
113 else if (o instanceof JSNumber) stack.push(JS.S("number"));
114 else stack.push(JS.S("object"));
120 stack.push(o == null ? null : o.keys());
125 stack.push(new LoopMarker(pc, pc > 0 && f.op[pc - 1] == LABEL ? (String)f.arg[pc - 1] : (String)null, scope));
131 while(!stack.empty()) {
133 if (o instanceof CallMarker) je("break or continue not within a loop");
134 if (o instanceof TryMarker) {
135 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
136 stack.push(new FinallyData(op, arg));
137 scope = ((TryMarker)o).scope;
138 pc = ((TryMarker)o).finallyLoc - 1;
141 if (o instanceof LoopMarker) {
142 if (arg == null || arg.equals(((LoopMarker)o).label)) {
143 int loopInstructionLocation = ((LoopMarker)o).location;
144 int endOfLoop = JS.toInt((JS)f.arg[loopInstructionLocation]) + loopInstructionLocation;
145 scope = ((LoopMarker)o).scope;
146 if (op == CONTINUE) { stack.push(o); stack.push(JS.F); }
147 pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
152 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
153 getSourceName() + ":" + getLine());
156 int[] jmps = (int[]) arg;
157 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
158 // each can be < 0 if the specified block does not exist
159 stack.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1], this));
164 JS retval = stack.pop();
165 while(!stack.empty()) {
166 Object o = stack.pop();
167 if (o instanceof TryMarker) {
168 if(((TryMarker)o).finallyLoc < 0) continue;
170 stack.push(new FinallyData(RETURN));
171 scope = ((TryMarker)o).scope;
172 pc = ((TryMarker)o).finallyLoc - 1;
174 } else if (o instanceof CallMarker) {
175 boolean didTrapPut = false;
176 if (o instanceof TrapMarker) { // handles return component of a read trap
177 TrapMarker tm = (TrapMarker) o;
178 boolean cascade = tm.t.isWriteTrap() && !tm.cascadeHappened && !JS.toBoolean(retval);
180 Trap t = tm.t.nextWriteTrap();
181 if(t == null && tm.t.target instanceof JS.Clone) {
182 t = ((JS.Clone)tm.t.target).clonee.getTrap(tm.t.key);
183 if(t != null) t = t.writeTrap();
186 tm.t = t; // we reuse the old trap marker
187 setupTrap(t,tm.val,tm);
188 pc--; // we increment it on the next iter
192 if(!tm.pauseOnPut) tm.t.target.put(tm.t.key,tm.val);
196 CallMarker cm = (CallMarker) o;
201 if (((TrapMarker)cm).pauseOnPut) { pc++; return ((TrapMarker)cm).val; }
202 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
206 if (f == null) return retval;
210 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
214 JS val = stack.pop();
215 JS key = stack.pop();
216 JS target = stack.peek();
217 if (target == null) throw je("tried to put " + JS.debugToString(val) + " to the " + JS.debugToString(key) + " property on the null value");
218 if (key == null) throw je("tried to assign \"" + JS.debugToString(val) + "\" to the null key");
221 TrapMarker tm = null;
222 if(target instanceof JSScope && key.jsequals(CASCADE)) {
223 CallMarker o = stack.findCall();
224 if(o instanceof TrapMarker) {
226 target = tm.t.target;
228 tm.cascadeHappened = true;
230 if(t.isReadTrap()) throw new JSExn("can't do a write cascade in a read trap");
231 t = t.nextWriteTrap();
234 if(tm == null) { // not cascading
235 t = target instanceof JSScope ? t = ((JSScope)target).top().getTrap(key) : target.getTrap(key);
236 if(t != null) t = t.writeTrap();
238 if(t == null && target instanceof JS.Clone) {
239 target = ((JS.Clone)target).clonee;
240 t = target.getTrap(key);
241 if(t != null) t = t.writeTrap();
247 setupTrap(t,val,new TrapMarker(this,t,val, tm != null && tm.pauseOnPut));
248 pc--; // we increment later
251 if (tm != null && tm.pauseOnPut) { pc++; return val; }
253 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
262 key = arg == null ? stack.pop() : (JS)arg;
263 target = stack.pop();
266 target = stack.peek();
270 if (key == null) throw je("tried to get the null key from " + target);
271 if (target == null) throw je("tried to get property \"" + key + "\" from the null object");
274 TrapMarker tm = null;
275 if(target instanceof JSScope && key.jsequals(CASCADE)) {
276 CallMarker o = stack.findCall();
277 if(o instanceof TrapMarker) {
279 target = tm.t.target;
282 if(t.isWriteTrap()) throw new JSExn("can't do a read cascade in a write trap");
283 t = t.nextReadTrap();
286 if(tm == null) { // not cascading
287 t = target instanceof JSScope ? t = ((JSScope)target).top().getTrap(key) : ((JS)target).getTrap(key);
288 if(t != null) t = t.readTrap();
290 if(t == null && target instanceof JS.Clone) {
291 target = ((JS.Clone)target).clonee;
292 t = target.getTrap(key);
293 if(t != null) t = t.readTrap();
297 setupTrap(t,null,new TrapMarker(this,t,null));
298 pc--; // we increment later
301 ret = target.get(key);
302 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
303 if (ret == JS.METHOD) ret = new Stub(target, key);
309 case CALL: case CALLMETHOD: {
310 int numArgs = JS.toInt((JS)arg);
312 JS[] rest = numArgs > 3 ? new JS[numArgs - 3] : null;
313 for(int i=numArgs - 1; i>2; i--) rest[i-3] = stack.pop();
314 JS a2 = numArgs <= 2 ? null : stack.pop();
315 JS a1 = numArgs <= 1 ? null : stack.pop();
316 JS a0 = numArgs <= 0 ? null : stack.pop();
320 JS object = stack.pop();
322 if (op == CALLMETHOD) {
323 if (object == JS.METHOD) {
324 method = stack.pop();
325 object = stack.pop();
326 } else if (object == null) {
327 method = stack.pop();
328 object = stack.pop();
329 throw new JSExn("function '"+JS.debugToString(method)+"' not found in " + object.getClass().getName());
336 if (object instanceof JSFunction) {
337 stack.push(new CallMarker(this));
338 stack.push(new JSArgs(a0,a1,a2,rest,numArgs,object));
339 f = (JSFunction)object;
340 scope = new JSScope(f.parentScope);
345 ret = method == null ? c.call(a0, a1, a2, rest, numArgs) : c.callMethod(method, a0, a1, a2, rest, numArgs);
348 if (pausecount > initialPauseCount) { pc++; return null; }
354 throw new JSExn(stack.pop(), this);
358 final Grammar r = (Grammar)arg;
359 final JSScope final_scope = scope;
360 Grammar r2 = new Grammar() {
361 public int match(String s, int start, Hash v, JSScope scope) throws JSExn {
362 return r.match(s, start, v, final_scope);
364 public int matchAndWrite(String s, int start, Hash v, JSScope scope, String key) throws JSExn {
365 return r.matchAndWrite(s, start, v, final_scope, key);
367 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
369 r.matchAndWrite((String)a0, 0, v, final_scope, "foo");
373 Object obj = stack.pop();
374 if (obj != null && obj instanceof Grammar) r2 = new Grammar.Alternative((Grammar)obj, r2);
379 case ADD_TRAP: case DEL_TRAP: {
380 JS val = stack.pop();
381 JS key = stack.pop();
382 JS js = stack.peek();
383 // A trap addition/removal
384 if(!(val instanceof JSFunction)) throw new JSExn("tried to add/remove a non-function trap");
385 if(js instanceof JSScope) {
386 JSScope s = (JSScope) js;
387 while(s.getParentScope() != null) {
388 if(s.has(key)) throw new JSExn("cannot trap a variable that isn't at the top level scope");
389 s = s.getParentScope();
393 if(op == ADD_TRAP) js.addTrap(key, (JSFunction)val);
394 else js.delTrap(key, (JSFunction)val);
399 int count = ((JSNumber)arg).toInt();
400 if(count < 2) throw new Error("this should never happen");
403 JS right = stack.pop();
404 JS left = stack.pop();
406 if(left instanceof JSString || right instanceof JSString)
407 ret = JS.S(JS.toString(left).concat(JS.toString(right)));
408 else if(left instanceof JSNumber.D || right instanceof JSNumber.D)
409 ret = JS.N(JS.toDouble(left) + JS.toDouble(right));
411 long l = JS.toLong(left) + JS.toLong(right);
412 if(l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) ret = JS.N(l);
417 JS[] args = new JS[count];
418 while(--count >= 0) args[count] = stack.pop();
419 if(args[0] instanceof JSString) {
420 StringBuffer sb = new StringBuffer(64);
421 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
422 stack.push(JS.S(sb.toString()));
425 for(int i=0;i<args.length;i++) if(args[i] instanceof JSString) numStrings++;
426 if(numStrings == 0) {
428 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
432 StringBuffer sb = new StringBuffer(64);
433 if(!(args[0] instanceof JSString || args[1] instanceof JSString)) {
436 d += JS.toDouble(args[i++]);
437 } while(!(args[i] instanceof JSString));
438 sb.append(JS.toString(JS.N(d)));
440 while(i < args.length) sb.append(JS.toString(args[i++]));
441 stack.push(JS.S(sb.toString()));
449 JS right = stack.pop();
450 JS left = stack.pop();
453 case BITOR: stack.push(JS.N(JS.toLong(left) | JS.toLong(right))); break;
454 case BITXOR: stack.push(JS.N(JS.toLong(left) ^ JS.toLong(right))); break;
455 case BITAND: stack.push(JS.N(JS.toLong(left) & JS.toLong(right))); break;
457 case SUB: stack.push(JS.N(JS.toDouble(left) - JS.toDouble(right))); break;
458 case MUL: stack.push(JS.N(JS.toDouble(left) * JS.toDouble(right))); break;
459 case DIV: stack.push(JS.N(JS.toDouble(left) / JS.toDouble(right))); break;
460 case MOD: stack.push(JS.N(JS.toDouble(left) % JS.toDouble(right))); break;
462 case LSH: stack.push(JS.N(JS.toLong(left) << JS.toLong(right))); break;
463 case RSH: stack.push(JS.N(JS.toLong(left) >> JS.toLong(right))); break;
464 case URSH: stack.push(JS.N(JS.toLong(left) >>> JS.toLong(right))); break;
466 //#repeat </<=/>/>= LT/LE/GT/GE
468 if(left instanceof JSString && right instanceof JSString)
469 stack.push(JS.B(JS.toString(left).compareTo(JS.toString(right)) < 0));
471 stack.push(JS.B(JS.toDouble(left) < JS.toDouble(right)));
478 if(left == null && right == null) ret = true;
479 else if(left == null || right == null) ret = false;
480 else ret = left.jsequals(right);
481 stack.push(JS.B(op == EQ ? ret : !ret)); break;
484 default: throw new Error("unknown opcode " + op);
490 pc--; // it'll get incremented on the next iteration
495 /** tries to find a handler withing the call chain for this exception
496 if a handler is found the interpreter is setup to call the exception handler
497 if a handler is not found the exception is thrown
499 void catchException(JSExn e) throws JSExn {
500 while(!stack.empty()) {
502 if (o instanceof CatchMarker || o instanceof TryMarker) {
503 boolean inCatch = o instanceof CatchMarker;
506 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
508 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
509 // run the catch block, this will implicitly run the finally block, if it exists
511 stack.push(catchMarker);
512 stack.push(e.getObject());
513 f = ((TryMarker)o).f;
514 scope = ((TryMarker)o).scope;
515 pc = ((TryMarker)o).catchLoc;
518 stack.push(new FinallyData(e));
519 f = ((TryMarker)o).f;
520 scope = ((TryMarker)o).scope;
521 pc = ((TryMarker)o).finallyLoc;
529 void setupTrap(Trap t, JS val, CallMarker cm) throws JSExn {
531 stack.push(t.isWriteTrap() ? new JSArgs(val,t.f) : new JSArgs(t.f));
533 scope = new TrapScope(t.f.parentScope,t);
538 // Markers //////////////////////////////////////////////////////////////////////
540 static class Marker extends JS {
541 public JS get(JS key) throws JSExn { throw new Error("this should not be accessible from a script"); }
542 public void put(JS key, JS val) throws JSExn { throw new Error("this should not be accessible from a script"); }
543 public String coerceToString() { throw new Error("this should not be accessible from a script"); }
544 public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn { throw new Error("this should not be accessible from a script"); }
547 static class CallMarker extends Marker {
551 public CallMarker(Interpreter cx) {
552 pc = cx == null ? -1 : cx.pc + 1;
553 scope = cx == null ? null : cx.scope;
554 f = cx == null ? null : cx.f;
558 static class TrapMarker extends CallMarker {
561 boolean cascadeHappened;
562 final boolean pauseOnPut;
563 public TrapMarker(Interpreter cx, Trap t, JS val) { this(cx,t,val,false); }
564 public TrapMarker(Interpreter cx, Trap t, JS val, boolean pauseOnPut) {
568 this.pauseOnPut = pauseOnPut;
572 static class CatchMarker extends Marker { }
573 private static CatchMarker catchMarker = new CatchMarker();
575 static class LoopMarker extends Marker {
576 final public int location;
577 final public String label;
578 final public JSScope scope;
579 public LoopMarker(int location, String label, JSScope scope) {
580 this.location = location;
585 static class TryMarker extends Marker {
586 final public int catchLoc;
587 final public int finallyLoc;
588 final public JSScope scope;
589 final public JSFunction f;
590 public TryMarker(int catchLoc, int finallyLoc, Interpreter cx) {
591 this.catchLoc = catchLoc;
592 this.finallyLoc = finallyLoc;
593 this.scope = cx.scope;
597 static class FinallyData extends Marker {
599 final public Object arg;
600 final public JSExn exn;
601 public FinallyData(int op) { this(op,null); }
602 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; this.exn = null; }
603 public FinallyData(JSExn exn) { this.exn = exn; this.op = -1; this.arg = null; } // Just throw this exn
606 static class TrapScope extends JSScope {
608 public TrapScope(JSScope parent, Trap t) {
609 super(parent); this.t = t;
611 public JS get(JS key) throws JSExn {
613 case "trapee": return t.target;
614 case "callee": return t.f;
615 case "trapname": return t.key;
617 return super.get(key);
621 static class JSArgs extends JS {
625 private final JS[] rest;
626 private final int nargs;
627 private final JS callee;
629 public JSArgs(JS callee) { this(null,null,null,null,0,callee); }
630 public JSArgs(JS a0, JS callee) { this(a0,null,null,null,1,callee); }
631 public JSArgs(JS a0, JS a1, JS a2, JS[] rest, int nargs, JS callee) {
632 this.a0 = a0; this.a1 = a1; this.a2 = a2;
633 this.rest = rest; this.nargs = nargs;
634 this.callee = callee;
637 public JS get(JS key) throws JSExn {
639 int n = JS.toInt(key);
644 default: return n>= 0 && n < nargs ? rest[n-3] : null;
648 case "callee": return callee;
649 case "length": return JS.N(nargs);
651 return super.get(key);
655 static class Stub extends JS {
658 public Stub(JS obj, JS method) { this.obj = obj; this.method = method; }
659 public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
660 return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs);
665 private static final int MAX_STACK_SIZE = 512;
666 private JS[] stack = new JS[64];
669 boolean empty() { return sp == 0; }
670 void push(JS o) throws JSExn { if(sp == stack.length) grow(); stack[sp++] = o; }
671 JS peek() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[sp-1]; }
672 final JS pop() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[--sp]; }
673 void swap() throws JSExn {
674 if(sp < 2) throw new JSExn("stack overflow");
675 JS tmp = stack[sp-2];
676 stack[sp-2] = stack[sp-1];
679 CallMarker findCall() {
680 for(int i=sp-1;i>=0;i--) if(stack[i] instanceof CallMarker) return (CallMarker) stack[i];
683 void grow() throws JSExn {
684 if(stack.length >= MAX_STACK_SIZE) throw new JSExn("Stack overflow");
685 JS[] stack2 = new JS[stack.length * 2];
686 System.arraycopy(stack,0,stack2,0,stack.length);
689 void backtrace(JSExn e) {
690 for(int i=sp-1;i>=0;i--) {
691 if (stack[i] instanceof CallMarker) {
692 CallMarker cm = (CallMarker)stack[i];
693 if(cm.f == null) break;
694 String s = cm.f.sourceName + ":" + cm.f.line[cm.pc-1];
695 if(cm instanceof Interpreter.TrapMarker)
696 s += " (trap on " + JS.debugToString(((Interpreter.TrapMarker)cm).t.key) + ")";