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, Pausable {
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, JS[] 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
32 stack.push(new JSArgs(args, f)); // FIXME: temprorary bug fix
34 throw new Error("should never happen");
38 Interpreter(JS.Trap t, JS val, boolean pauseOnPut) {
41 setupTrap(t,val,new TrapMarker(null,t,val,pauseOnPut));
43 throw new Error("should never happen");
47 private boolean get = false;
48 // FIXME: split this stuff out into a Script instance control object
49 // so it's possible to make JS either single or multi threaded.
50 /** this is the only synchronization point we need in order to be threadsafe */
51 public synchronized Object run(Object o) throws JSExn {
52 if (f == null) throw new AlreadyRunningException("function already finished");
53 if (scope == null) throw new RuntimeException("scope is null");
55 Thread t = Thread.currentThread();
56 Interpreter old = (Interpreter)threadToInterpreter.get(t);
57 threadToInterpreter.put(t, this);
59 if (get) stack.push(o);
64 if (old == null) threadToInterpreter.remove(t);
65 else threadToInterpreter.put(t, old);
69 public void pause() throws NotPausableException {
70 if (pausecount == -1 || f == null) throw new NotPausableException();
73 case Tokens.RETURN: case ByteCodes.PUT: get = false; break;
74 case ByteCodes.GET: case ByteCodes.CALL: get = true; break;
75 default: throw new Error("paused on unexpected bytecode: " + f.op[pc]);
79 static int getLine() {
80 Interpreter c = Interpreter.current();
81 return c == null || c.f == null || c.pc < 0 || c.pc >= c.f.size ? -1 : c.f.line[c.pc];
84 static String getSourceName() {
85 Interpreter c = Interpreter.current();
86 return c == null || c.f == null ? null : c.f.sourceName;
89 private static JSExn je(String s) { return new JSExn(getSourceName() + ":" + getLine() + " " + s); }
91 private JS run() throws JSExn {
93 // if pausecount changes after a get/put/call, we know we've been paused
94 final int initialPauseCount = pausecount;
99 Object arg = f.arg[pc];
100 if(op == FINALLY_DONE) {
101 FinallyData fd = (FinallyData) stack.pop();
102 if(fd == null) continue OUTER; // NOP
103 if(fd.exn != null) throw fd.exn;
108 case LITERAL: stack.push((JS)arg); break;
109 case OBJECT: stack.push(new JS.Obj()); break;
110 case ARRAY: stack.push(new JSArray(JSU.toInt((JS)arg))); break;
111 //case DECLARE: scope.declare((JS)(arg==null ? stack.peek() : arg)); if(arg != null) stack.push((JS)arg); break;
112 case JT: if (JSU.toBoolean((JS)stack.pop())) pc += JSU.toInt((JS)arg) - 1; break;
113 case JF: if (!JSU.toBoolean((JS)stack.pop())) pc += JSU.toInt((JS)arg) - 1; break;
114 case JMP: pc += JSU.toInt((JS)arg) - 1; break;
115 case POP: stack.pop(); break;
116 case SWAP: stack.swap(); break;
117 case DUP: stack.push(stack.peek()); break;
119 int n = JSU.toInt((JS)arg);
120 scope = new JSScope(scope,(n>>>16)&0xffff,(n>>>0)&0xffff);
123 case OLDSCOPE: scope = scope.parent; break;
124 case GLOBALSCOPE: stack.push(scope.getGlobal()); break;
125 case SCOPEGET: stack.push(scope.get((JS)arg)); break;
127 // FIXME: HACK: share this around more and find the callee.
128 Object val = stack.peek();
129 if (val != null && val instanceof JS[]) val = new JSArgs((JS[])val, null);
130 scope.put((JS)arg, (JS)val); break;
132 case ASSERT: if (!JSU.toBoolean((JS)stack.pop())) throw je("ibex.assertion.failed"); break;
133 case BITNOT: stack.push(JSU.N(~JSU.toLong((JS)stack.pop()))); break;
134 case BANG: stack.push(JSU.B(!JSU.toBoolean((JS)stack.pop()))); break;
135 case NEWFUNCTION: stack.push(((JSFunction)arg)._cloneWithNewParentScope(scope)); break;
139 Object o = stack.pop();
140 if (o == null) stack.push(null);
141 else if (o instanceof JSString) stack.push(JSU.S("string"));
142 else if (o instanceof JSNumber.B) stack.push(JSU.S("boolean"));
143 else if (o instanceof JSNumber) stack.push(JSU.S("number"));
144 else stack.push(JSU.S("object"));
149 JS o = (JS)stack.peek();
150 stack.push(o == null ? null : o.keys());
155 stack.push(new LoopMarker(pc, (String)(pc > 0 && f.op[pc - 1] == LABEL ? f.arg[pc - 1] : null), scope));
161 while(!stack.empty()) {
162 JS o = (JS)stack.pop();
163 if (o instanceof CallMarker) je("break or continue not within a loop");
164 if (o instanceof TryMarker) {
165 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
166 stack.push(new FinallyData(op, arg));
167 scope = ((TryMarker)o).scope;
168 pc = ((TryMarker)o).finallyLoc - 1;
171 if (o instanceof LoopMarker) {
172 if (arg == null || arg.equals(((LoopMarker)o).label)) {
173 int loopInstructionLocation = ((LoopMarker)o).location;
174 int endOfLoop = JSU.toInt((JS)f.arg[loopInstructionLocation]) + loopInstructionLocation;
175 scope = ((LoopMarker)o).scope;
176 if (op == CONTINUE) { stack.push(o); stack.push(JSU.F); }
177 pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
182 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
183 getSourceName() + ":" + getLine());
186 int[] jmps = (int[]) arg;
187 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
188 // each can be < 0 if the specified block does not exist
189 stack.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1], this));
194 JS retval = (JS)stack.pop();
195 while(!stack.empty()) {
196 Object o = stack.pop();
197 if (o instanceof TryMarker) {
198 if(((TryMarker)o).finallyLoc < 0) continue;
200 stack.push(new FinallyData(RETURN));
201 scope = ((TryMarker)o).scope;
202 pc = ((TryMarker)o).finallyLoc - 1;
204 } else if (o instanceof CallMarker) {
205 boolean didTrapPut = false;
206 if (o instanceof TrapMarker) { // handles return component of a write trap
207 TrapMarker tm = (TrapMarker) o;
208 boolean cascade = tm.t.isWriteTrap() && !tm.cascadeHappened && !JSU.toBoolean(retval);
210 JS.Trap t = tm.t.nextWrite();
211 if(t == null && tm.t.target() instanceof JS.Clone) {
212 t = ((JS.Clone)tm.t.target()).clonee.getTrap(tm.t.key());
213 if(t != null && !t.isWriteTrap()) t = t.nextWrite();
216 tm.t = t; // we reuse the old trap marker
217 setupTrap(t, tm.val, tm);
218 pc--; // we increment it on the next iter
222 if(!tm.pauseOnPut) tm.t.target().put(tm.t.key(), tm.val);
226 CallMarker cm = (CallMarker) o;
231 if (((TrapMarker)cm).pauseOnPut) { pc++; return ((TrapMarker)cm).val; }
232 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
236 if (f == null) return retval;
240 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
244 boolean write = JSU.toBoolean((JS)arg);
245 JS val = write ? (JS)stack.pop() : null;
246 CallMarker o = stack.findCall();
247 if(!(o instanceof TrapMarker)) throw new JSExn("tried to CASCADE while not in a trap");
248 TrapMarker tm = (TrapMarker) o;
250 JS target = tm.t.target();
251 if(tm.t.isWriteTrap() != write)
252 throw new JSExn("tried to do a "+(write?"write":"read") + " cascade in a " + (write?"read":"write") + " trap");
253 JS.Trap t = write ? tm.t.nextWrite() : tm.t.nextRead();
254 while (t == null && target instanceof JS.Clone) {
255 target = ((JS.Clone)target).clonee;
256 t = target.getTrap(key);
257 if(t != null) t = write ? t.write() : t.read();
260 tm.cascadeHappened = true;
264 setupTrap(t,val,new TrapMarker(this,t,val,tm.pauseOnPut));
265 pc--; // we increment later
268 if (tm.pauseOnPut) { pc++; return val; }
271 JS ret = target.get(key);
272 if (ret != null && ret instanceof JS.Method) ret = new Stub(target, key);
275 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
281 JS val = (JS)stack.pop();
282 JS key = (JS)stack.pop();
283 JS target = (JS)stack.peek();
284 if (target == null) throw je("tried to put " + JSU.str(val) + " to the " + JSU.str(key) + " property on the null value");
285 if (key == null) throw je("tried to assign \"" + JSU.str(val) + "\" to the null key");
287 JS.Trap t = target.getTrap(key);
288 if(t != null) t = t.write();
290 if(t == null && target instanceof JS.Clone) {
291 target = ((JS.Clone)target).clonee;
292 t = target.getTrap(key);
293 if(t != null) t = t.nextWrite();
299 setupTrap(t,val,new TrapMarker(this,t,val));
300 pc--; // we increment later
303 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
312 key = arg == null ? (JS)stack.pop() : (JS)arg;
313 target = (JS)stack.pop();
315 key = (JS)stack.pop();
316 target = (JS)stack.peek();
320 if (key == null) throw je("tried to get the null key from " + JSU.str(target));
321 if (target == null) throw je("tried to get property \"" + JSU.str(key) + "\" from the null object");
324 try { t = target.getTrap(key); } catch (JSExn e) {}
325 if(t != null) t = t.read();
327 if(t == null && target instanceof JS.Clone) {
328 target = ((JS.Clone)target).clonee;
329 t = target.getTrap(key);
330 if(t != null) t = t.nextRead();
334 setupTrap(t,null,new TrapMarker(this,t,null));
335 pc--; // we increment later
337 ret = target.get(key);
338 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
340 if (ret != null && ret instanceof JS.Method) ret = new Stub(target, key);
346 case CALL: case CALLMETHOD: {
348 if (arg instanceof JSNumber.I) {
349 // FIXME: we should be able to recycle JS[]'s here
350 jsargs = new JS[((JSNumber.I)arg).toInt()];
351 for (int i=0; i < jsargs.length; i++) jsargs[i] = (JS)stack.pop();
352 } else jsargs = (JS[])arg;
356 JS object = (JS)stack.pop();
358 if (op == CALLMETHOD) {
359 if (object == null) {
360 method = (JS)stack.pop();
361 object = (JS)stack.pop();
362 throw new JSExn("function '"+JSU.str(method)+"' not found in " + object.getClass().getName());
363 } else if (object instanceof JS.Method) {
364 method = (JS)stack.pop();
365 object = (JS)stack.pop();
372 if (object instanceof JSFunction) {
373 stack.push(new CallMarker(this));
375 f = (JSFunction)object;
376 scope = f.parentScope;
381 ret = c.call(method, jsargs);
384 if (pausecount > initialPauseCount) { pc++; return null; }
390 throw new JSExn((JS)stack.pop(), this);
392 case ADD_TRAP: case DEL_TRAP: {
393 JS val = (JS)stack.pop();
394 JS key = (JS)stack.pop();
395 JS 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, val);
399 else js.delTrap(key, val);
404 int count = ((JSNumber)arg).toInt();
405 if(count < 2) throw new Error("this should never happen");
408 JS right = (JS)stack.pop();
409 JS left = (JS)stack.pop();
411 if(left instanceof JSString || right instanceof JSString)
412 ret = JSU.S(JSU.toString(left).concat(JSU.toString(right)));
413 else if(left instanceof JSNumber.D || right instanceof JSNumber.D)
414 ret = JSU.N(JSU.toDouble(left) + JSU.toDouble(right));
416 long l = JSU.toLong(left) + JSU.toLong(right);
417 if(l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) ret = JSU.N(l);
422 JS[] args = new JS[count];
423 while(--count >= 0) args[count] = (JS)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(JSU.toString(args[i]));
427 stack.push(JSU.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 += JSU.toDouble(args[i]);
434 stack.push(JSU.N(d));
437 StringBuffer sb = new StringBuffer(64);
438 if(!(args[0] instanceof JSString || args[1] instanceof JSString)) {
441 d += JSU.toDouble(args[i++]);
442 } while(!(args[i] instanceof JSString));
443 sb.append(JSU.toString(JSU.N(d)));
445 while(i < args.length) sb.append(JSU.toString(args[i++]));
446 stack.push(JSU.S(sb.toString()));
454 JS right = (JS)stack.pop();
455 JS left = (JS)stack.pop();
458 case BITOR: stack.push(JSU.N(JSU.toLong(left) | JSU.toLong(right))); break;
459 case BITXOR: stack.push(JSU.N(JSU.toLong(left) ^ JSU.toLong(right))); break;
460 case BITAND: stack.push(JSU.N(JSU.toLong(left) & JSU.toLong(right))); break;
462 case SUB: stack.push(JSU.N(JSU.toDouble(left) - JSU.toDouble(right))); break;
463 case MUL: stack.push(JSU.N(JSU.toDouble(left) * JSU.toDouble(right))); break;
464 case DIV: stack.push(JSU.N(JSU.toDouble(left) / JSU.toDouble(right))); break;
465 case MOD: stack.push(JSU.N(JSU.toDouble(left) % JSU.toDouble(right))); break;
467 case LSH: stack.push(JSU.N(JSU.toLong(left) << JSU.toLong(right))); break;
468 case RSH: stack.push(JSU.N(JSU.toLong(left) >> JSU.toLong(right))); break;
469 case URSH: stack.push(JSU.N(JSU.toLong(left) >>> JSU.toLong(right))); break;
471 //#repeat </<=/>/>= LT/LE/GT/GE
473 if(left instanceof JSString && right instanceof JSString)
474 stack.push(JSU.B(JSU.toString(left).compareTo(JSU.toString(right)) < 0));
476 stack.push(JSU.B(JSU.toDouble(left) < JSU.toDouble(right)));
483 if(left == null && right == null) ret = true;
484 else if(left == null || right == null) ret = false;
485 else ret = left.equals(right);
486 stack.push(JSU.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()) {
506 Object o = stack.pop();
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(JS.Trap t, JS val, CallMarker cm) throws JSExn {
536 stack.push(new TrapArgs(t, val));
537 f = (JSFunction)t.function();
538 scope = f.parentScope;
543 // Markers //////////////////////////////////////////////////////////////////////
545 static class Marker {}
547 static class CallMarker extends Marker {
551 public CallMarker(Interpreter cx) {
552 pc = cx == null ? -1 : cx.pc + 1;
553 scope = cx == null ? null : cx.scope;
554 f = cx == null ? null : cx.f;
558 static class TrapMarker extends CallMarker {
561 boolean cascadeHappened;
562 final boolean pauseOnPut;
563 public TrapMarker(Interpreter cx, JS.Trap t, JS val) { this(cx,t,val,false); }
564 public TrapMarker(Interpreter cx, JS.Trap t, JS val, boolean pauseOnPut) {
568 this.pauseOnPut = pauseOnPut;
572 static class CatchMarker extends Marker { }
573 private static final CatchMarker catchMarker = new CatchMarker();
575 static class LoopMarker extends Marker {
576 final public int location;
577 final public String label;
578 final public JSScope scope;
579 public LoopMarker(int location, String label, JSScope scope) {
580 this.location = location;
585 static class TryMarker extends Marker {
586 final public int catchLoc;
587 final public int finallyLoc;
588 final public JSScope scope;
589 final public JSFunction f;
590 public TryMarker(int catchLoc, int finallyLoc, Interpreter cx) {
591 this.catchLoc = catchLoc;
592 this.finallyLoc = finallyLoc;
593 this.scope = cx.scope;
597 static class FinallyData extends Marker {
599 final public Object arg;
600 final public JSExn exn;
601 public FinallyData(int op) { this(op,null); }
602 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; this.exn = null; }
603 public FinallyData(JSExn exn) { this.exn = exn; this.op = -1; this.arg = null; } // Just throw this exn
606 static class JSArgs extends JS.Immutable {
607 private final JS[] args;
608 private final JS callee;
610 public JSArgs(JS[] args, JS callee) { this.args = args; this.callee = callee; }
612 public JS get(JS key) throws JSExn {
613 if(JSU.isInt(key)) return args[JSU.toInt(key)];
614 //#switch(JSU.toString(key))
615 case "callee": return callee;
616 case "length": return JSU.N(args.length);
618 return super.get(key);
622 static class TrapArgs extends JS.Immutable {
625 public TrapArgs(Trap t, JS val) { this.t = t; this.val = val; }
626 public JS get(JS key) throws JSExn {
627 if(JSU.isInt(key) && JSU.toInt(key) == 0) return val;
628 //#switch(JSU.str(key))
629 case "trapee": return t.target();
630 case "callee": return t.function();
631 case "trapname": return t.key();
632 case "length": return t.isWriteTrap() ? JSU.ONE : JSU.ZERO;
634 return super.get(key);
638 static class Stub extends JS.Immutable {
641 public Stub(JS obj, JS method) { this.obj = obj; this.method = method; }
642 public JS call(JS method, JS[] args) throws JSExn {
643 if (method==null) return obj.call(this.method, args);
644 return super.call(method, args);
648 static final class Stack {
649 private static final int MAX_STACK_SIZE = 512;
650 private Object[] stack = new Object[8];
653 boolean empty() { return sp == 0; }
654 void push(Object o) throws JSExn { if(sp == stack.length) grow(); stack[sp++] = o; }
655 Object peek() { if(sp == 0) throw new RuntimeException("stack underflow"); return stack[sp-1]; }
656 final Object pop() { if(sp == 0) throw new RuntimeException("stack underflow"); return stack[--sp]; }
657 void swap() throws JSExn {
658 if(sp < 2) throw new JSExn("stack overflow");
659 Object tmp = stack[sp-2];
660 stack[sp-2] = stack[sp-1];
663 CallMarker findCall() {
664 for(int i=sp-1;i>=0;i--) if(stack[i] instanceof CallMarker) return (CallMarker) stack[i];
667 void grow() throws JSExn {
668 if(stack.length >= MAX_STACK_SIZE) throw new JSExn("stack overflow");
669 Object[] stack2 = new Object[stack.length * 2];
670 System.arraycopy(stack,0,stack2,0,stack.length);
674 void backtrace(JSExn e) {
675 for(int i=sp-1;i>=0;i--) {
676 if (stack[i] instanceof CallMarker) {
677 CallMarker cm = (CallMarker)stack[i];
678 if(cm.f == null) break;
679 String s = cm.f.sourceName + ":" + cm.f.line[cm.pc-1];
680 if(cm instanceof Interpreter.TrapMarker)
681 s += " (trap on " + JSU.str(((Interpreter.TrapMarker)cm).t.key()) + ")";