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;
104 if (JS.checkAssertions && !JS.toBoolean(o))
105 throw je("ibex.assertion.failed");
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 read 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 JS val = stack.pop();
220 JS key = stack.pop();
221 JS target = stack.peek();
222 if (target == null) throw je("tried to put " + JS.debugToString(val) + " to the " + JS.debugToString(key) + " property on the null value");
223 if (key == null) throw je("tried to assign \"" + JS.debugToString(val) + "\" to the null key");
226 TrapMarker tm = null;
227 if(target instanceof JSScope && key.jsequals(CASCADE)) {
228 CallMarker o = stack.findCall();
229 if(o instanceof TrapMarker) {
231 target = tm.t.target;
233 tm.cascadeHappened = true;
235 if(t.isReadTrap()) throw new JSExn("can't do a write cascade in a read trap");
236 t = t.nextWriteTrap();
239 if(tm == null) { // not cascading
240 t = target instanceof JSScope ? t = ((JSScope)target).top().getTrap(key) : target.getTrap(key);
241 if(t != null) t = t.writeTrap();
243 if(t == null && target instanceof JS.Clone) {
244 target = ((JS.Clone)target).clonee;
245 t = target.getTrap(key);
246 if(t != null) t = t.writeTrap();
252 setupTrap(t,val,new TrapMarker(this,t,val, tm != null && tm.pauseOnPut));
253 pc--; // we increment later
256 if (tm != null && tm.pauseOnPut) { pc++; return val; }
258 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
267 key = arg == null ? stack.pop() : (JS)arg;
268 target = stack.pop();
271 target = stack.peek();
275 if (key == null) throw je("tried to get the null key from " + target);
276 if (target == null) throw je("tried to get property \"" + key + "\" from the null object");
279 TrapMarker tm = null;
280 if(target instanceof JSScope && key.jsequals(CASCADE)) {
281 CallMarker o = stack.findCall();
282 if(o instanceof TrapMarker) {
284 target = tm.t.target;
287 if(t.isWriteTrap()) throw new JSExn("can't do a read cascade in a write trap");
288 t = t.nextReadTrap();
291 if(tm == null) { // not cascading
292 t = target instanceof JSScope ? t = ((JSScope)target).top().getTrap(key) : ((JS)target).getTrap(key);
293 if(t != null) t = t.readTrap();
295 if(t == null && target instanceof JS.Clone) {
296 target = ((JS.Clone)target).clonee;
297 t = target.getTrap(key);
298 if(t != null) t = t.readTrap();
302 setupTrap(t,null,new TrapMarker(this,t,null));
303 pc--; // we increment later
306 ret = target.get(key);
307 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
308 if (ret == JS.METHOD) ret = new Stub(target, key);
314 case CALL: case CALLMETHOD: {
315 int numArgs = JS.toInt((JS)arg);
317 JS[] rest = numArgs > 3 ? new JS[numArgs - 3] : null;
318 for(int i=numArgs - 1; i>2; i--) rest[i-3] = stack.pop();
319 JS a2 = numArgs <= 2 ? null : stack.pop();
320 JS a1 = numArgs <= 1 ? null : stack.pop();
321 JS a0 = numArgs <= 0 ? null : stack.pop();
325 JS object = stack.pop();
327 if (op == CALLMETHOD) {
328 if (object == JS.METHOD) {
329 method = stack.pop();
330 object = stack.pop();
331 } else if (object == null) {
332 method = stack.pop();
333 object = stack.pop();
334 throw new JSExn("function '"+JS.debugToString(method)+"' not found in " + object.getClass().getName());
341 if (object instanceof JSFunction) {
342 stack.push(new CallMarker(this));
343 stack.push(new JSArgs(a0,a1,a2,rest,numArgs,object));
344 f = (JSFunction)object;
345 scope = new JSScope(f.parentScope);
350 ret = method == null ? c.call(a0, a1, a2, rest, numArgs) : c.callMethod(method, a0, a1, a2, rest, numArgs);
353 if (pausecount > initialPauseCount) { pc++; return null; }
359 throw new JSExn(stack.pop(), this);
363 final Grammar r = (Grammar)arg;
364 final JSScope final_scope = scope;
365 Grammar r2 = new Grammar() {
366 public int match(String s, int start, Hash v, JSScope scope) throws JSExn {
367 return r.match(s, start, v, final_scope);
369 public int matchAndWrite(String s, int start, Hash v, JSScope scope, String key) throws JSExn {
370 return r.matchAndWrite(s, start, v, final_scope, key);
372 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
374 r.matchAndWrite((String)a0, 0, v, final_scope, "foo");
378 Object obj = stack.pop();
379 if (obj != null && obj instanceof Grammar) r2 = new Grammar.Alternative((Grammar)obj, r2);
384 case ADD_TRAP: case DEL_TRAP: {
385 JS val = stack.pop();
386 JS key = stack.pop();
387 JS js = stack.peek();
388 // A trap addition/removal
389 if(!(val instanceof JSFunction)) throw new JSExn("tried to add/remove a non-function trap");
390 if(js instanceof JSScope) {
391 JSScope s = (JSScope) js;
392 while(s.getParentScope() != null) {
393 if(s.has(key)) throw new JSExn("cannot trap a variable that isn't at the top level scope");
394 s = s.getParentScope();
398 if(op == ADD_TRAP) js.addTrap(key, (JSFunction)val);
399 else js.delTrap(key, (JSFunction)val);
404 int count = ((JSNumber)arg).toInt();
405 if(count < 2) throw new Error("this should never happen");
408 JS right = stack.pop();
409 JS left = stack.pop();
411 if(left instanceof JSString || right instanceof JSString)
412 ret = JS.S(JS.toString(left).concat(JS.toString(right)));
413 else if(left instanceof JSNumber.D || right instanceof JSNumber.D)
414 ret = JS.N(JS.toDouble(left) + JS.toDouble(right));
416 long l = JS.toLong(left) + JS.toLong(right);
417 if(l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) ret = JS.N(l);
422 JS[] args = new JS[count];
423 while(--count >= 0) args[count] = stack.pop();
424 if(args[0] instanceof JSString) {
425 StringBuffer sb = new StringBuffer(64);
426 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
427 stack.push(JS.S(sb.toString()));
430 for(int i=0;i<args.length;i++) if(args[i] instanceof JSString) numStrings++;
431 if(numStrings == 0) {
433 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
437 StringBuffer sb = new StringBuffer(64);
438 if(!(args[0] instanceof JSString || args[1] instanceof JSString)) {
441 d += JS.toDouble(args[i++]);
442 } while(!(args[i] instanceof JSString));
443 sb.append(JS.toString(JS.N(d)));
445 while(i < args.length) sb.append(JS.toString(args[i++]));
446 stack.push(JS.S(sb.toString()));
454 JS right = stack.pop();
455 JS left = stack.pop();
458 case BITOR: stack.push(JS.N(JS.toLong(left) | JS.toLong(right))); break;
459 case BITXOR: stack.push(JS.N(JS.toLong(left) ^ JS.toLong(right))); break;
460 case BITAND: stack.push(JS.N(JS.toLong(left) & JS.toLong(right))); break;
462 case SUB: stack.push(JS.N(JS.toDouble(left) - JS.toDouble(right))); break;
463 case MUL: stack.push(JS.N(JS.toDouble(left) * JS.toDouble(right))); break;
464 case DIV: stack.push(JS.N(JS.toDouble(left) / JS.toDouble(right))); break;
465 case MOD: stack.push(JS.N(JS.toDouble(left) % JS.toDouble(right))); break;
467 case LSH: stack.push(JS.N(JS.toLong(left) << JS.toLong(right))); break;
468 case RSH: stack.push(JS.N(JS.toLong(left) >> JS.toLong(right))); break;
469 case URSH: stack.push(JS.N(JS.toLong(left) >>> JS.toLong(right))); break;
471 //#repeat </<=/>/>= LT/LE/GT/GE
473 if(left instanceof JSString && right instanceof JSString)
474 stack.push(JS.B(JS.toString(left).compareTo(JS.toString(right)) < 0));
476 stack.push(JS.B(JS.toDouble(left) < JS.toDouble(right)));
483 if(left == null && right == null) ret = true;
484 else if(left == null || right == null) ret = false;
485 else ret = left.jsequals(right);
486 stack.push(JS.B(op == EQ ? ret : !ret)); break;
489 default: throw new Error("unknown opcode " + op);
495 pc--; // it'll get incremented on the next iteration
500 /** tries to find a handler withing the call chain for this exception
501 if a handler is found the interpreter is setup to call the exception handler
502 if a handler is not found the exception is thrown
504 void catchException(JSExn e) throws JSExn {
505 while(!stack.empty()) {
507 if (o instanceof CatchMarker || o instanceof TryMarker) {
508 boolean inCatch = o instanceof CatchMarker;
511 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
513 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
514 // run the catch block, this will implicitly run the finally block, if it exists
516 stack.push(catchMarker);
517 stack.push(e.getObject());
518 f = ((TryMarker)o).f;
519 scope = ((TryMarker)o).scope;
520 pc = ((TryMarker)o).catchLoc;
523 stack.push(new FinallyData(e));
524 f = ((TryMarker)o).f;
525 scope = ((TryMarker)o).scope;
526 pc = ((TryMarker)o).finallyLoc;
534 void setupTrap(Trap t, JS val, CallMarker cm) throws JSExn {
536 stack.push(t.isWriteTrap() ? new JSArgs(val,t.f) : new JSArgs(t.f));
538 scope = new TrapScope(t.f.parentScope,t);
543 // Markers //////////////////////////////////////////////////////////////////////
545 static class Marker extends JS {
546 public JS get(JS key) throws JSExn { throw new Error("this should not be accessible from a script"); }
547 public void put(JS key, JS val) throws JSExn { throw new Error("this should not be accessible from a script"); }
548 public String coerceToString() { throw new Error("this should not be accessible from a script"); }
549 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"); }
552 static class CallMarker extends Marker {
556 public CallMarker(Interpreter cx) {
557 pc = cx == null ? -1 : cx.pc + 1;
558 scope = cx == null ? null : cx.scope;
559 f = cx == null ? null : cx.f;
563 static class TrapMarker extends CallMarker {
566 boolean cascadeHappened;
567 final boolean pauseOnPut;
568 public TrapMarker(Interpreter cx, Trap t, JS val) { this(cx,t,val,false); }
569 public TrapMarker(Interpreter cx, Trap t, JS val, boolean pauseOnPut) {
573 this.pauseOnPut = pauseOnPut;
577 static class CatchMarker extends Marker { }
578 private static CatchMarker catchMarker = new CatchMarker();
580 static class LoopMarker extends Marker {
581 final public int location;
582 final public String label;
583 final public JSScope scope;
584 public LoopMarker(int location, String label, JSScope scope) {
585 this.location = location;
590 static class TryMarker extends Marker {
591 final public int catchLoc;
592 final public int finallyLoc;
593 final public JSScope scope;
594 final public JSFunction f;
595 public TryMarker(int catchLoc, int finallyLoc, Interpreter cx) {
596 this.catchLoc = catchLoc;
597 this.finallyLoc = finallyLoc;
598 this.scope = cx.scope;
602 static class FinallyData extends Marker {
604 final public Object arg;
605 final public JSExn exn;
606 public FinallyData(int op) { this(op,null); }
607 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; this.exn = null; }
608 public FinallyData(JSExn exn) { this.exn = exn; this.op = -1; this.arg = null; } // Just throw this exn
611 static class TrapScope extends JSScope {
613 public TrapScope(JSScope parent, Trap t) {
614 super(parent); this.t = t;
616 public JS get(JS key) throws JSExn {
618 case "trapee": return t.target;
619 case "callee": return t.f;
620 case "trapname": return t.key;
622 return super.get(key);
626 static class JSArgs extends JS {
630 private final JS[] rest;
631 private final int nargs;
632 private final JS callee;
634 public JSArgs(JS callee) { this(null,null,null,null,0,callee); }
635 public JSArgs(JS a0, JS callee) { this(a0,null,null,null,1,callee); }
636 public JSArgs(JS a0, JS a1, JS a2, JS[] rest, int nargs, JS callee) {
637 this.a0 = a0; this.a1 = a1; this.a2 = a2;
638 this.rest = rest; this.nargs = nargs;
639 this.callee = callee;
642 public JS get(JS key) throws JSExn {
644 int n = JS.toInt(key);
649 default: return n>= 0 && n < nargs ? rest[n-3] : null;
653 case "callee": return callee;
654 case "length": return JS.N(nargs);
656 return super.get(key);
660 static class Stub extends JS {
663 public Stub(JS obj, JS method) { this.obj = obj; this.method = method; }
664 public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
665 return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs);
670 private static final int MAX_STACK_SIZE = 512;
671 private JS[] stack = new JS[64];
674 boolean empty() { return sp == 0; }
675 void push(JS o) throws JSExn { if(sp == stack.length) grow(); stack[sp++] = o; }
676 JS peek() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[sp-1]; }
677 final JS pop() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[--sp]; }
678 void swap() throws JSExn {
679 if(sp < 2) throw new JSExn("stack overflow");
680 JS tmp = stack[sp-2];
681 stack[sp-2] = stack[sp-1];
684 CallMarker findCall() {
685 for(int i=sp-1;i>=0;i--) if(stack[i] instanceof CallMarker) return (CallMarker) stack[i];
688 void grow() throws JSExn {
689 if(stack.length >= MAX_STACK_SIZE) throw new JSExn("Stack overflow");
690 JS[] stack2 = new JS[stack.length * 2];
691 System.arraycopy(stack,0,stack2,0,stack.length);
694 void backtrace(JSExn e) {
695 for(int i=sp-1;i>=0;i--) {
696 if (stack[i] instanceof CallMarker) {
697 CallMarker cm = (CallMarker)stack[i];
698 if(cm.f == null) break;
699 String s = cm.f.sourceName + ":" + cm.f.line[cm.pc-1];
700 if(cm instanceof Interpreter.TrapMarker)
701 s += " (trap on " + JS.debugToString(((Interpreter.TrapMarker)cm).t.key) + ")";