1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
8 /** Encapsulates a single JS interpreter (ie call stack) */
9 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 Vec stack = new Vec(); ///< the object stack
24 int pc = 0; ///< the program counter
26 Interpreter(JSFunction f, boolean pauseable, JSArray args) {
27 stack.push(new Interpreter.CallMarker(this)); // the "root function returned" marker -- f==null
29 this.pausecount = pauseable ? 0 : -1;
30 this.scope = new JSScope(f.parentScope);
34 /** this is the only synchronization point we need in order to be threadsafe */
35 synchronized Object resume() throws JSExn {
36 Thread t = Thread.currentThread();
37 Interpreter old = (Interpreter)threadToInterpreter.get(t);
38 threadToInterpreter.put(t, this);
42 if (old == null) threadToInterpreter.remove(t);
43 else threadToInterpreter.put(t, old);
47 private static JSExn je(String s) { return new JSExn(JS.getSourceName() + ":" + JS.getLine() + " " + s); }
49 // FIXME: double check the trap logic
50 private Object run() throws JSExn {
52 // if pausecount changes after a get/put/call, we know we've been paused
53 final int initialPauseCount = pausecount;
57 if (f == null) return stack.pop();
59 Object arg = f.arg[pc];
60 if(op == FINALLY_DONE) {
61 FinallyData fd = (FinallyData) stack.pop();
62 if(fd == null) continue OUTER; // NOP
67 case LITERAL: stack.push(arg); break;
68 case OBJECT: stack.push(new JS()); break;
69 case ARRAY: stack.push(new JSArray(JS.toNumber(arg).intValue())); break;
70 case DECLARE: scope.declare((String)(arg==null ? stack.peek() : arg)); if(arg != null) stack.push(arg); break;
71 case TOPSCOPE: stack.push(scope); break;
72 case JT: if (JS.toBoolean(stack.pop())) pc += JS.toNumber(arg).intValue() - 1; break;
73 case JF: if (!JS.toBoolean(stack.pop())) pc += JS.toNumber(arg).intValue() - 1; break;
74 case JMP: pc += JS.toNumber(arg).intValue() - 1; break;
75 case POP: stack.pop(); break;
77 int depth = (arg == null ? 1 : JS.toInt(arg));
78 Object save = stack.elementAt(stack.size() - 1);
79 for(int i=stack.size() - 1; i > stack.size() - 1 - depth; i--)
80 stack.setElementAt(stack.elementAt(i-1), i);
81 stack.setElementAt(save, stack.size() - depth - 1);
83 case DUP: stack.push(stack.peek()); break;
84 case NEWSCOPE: scope = new JSScope(scope); break;
85 case OLDSCOPE: scope = scope.getParentScope(); break;
86 case ASSERT: if (!JS.toBoolean(stack.pop())) throw je("assertion failed"); break;
87 case BITNOT: stack.push(JS.N(~JS.toLong(stack.pop()))); break;
88 case BANG: stack.push(JS.B(!JS.toBoolean(stack.pop()))); break;
89 case NEWFUNCTION: stack.push(((JSFunction)arg).cloneWithNewParentScope(scope)); break;
93 Object o = stack.pop();
94 if (o == null) stack.push(null);
95 else if (o instanceof JS) stack.push(((JS)o).typeName());
96 else if (o instanceof String) stack.push("string");
97 else if (o instanceof Number) stack.push("number");
98 else if (o instanceof Boolean) stack.push("boolean");
99 else stack.push("unknown");
104 Object o = stack.peek();
105 Enumeration e = ((JS)o).keys();
106 JSArray a = new JSArray();
107 while(e.hasMoreElements()) a.addElement(e.nextElement());
113 stack.push(new LoopMarker(pc, pc > 0 && f.op[pc - 1] == LABEL ? (String)f.arg[pc - 1] : (String)null, scope));
114 stack.push(Boolean.TRUE);
119 while(stack.size() > 0) {
120 Object o = stack.pop();
121 if (o instanceof CallMarker) je("break or continue not within a loop");
122 if (o instanceof TryMarker) {
123 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
124 stack.push(new FinallyData(op, arg));
125 scope = ((TryMarker)o).scope;
126 pc = ((TryMarker)o).finallyLoc - 1;
129 if (o instanceof LoopMarker) {
130 if (arg == null || arg.equals(((LoopMarker)o).label)) {
131 int loopInstructionLocation = ((LoopMarker)o).location;
132 int endOfLoop = ((Integer)f.arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
133 scope = ((LoopMarker)o).scope;
134 if (op == CONTINUE) { stack.push(o); stack.push(Boolean.FALSE); }
135 pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
140 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
141 JS.getSourceName() + ":" + JS.getLine());
144 int[] jmps = (int[]) arg;
145 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
146 // each can be < 0 if the specified block does not exist
147 stack.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1], scope));
152 Object retval = stack.pop();
153 while(stack.size() > 0) {
154 Object o = stack.pop();
155 if (o instanceof TryMarker) {
156 if(((TryMarker)o).finallyLoc < 0) continue;
158 stack.push(new FinallyData(RETURN));
159 scope = ((TryMarker)o).scope;
160 pc = ((TryMarker)o).finallyLoc - 1;
162 } else if (o instanceof CallMarker) {
163 if (scope instanceof Trap.TrapScope) { // handles return component of a read trap
164 Trap.TrapScope ts = (Trap.TrapScope)scope;
165 if (retval != null) ts.cascadeHappened = true;
166 if (!ts.cascadeHappened) {
167 ts.cascadeHappened = true;
169 while (t != null && t.f.numFormalArgs == 0) t = t.next;
171 ((JS)ts.t.trapee).put(ts.t.name, ts.val);
172 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
175 JSArray args = new JSArray();
176 args.addElement(ts.val);
179 scope = new Trap.TrapScope(f.parentScope, t, ts.val);
185 scope = ((CallMarker)o).scope;
186 pc = ((CallMarker)o).pc - 1;
187 f = (JSFunction)((CallMarker)o).f;
192 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
196 Object val = stack.pop();
197 Object key = stack.pop();
198 Object target = stack.peek();
200 throw je("tried to put a value to the " + key + " property on the null value");
201 if (!(target instanceof JS))
202 throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
204 throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
207 if (target instanceof Trap.TrapScope && key.equals("cascade")) {
208 Trap.TrapScope ts = (Trap.TrapScope)target;
210 ts.cascadeHappened = true;
211 while (t != null && t.f.numFormalArgs == 0) t = t.next;
212 if (t == null) { target = ts.t.trapee; key = ts.t.name; }
214 } else if (target instanceof Trap.TrapScope && key.equals(((Trap.TrapScope)target).t.name)) {
215 throw je("tried to put to " + key + " inside a trap it owns; use cascade instead");
217 } else if (target instanceof JS) {
218 if (target instanceof JSScope) {
219 JSScope p = (JSScope)target; // search the scope-path for the trap
221 while (t == null && p.getParentScope() != null) { p = p.getParentScope(); t = p.getTrap(key); }
223 t = ((JS)target).getTrap(key);
226 while (t != null && t.f.numFormalArgs == 0) t = t.next; // find the first write trap
228 stack.push(new CallMarker(this));
229 JSArray args = new JSArray();
230 args.addElement(val);
236 scope = new Trap.TrapScope(f.parentScope, t, val);
240 ((JS)target).put(key, val);
241 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
250 v = arg == null ? stack.pop() : arg;
258 if (v == null) throw je("tried to get the null key from " + o);
259 if (o == null) throw je("tried to get property \"" + v + "\" from the null object");
260 if (o instanceof String || o instanceof Number || o instanceof Boolean) {
261 ret = getFromPrimitive(o,v);
264 } else if (o instanceof JS) {
266 if (o instanceof Trap.TrapScope && v.equals("cascade")) {
267 t = ((Trap.TrapScope)o).t.next;
268 while (t != null && t.f.numFormalArgs != 0) t = t.next;
269 if (t == null) { v = ((Trap.TrapScope)o).t.name; o = ((Trap.TrapScope)o).t.trapee; }
271 } else if (o instanceof JS) {
272 if (o instanceof JSScope) {
273 JSScope p = (JSScope)o; // search the scope-path for the trap
275 while (t == null && p.getParentScope() != null) { p = p.getParentScope(); t = p.getTrap(v); }
277 t = ((JS)o).getTrap(v);
280 while (t != null && t.f.numFormalArgs != 0) t = t.next; // get first read trap
282 stack.push(new CallMarker(this));
283 JSArray args = new JSArray();
289 scope = new Trap.TrapScope(f.parentScope, t, null);
290 ((Trap.TrapScope)scope).cascadeHappened = true;
294 ret = ((JS)o).get(v);
295 if (ret == JS.METHOD) ret = new Stub((JS)o, v);
296 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
300 throw je("tried to get property " + v + " from a " + o.getClass().getName());
303 case CALL: case CALLMETHOD: {
304 int numArgs = JS.toInt(arg);
305 Object method = null;
307 Object object = stack.pop();
309 if (op == CALLMETHOD) {
310 if (object == JS.METHOD) {
311 method = stack.pop();
312 object = stack.pop();
313 } else if (object == null) {
314 Object name = stack.pop();
316 throw new JSExn("function '"+name+"' not found");
322 Object[] rest = numArgs > 3 ? new Object[numArgs - 3] : null;
323 for(int i=numArgs - 1; i>2; i--) rest[i-3] = stack.pop();
324 Object a2 = numArgs <= 2 ? null : stack.pop();
325 Object a1 = numArgs <= 1 ? null : stack.pop();
326 Object a0 = numArgs <= 0 ? null : stack.pop();
328 if (object instanceof String || object instanceof Number || object instanceof Boolean) {
329 ret = callMethodOnPrimitive(object, method, a0, a1, a2, null, numArgs);
331 } else if (object instanceof JSFunction) {
332 // FIXME: use something similar to call0/call1/call2 here
333 JSArray arguments = new JSArray();
334 for(int i=0; i<numArgs; i++) arguments.addElement(i==0?a0:i==1?a1:i==2?a2:rest[i-3]);
335 stack.push(new CallMarker(this));
336 stack.push(arguments);
337 f = (JSFunction)object;
338 scope = new JSScope(f.parentScope);
342 } else if (object instanceof JS) {
344 ret = method == null ? c.call(a0, a1, a2, rest, numArgs) : c.callMethod(method, a0, a1, a2, rest, numArgs);
347 throw new JSExn("can't call a " + object + " @" + pc + "\n" + f.dump());
350 if (pausecount > initialPauseCount) { pc++; return null; }
356 Object o = stack.pop();
357 if(o instanceof JSExn) throw (JSExn)o;
361 case ASSIGN_SUB: case ASSIGN_ADD: {
362 Object val = stack.pop();
363 Object old = stack.pop();
364 Object key = stack.pop();
365 Object obj = stack.peek();
366 if (val instanceof JSFunction && obj instanceof JSScope) {
367 JSScope parent = (JSScope)obj;
368 while(parent.getParentScope() != null) parent = parent.getParentScope();
369 if (parent instanceof JS) {
371 if (op == ASSIGN_ADD) b.addTrap(key, (JSFunction)val);
372 else b.delTrap(key, (JSFunction)val);
373 // skip over the "normal" implementation of +=/-=
374 pc += ((Integer)arg).intValue() - 1;
378 // use the "normal" implementation
386 int count = ((Number)arg).intValue();
387 if(count < 2) throw new Error("this should never happen");
390 Object right = stack.pop();
391 Object left = stack.pop();
392 if(left instanceof String || right instanceof String)
393 stack.push(JS.toString(left).concat(JS.toString(right)));
394 else stack.push(JS.N(JS.toDouble(left) + JS.toDouble(right)));
396 Object[] args = new Object[count];
397 while(--count >= 0) args[count] = stack.pop();
398 if(args[0] instanceof String) {
399 StringBuffer sb = new StringBuffer(64);
400 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
401 stack.push(sb.toString());
404 for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
405 if(numStrings == 0) {
407 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
411 StringBuffer sb = new StringBuffer(64);
412 if(!(args[0] instanceof String || args[1] instanceof String)) {
415 d += JS.toDouble(args[i++]);
416 } while(!(args[i] instanceof String));
417 sb.append(JS.toString(JS.N(d)));
419 while(i < args.length) sb.append(JS.toString(args[i++]));
420 stack.push(sb.toString());
428 Object right = stack.pop();
429 Object left = stack.pop();
432 case BITOR: stack.push(JS.N(JS.toLong(left) | JS.toLong(right))); break;
433 case BITXOR: stack.push(JS.N(JS.toLong(left) ^ JS.toLong(right))); break;
434 case BITAND: stack.push(JS.N(JS.toLong(left) & JS.toLong(right))); break;
436 case SUB: stack.push(JS.N(JS.toDouble(left) - JS.toDouble(right))); break;
437 case MUL: stack.push(JS.N(JS.toDouble(left) * JS.toDouble(right))); break;
438 case DIV: stack.push(JS.N(JS.toDouble(left) / JS.toDouble(right))); break;
439 case MOD: stack.push(JS.N(JS.toDouble(left) % JS.toDouble(right))); break;
441 case LSH: stack.push(JS.N(JS.toLong(left) << JS.toLong(right))); break;
442 case RSH: stack.push(JS.N(JS.toLong(left) >> JS.toLong(right))); break;
443 case URSH: stack.push(JS.N(JS.toLong(left) >>> JS.toLong(right))); break;
445 case LT: case LE: case GT: case GE: {
446 if (left == null) left = JS.N(0);
447 if (right == null) right = JS.N(0);
449 if (left instanceof String || right instanceof String) {
450 result = left.toString().compareTo(right.toString());
452 result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
454 stack.push(JS.B((op == LT && result < 0) || (op == LE && result <= 0) ||
455 (op == GT && result > 0) || (op == GE && result >= 0)));
464 if (l == null) { Object tmp = r; r = l; l = tmp; }
465 if (l == null && r == null) ret = true;
466 else if (r == null) ret = false; // l != null, so its false
467 else if (l instanceof Boolean) ret = JS.B(JS.toBoolean(r)).equals(l);
468 else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
469 else if (l instanceof String) ret = r != null && l.equals(r.toString());
470 else ret = l.equals(r);
471 stack.push(JS.B(op == EQ ? ret : !ret)); break;
474 default: throw new Error("unknown opcode " + op);
479 while(stack.size() > 0) {
480 Object o = stack.pop();
481 if (o instanceof CatchMarker || o instanceof TryMarker) {
482 boolean inCatch = o instanceof CatchMarker;
485 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
487 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
488 // run the catch block, this will implicitly run the finally block, if it exists
490 stack.push(catchMarker);
491 stack.push(e.getObject());
492 scope = ((TryMarker)o).scope;
493 pc = ((TryMarker)o).catchLoc - 1;
497 stack.push(new FinallyData(THROW));
498 scope = ((TryMarker)o).scope;
499 pc = ((TryMarker)o).finallyLoc - 1;
503 // no handler found within this func
504 if(o instanceof CallMarker) throw e;
513 // Markers //////////////////////////////////////////////////////////////////////
515 public static class CallMarker {
519 public CallMarker(Interpreter cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
522 public static class CatchMarker { public CatchMarker() { } }
523 private static CatchMarker catchMarker = new CatchMarker();
525 public static class LoopMarker {
528 public JSScope scope;
529 public LoopMarker(int location, String label, JSScope scope) {
530 this.location = location;
535 public static class TryMarker {
537 public int finallyLoc;
538 public JSScope scope;
539 public TryMarker(int catchLoc, int finallyLoc, JSScope scope) {
540 this.catchLoc = catchLoc;
541 this.finallyLoc = finallyLoc;
545 public static class FinallyData {
548 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
549 public FinallyData(int op) { this(op,null); }
553 // Operations on Primitives //////////////////////////////////////////////////////////////////////
555 static Object callMethodOnPrimitive(Object o, Object method, Object arg0, Object arg1, Object arg2, Object[] rest, int alength) throws JSExn {
556 if (method == null || !(method instanceof String) || "".equals(method))
557 throw new JSExn("attempt to call a non-existant method on a primitive");
559 if (o instanceof Number) {
561 case "toFixed": throw new JSExn("toFixed() not implemented");
562 case "toExponential": throw new JSExn("toExponential() not implemented");
563 case "toPrecision": throw new JSExn("toPrecision() not implemented");
565 int radix = alength >= 1 ? JS.toInt(arg0) : 10;
566 return Long.toString(((Number)o).longValue(),radix);
569 } else if (o instanceof Boolean) {
570 // No methods for Booleans
571 throw new JSExn("attempt to call a method on a Boolean");
574 String s = JS.toString(o);
575 int slength = s.length();
578 int a = alength >= 1 ? JS.toInt(arg0) : 0;
579 int b = alength >= 2 ? JS.toInt(arg1) : slength;
580 if (a > slength) a = slength;
581 if (b > slength) b = slength;
584 if (a > b) { int tmp = a; a = b; b = tmp; }
585 return s.substring(a,b);
588 int start = alength >= 1 ? JS.toInt(arg0) : 0;
589 int len = alength >= 2 ? JS.toInt(arg1) : Integer.MAX_VALUE;
590 if (start < 0) start = slength + start;
591 if (start < 0) start = 0;
592 if (len < 0) len = 0;
593 if (len > slength - start) len = slength - start;
594 if (len <= 0) return "";
595 return s.substring(start,start+len);
598 int p = alength >= 1 ? JS.toInt(arg0) : 0;
599 if (p < 0 || p >= slength) return "";
600 return s.substring(p,p+1);
603 int p = alength >= 1 ? JS.toInt(arg0) : 0;
604 if (p < 0 || p >= slength) return JS.N(Double.NaN);
605 return JS.N(s.charAt(p));
608 StringBuffer sb = new StringBuffer(slength*2).append(s);
609 for(int i=0;i<alength;i++) sb.append(i==0?arg0:i==1?arg1:i==2?arg2:rest[i-3]);
610 return sb.toString();
613 String search = alength >= 1 ? arg0.toString() : "null";
614 int start = alength >= 2 ? JS.toInt(arg1) : 0;
615 // Java's indexOf handles an out of bounds start index, it'll return -1
616 return JS.N(s.indexOf(search,start));
618 case "lastIndexOf": {
619 String search = alength >= 1 ? arg0.toString() : "null";
620 int start = alength >= 2 ? JS.toInt(arg1) : 0;
621 // Java's indexOf handles an out of bounds start index, it'll return -1
622 return JS.N(s.lastIndexOf(search,start));
624 case "match": return JSRegexp.stringMatch(s,arg0);
625 case "replace": return JSRegexp.stringReplace(s,(String)arg0,arg1);
626 case "search": return JSRegexp.stringSearch(s,arg0);
627 case "split": return JSRegexp.stringSplit(s,arg0,arg1,alength);
628 case "toLowerCase": return s.toLowerCase();
629 case "toUpperCase": return s.toUpperCase();
630 case "toString": return s;
632 int a = alength >= 1 ? JS.toInt(arg0) : 0;
633 int b = alength >= 2 ? JS.toInt(arg1) : slength;
634 if (a < 0) a = slength + a;
635 if (b < 0) b = slength + b;
638 if (a > slength) a = slength;
639 if (b > slength) b = slength;
640 if (a > b) return "";
641 return s.substring(a,b);
644 throw new JSExn("Attempted to call non-existent method: " + method);
647 static Object getFromPrimitive(Object o, Object key) throws JSExn {
648 boolean returnJS = false;
649 if (o instanceof Boolean) {
650 throw new JSExn("cannot call methods on Booleans");
651 } else if (o instanceof Number) {
652 if (key.equals("toPrecision") || key.equals("toExponential") || key.equals("toFixed"))
656 // the string stuff applies to everything
657 String s = o.toString();
659 // this is sort of ugly, but this list should never change
660 // These should provide a complete (enough) implementation of the ECMA-262 String object
663 case "length": return JS.N(s.length());
664 case "substring": returnJS = true; break;
665 case "charAt": returnJS = true; break;
666 case "charCodeAt": returnJS = true; break;
667 case "concat": returnJS = true; break;
668 case "indexOf": returnJS = true; break;
669 case "lastIndexOf": returnJS = true; break;
670 case "match": returnJS = true; break;
671 case "replace": returnJS = true; break;
672 case "seatch": returnJS = true; break;
673 case "slice": returnJS = true; break;
674 case "split": returnJS = true; break;
675 case "toLowerCase": returnJS = true; break;
676 case "toUpperCase": returnJS = true; break;
677 case "toString": returnJS = true; break;
678 case "substr": returnJS = true; break;
682 final Object target = o;
683 final String method = key.toString();
685 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
686 if (nargs > 2) throw new JSExn("cannot call that method with that many arguments");
687 return callMethodOnPrimitive(target, method, a0, a1, a2, rest, nargs);
694 private static class Stub extends JS {
695 private Object method;
697 public Stub(JS obj, Object method) { this.obj = obj; this.method = method; }
698 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
699 return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs);