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() {
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) {
164 Trap.TrapScope ts = (Trap.TrapScope)scope;
165 if (!ts.cascadeHappened) {
166 ts.cascadeHappened = true;
168 while (t != null && t.f.numFormalArgs == 0) t = t.next;
170 ((JS)ts.t.trapee).put(t.name, ts.val);
171 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
174 JSArray args = new JSArray();
175 args.addElement(ts.val);
178 scope = new Trap.TrapScope(f.parentScope, t, ts.val);
184 scope = ((CallMarker)o).scope;
185 pc = ((CallMarker)o).pc;
186 f = (JSFunction)((CallMarker)o).f;
191 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
195 Object val = stack.pop();
196 Object key = stack.pop();
197 Object target = stack.peek();
199 throw je("tried to put a value to the " + key + " property on the null value");
200 if (!(target instanceof JS))
201 throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
203 throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
205 if (target instanceof JS) {
206 t = ((JS)target).getTrap(val);
207 while (t != null && t.f.numFormalArgs == 0) t = t.next;
208 } else if (target instanceof Trap.TrapScope && key.equals("cascade")) {
209 Trap.TrapScope ts = (Trap.TrapScope)target;
211 ts.cascadeHappened = true;
212 while (t != null && t.f.numFormalArgs == 0) t = t.next;
213 if (t == null) target = ts.t.trapee;
216 stack.push(new CallMarker(this));
217 JSArray args = new JSArray();
218 args.addElement(val);
221 scope = new Trap.TrapScope(f.parentScope, t, val);
225 ((JS)target).put(key, val);
226 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
235 v = arg == null ? stack.pop() : arg;
243 if (v == null) throw je("tried to get the null key from " + o);
244 if (o == null) throw je("tried to get property \"" + v + "\" from the null value @" + pc + "\n" + f.dump());
245 if (o instanceof String || o instanceof Number || o instanceof Boolean) {
246 ret = getFromPrimitive(o,v);
249 } else if (o instanceof JS) {
251 if (o instanceof JS) {
252 t = ((JS)o).getTrap(v);
253 while (t != null && t.f.numFormalArgs != 0) t = t.next;
254 } else if (o instanceof Trap.TrapScope && v.equals("cascade")) {
255 t = ((Trap.TrapScope)o).t.next;
256 while (t != null && t.f.numFormalArgs != 0) t = t.next;
257 if (t == null) o = ((Trap.TrapScope)o).t.trapee;
260 stack.push(new CallMarker(this));
261 JSArray args = new JSArray();
264 scope = new Trap.TrapScope(f.parentScope, t, null);
265 ((Trap.TrapScope)scope).cascadeHappened = true;
269 ret = ((JS)o).get(v);
270 if (ret == JS.METHOD) ret = new Stub((JS)o, v);
271 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
275 throw je("tried to get property " + v + " from a " + o.getClass().getName());
278 case CALL: case CALLMETHOD: {
279 int numArgs = JS.toInt(arg);
280 Object method = null;
282 Object object = stack.pop();
284 if (op == CALLMETHOD) {
285 if (object == JS.METHOD) {
286 method = stack.pop();
287 object = stack.pop();
294 if (object instanceof String || object instanceof Number || object instanceof Boolean) {
295 if (numArgs > 2) throw new JSExn("too many arguments to primitive method");
296 Object arg1 = numArgs >= 2 ? stack.pop() : null;
297 Object arg0 = numArgs >= 1 ? stack.pop() : null;
298 ret = callMethodOnPrimitive(object, method, arg0, arg1, numArgs);
300 } else if (object instanceof JSFunction) {
301 // FEATURE: use something similar to call0/call1/call2 here
302 JSArray arguments = new JSArray();
303 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(stack.pop(), j);
304 stack.push(new CallMarker(this));
305 stack.push(arguments);
306 f = (JSFunction)object;
307 scope = new JSScope(f.parentScope);
311 } else if (object instanceof JS) {
313 Object[] rest = numArgs > 3 ? new Object[numArgs - 3] : null;
314 for(int i=numArgs - 1; i>2; i--) rest[i-3] = stack.pop();
315 Object a2 = numArgs <= 2 ? null : stack.pop();
316 Object a1 = numArgs <= 1 ? null : stack.pop();
317 Object a0 = numArgs <= 0 ? null : stack.pop();
318 ret = method == null ? c.call(a0, a1, a2, rest, numArgs) : c.callMethod(method, a0, a1, a2, rest, numArgs);
321 throw new JSExn("can't call a " + object + " @" + pc + "\n" + f.dump());
324 if (pausecount > initialPauseCount) { pc++; return null; }
330 Object o = stack.pop();
331 if(o instanceof JSExn) throw (JSExn)o;
335 case ASSIGN_SUB: case ASSIGN_ADD: {
336 Object val = stack.pop();
337 Object old = stack.pop();
338 Object key = stack.pop();
339 Object obj = stack.peek();
340 if (val instanceof JSFunction && obj instanceof JSScope) {
341 JSScope parent = (JSScope)obj;
342 while(parent.getParentScope() != null) parent = parent.getParentScope();
343 if (parent instanceof JS) {
345 if (op == ASSIGN_ADD) b.addTrap(key, (JSFunction)val);
346 else b.delTrap(key, (JSFunction)val);
347 // skip over the "normal" implementation of +=/-=
348 pc += ((Integer)arg).intValue() - 1;
352 // use the "normal" implementation
360 int count = ((Number)arg).intValue();
361 if(count < 2) throw new Error("this should never happen");
364 Object right = stack.pop();
365 Object left = stack.pop();
366 if(left instanceof String || right instanceof String)
367 stack.push(JS.toString(left).concat(JS.toString(right)));
368 else stack.push(JS.N(JS.toDouble(left) + JS.toDouble(right)));
370 Object[] args = new Object[count];
371 while(--count >= 0) args[count] = stack.pop();
372 if(args[0] instanceof String) {
373 StringBuffer sb = new StringBuffer(64);
374 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
375 stack.push(sb.toString());
378 for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
379 if(numStrings == 0) {
381 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
385 StringBuffer sb = new StringBuffer(64);
386 if(!(args[0] instanceof String || args[1] instanceof String)) {
389 d += JS.toDouble(args[i++]);
390 } while(!(args[i] instanceof String));
391 sb.append(JS.toString(JS.N(d)));
393 while(i < args.length) sb.append(JS.toString(args[i++]));
394 stack.push(sb.toString());
402 Object right = stack.pop();
403 Object left = stack.pop();
406 case BITOR: stack.push(JS.N(JS.toLong(left) | JS.toLong(right))); break;
407 case BITXOR: stack.push(JS.N(JS.toLong(left) ^ JS.toLong(right))); break;
408 case BITAND: stack.push(JS.N(JS.toLong(left) & JS.toLong(right))); break;
410 case SUB: stack.push(JS.N(JS.toDouble(left) - JS.toDouble(right))); break;
411 case MUL: stack.push(JS.N(JS.toDouble(left) * JS.toDouble(right))); break;
412 case DIV: stack.push(JS.N(JS.toDouble(left) / JS.toDouble(right))); break;
413 case MOD: stack.push(JS.N(JS.toDouble(left) % JS.toDouble(right))); break;
415 case LSH: stack.push(JS.N(JS.toLong(left) << JS.toLong(right))); break;
416 case RSH: stack.push(JS.N(JS.toLong(left) >> JS.toLong(right))); break;
417 case URSH: stack.push(JS.N(JS.toLong(left) >>> JS.toLong(right))); break;
419 case LT: case LE: case GT: case GE: {
420 if (left == null) left = JS.N(0);
421 if (right == null) right = JS.N(0);
423 if (left instanceof String || right instanceof String) {
424 result = left.toString().compareTo(right.toString());
426 result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
428 stack.push(JS.B((op == LT && result < 0) || (op == LE && result <= 0) ||
429 (op == GT && result > 0) || (op == GE && result >= 0)));
438 if (l == null) { Object tmp = r; r = l; l = tmp; }
439 if (l == null && r == null) ret = true;
440 else if (r == null) ret = false; // l != null, so its false
441 else if (l instanceof Boolean) ret = JS.B(JS.toBoolean(r)).equals(l);
442 else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
443 else if (l instanceof String) ret = r != null && l.equals(r.toString());
444 else ret = l.equals(r);
445 stack.push(JS.B(op == EQ ? ret : !ret)); break;
448 default: throw new Error("unknown opcode " + op);
453 while(stack.size() > 0) {
454 Object o = stack.pop();
455 if (o instanceof CatchMarker || o instanceof TryMarker) {
456 boolean inCatch = o instanceof CatchMarker;
459 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
461 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
462 // run the catch block, this will implicitly run the finally block, if it exists
464 stack.push(catchMarker);
465 stack.push(e.getObject());
466 scope = ((TryMarker)o).scope;
467 pc = ((TryMarker)o).catchLoc - 1;
471 stack.push(new FinallyData(THROW));
472 scope = ((TryMarker)o).scope;
473 pc = ((TryMarker)o).finallyLoc - 1;
477 // no handler found within this func
478 if(o instanceof CallMarker) throw e;
487 // Markers //////////////////////////////////////////////////////////////////////
489 public static class CallMarker {
493 public CallMarker(Interpreter cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
496 public static class CatchMarker { public CatchMarker() { } }
497 private static CatchMarker catchMarker = new CatchMarker();
499 public static class LoopMarker {
502 public JSScope scope;
503 public LoopMarker(int location, String label, JSScope scope) {
504 this.location = location;
509 public static class TryMarker {
511 public int finallyLoc;
512 public JSScope scope;
513 public TryMarker(int catchLoc, int finallyLoc, JSScope scope) {
514 this.catchLoc = catchLoc;
515 this.finallyLoc = finallyLoc;
519 public static class FinallyData {
522 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
523 public FinallyData(int op) { this(op,null); }
527 // Operations on Primitives //////////////////////////////////////////////////////////////////////
529 static Object callMethodOnPrimitive(Object o, Object method, Object arg0, Object arg1, int alength) {
530 if (o instanceof Number) {
532 case "toFixed": throw new JSExn("toFixed() not implemented");
533 case "toExponential": throw new JSExn("toExponential() not implemented");
534 case "toPrecision": throw new JSExn("toPrecision() not implemented");
536 int radix = alength >= 1 ? JS.toInt(arg0) : 10;
537 return Long.toString(((Number)o).longValue(),radix);
540 } else if (o instanceof Boolean) {
541 // No methods for Booleans
542 throw new JSExn("attempt to call a method on a Boolean");
545 String s = JS.toString(o);
546 int slength = s.length();
549 int a = alength >= 1 ? JS.toInt(arg0) : 0;
550 int b = alength >= 2 ? JS.toInt(arg1) : slength;
551 if (a > slength) a = slength;
552 if (b > slength) b = slength;
555 if (a > b) { int tmp = a; a = b; b = tmp; }
556 return s.substring(a,b);
559 int start = alength >= 1 ? JS.toInt(arg0) : 0;
560 int len = alength >= 2 ? JS.toInt(arg1) : Integer.MAX_VALUE;
561 if (start < 0) start = slength + start;
562 if (start < 0) start = 0;
563 if (len < 0) len = 0;
564 if (len > slength - start) len = slength - start;
565 if (len <= 0) return "";
566 return s.substring(start,start+len);
569 int p = alength >= 1 ? JS.toInt(arg0) : 0;
570 if (p < 0 || p >= slength) return "";
571 return s.substring(p,p+1);
574 int p = alength >= 1 ? JS.toInt(arg0) : 0;
575 if (p < 0 || p >= slength) return JS.N(Double.NaN);
576 return JS.N(s.charAt(p));
579 // FIXME takes variable number of arguments...
581 StringBuffer sb = new StringBuffer(slength*2).append(s);
582 for(int i=0;i<alength;i++) sb.append(args.elementAt(i));
583 return sb.toString();
587 String search = alength >= 1 ? arg0.toString() : "null";
588 int start = alength >= 2 ? JS.toInt(arg1) : 0;
589 // Java's indexOf handles an out of bounds start index, it'll return -1
590 return JS.N(s.indexOf(search,start));
592 case "lastIndexOf": {
593 String search = alength >= 1 ? arg0.toString() : "null";
594 int start = alength >= 2 ? JS.toInt(arg1) : 0;
595 // Java's indexOf handles an out of bounds start index, it'll return -1
596 return JS.N(s.lastIndexOf(search,start));
598 case "match": return JSRegexp.stringMatch(s,arg0);
599 case "replace": return JSRegexp.stringReplace(s,(String)arg0,arg1);
600 case "search": return JSRegexp.stringSearch(s,arg0);
601 case "split": return JSRegexp.stringSplit(s,(String)arg0,arg1);
602 case "toLowerCase": return s.toLowerCase();
603 case "toUpperCase": return s.toUpperCase();
604 case "toString": return s;
606 int a = alength >= 1 ? JS.toInt(arg0) : 0;
607 int b = alength >= 2 ? JS.toInt(arg1) : slength;
608 if (a < 0) a = slength + a;
609 if (b < 0) b = slength + b;
612 if (a > slength) a = slength;
613 if (b > slength) b = slength;
614 if (a > b) return "";
615 return s.substring(a,b);
618 throw new JSExn("Attempted to call non-existent method: " + method);
621 static Object getFromPrimitive(Object o, Object key) {
622 boolean returnJS = false;
623 if (o instanceof Boolean) {
624 throw new JSExn("cannot call methods on Booleans");
625 } else if (o instanceof Number) {
626 if (key.equals("toPrecision") || key.equals("toExponential") || key.equals("toFixed"))
630 // the string stuff applies to everything
631 String s = o.toString();
633 // this is sort of ugly, but this list should never change
634 // These should provide a complete (enough) implementation of the ECMA-262 String object
637 case "length": return JS.N(s.length());
638 case "substring": returnJS = true; break;
639 case "charAt": returnJS = true; break;
640 case "charCodeAt": returnJS = true; break;
641 case "concat": returnJS = true; break;
642 case "indexOf": returnJS = true; break;
643 case "lastIndexOf": returnJS = true; break;
644 case "match": returnJS = true; break;
645 case "replace": returnJS = true; break;
646 case "seatch": returnJS = true; break;
647 case "slice": returnJS = true; break;
648 case "split": returnJS = true; break;
649 case "toLowerCase": returnJS = true; break;
650 case "toUpperCase": returnJS = true; break;
651 case "toString": returnJS = true; break;
652 case "substr": returnJS = true; break;
656 final Object target = o;
657 final String method = key.toString();
659 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) {
660 if (nargs > 2) throw new JSExn("cannot call that method with that many arguments");
661 return callMethodOnPrimitive(target, method, a0, a1, nargs);
668 private static class Stub extends JS {
669 private Object method;
671 public Stub(JS obj, Object method) { this.obj = obj; this.method = method; }
672 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) {
673 return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs);