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.isWriteTrap() && !tm.cascadeHappened && !JS.toBoolean(retval);
175 Trap t = tm.t.nextWriteTrap();
176 if(t == null && tm.target instanceof JS.Clone) {
177 tm.target = ((JS.Clone)tm.target).clonee;
178 t = tm.target.getTrap(tm.key);
179 if(t != null) t = t.writeTrap();
182 tm.t = t; // we reuse the old trap marker
183 setupTrap(t,tm.val,tm);
184 pc--; // we increment it on the next iter
187 tm.target.put(tm.key,tm.val);
191 CallMarker cm = (CallMarker) o;
196 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
197 if(f == null) return retval;
201 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
205 JS val = stack.pop();
206 JS key = stack.pop();
207 JS target = stack.peek();
208 if (target == null) throw je("tried to put " + JS.debugToString(val) + " to the " + JS.debugToString(key) + " property on the null value");
209 if (key == null) throw je("tried to assign \"" + JS.debugToString(val) + "\" to the null key");
212 TrapMarker tm = null;
213 if(target instanceof JSScope && key.jsequals(CASCADE)) {
214 CallMarker o = stack.findCall();
215 if(o instanceof TrapMarker) {
219 tm.cascadeHappened = true;
221 if(t.isReadTrap()) throw new JSExn("can't do a write cascade in a read trap");
222 t = t.nextWriteTrap();
225 if(tm == null) { // not cascading
226 t = target instanceof JSScope ? t = ((JSScope)target).top().getTrap(key) : target.getTrap(key);
227 if(t != null) t = t.writeTrap();
229 if(t == null && target instanceof JS.Clone) {
230 target = ((JS.Clone)target).clonee;
231 t = target.getTrap(key);
232 if(t != null) t = t.writeTrap();
238 setupTrap(t,val,new TrapMarker(this,t,target,key,val));
239 pc--; // we increment later
243 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
252 key = arg == null ? stack.pop() : (JS)arg;
253 target = stack.pop();
256 target = stack.peek();
260 if (key == null) throw je("tried to get the null key from " + target);
261 if (target == null) throw je("tried to get property \"" + key + "\" from the null object");
264 TrapMarker tm = null;
265 if(target instanceof JSScope && key.jsequals(CASCADE)) {
266 CallMarker o = stack.findCall();
267 if(o instanceof TrapMarker) {
272 if(t.isWriteTrap()) throw new JSExn("can't do a read cascade in a write trap");
273 t = t.nextReadTrap();
276 if(tm == null) { // not cascading
277 t = target instanceof JSScope ? t = ((JSScope)target).top().getTrap(key) : ((JS)target).getTrap(key);
278 if(t != null) t = t.readTrap();
280 if(t == null && target instanceof JS.Clone) {
281 target = ((JS.Clone)target).clonee;
282 t = target.getTrap(key);
283 if(t != null) t = t.readTrap();
287 setupTrap(t,null,new TrapMarker(this,t,target,key,null));
288 pc--; // we increment later
291 ret = target.get(key);
292 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
293 if (ret == JS.METHOD) ret = new Stub(target, key);
299 case CALL: case CALLMETHOD: {
300 int numArgs = JS.toInt((JS)arg);
302 JS[] rest = numArgs > 3 ? new JS[numArgs - 3] : null;
303 for(int i=numArgs - 1; i>2; i--) rest[i-3] = stack.pop();
304 JS a2 = numArgs <= 2 ? null : stack.pop();
305 JS a1 = numArgs <= 1 ? null : stack.pop();
306 JS a0 = numArgs <= 0 ? null : stack.pop();
310 JS object = stack.pop();
312 if (op == CALLMETHOD) {
313 if (object == JS.METHOD) {
314 method = stack.pop();
315 object = stack.pop();
316 } else if (object == null) {
317 method = stack.pop();
318 object = stack.pop();
319 throw new JSExn("function '"+JS.debugToString(method)+"' not found in " + object.getClass().getName());
326 if (object instanceof JSFunction) {
327 stack.push(new CallMarker(this));
328 stack.push(new JSArgs(a0,a1,a2,rest,numArgs,object));
329 f = (JSFunction)object;
330 scope = new JSScope(f.parentScope);
335 ret = method == null ? c.call(a0, a1, a2, rest, numArgs) : c.callMethod(method, a0, a1, a2, rest, numArgs);
338 if (pausecount > initialPauseCount) { pc++; return null; }
344 throw new JSExn(stack.pop(), this);
348 final Grammar r = (Grammar)arg;
349 final JSScope final_scope = scope;
350 Grammar r2 = new Grammar() {
351 public int match(String s, int start, Hash v, JSScope scope) throws JSExn {
352 return r.match(s, start, v, final_scope);
354 public int matchAndWrite(String s, int start, Hash v, JSScope scope, String key) throws JSExn {
355 return r.matchAndWrite(s, start, v, final_scope, key);
357 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
359 r.matchAndWrite((String)a0, 0, v, final_scope, "foo");
363 Object obj = stack.pop();
364 if (obj != null && obj instanceof Grammar) r2 = new Grammar.Alternative((Grammar)obj, r2);
369 case ADD_TRAP: case DEL_TRAP: {
370 JS val = stack.pop();
371 JS key = stack.pop();
372 JS js = stack.peek();
373 // A trap addition/removal
374 if(!(val instanceof JSFunction)) throw new JSExn("tried to add/remove a non-function trap");
375 if(js instanceof JSScope) {
376 JSScope s = (JSScope) js;
377 while(s.getParentScope() != null) {
378 if(s.has(key)) throw new JSExn("cannot trap a variable that isn't at the top level scope");
379 s = s.getParentScope();
383 if(op == ADD_TRAP) js.addTrap(key, (JSFunction)val);
384 else js.delTrap(key, (JSFunction)val);
389 int count = ((JSNumber)arg).toInt();
390 if(count < 2) throw new Error("this should never happen");
393 JS right = stack.pop();
394 JS left = stack.pop();
396 if(left instanceof JSString || right instanceof JSString)
397 ret = JS.S(JS.toString(left).concat(JS.toString(right)));
398 else if(left instanceof JSNumber.D || right instanceof JSNumber.D)
399 ret = JS.N(JS.toDouble(left) + JS.toDouble(right));
401 long l = JS.toLong(left) + JS.toLong(right);
402 if(l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) ret = JS.N(l);
407 JS[] args = new JS[count];
408 while(--count >= 0) args[count] = stack.pop();
409 if(args[0] instanceof JSString) {
410 StringBuffer sb = new StringBuffer(64);
411 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
412 stack.push(JS.S(sb.toString()));
415 for(int i=0;i<args.length;i++) if(args[i] instanceof JSString) numStrings++;
416 if(numStrings == 0) {
418 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
422 StringBuffer sb = new StringBuffer(64);
423 if(!(args[0] instanceof JSString || args[1] instanceof JSString)) {
426 d += JS.toDouble(args[i++]);
427 } while(!(args[i] instanceof JSString));
428 sb.append(JS.toString(JS.N(d)));
430 while(i < args.length) sb.append(JS.toString(args[i++]));
431 stack.push(JS.S(sb.toString()));
439 JS right = stack.pop();
440 JS left = stack.pop();
443 case BITOR: stack.push(JS.N(JS.toLong(left) | JS.toLong(right))); break;
444 case BITXOR: stack.push(JS.N(JS.toLong(left) ^ JS.toLong(right))); break;
445 case BITAND: stack.push(JS.N(JS.toLong(left) & JS.toLong(right))); break;
447 case SUB: stack.push(JS.N(JS.toDouble(left) - JS.toDouble(right))); break;
448 case MUL: stack.push(JS.N(JS.toDouble(left) * JS.toDouble(right))); break;
449 case DIV: stack.push(JS.N(JS.toDouble(left) / JS.toDouble(right))); break;
450 case MOD: stack.push(JS.N(JS.toDouble(left) % JS.toDouble(right))); break;
452 case LSH: stack.push(JS.N(JS.toLong(left) << JS.toLong(right))); break;
453 case RSH: stack.push(JS.N(JS.toLong(left) >> JS.toLong(right))); break;
454 case URSH: stack.push(JS.N(JS.toLong(left) >>> JS.toLong(right))); break;
456 //#repeat </<=/>/>= LT/LE/GT/GE
458 if(left instanceof JSString && right instanceof JSString)
459 stack.push(JS.B(JS.toString(left).compareTo(JS.toString(right)) < 0));
461 stack.push(JS.B(JS.toDouble(left) < JS.toDouble(right)));
468 if(left == null && right == null) ret = true;
469 else if(left == null || right == null) ret = false;
470 else ret = left.jsequals(right);
471 stack.push(JS.B(op == EQ ? ret : !ret)); break;
474 default: throw new Error("unknown opcode " + op);
480 pc--; // it'll get incremented on the next iteration
485 /** tries to find a handler withing the call chain for this exception
486 if a handler is found the interpreter is setup to call the exception handler
487 if a handler is not found the exception is thrown
489 void catchException(JSExn e) throws JSExn {
490 while(!stack.empty()) {
492 if (o instanceof CatchMarker || o instanceof TryMarker) {
493 boolean inCatch = o instanceof CatchMarker;
496 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
498 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
499 // run the catch block, this will implicitly run the finally block, if it exists
501 stack.push(catchMarker);
502 stack.push(e.getObject());
503 f = ((TryMarker)o).f;
504 scope = ((TryMarker)o).scope;
505 pc = ((TryMarker)o).catchLoc;
508 stack.push(new FinallyData(e));
509 f = ((TryMarker)o).f;
510 scope = ((TryMarker)o).scope;
511 pc = ((TryMarker)o).finallyLoc;
519 void setupTrap(Trap t, JS val, CallMarker cm) throws JSExn {
521 stack.push(t.isWriteTrap() ? new JSArgs(val,t.f) : new JSArgs(t.f));
523 scope = new TrapScope(t.f.parentScope,t.target,t.f,t.key);
528 // Markers //////////////////////////////////////////////////////////////////////
530 static class Marker extends JS {
531 public JS get(JS key) throws JSExn { throw new Error("this should not be accessible from a script"); }
532 public void put(JS key, JS val) throws JSExn { throw new Error("this should not be accessible from a script"); }
533 public String coerceToString() { throw new Error("this should not be accessible from a script"); }
534 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"); }
537 static class CallMarker extends Marker {
541 public CallMarker(Interpreter cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
542 public CallMarker() { pc = -1; scope = null; f = null; }
545 static class TrapMarker extends CallMarker {
550 boolean cascadeHappened;
551 public TrapMarker(Interpreter cx, Trap t, JS target, JS key, JS val) {
554 this.target = target;
560 static class CatchMarker extends Marker { }
561 private static CatchMarker catchMarker = new CatchMarker();
563 static class LoopMarker extends Marker {
564 final public int location;
565 final public String label;
566 final public JSScope scope;
567 public LoopMarker(int location, String label, JSScope scope) {
568 this.location = location;
573 static class TryMarker extends Marker {
574 final public int catchLoc;
575 final public int finallyLoc;
576 final public JSScope scope;
577 final public JSFunction f;
578 public TryMarker(int catchLoc, int finallyLoc, Interpreter cx) {
579 this.catchLoc = catchLoc;
580 this.finallyLoc = finallyLoc;
581 this.scope = cx.scope;
585 static class FinallyData extends Marker {
587 final public Object arg;
588 final public JSExn exn;
589 public FinallyData(int op) { this(op,null); }
590 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; this.exn = null; }
591 public FinallyData(JSExn exn) { this.exn = exn; this.op = -1; this.arg = null; } // Just throw this exn
594 static class TrapScope extends JSScope {
598 public TrapScope(JSScope parent, JS trapee, JS callee, JS trapname) {
599 super(parent); this.trapee = trapee; this.callee = callee; this.trapname = trapname;
601 public JS get(JS key) throws JSExn {
602 if(JS.isString(key)) {
603 //#switch(JS.toString(key))
604 case "trapee": return trapee;
605 case "callee": return callee;
606 case "trapname": return trapname;
609 return super.get(key);
613 static class JSArgs extends JS {
617 private final JS[] rest;
618 private final int nargs;
619 private final JS callee;
621 public JSArgs(JS callee) { this(null,null,null,null,0,callee); }
622 public JSArgs(JS a0, JS callee) { this(a0,null,null,null,1,callee); }
623 public JSArgs(JS a0, JS a1, JS a2, JS[] rest, int nargs, JS callee) {
624 this.a0 = a0; this.a1 = a1; this.a2 = a2;
625 this.rest = rest; this.nargs = nargs;
626 this.callee = callee;
629 public JS get(JS key) throws JSExn {
631 int n = JS.toInt(key);
636 default: return n>= 0 && n < nargs ? rest[n-3] : null;
639 //#switch(JS.toString(key))
640 case "callee": return callee;
641 case "length": return JS.N(nargs);
643 return super.get(key);
647 static class Stub extends JS {
650 public Stub(JS obj, JS method) { this.obj = obj; this.method = method; }
651 public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
652 return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs);
657 private static final int MAX_STACK_SIZE = 512;
658 private JS[] stack = new JS[64];
661 boolean empty() { return sp == 0; }
662 void push(JS o) throws JSExn { if(sp == stack.length) grow(); stack[sp++] = o; }
663 JS peek() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[sp-1]; }
664 final JS pop() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[--sp]; }
665 void swap() throws JSExn {
666 if(sp < 2) throw new JSExn("stack overflow");
667 JS tmp = stack[sp-2];
668 stack[sp-2] = stack[sp-1];
671 CallMarker findCall() {
672 for(int i=sp-1;i>=0;i--) if(stack[i] instanceof CallMarker) return (CallMarker) stack[i];
675 void grow() throws JSExn {
676 if(stack.length >= MAX_STACK_SIZE) throw new JSExn("Stack overflow");
677 JS[] stack2 = new JS[stack.length * 2];
678 System.arraycopy(stack,0,stack2,0,stack.length);
681 void backtrace(JSExn e) {
682 for(int i=sp-1;i>=0;i--) {
683 if (stack[i] instanceof CallMarker) {
684 CallMarker cm = (CallMarker)stack[i];
685 if(cm.f == null) break;
686 String s = cm.f.sourceName + ":" + cm.f.line[cm.pc-1];
687 if(cm instanceof Interpreter.TrapMarker)
688 s += " (trap on " + JS.debugToString(((Interpreter.TrapMarker)cm).key) + ")";