1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
7 import org.ibex.util.*;
10 /** Encapsulates a single JS interpreter (ie call stack) */
11 class Interpreter implements ByteCodes, Tokens {
12 // Thread-Interpreter Mapping /////////////////////////////////////////////////////////////////////////
14 static Interpreter current() { return (Interpreter)threadToInterpreter.get(Thread.currentThread()); }
15 private static Hashtable threadToInterpreter = new Hashtable();
18 // Instance members and methods //////////////////////////////////////////////////////////////////////
20 int pausecount; ///< the number of times pause() has been invoked; -1 indicates unpauseable
21 JSFunction f = null; ///< the currently-executing JSFunction
22 JSScope scope; ///< the current top-level scope (LIFO stack via NEWSCOPE/OLDSCOPE)
23 final Stack stack = new Stack(); ///< the object stack
24 int pc = 0; ///< the program counter
26 Interpreter(JSFunction f, boolean pauseable, JSArgs args) {
28 this.pausecount = pauseable ? 0 : -1;
29 this.scope = f.parentScope;
31 stack.push(new CallMarker(null)); // the "root function returned" marker -- f==null
34 throw new Error("should never happen");
38 Interpreter(Trap t, JS val, boolean pauseOnPut) {
41 setupTrap(t,val,new TrapMarker(null,t,val,pauseOnPut));
43 throw new Error("should never happen");
47 /** this is the only synchronization point we need in order to be threadsafe */
48 synchronized JS resume() throws JSExn {
49 if(f == null) throw new RuntimeException("function already finished");
50 if(scope == null) throw new RuntimeException("scope is null");
51 Thread t = Thread.currentThread();
52 Interpreter old = (Interpreter)threadToInterpreter.get(t);
53 threadToInterpreter.put(t, this);
57 if (old == null) threadToInterpreter.remove(t);
58 else threadToInterpreter.put(t, old);
62 static int getLine() {
63 Interpreter c = Interpreter.current();
64 return c == null || c.f == null || c.pc < 0 || c.pc >= c.f.size ? -1 : c.f.line[c.pc];
67 static String getSourceName() {
68 Interpreter c = Interpreter.current();
69 return c == null || c.f == null ? null : c.f.sourceName;
72 private static JSExn je(String s) { return new JSExn(getSourceName() + ":" + getLine() + " " + s); }
74 private JS run() throws JSExn {
76 // if pausecount changes after a get/put/call, we know we've been paused
77 final int initialPauseCount = pausecount;
82 Object arg = f.arg[pc];
83 if(op == FINALLY_DONE) {
84 FinallyData fd = (FinallyData) stack.pop();
85 if(fd == null) continue OUTER; // NOP
86 if(fd.exn != null) throw fd.exn;
91 case LITERAL: stack.push((JS)arg); break;
92 case OBJECT: stack.push(new JS.O()); break;
93 case ARRAY: stack.push(new JSArray(JS.toInt((JS)arg))); break;
94 //case DECLARE: scope.declare((JS)(arg==null ? stack.peek() : arg)); if(arg != null) stack.push((JS)arg); break;
95 case JT: if (JS.toBoolean(stack.pop())) pc += JS.toInt((JS)arg) - 1; break;
96 case JF: if (!JS.toBoolean(stack.pop())) pc += JS.toInt((JS)arg) - 1; break;
97 case JMP: pc += JS.toInt((JS)arg) - 1; break;
98 case POP: stack.pop(); break;
99 case SWAP: stack.swap(); break;
100 case DUP: stack.push(stack.peek()); break;
102 int n = JS.toInt((JS)arg);
103 scope = new JSScope(scope,(n>>>16)&0xffff,(n>>>0)&0xffff);
106 case OLDSCOPE: scope = scope.parent; break;
107 case GLOBALSCOPE: stack.push(scope.getGlobal()); break;
108 case SCOPEGET: stack.push(scope.get((JS)arg)); break;
109 case SCOPEPUT: scope.put((JS)arg,stack.peek()); break;
110 case ASSERT: if (!JS.toBoolean(stack.pop())) throw je("ibex.assertion.failed"); break;
111 case BITNOT: stack.push(JS.N(~JS.toLong(stack.pop()))); break;
112 case BANG: stack.push(JS.B(!JS.toBoolean(stack.pop()))); break;
113 case NEWFUNCTION: stack.push(((JSFunction)arg)._cloneWithNewParentScope(scope)); break;
117 Object o = stack.pop();
118 if (o == null) stack.push(null);
119 else if (o instanceof JSString) stack.push(JS.S("string"));
120 else if (o instanceof JSNumber.B) stack.push(JS.S("boolean"));
121 else if (o instanceof JSNumber) stack.push(JS.S("number"));
122 else stack.push(JS.S("object"));
128 stack.push(o == null ? null : o.keys());
133 stack.push(new LoopMarker(pc, pc > 0 && f.op[pc - 1] == LABEL ? (String)f.arg[pc - 1] : (String)null, scope));
139 while(!stack.empty()) {
141 if (o instanceof CallMarker) je("break or continue not within a loop");
142 if (o instanceof TryMarker) {
143 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
144 stack.push(new FinallyData(op, arg));
145 scope = ((TryMarker)o).scope;
146 pc = ((TryMarker)o).finallyLoc - 1;
149 if (o instanceof LoopMarker) {
150 if (arg == null || arg.equals(((LoopMarker)o).label)) {
151 int loopInstructionLocation = ((LoopMarker)o).location;
152 int endOfLoop = JS.toInt((JS)f.arg[loopInstructionLocation]) + loopInstructionLocation;
153 scope = ((LoopMarker)o).scope;
154 if (op == CONTINUE) { stack.push(o); stack.push(JS.F); }
155 pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
160 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
161 getSourceName() + ":" + getLine());
164 int[] jmps = (int[]) arg;
165 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
166 // each can be < 0 if the specified block does not exist
167 stack.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1], this));
172 JS retval = stack.pop();
173 while(!stack.empty()) {
174 Object o = stack.pop();
175 if (o instanceof TryMarker) {
176 if(((TryMarker)o).finallyLoc < 0) continue;
178 stack.push(new FinallyData(RETURN));
179 scope = ((TryMarker)o).scope;
180 pc = ((TryMarker)o).finallyLoc - 1;
182 } else if (o instanceof CallMarker) {
183 boolean didTrapPut = false;
184 if (o instanceof TrapMarker) { // handles return component of a write trap
185 TrapMarker tm = (TrapMarker) o;
186 boolean cascade = tm.t.isWriteTrap() && !tm.cascadeHappened && !JS.toBoolean(retval);
188 Trap t = tm.t.nextWriteTrap();
189 if(t == null && tm.t.target instanceof JS.Clone) {
190 t = ((JS.Clone)tm.t.target).clonee.getTrap(tm.t.key);
191 if(t != null) t = t.writeTrap();
194 tm.t = t; // we reuse the old trap marker
195 setupTrap(t,tm.val,tm);
196 pc--; // we increment it on the next iter
200 if(!tm.pauseOnPut) tm.t.target.put(tm.t.key,tm.val);
204 CallMarker cm = (CallMarker) o;
209 if (((TrapMarker)cm).pauseOnPut) { pc++; return ((TrapMarker)cm).val; }
210 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
214 if (f == null) return retval;
218 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
222 boolean write = JS.toBoolean((JS)arg);
223 JS val = write ? stack.pop() : null;
224 CallMarker o = stack.findCall();
225 if(!(o instanceof TrapMarker)) throw new JSExn("tried to CASCADE while not in a trap");
226 TrapMarker tm = (TrapMarker) o;
228 JS target = tm.t.target;
229 if(tm.t.isWriteTrap() != write) throw new JSExn("tried to do a " + (write?"write":"read") + " cascade in a " + (write?"read":"write") + " trap");
230 Trap t = write ? tm.t.nextWriteTrap() : tm.t.nextReadTrap();
231 // FIXME: Doesn't handle multiple levels of clone's (probably can just make this a while loop)
232 if(t == null && target instanceof JS.Clone) {
233 target = ((JS.Clone)target).clonee;
234 t = target.getTrap(key);
235 if(t != null) t = write ? t.writeTrap() : t.readTrap();
238 tm.cascadeHappened = true;
242 setupTrap(t,val,new TrapMarker(this,t,val,tm.pauseOnPut));
243 pc--; // we increment later
246 if (tm.pauseOnPut) { pc++; return val; }
249 JS ret = target.get(key);
250 if (ret == JS.METHOD) ret = new Stub(target, key);
253 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
259 JS val = stack.pop();
260 JS key = stack.pop();
261 JS target = stack.peek();
262 if (target == null) throw je("tried to put " + JS.debugToString(val) + " to the " + JS.debugToString(key) + " property on the null value");
263 if (key == null) throw je("tried to assign \"" + JS.debugToString(val) + "\" to the null key");
265 Trap t = target.getTrap(key);
266 if(t != null) t = t.writeTrap();
268 if(t == null && target instanceof JS.Clone) {
269 target = ((JS.Clone)target).clonee;
270 t = target.getTrap(key);
271 if(t != null) t = t.writeTrap();
277 setupTrap(t,val,new TrapMarker(this,t,val));
278 pc--; // we increment later
281 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
290 key = arg == null ? stack.pop() : (JS)arg;
291 target = stack.pop();
294 target = stack.peek();
298 if (key == null) throw je("tried to get the null key from " + JS.debugToString(target));
299 if (target == null) throw je("tried to get property \"" + JS.debugToString(key) + "\" from the null object");
301 Trap t = target.getTrap(key);
302 if(t != null) t = t.readTrap();
304 if(t == null && target instanceof JS.Clone) {
305 target = ((JS.Clone)target).clonee;
306 t = target.getTrap(key);
307 if(t != null) t = t.readTrap();
311 setupTrap(t,null,new TrapMarker(this,t,null));
312 pc--; // we increment later
314 ret = target.get(key);
315 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
316 if (ret == JS.METHOD) ret = new Stub(target, key);
322 case CALL: case CALLMETHOD: {
323 int numArgs = JS.toInt((JS)arg);
325 JS[] rest = numArgs > 3 ? new JS[numArgs - 3] : null;
326 for(int i=numArgs - 1; i>2; i--) rest[i-3] = stack.pop();
327 JS a2 = numArgs <= 2 ? null : stack.pop();
328 JS a1 = numArgs <= 1 ? null : stack.pop();
329 JS a0 = numArgs <= 0 ? null : stack.pop();
333 JS object = stack.pop();
335 if (op == CALLMETHOD) {
336 if (object == JS.METHOD) {
337 method = stack.pop();
338 object = stack.pop();
339 } else if (object == null) {
340 method = stack.pop();
341 object = stack.pop();
342 throw new JSExn("function '"+JS.debugToString(method)+"' not found in " + object.getClass().getName());
349 if (object instanceof JSFunction) {
350 stack.push(new CallMarker(this));
351 stack.push(new JSArgs(a0,a1,a2,rest,numArgs,object));
352 f = (JSFunction)object;
353 scope = f.parentScope;
358 ret = method == null ? c.call(a0, a1, a2, rest, numArgs) : c.callMethod(method, a0, a1, a2, rest, numArgs);
361 if (pausecount > initialPauseCount) { pc++; return null; }
367 throw new JSExn(stack.pop(), this);
371 final Grammar r = (Grammar)arg;
372 final JSScope final_scope = scope;
373 Grammar r2 = new Grammar() {
374 public int match(String s, int start, Hash v, JSScope scope) throws JSExn {
375 return r.match(s, start, v, final_scope);
377 public int matchAndWrite(String s, int start, Hash v, JSScope scope, String key) throws JSExn {
378 return r.matchAndWrite(s, start, v, final_scope, key);
380 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
382 r.matchAndWrite((String)a0, 0, v, final_scope, "foo");
386 Object obj = stack.pop();
387 if (obj != null && obj instanceof Grammar) r2 = new Grammar.Alternative((Grammar)obj, r2);
392 case ADD_TRAP: case DEL_TRAP: {
393 JS val = stack.pop();
394 JS key = stack.pop();
395 JS js = stack.peek();
396 // A trap addition/removal
397 if(!(val instanceof JSFunction)) throw new JSExn("tried to add/remove a non-function trap");
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(new TrapArgs(t,val));
538 scope = f.parentScope;
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 TrapArgs extends JS {
614 public TrapArgs(Trap t, JS val) { this.t = t; this.val = val; }
615 public JS get(JS key) throws JSExn {
616 if(JS.isInt(key) && JS.toInt(key) == 0) return val;
617 //#switch(JS.toString(key))
618 case "trapee": return t.target;
619 case "callee": return t.f;
620 case "trapname": return t.key;
621 case "length": return t.isWriteTrap() ? ONE : ZERO;
623 return super.get(key);
627 static class JSArgs extends JS {
631 private final JS[] rest;
632 private final int nargs;
633 private final JS callee;
635 public JSArgs(JS callee) { this(null,null,null,null,0,callee); }
636 public JSArgs(JS a0, JS callee) { this(a0,null,null,null,1,callee); }
637 public JSArgs(JS a0, JS a1, JS a2, JS[] rest, int nargs, JS callee) {
638 this.a0 = a0; this.a1 = a1; this.a2 = a2;
639 this.rest = rest; this.nargs = nargs;
640 this.callee = callee;
643 public JS get(JS key) throws JSExn {
645 int n = JS.toInt(key);
650 default: return n>= 0 && n < nargs ? rest[n-3] : null;
653 //#switch(JS.toString(key))
654 case "callee": return callee;
655 case "length": return JS.N(nargs);
657 return super.get(key);
661 static class Stub extends JS {
664 public Stub(JS obj, JS method) { this.obj = obj; this.method = method; }
665 public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
666 return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs);
671 private static final int MAX_STACK_SIZE = 512;
672 private JS[] stack = new JS[64];
675 boolean empty() { return sp == 0; }
676 void push(JS o) throws JSExn { if(sp == stack.length) grow(); stack[sp++] = o; }
677 JS peek() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[sp-1]; }
678 final JS pop() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[--sp]; }
679 void swap() throws JSExn {
680 if(sp < 2) throw new JSExn("stack overflow");
681 JS tmp = stack[sp-2];
682 stack[sp-2] = stack[sp-1];
685 CallMarker findCall() {
686 for(int i=sp-1;i>=0;i--) if(stack[i] instanceof CallMarker) return (CallMarker) stack[i];
689 void grow() throws JSExn {
690 if(stack.length >= MAX_STACK_SIZE) throw new JSExn("Stack overflow");
691 JS[] stack2 = new JS[stack.length * 2];
692 System.arraycopy(stack,0,stack2,0,stack.length);
695 void backtrace(JSExn e) {
696 for(int i=sp-1;i>=0;i--) {
697 if (stack[i] instanceof CallMarker) {
698 CallMarker cm = (CallMarker)stack[i];
699 if(cm.f == null) break;
700 String s = cm.f.sourceName + ":" + cm.f.line[cm.pc-1];
701 if(cm instanceof Interpreter.TrapMarker)
702 s += " (trap on " + JS.debugToString(((Interpreter.TrapMarker)cm).t.key) + ")";