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()); // the "root function returned" marker -- f==null
33 throw new Error("should never happen");
37 /** this is the only synchronization point we need in order to be threadsafe */
38 synchronized JS resume() throws JSExn {
39 if(f == null) throw new RuntimeException("function already finished");
40 Thread t = Thread.currentThread();
41 Interpreter old = (Interpreter)threadToInterpreter.get(t);
42 threadToInterpreter.put(t, this);
46 if (old == null) threadToInterpreter.remove(t);
47 else threadToInterpreter.put(t, old);
51 static int getLine() {
52 Interpreter c = Interpreter.current();
53 return c == null || c.f == null || c.pc < 0 || c.pc >= c.f.size ? -1 : c.f.line[c.pc];
56 static String getSourceName() {
57 Interpreter c = Interpreter.current();
58 return c == null || c.f == null ? null : c.f.sourceName;
61 private static JSExn je(String s) { return new JSExn(getSourceName() + ":" + getLine() + " " + s); }
63 private JS run() throws JSExn {
65 // if pausecount changes after a get/put/call, we know we've been paused
66 final int initialPauseCount = pausecount;
71 Object arg = f.arg[pc];
72 if(op == FINALLY_DONE) {
73 FinallyData fd = (FinallyData) stack.pop();
74 if(fd == null) continue OUTER; // NOP
75 if(fd.exn != null) throw fd.exn;
80 case LITERAL: stack.push((JS)arg); break;
81 case OBJECT: stack.push(new JS.O()); break;
82 case ARRAY: stack.push(new JSArray(JS.toInt((JS)arg))); break;
83 case DECLARE: scope.declare((JS)(arg==null ? stack.peek() : arg)); if(arg != null) stack.push((JS)arg); break;
84 case TOPSCOPE: stack.push(scope); break;
85 case JT: if (JS.toBoolean(stack.pop())) pc += JS.toInt((JS)arg) - 1; break;
86 case JF: if (!JS.toBoolean(stack.pop())) pc += JS.toInt((JS)arg) - 1; break;
87 case JMP: pc += JS.toInt((JS)arg) - 1; break;
88 case POP: stack.pop(); break;
89 case SWAP: stack.swap(); break;
90 case DUP: stack.push(stack.peek()); break;
91 case NEWSCOPE: scope = new JSScope(scope); break;
92 case OLDSCOPE: scope = scope.getParentScope(); break;
95 if (JS.checkAssertions && !JS.toBoolean(o))
96 throw je("ibex.assertion.failed");
99 case BITNOT: stack.push(JS.N(~JS.toLong(stack.pop()))); break;
100 case BANG: stack.push(JS.B(!JS.toBoolean(stack.pop()))); break;
101 case NEWFUNCTION: stack.push(((JSFunction)arg)._cloneWithNewParentScope(scope)); break;
105 Object o = stack.pop();
106 if (o == null) stack.push(null);
107 else if (o instanceof JSString) stack.push(JS.S("string"));
108 else if (o instanceof JSNumber.B) stack.push(JS.S("boolean"));
109 else if (o instanceof JSNumber) stack.push(JS.S("number"));
110 else stack.push(JS.S("object"));
116 stack.push(o == null ? null : o.keys());
121 stack.push(new LoopMarker(pc, pc > 0 && f.op[pc - 1] == LABEL ? (String)f.arg[pc - 1] : (String)null, scope));
127 while(!stack.empty()) {
129 if (o instanceof CallMarker) je("break or continue not within a loop");
130 if (o instanceof TryMarker) {
131 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
132 stack.push(new FinallyData(op, arg));
133 scope = ((TryMarker)o).scope;
134 pc = ((TryMarker)o).finallyLoc - 1;
137 if (o instanceof LoopMarker) {
138 if (arg == null || arg.equals(((LoopMarker)o).label)) {
139 int loopInstructionLocation = ((LoopMarker)o).location;
140 int endOfLoop = JS.toInt((JS)f.arg[loopInstructionLocation]) + loopInstructionLocation;
141 scope = ((LoopMarker)o).scope;
142 if (op == CONTINUE) { stack.push(o); stack.push(JS.F); }
143 pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
148 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
149 getSourceName() + ":" + getLine());
152 int[] jmps = (int[]) arg;
153 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
154 // each can be < 0 if the specified block does not exist
155 stack.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1], this));
160 JS retval = stack.pop();
161 while(!stack.empty()) {
162 Object o = stack.pop();
163 if (o instanceof TryMarker) {
164 if(((TryMarker)o).finallyLoc < 0) continue;
166 stack.push(new FinallyData(RETURN));
167 scope = ((TryMarker)o).scope;
168 pc = ((TryMarker)o).finallyLoc - 1;
170 } else if (o instanceof CallMarker) {
171 if (o instanceof TrapMarker) { // handles return component of a read trap
172 TrapMarker tm = (TrapMarker) o;
173 boolean cascade = tm.t.writeTrap() && !tm.cascadeHappened && !JS.toBoolean(retval);
176 while(t != null && t.readTrap()) t = t.next;
180 stack.push(new JSArgs(tm.val,t.f));
182 scope = new JSScope(f.parentScope);
186 tm.trapee.put(tm.key,tm.val);
190 scope = ((CallMarker)o).scope;
191 pc = ((CallMarker)o).pc - 1;
192 f = (JSFunction)((CallMarker)o).f;
194 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
195 if(f == null) return retval;
199 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
203 JS val = stack.pop();
204 JS key = stack.pop();
205 JS target = stack.peek();
206 if (target == null) throw je("tried to put " + JS.debugToString(val) + " to the " + JS.debugToString(key) + " property on the null value");
207 if (key == null) throw je("tried to assign \"" + JS.debugToString(val) + "\" to the null key");
210 TrapMarker tm = null;
211 if(target instanceof JSScope && key.jsequals(CASCADE)) {
212 CallMarker o = stack.findCall();
213 if(o instanceof TrapMarker) {
217 tm.cascadeHappened = true;
219 if(t.readTrap()) throw new JSExn("can't do a write cascade in a read trap");
221 while(t != null && t.readTrap()) t = t.next;
224 if(tm == null) { // didn't find a trap marker, try to find a trap
225 t = target instanceof JSScope ? t = ((JSScope)target).top().getTrap(key) : ((JS)target).getTrap(key);
226 while(t != null && t.readTrap()) t = t.next;
232 stack.push(new TrapMarker(this,t,target,key,val));
233 stack.push(new JSArgs(val,t.f));
235 scope = new TrapScope(f.parentScope,target,f,key);
240 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
249 key = arg == null ? stack.pop() : (JS)arg;
250 target = stack.pop();
253 target = stack.peek();
257 if (key == null) throw je("tried to get the null key from " + target);
258 if (target == null) throw je("tried to get property \"" + key + "\" from the null object");
261 TrapMarker tm = null;
262 if(target instanceof JSScope && key.jsequals(CASCADE)) {
263 CallMarker o = stack.findCall();
264 if(o instanceof TrapMarker) {
269 if(t.writeTrap()) throw new JSExn("can't do a read cascade in a write trap");
271 while(t != null && t.writeTrap()) t = t.next;
272 if(t != null) tm.cascadeHappened = true;
275 if(tm == null) { // didn't find a trap marker, try to find a trap
276 t = target instanceof JSScope ? t = ((JSScope)target).top().getTrap(key) : ((JS)target).getTrap(key);
277 while(t != null && t.writeTrap()) t = t.next;
281 stack.push(new TrapMarker(this,t,(JS)target,key,null));
282 stack.push(new JSArgs(t.f));
284 scope = new TrapScope(f.parentScope,target,f,key);
288 ret = target.get(key);
289 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
290 if (ret == JS.METHOD) ret = new Stub(target, key);
296 case CALL: case CALLMETHOD: {
297 int numArgs = JS.toInt((JS)arg);
299 JS[] rest = numArgs > 3 ? new JS[numArgs - 3] : null;
300 for(int i=numArgs - 1; i>2; i--) rest[i-3] = stack.pop();
301 JS a2 = numArgs <= 2 ? null : stack.pop();
302 JS a1 = numArgs <= 1 ? null : stack.pop();
303 JS a0 = numArgs <= 0 ? null : stack.pop();
307 JS object = stack.pop();
309 if (op == CALLMETHOD) {
310 if (object == JS.METHOD) {
311 method = stack.pop();
312 object = stack.pop();
313 } else if (object == null) {
314 method = stack.pop();
315 object = stack.pop();
316 throw new JSExn("function '"+JS.debugToString(method)+"' not found in " + object.getClass().getName());
323 if (object instanceof JSFunction) {
324 stack.push(new CallMarker(this));
325 stack.push(new JSArgs(a0,a1,a2,rest,numArgs,object));
326 f = (JSFunction)object;
327 scope = new JSScope(f.parentScope);
332 ret = method == null ? c.call(a0, a1, a2, rest, numArgs) : c.callMethod(method, a0, a1, a2, rest, numArgs);
335 if (pausecount > initialPauseCount) { pc++; return null; }
341 throw new JSExn(stack.pop(), this);
345 final Grammar r = (Grammar)arg;
346 final JSScope final_scope = scope;
347 Grammar r2 = new Grammar() {
348 public int match(String s, int start, Hash v, JSScope scope) throws JSExn {
349 return r.match(s, start, v, final_scope);
351 public int matchAndWrite(String s, int start, Hash v, JSScope scope, String key) throws JSExn {
352 return r.matchAndWrite(s, start, v, final_scope, key);
354 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
356 r.matchAndWrite((String)a0, 0, v, final_scope, "foo");
360 Object obj = stack.pop();
361 if (obj != null && obj instanceof Grammar) r2 = new Grammar.Alternative((Grammar)obj, r2);
366 case ADD_TRAP: case DEL_TRAP: {
367 JS val = stack.pop();
368 JS key = stack.pop();
369 JS js = stack.peek();
370 // A trap addition/removal
371 if(!(val instanceof JSFunction)) throw new JSExn("tried to add/remove a non-function trap");
372 if(js instanceof JSScope) {
373 JSScope s = (JSScope) js;
374 while(s.getParentScope() != null) {
375 if(s.has(key)) throw new JSExn("cannot trap a variable that isn't at the top level scope");
376 s = s.getParentScope();
380 if(op == ADD_TRAP) js.addTrap(key, (JSFunction)val);
381 else js.delTrap(key, (JSFunction)val);
386 int count = ((JSNumber)arg).toInt();
387 if(count < 2) throw new Error("this should never happen");
390 JS right = stack.pop();
391 JS left = stack.pop();
393 if(left instanceof JSString || right instanceof JSString)
394 ret = JS.S(JS.toString(left).concat(JS.toString(right)));
395 else if(left instanceof JSNumber.D || right instanceof JSNumber.D)
396 ret = JS.N(JS.toDouble(left) + JS.toDouble(right));
398 long l = JS.toLong(left) + JS.toLong(right);
399 if(l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) ret = JS.N(l);
404 JS[] args = new JS[count];
405 while(--count >= 0) args[count] = stack.pop();
406 if(args[0] instanceof JSString) {
407 StringBuffer sb = new StringBuffer(64);
408 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
409 stack.push(JS.S(sb.toString()));
412 for(int i=0;i<args.length;i++) if(args[i] instanceof JSString) numStrings++;
413 if(numStrings == 0) {
415 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
419 StringBuffer sb = new StringBuffer(64);
420 if(!(args[0] instanceof JSString || args[1] instanceof JSString)) {
423 d += JS.toDouble(args[i++]);
424 } while(!(args[i] instanceof JSString));
425 sb.append(JS.toString(JS.N(d)));
427 while(i < args.length) sb.append(JS.toString(args[i++]));
428 stack.push(JS.S(sb.toString()));
436 JS right = stack.pop();
437 JS left = stack.pop();
440 case BITOR: stack.push(JS.N(JS.toLong(left) | JS.toLong(right))); break;
441 case BITXOR: stack.push(JS.N(JS.toLong(left) ^ JS.toLong(right))); break;
442 case BITAND: stack.push(JS.N(JS.toLong(left) & JS.toLong(right))); break;
444 case SUB: stack.push(JS.N(JS.toDouble(left) - JS.toDouble(right))); break;
445 case MUL: stack.push(JS.N(JS.toDouble(left) * JS.toDouble(right))); break;
446 case DIV: stack.push(JS.N(JS.toDouble(left) / JS.toDouble(right))); break;
447 case MOD: stack.push(JS.N(JS.toDouble(left) % JS.toDouble(right))); break;
449 case LSH: stack.push(JS.N(JS.toLong(left) << JS.toLong(right))); break;
450 case RSH: stack.push(JS.N(JS.toLong(left) >> JS.toLong(right))); break;
451 case URSH: stack.push(JS.N(JS.toLong(left) >>> JS.toLong(right))); break;
453 //#repeat </<=/>/>= LT/LE/GT/GE
455 if(left instanceof JSString && right instanceof JSString)
456 stack.push(JS.B(JS.toString(left).compareTo(JS.toString(right)) < 0));
458 stack.push(JS.B(JS.toDouble(left) < JS.toDouble(right)));
465 if(left == null && right == null) ret = true;
466 else if(left == null || right == null) ret = false;
467 else ret = left.jsequals(right);
468 stack.push(JS.B(op == EQ ? ret : !ret)); break;
471 default: throw new Error("unknown opcode " + op);
477 pc--; // it'll get incremented on the next iteration
482 /** tries to find a handler withing the call chain for this exception
483 if a handler is found the interpreter is setup to call the exception handler
484 if a handler is not found the exception is thrown
486 void catchException(JSExn e) throws JSExn {
487 while(!stack.empty()) {
489 if (o instanceof CatchMarker || o instanceof TryMarker) {
490 boolean inCatch = o instanceof CatchMarker;
493 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
495 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
496 // run the catch block, this will implicitly run the finally block, if it exists
498 stack.push(catchMarker);
499 stack.push(e.getObject());
500 f = ((TryMarker)o).f;
501 scope = ((TryMarker)o).scope;
502 pc = ((TryMarker)o).catchLoc;
505 stack.push(new FinallyData(e));
506 f = ((TryMarker)o).f;
507 scope = ((TryMarker)o).scope;
508 pc = ((TryMarker)o).finallyLoc;
518 // Markers //////////////////////////////////////////////////////////////////////
520 static class Marker extends JS {
521 public JS get(JS key) throws JSExn { throw new Error("this should not be accessible from a script"); }
522 public void put(JS key, JS val) throws JSExn { throw new Error("this should not be accessible from a script"); }
523 public String coerceToString() { throw new Error("this should not be accessible from a script"); }
524 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"); }
527 static class CallMarker extends Marker {
531 public CallMarker(Interpreter cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
532 public CallMarker() { pc = -1; scope = null; f = null; }
535 static class TrapMarker extends CallMarker {
540 boolean cascadeHappened;
541 public TrapMarker(Interpreter cx, Trap t, JS trapee, JS key, JS val) {
544 this.trapee = trapee;
550 static class CatchMarker extends Marker { }
551 private static CatchMarker catchMarker = new CatchMarker();
553 static class LoopMarker extends Marker {
554 final public int location;
555 final public String label;
556 final public JSScope scope;
557 public LoopMarker(int location, String label, JSScope scope) {
558 this.location = location;
563 static class TryMarker extends Marker {
564 final public int catchLoc;
565 final public int finallyLoc;
566 final public JSScope scope;
567 final public JSFunction f;
568 public TryMarker(int catchLoc, int finallyLoc, Interpreter cx) {
569 this.catchLoc = catchLoc;
570 this.finallyLoc = finallyLoc;
571 this.scope = cx.scope;
575 static class FinallyData extends Marker {
577 final public Object arg;
578 final public JSExn exn;
579 public FinallyData(int op) { this(op,null); }
580 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; this.exn = null; }
581 public FinallyData(JSExn exn) { this.exn = exn; this.op = -1; this.arg = null; } // Just throw this exn
584 static class TrapScope extends JSScope {
588 public TrapScope(JSScope parent, JS trapee, JS callee, JS trapname) {
589 super(parent); this.trapee = trapee; this.callee = callee; this.trapname = trapname;
591 public JS get(JS key) throws JSExn {
592 if(JS.isString(key)) {
593 //#switch(JS.toString(key))
594 case "trapee": return trapee;
595 case "callee": return callee;
596 case "trapname": return trapname;
599 return super.get(key);
603 static class JSArgs extends JS {
607 private final JS[] rest;
608 private final int nargs;
609 private final JS callee;
611 public JSArgs(JS callee) { this(null,null,null,null,0,callee); }
612 public JSArgs(JS a0, JS callee) { this(a0,null,null,null,1,callee); }
613 public JSArgs(JS a0, JS a1, JS a2, JS[] rest, int nargs, JS callee) {
614 this.a0 = a0; this.a1 = a1; this.a2 = a2;
615 this.rest = rest; this.nargs = nargs;
616 this.callee = callee;
619 public JS get(JS key) throws JSExn {
621 int n = JS.toInt(key);
626 default: return n>= 0 && n < nargs ? rest[n-3] : null;
629 //#switch(JS.toString(key))
630 case "callee": return callee;
631 case "length": return JS.N(nargs);
633 return super.get(key);
637 static class Stub extends JS {
640 public Stub(JS obj, JS method) { this.obj = obj; this.method = method; }
641 public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
642 return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs);
647 private static final int MAX_STACK_SIZE = 512;
648 private JS[] stack = new JS[64];
651 boolean empty() { return sp == 0; }
652 void push(JS o) throws JSExn { if(sp == stack.length) grow(); stack[sp++] = o; }
653 JS peek() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[sp-1]; }
654 final JS pop() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[--sp]; }
655 void swap() throws JSExn {
656 if(sp < 2) throw new JSExn("stack overflow");
657 JS tmp = stack[sp-2];
658 stack[sp-2] = stack[sp-1];
661 CallMarker findCall() {
662 for(int i=sp-1;i>=0;i--) if(stack[i] instanceof CallMarker) return (CallMarker) stack[i];
665 void grow() throws JSExn {
666 if(stack.length >= MAX_STACK_SIZE) throw new JSExn("Stack overflow");
667 JS[] stack2 = new JS[stack.length * 2];
668 System.arraycopy(stack,0,stack2,0,stack.length);
671 void backtrace(JSExn e) {
672 for(int i=sp-1;i>=0;i--) {
673 if (stack[i] instanceof CallMarker) {
674 CallMarker cm = (CallMarker)stack[i];
675 if(cm.f == null) break;
676 String s = cm.f.sourceName + ":" + cm.f.line[cm.pc-1];
677 if(cm instanceof Interpreter.TrapMarker)
678 s += " (trap on " + JS.debugToString(((Interpreter.TrapMarker)cm).key) + ")";