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 // Thread-Interpreter Mapping /////////////////////////////////////////////////////////////////////////
11 static Interpreter current() { return (Interpreter)threadToInterpreter.get(Thread.currentThread()); }
12 private static Hashtable threadToInterpreter = new Hashtable();
15 // Instance members and methods //////////////////////////////////////////////////////////////////////
17 int pausecount; ///< the number of times pause() has been invoked; -1 indicates unpauseable
18 JSFunction f = null; ///< the currently-executing JSFunction
19 JSScope scope; ///< the current top-level scope (LIFO stack via NEWSCOPE/OLDSCOPE)
20 final Stack stack = new Stack(); ///< the object stack
21 int pc = 0; ///< the program counter
23 Interpreter(JSFunction f, boolean pauseable, JSArgs args) {
25 this.pausecount = pauseable ? 0 : -1;
26 this.scope = f.parentScope;
28 stack.push(new CallMarker(null)); // the "root function returned" marker -- f==null
31 throw new Error("should never happen");
35 Interpreter(Trap t, JS val, boolean pauseOnPut) {
38 setupTrap(t,val,new TrapMarker(null,t,val,pauseOnPut));
40 throw new Error("should never happen");
44 /** this is the only synchronization point we need in order to be threadsafe */
45 synchronized JS resume() throws JSExn {
46 if(f == null) throw new RuntimeException("function already finished");
47 if(scope == null) throw new RuntimeException("scope is null");
48 Thread t = Thread.currentThread();
49 Interpreter old = (Interpreter)threadToInterpreter.get(t);
50 threadToInterpreter.put(t, this);
54 if (old == null) threadToInterpreter.remove(t);
55 else threadToInterpreter.put(t, old);
59 static int getLine() {
60 Interpreter c = Interpreter.current();
61 return c == null || c.f == null || c.pc < 0 || c.pc >= c.f.size ? -1 : c.f.line[c.pc];
64 static String getSourceName() {
65 Interpreter c = Interpreter.current();
66 return c == null || c.f == null ? null : c.f.sourceName;
69 private static JSExn je(String s) { return new JSExn(getSourceName() + ":" + getLine() + " " + s); }
71 private JS run() throws JSExn {
73 // if pausecount changes after a get/put/call, we know we've been paused
74 final int initialPauseCount = pausecount;
79 Object arg = f.arg[pc];
80 if(op == FINALLY_DONE) {
81 FinallyData fd = (FinallyData) stack.pop();
82 if(fd == null) continue OUTER; // NOP
83 if(fd.exn != null) throw fd.exn;
88 case LITERAL: stack.push((JS)arg); break;
89 case OBJECT: stack.push(new JS.O()); break;
90 case ARRAY: stack.push(new JSArray(JS.toInt((JS)arg))); break;
91 //case DECLARE: scope.declare((JS)(arg==null ? stack.peek() : arg)); if(arg != null) stack.push((JS)arg); break;
92 case JT: if (JS.toBoolean(stack.pop())) pc += JS.toInt((JS)arg) - 1; break;
93 case JF: if (!JS.toBoolean(stack.pop())) pc += JS.toInt((JS)arg) - 1; break;
94 case JMP: pc += JS.toInt((JS)arg) - 1; break;
95 case POP: stack.pop(); break;
96 case SWAP: stack.swap(); break;
97 case DUP: stack.push(stack.peek()); break;
99 int n = JS.toInt((JS)arg);
100 scope = new JSScope(scope,(n>>>16)&0xffff,(n>>>0)&0xffff);
103 case OLDSCOPE: scope = scope.parent; break;
104 case GLOBALSCOPE: stack.push(scope.getGlobal()); break;
105 case SCOPEGET: stack.push(scope.get((JS)arg)); break;
106 case SCOPEPUT: scope.put((JS)arg,stack.peek()); break;
107 case ASSERT: if (!JS.toBoolean(stack.pop())) throw je("ibex.assertion.failed"); break;
108 case BITNOT: stack.push(JS.N(~JS.toLong(stack.pop()))); break;
109 case BANG: stack.push(JS.B(!JS.toBoolean(stack.pop()))); break;
110 case NEWFUNCTION: stack.push(((JSFunction)arg)._cloneWithNewParentScope(scope)); break;
114 Object o = stack.pop();
115 if (o == null) stack.push(null);
116 else if (o instanceof JSString) stack.push(JS.S("string"));
117 else if (o instanceof JSNumber.B) stack.push(JS.S("boolean"));
118 else if (o instanceof JSNumber) stack.push(JS.S("number"));
119 else stack.push(JS.S("object"));
125 stack.push(o == null ? null : o.keys());
130 stack.push(new LoopMarker(pc, pc > 0 && f.op[pc - 1] == LABEL ? (String)f.arg[pc - 1] : (String)null, scope));
136 while(!stack.empty()) {
138 if (o instanceof CallMarker) je("break or continue not within a loop");
139 if (o instanceof TryMarker) {
140 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
141 stack.push(new FinallyData(op, arg));
142 scope = ((TryMarker)o).scope;
143 pc = ((TryMarker)o).finallyLoc - 1;
146 if (o instanceof LoopMarker) {
147 if (arg == null || arg.equals(((LoopMarker)o).label)) {
148 int loopInstructionLocation = ((LoopMarker)o).location;
149 int endOfLoop = JS.toInt((JS)f.arg[loopInstructionLocation]) + loopInstructionLocation;
150 scope = ((LoopMarker)o).scope;
151 if (op == CONTINUE) { stack.push(o); stack.push(JS.F); }
152 pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
157 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
158 getSourceName() + ":" + getLine());
161 int[] jmps = (int[]) arg;
162 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
163 // each can be < 0 if the specified block does not exist
164 stack.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1], this));
169 JS retval = stack.pop();
170 while(!stack.empty()) {
171 Object o = stack.pop();
172 if (o instanceof TryMarker) {
173 if(((TryMarker)o).finallyLoc < 0) continue;
175 stack.push(new FinallyData(RETURN));
176 scope = ((TryMarker)o).scope;
177 pc = ((TryMarker)o).finallyLoc - 1;
179 } else if (o instanceof CallMarker) {
180 boolean didTrapPut = false;
181 if (o instanceof TrapMarker) { // handles return component of a write trap
182 TrapMarker tm = (TrapMarker) o;
183 boolean cascade = tm.t.isWriteTrap() && !tm.cascadeHappened && !JS.toBoolean(retval);
185 Trap t = tm.t.nextWriteTrap();
186 if(t == null && tm.t.target instanceof JS.Clone) {
187 t = ((JS.Clone)tm.t.target).clonee.getTrap(tm.t.key);
188 if(t != null) t = t.writeTrap();
191 tm.t = t; // we reuse the old trap marker
192 setupTrap(t,tm.val,tm);
193 pc--; // we increment it on the next iter
197 if(!tm.pauseOnPut) tm.t.target.put(tm.t.key,tm.val);
201 CallMarker cm = (CallMarker) o;
206 if (((TrapMarker)cm).pauseOnPut) { pc++; return ((TrapMarker)cm).val; }
207 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
211 if (f == null) return retval;
215 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
219 boolean write = JS.toBoolean((JS)arg);
220 JS val = write ? stack.pop() : null;
221 CallMarker o = stack.findCall();
222 if(!(o instanceof TrapMarker)) throw new JSExn("tried to CASCADE while not in a trap");
223 TrapMarker tm = (TrapMarker) o;
225 JS target = tm.t.target;
226 if(tm.t.isWriteTrap() != write) throw new JSExn("tried to do a " + (write?"write":"read") + " cascade in a " + (write?"read":"write") + " trap");
227 Trap t = write ? tm.t.nextWriteTrap() : tm.t.nextReadTrap();
228 // FIXME: Doesn't handle multiple levels of clone's (probably can just make this a while loop)
229 if(t == null && target instanceof JS.Clone) {
230 target = ((JS.Clone)target).clonee;
231 t = target.getTrap(key);
232 if(t != null) t = write ? t.writeTrap() : t.readTrap();
235 tm.cascadeHappened = true;
239 setupTrap(t,val,new TrapMarker(this,t,val,tm.pauseOnPut));
240 pc--; // we increment later
243 if (tm.pauseOnPut) { pc++; return val; }
246 JS ret = target.get(key);
247 if (ret == JS.METHOD) ret = new Stub(target, key);
250 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
256 JS val = stack.pop();
257 JS key = stack.pop();
258 JS target = stack.peek();
259 if (target == null) throw je("tried to put " + JS.debugToString(val) + " to the " + JS.debugToString(key) + " property on the null value");
260 if (key == null) throw je("tried to assign \"" + JS.debugToString(val) + "\" to the null key");
262 Trap t = target.getTrap(key);
263 if(t != null) t = t.writeTrap();
265 if(t == null && target instanceof JS.Clone) {
266 target = ((JS.Clone)target).clonee;
267 t = target.getTrap(key);
268 if(t != null) t = t.writeTrap();
274 setupTrap(t,val,new TrapMarker(this,t,val));
275 pc--; // we increment later
278 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
287 key = arg == null ? stack.pop() : (JS)arg;
288 target = stack.pop();
291 target = stack.peek();
295 if (key == null) throw je("tried to get the null key from " + JS.debugToString(target));
296 if (target == null) throw je("tried to get property \"" + JS.debugToString(key) + "\" from the null object");
298 Trap t = target.getTrap(key);
299 if(t != null) t = t.readTrap();
301 if(t == null && target instanceof JS.Clone) {
302 target = ((JS.Clone)target).clonee;
303 t = target.getTrap(key);
304 if(t != null) t = t.readTrap();
308 setupTrap(t,null,new TrapMarker(this,t,null));
309 pc--; // we increment later
311 ret = target.get(key);
312 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
313 if (ret == JS.METHOD) ret = new Stub(target, key);
319 case CALL: case CALLMETHOD: {
320 int numArgs = JS.toInt((JS)arg);
322 JS[] rest = numArgs > 3 ? new JS[numArgs - 3] : null;
323 for(int i=numArgs - 1; i>2; i--) rest[i-3] = stack.pop();
324 JS a2 = numArgs <= 2 ? null : stack.pop();
325 JS a1 = numArgs <= 1 ? null : stack.pop();
326 JS a0 = numArgs <= 0 ? null : stack.pop();
330 JS object = stack.pop();
332 if (op == CALLMETHOD) {
333 if (object == JS.METHOD) {
334 method = stack.pop();
335 object = stack.pop();
336 } else if (object == null) {
337 method = stack.pop();
338 object = stack.pop();
339 throw new JSExn("function '"+JS.debugToString(method)+"' not found in " + object.getClass().getName());
346 if (object instanceof JSFunction) {
347 stack.push(new CallMarker(this));
348 stack.push(new JSArgs(a0,a1,a2,rest,numArgs,object));
349 f = (JSFunction)object;
350 scope = f.parentScope;
355 ret = method == null ? c.call(a0, a1, a2, rest, numArgs) : c.callMethod(method, a0, a1, a2, rest, numArgs);
358 if (pausecount > initialPauseCount) { pc++; return null; }
364 throw new JSExn(stack.pop(), this);
368 final Grammar r = (Grammar)arg;
369 final JSScope final_scope = scope;
370 Grammar r2 = new Grammar() {
371 public int match(String s, int start, Hash v, JSScope scope) throws JSExn {
372 return r.match(s, start, v, final_scope);
374 public int matchAndWrite(String s, int start, Hash v, JSScope scope, String key) throws JSExn {
375 return r.matchAndWrite(s, start, v, final_scope, key);
377 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
379 r.matchAndWrite((String)a0, 0, v, final_scope, "foo");
383 Object obj = stack.pop();
384 if (obj != null && obj instanceof Grammar) r2 = new Grammar.Alternative((Grammar)obj, r2);
389 case ADD_TRAP: case DEL_TRAP: {
390 JS val = stack.pop();
391 JS key = stack.pop();
392 JS js = stack.peek();
393 // A trap addition/removal
394 if(!(val instanceof JSFunction)) throw new JSExn("tried to add/remove a non-function trap");
395 if(op == ADD_TRAP) js.addTrap(key, (JSFunction)val);
396 else js.delTrap(key, (JSFunction)val);
401 int count = ((JSNumber)arg).toInt();
402 if(count < 2) throw new Error("this should never happen");
405 JS right = stack.pop();
406 JS left = stack.pop();
408 if(left instanceof JSString || right instanceof JSString)
409 ret = JS.S(JS.toString(left).concat(JS.toString(right)));
410 else if(left instanceof JSNumber.D || right instanceof JSNumber.D)
411 ret = JS.N(JS.toDouble(left) + JS.toDouble(right));
413 long l = JS.toLong(left) + JS.toLong(right);
414 if(l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) ret = JS.N(l);
419 JS[] args = new JS[count];
420 while(--count >= 0) args[count] = stack.pop();
421 if(args[0] instanceof JSString) {
422 StringBuffer sb = new StringBuffer(64);
423 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
424 stack.push(JS.S(sb.toString()));
427 for(int i=0;i<args.length;i++) if(args[i] instanceof JSString) numStrings++;
428 if(numStrings == 0) {
430 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
434 StringBuffer sb = new StringBuffer(64);
435 if(!(args[0] instanceof JSString || args[1] instanceof JSString)) {
438 d += JS.toDouble(args[i++]);
439 } while(!(args[i] instanceof JSString));
440 sb.append(JS.toString(JS.N(d)));
442 while(i < args.length) sb.append(JS.toString(args[i++]));
443 stack.push(JS.S(sb.toString()));
451 JS right = stack.pop();
452 JS left = stack.pop();
455 case BITOR: stack.push(JS.N(JS.toLong(left) | JS.toLong(right))); break;
456 case BITXOR: stack.push(JS.N(JS.toLong(left) ^ JS.toLong(right))); break;
457 case BITAND: stack.push(JS.N(JS.toLong(left) & JS.toLong(right))); break;
459 case SUB: stack.push(JS.N(JS.toDouble(left) - JS.toDouble(right))); break;
460 case MUL: stack.push(JS.N(JS.toDouble(left) * JS.toDouble(right))); break;
461 case DIV: stack.push(JS.N(JS.toDouble(left) / JS.toDouble(right))); break;
462 case MOD: stack.push(JS.N(JS.toDouble(left) % JS.toDouble(right))); break;
464 case LSH: stack.push(JS.N(JS.toLong(left) << JS.toLong(right))); break;
465 case RSH: stack.push(JS.N(JS.toLong(left) >> JS.toLong(right))); break;
466 case URSH: stack.push(JS.N(JS.toLong(left) >>> JS.toLong(right))); break;
468 //#repeat </<=/>/>= LT/LE/GT/GE
470 if(left instanceof JSString && right instanceof JSString)
471 stack.push(JS.B(JS.toString(left).compareTo(JS.toString(right)) < 0));
473 stack.push(JS.B(JS.toDouble(left) < JS.toDouble(right)));
480 if(left == null && right == null) ret = true;
481 else if(left == null || right == null) ret = false;
482 else ret = left.jsequals(right);
483 stack.push(JS.B(op == EQ ? ret : !ret)); break;
486 default: throw new Error("unknown opcode " + op);
492 pc--; // it'll get incremented on the next iteration
497 /** tries to find a handler withing the call chain for this exception
498 if a handler is found the interpreter is setup to call the exception handler
499 if a handler is not found the exception is thrown
501 void catchException(JSExn e) throws JSExn {
502 while(!stack.empty()) {
504 if (o instanceof CatchMarker || o instanceof TryMarker) {
505 boolean inCatch = o instanceof CatchMarker;
508 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
510 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
511 // run the catch block, this will implicitly run the finally block, if it exists
513 stack.push(catchMarker);
514 stack.push(e.getObject());
515 f = ((TryMarker)o).f;
516 scope = ((TryMarker)o).scope;
517 pc = ((TryMarker)o).catchLoc;
520 stack.push(new FinallyData(e));
521 f = ((TryMarker)o).f;
522 scope = ((TryMarker)o).scope;
523 pc = ((TryMarker)o).finallyLoc;
531 void setupTrap(Trap t, JS val, CallMarker cm) throws JSExn {
533 stack.push(new TrapArgs(t,val));
535 scope = f.parentScope;
540 // Markers //////////////////////////////////////////////////////////////////////
542 static class Marker extends JS {
543 public JS get(JS key) throws JSExn { throw new Error("this should not be accessible from a script"); }
544 public void put(JS key, JS val) throws JSExn { throw new Error("this should not be accessible from a script"); }
545 public String coerceToString() { throw new Error("this should not be accessible from a script"); }
546 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"); }
549 static class CallMarker extends Marker {
553 public CallMarker(Interpreter cx) {
554 pc = cx == null ? -1 : cx.pc + 1;
555 scope = cx == null ? null : cx.scope;
556 f = cx == null ? null : cx.f;
560 static class TrapMarker extends CallMarker {
563 boolean cascadeHappened;
564 final boolean pauseOnPut;
565 public TrapMarker(Interpreter cx, Trap t, JS val) { this(cx,t,val,false); }
566 public TrapMarker(Interpreter cx, Trap t, JS val, boolean pauseOnPut) {
570 this.pauseOnPut = pauseOnPut;
574 static class CatchMarker extends Marker { }
575 private static CatchMarker catchMarker = new CatchMarker();
577 static class LoopMarker extends Marker {
578 final public int location;
579 final public String label;
580 final public JSScope scope;
581 public LoopMarker(int location, String label, JSScope scope) {
582 this.location = location;
587 static class TryMarker extends Marker {
588 final public int catchLoc;
589 final public int finallyLoc;
590 final public JSScope scope;
591 final public JSFunction f;
592 public TryMarker(int catchLoc, int finallyLoc, Interpreter cx) {
593 this.catchLoc = catchLoc;
594 this.finallyLoc = finallyLoc;
595 this.scope = cx.scope;
599 static class FinallyData extends Marker {
601 final public Object arg;
602 final public JSExn exn;
603 public FinallyData(int op) { this(op,null); }
604 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; this.exn = null; }
605 public FinallyData(JSExn exn) { this.exn = exn; this.op = -1; this.arg = null; } // Just throw this exn
608 static class TrapArgs extends JS {
611 public TrapArgs(Trap t, JS val) { this.t = t; this.val = val; }
612 public JS get(JS key) throws JSExn {
613 if(JS.isInt(key) && JS.toInt(key) == 0) return val;
614 //#switch(JS.toString(key))
615 case "trapee": return t.target;
616 case "callee": return t.f;
617 case "trapname": return t.key;
618 case "length": return t.isWriteTrap() ? ONE : ZERO;
620 return super.get(key);
624 static class JSArgs extends JS {
628 private final JS[] rest;
629 private final int nargs;
630 private final JS callee;
632 public JSArgs(JS callee) { this(null,null,null,null,0,callee); }
633 public JSArgs(JS a0, JS callee) { this(a0,null,null,null,1,callee); }
634 public JSArgs(JS a0, JS a1, JS a2, JS[] rest, int nargs, JS callee) {
635 this.a0 = a0; this.a1 = a1; this.a2 = a2;
636 this.rest = rest; this.nargs = nargs;
637 this.callee = callee;
640 public JS get(JS key) throws JSExn {
642 int n = JS.toInt(key);
647 default: return n>= 0 && n < nargs ? rest[n-3] : null;
650 //#switch(JS.toString(key))
651 case "callee": return callee;
652 case "length": return JS.N(nargs);
654 return super.get(key);
658 static class Stub extends JS {
661 public Stub(JS obj, JS method) { this.obj = obj; this.method = method; }
662 public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
663 return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs);
668 private static final int MAX_STACK_SIZE = 512;
669 private JS[] stack = new JS[64];
672 boolean empty() { return sp == 0; }
673 void push(JS o) throws JSExn { if(sp == stack.length) grow(); stack[sp++] = o; }
674 JS peek() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[sp-1]; }
675 final JS pop() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[--sp]; }
676 void swap() throws JSExn {
677 if(sp < 2) throw new JSExn("stack overflow");
678 JS tmp = stack[sp-2];
679 stack[sp-2] = stack[sp-1];
682 CallMarker findCall() {
683 for(int i=sp-1;i>=0;i--) if(stack[i] instanceof CallMarker) return (CallMarker) stack[i];
686 void grow() throws JSExn {
687 if(stack.length >= MAX_STACK_SIZE) throw new JSExn("Stack overflow");
688 JS[] stack2 = new JS[stack.length * 2];
689 System.arraycopy(stack,0,stack2,0,stack.length);
692 void backtrace(JSExn e) {
693 for(int i=sp-1;i>=0;i--) {
694 if (stack[i] instanceof CallMarker) {
695 CallMarker cm = (CallMarker)stack[i];
696 if(cm.f == null) break;
697 String s = cm.f.sourceName + ":" + cm.f.line[cm.pc-1];
698 if(cm instanceof Interpreter.TrapMarker)
699 s += " (trap on " + JS.debugToString(((Interpreter.TrapMarker)cm).t.key) + ")";