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
63 if(fd.exn != null) throw fd.exn;
68 case LITERAL: stack.push(arg); break;
69 case OBJECT: stack.push(new JS()); break;
70 case ARRAY: stack.push(new JSArray(JS.toNumber(arg).intValue())); break;
71 case DECLARE: scope.declare((String)(arg==null ? stack.peek() : arg)); if(arg != null) stack.push(arg); break;
72 case TOPSCOPE: stack.push(scope); break;
73 case JT: if (JS.toBoolean(stack.pop())) pc += JS.toNumber(arg).intValue() - 1; break;
74 case JF: if (!JS.toBoolean(stack.pop())) pc += JS.toNumber(arg).intValue() - 1; break;
75 case JMP: pc += JS.toNumber(arg).intValue() - 1; break;
76 case POP: stack.pop(); break;
78 int depth = (arg == null ? 1 : JS.toInt(arg));
79 Object save = stack.elementAt(stack.size() - 1);
80 for(int i=stack.size() - 1; i > stack.size() - 1 - depth; i--)
81 stack.setElementAt(stack.elementAt(i-1), i);
82 stack.setElementAt(save, stack.size() - depth - 1);
84 case DUP: stack.push(stack.peek()); break;
85 case NEWSCOPE: scope = new JSScope(scope); break;
86 case OLDSCOPE: scope = scope.getParentScope(); break;
87 case ASSERT: if (!JS.toBoolean(stack.pop())) throw je("xwt.assertion.failed" /*FEATURE: line number*/); break;
88 case BITNOT: stack.push(JS.N(~JS.toLong(stack.pop()))); break;
89 case BANG: stack.push(JS.B(!JS.toBoolean(stack.pop()))); break;
90 case NEWFUNCTION: stack.push(((JSFunction)arg).cloneWithNewParentScope(scope)); break;
94 Object o = stack.pop();
95 if (o == null) stack.push(null);
96 else if (o instanceof JS) stack.push(((JS)o).typeName());
97 else if (o instanceof String) stack.push("string");
98 else if (o instanceof Number) stack.push("number");
99 else if (o instanceof Boolean) stack.push("boolean");
100 else stack.push("unknown");
105 Object o = stack.peek();
106 Enumeration e = ((JS)o).keys();
107 JSArray a = new JSArray();
108 while(e.hasMoreElements()) a.addElement(e.nextElement());
114 stack.push(new LoopMarker(pc, pc > 0 && f.op[pc - 1] == LABEL ? (String)f.arg[pc - 1] : (String)null, scope));
115 stack.push(Boolean.TRUE);
120 while(stack.size() > 0) {
121 Object o = stack.pop();
122 if (o instanceof CallMarker) je("break or continue not within a loop");
123 if (o instanceof TryMarker) {
124 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
125 stack.push(new FinallyData(op, arg));
126 scope = ((TryMarker)o).scope;
127 pc = ((TryMarker)o).finallyLoc - 1;
130 if (o instanceof LoopMarker) {
131 if (arg == null || arg.equals(((LoopMarker)o).label)) {
132 int loopInstructionLocation = ((LoopMarker)o).location;
133 int endOfLoop = ((Integer)f.arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
134 scope = ((LoopMarker)o).scope;
135 if (op == CONTINUE) { stack.push(o); stack.push(Boolean.FALSE); }
136 pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
141 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
142 JS.getSourceName() + ":" + JS.getLine());
145 int[] jmps = (int[]) arg;
146 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
147 // each can be < 0 if the specified block does not exist
148 stack.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1], this));
153 Object retval = stack.pop();
154 while(stack.size() > 0) {
155 Object o = stack.pop();
156 if (o instanceof TryMarker) {
157 if(((TryMarker)o).finallyLoc < 0) continue;
159 stack.push(new FinallyData(RETURN));
160 scope = ((TryMarker)o).scope;
161 pc = ((TryMarker)o).finallyLoc - 1;
163 } else if (o instanceof CallMarker) {
164 if (scope instanceof Trap.TrapScope) { // handles return component of a read trap
165 Trap.TrapScope ts = (Trap.TrapScope)scope;
166 if (retval != null && retval instanceof Boolean && ((Boolean)retval).booleanValue())
167 ts.cascadeHappened = true;
168 if (!ts.cascadeHappened) {
169 ts.cascadeHappened = true;
171 while (t != null && t.f.numFormalArgs == 0) t = t.next;
173 ((JS)ts.t.trapee).put(ts.t.name, ts.val);
174 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
177 JSArray args = new JSArray();
178 args.addElement(ts.val);
181 scope = new Trap.TrapScope(f.parentScope, t, ts.val);
187 scope = ((CallMarker)o).scope;
188 pc = ((CallMarker)o).pc - 1;
189 f = (JSFunction)((CallMarker)o).f;
194 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
198 Object val = stack.pop();
199 Object key = stack.pop();
200 Object target = stack.peek();
202 throw je("tried to put a value to the " + key + " property on the null value");
203 if (!(target instanceof JS))
204 throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
206 throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
209 if (target instanceof Trap.TrapScope && key.equals("cascade")) {
210 Trap.TrapScope ts = (Trap.TrapScope)target;
212 ts.cascadeHappened = true;
213 while (t != null && t.f.numFormalArgs == 0) t = t.next;
214 if (t == null) { target = ts.t.trapee; key = ts.t.name; }
216 } else if (target instanceof Trap.TrapScope && key.equals(((Trap.TrapScope)target).t.name)) {
217 throw je("tried to put to " + key + " inside a trap it owns; use cascade instead");
219 } else if (target instanceof JS) {
220 if (target instanceof JSScope) {
221 JSScope p = (JSScope)target; // search the scope-path for the trap
223 while (t == null && p.getParentScope() != null) { p = p.getParentScope(); t = p.getTrap(key); }
225 t = ((JS)target).getTrap(key);
228 while (t != null && t.f.numFormalArgs == 0) t = t.next; // find the first write trap
230 stack.push(new CallMarker(this));
231 JSArray args = new JSArray();
232 args.addElement(val);
238 scope = new Trap.TrapScope(f.parentScope, t, val);
242 ((JS)target).put(key, val);
243 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
252 v = arg == null ? stack.pop() : arg;
260 if (v == null) throw je("tried to get the null key from " + o);
261 if (o == null) throw je("tried to get property \"" + v + "\" from the null object");
262 if (o instanceof String || o instanceof Number || o instanceof Boolean) {
263 ret = getFromPrimitive(o,v);
266 } else if (o instanceof JS) {
268 if (o instanceof Trap.TrapScope && v.equals("cascade")) {
269 t = ((Trap.TrapScope)o).t.next;
270 while (t != null && t.f.numFormalArgs != 0) t = t.next;
271 if (t == null) { v = ((Trap.TrapScope)o).t.name; o = ((Trap.TrapScope)o).t.trapee; }
273 } else if (o instanceof JS) {
274 if (o instanceof JSScope) {
275 JSScope p = (JSScope)o; // search the scope-path for the trap
277 while (t == null && p.getParentScope() != null) { p = p.getParentScope(); t = p.getTrap(v); }
279 t = ((JS)o).getTrap(v);
282 while (t != null && t.f.numFormalArgs != 0) t = t.next; // get first read trap
284 stack.push(new CallMarker(this));
285 JSArray args = new JSArray();
291 scope = new Trap.TrapScope(f.parentScope, t, null);
292 ((Trap.TrapScope)scope).cascadeHappened = true;
296 ret = ((JS)o).get(v);
297 if (ret == JS.METHOD) ret = new Stub((JS)o, v);
298 if (pausecount > initialPauseCount) { pc++; return null; } // we were paused
302 throw je("tried to get property " + v + " from a " + o.getClass().getName());
305 case CALL: case CALLMETHOD: {
306 int numArgs = JS.toInt(arg);
307 Object method = null;
309 Object object = stack.pop();
311 if (op == CALLMETHOD) {
312 if (object == JS.METHOD) {
313 method = stack.pop();
314 object = stack.pop();
315 } else if (object == null) {
316 Object name = stack.pop();
318 throw new JSExn("function '"+name+"' not found");
324 Object[] rest = numArgs > 3 ? new Object[numArgs - 3] : null;
325 for(int i=numArgs - 1; i>2; i--) rest[i-3] = stack.pop();
326 Object a2 = numArgs <= 2 ? null : stack.pop();
327 Object a1 = numArgs <= 1 ? null : stack.pop();
328 Object a0 = numArgs <= 0 ? null : stack.pop();
330 if (object instanceof String || object instanceof Number || object instanceof Boolean) {
331 ret = callMethodOnPrimitive(object, method, a0, a1, a2, null, numArgs);
333 } else if (object instanceof JSFunction) {
334 // FIXME: use something similar to call0/call1/call2 here
335 JSArray arguments = new JSArray();
336 for(int i=0; i<numArgs; i++) arguments.addElement(i==0?a0:i==1?a1:i==2?a2:rest[i-3]);
337 stack.push(new CallMarker(this));
338 stack.push(arguments);
339 f = (JSFunction)object;
340 scope = new JSScope(f.parentScope);
344 } else if (object instanceof JS) {
346 ret = method == null ? c.call(a0, a1, a2, rest, numArgs) : c.callMethod(method, a0, a1, a2, rest, numArgs);
349 throw new JSExn("can't call a " + object + " @" + pc + "\n" + f.dump());
352 if (pausecount > initialPauseCount) { pc++; return null; }
358 throw new JSExn(stack.pop());
361 final Grammar r = (Grammar)arg;
362 final JSScope final_scope = scope;
363 Grammar r2 = new Grammar() {
364 public int match(String s, int start, Hash v, JSScope scope) throws JSExn {
365 return r.match(s, start, v, final_scope);
367 public int matchAndWrite(String s, int start, Hash v, JSScope scope, String key) throws JSExn {
368 return r.matchAndWrite(s, start, v, final_scope, key);
370 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
372 r.matchAndWrite((String)a0, 0, v, final_scope, "foo");
376 Object obj = stack.pop();
377 if (obj != null && obj instanceof Grammar) r2 = new Grammar.Alternative((Grammar)obj, r2);
382 case ASSIGN_SUB: case ASSIGN_ADD: {
383 Object val = stack.pop();
384 Object key = stack.pop();
385 Object obj = stack.peek();
386 if (val instanceof JSFunction && obj instanceof JS) {
387 // A trap addition/removal
388 JS js = obj instanceof JSScope ? ((JSScope)obj).top() : (JS) obj;
389 if(op == ASSIGN_ADD) js.addTrap(key, (JSFunction)val);
390 else js.delTrap(key, (JSFunction)val);
391 pc += ((Integer)arg).intValue() - 1;
393 // The following setup is VERY important. The generated bytecode depends on the stack
394 // being setup like this (top to bottom) KEY, OBJ, VAL, KEY, OBJ
404 int count = ((Number)arg).intValue();
405 if(count < 2) throw new Error("this should never happen");
408 Object right = stack.pop();
409 Object left = stack.pop();
410 if(left instanceof String || right instanceof String)
411 stack.push(JS.toString(left).concat(JS.toString(right)));
412 else stack.push(JS.N(JS.toDouble(left) + JS.toDouble(right)));
414 Object[] args = new Object[count];
415 while(--count >= 0) args[count] = stack.pop();
416 if(args[0] instanceof String) {
417 StringBuffer sb = new StringBuffer(64);
418 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
419 stack.push(sb.toString());
422 for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
423 if(numStrings == 0) {
425 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
429 StringBuffer sb = new StringBuffer(64);
430 if(!(args[0] instanceof String || args[1] instanceof String)) {
433 d += JS.toDouble(args[i++]);
434 } while(!(args[i] instanceof String));
435 sb.append(JS.toString(JS.N(d)));
437 while(i < args.length) sb.append(JS.toString(args[i++]));
438 stack.push(sb.toString());
446 Object right = stack.pop();
447 Object left = stack.pop();
450 case BITOR: stack.push(JS.N(JS.toLong(left) | JS.toLong(right))); break;
451 case BITXOR: stack.push(JS.N(JS.toLong(left) ^ JS.toLong(right))); break;
452 case BITAND: stack.push(JS.N(JS.toLong(left) & JS.toLong(right))); break;
454 case SUB: stack.push(JS.N(JS.toDouble(left) - JS.toDouble(right))); break;
455 case MUL: stack.push(JS.N(JS.toDouble(left) * JS.toDouble(right))); break;
456 case DIV: stack.push(JS.N(JS.toDouble(left) / JS.toDouble(right))); break;
457 case MOD: stack.push(JS.N(JS.toDouble(left) % JS.toDouble(right))); break;
459 case LSH: stack.push(JS.N(JS.toLong(left) << JS.toLong(right))); break;
460 case RSH: stack.push(JS.N(JS.toLong(left) >> JS.toLong(right))); break;
461 case URSH: stack.push(JS.N(JS.toLong(left) >>> JS.toLong(right))); break;
463 case LT: case LE: case GT: case GE: {
464 if (left == null) left = JS.N(0);
465 if (right == null) right = JS.N(0);
467 if (left instanceof String || right instanceof String) {
468 result = left.toString().compareTo(right.toString());
470 result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
472 stack.push(JS.B((op == LT && result < 0) || (op == LE && result <= 0) ||
473 (op == GT && result > 0) || (op == GE && result >= 0)));
482 if (l == null) { Object tmp = r; r = l; l = tmp; }
483 if (l == null && r == null) ret = true;
484 else if (r == null) ret = false; // l != null, so its false
485 else if (l instanceof Boolean) ret = JS.B(JS.toBoolean(r)).equals(l);
486 else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
487 else if (l instanceof String) ret = r != null && l.equals(r.toString());
488 else ret = l.equals(r);
489 stack.push(JS.B(op == EQ ? ret : !ret)); break;
492 default: throw new Error("unknown opcode " + op);
497 if(f.op[pc] != FINALLY_DONE) e.addBacktrace(f.sourceName,f.line[pc]);
498 while(stack.size() > 0) {
499 Object o = stack.pop();
500 if (o instanceof CatchMarker || o instanceof TryMarker) {
501 boolean inCatch = o instanceof CatchMarker;
504 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
506 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
507 // run the catch block, this will implicitly run the finally block, if it exists
509 stack.push(catchMarker);
510 stack.push(e.getObject());
511 f = ((TryMarker)o).f;
512 scope = ((TryMarker)o).scope;
513 pc = ((TryMarker)o).catchLoc - 1;
516 stack.push(new FinallyData(e));
517 f = ((TryMarker)o).f;
518 scope = ((TryMarker)o).scope;
519 pc = ((TryMarker)o).finallyLoc - 1;
522 } else if(o instanceof CallMarker) {
523 CallMarker cm = (CallMarker) o;
525 e.addBacktrace("<java>",0); // This might not even be worth mentioning
527 e.addBacktrace(cm.f.sourceName,cm.f.line[cm.pc-1]);
537 // Markers //////////////////////////////////////////////////////////////////////
539 public static class CallMarker {
543 public CallMarker(Interpreter cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
546 public static class CatchMarker { public CatchMarker() { } }
547 private static CatchMarker catchMarker = new CatchMarker();
549 public static class LoopMarker {
552 public JSScope scope;
553 public LoopMarker(int location, String label, JSScope scope) {
554 this.location = location;
559 public static class TryMarker {
561 public int finallyLoc;
562 public JSScope scope;
564 public TryMarker(int catchLoc, int finallyLoc, Interpreter cx) {
565 this.catchLoc = catchLoc;
566 this.finallyLoc = finallyLoc;
567 this.scope = cx.scope;
571 public static class FinallyData {
575 public FinallyData(int op) { this(op,null); }
576 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
577 public FinallyData(JSExn exn) { this.exn = exn; } // Just throw this exn
581 // Operations on Primitives //////////////////////////////////////////////////////////////////////
583 static Object callMethodOnPrimitive(Object o, Object method, Object arg0, Object arg1, Object arg2, Object[] rest, int alength) throws JSExn {
584 if (method == null || !(method instanceof String) || "".equals(method))
585 throw new JSExn("attempt to call a non-existant method on a primitive");
587 if (o instanceof Number) {
589 case "toFixed": throw new JSExn("toFixed() not implemented");
590 case "toExponential": throw new JSExn("toExponential() not implemented");
591 case "toPrecision": throw new JSExn("toPrecision() not implemented");
593 int radix = alength >= 1 ? JS.toInt(arg0) : 10;
594 return Long.toString(((Number)o).longValue(),radix);
597 } else if (o instanceof Boolean) {
598 // No methods for Booleans
599 throw new JSExn("attempt to call a method on a Boolean");
602 String s = JS.toString(o);
603 int slength = s.length();
606 int a = alength >= 1 ? JS.toInt(arg0) : 0;
607 int b = alength >= 2 ? JS.toInt(arg1) : slength;
608 if (a > slength) a = slength;
609 if (b > slength) b = slength;
612 if (a > b) { int tmp = a; a = b; b = tmp; }
613 return s.substring(a,b);
616 int start = alength >= 1 ? JS.toInt(arg0) : 0;
617 int len = alength >= 2 ? JS.toInt(arg1) : Integer.MAX_VALUE;
618 if (start < 0) start = slength + start;
619 if (start < 0) start = 0;
620 if (len < 0) len = 0;
621 if (len > slength - start) len = slength - start;
622 if (len <= 0) return "";
623 return s.substring(start,start+len);
626 int p = alength >= 1 ? JS.toInt(arg0) : 0;
627 if (p < 0 || p >= slength) return "";
628 return s.substring(p,p+1);
631 int p = alength >= 1 ? JS.toInt(arg0) : 0;
632 if (p < 0 || p >= slength) return JS.N(Double.NaN);
633 return JS.N(s.charAt(p));
636 StringBuffer sb = new StringBuffer(slength*2).append(s);
637 for(int i=0;i<alength;i++) sb.append(i==0?arg0:i==1?arg1:i==2?arg2:rest[i-3]);
638 return sb.toString();
641 String search = alength >= 1 ? arg0.toString() : "null";
642 int start = alength >= 2 ? JS.toInt(arg1) : 0;
643 // Java's indexOf handles an out of bounds start index, it'll return -1
644 return JS.N(s.indexOf(search,start));
646 case "lastIndexOf": {
647 String search = alength >= 1 ? arg0.toString() : "null";
648 int start = alength >= 2 ? JS.toInt(arg1) : 0;
649 // Java's indexOf handles an out of bounds start index, it'll return -1
650 return JS.N(s.lastIndexOf(search,start));
652 case "match": return JSRegexp.stringMatch(s,arg0);
653 case "replace": return JSRegexp.stringReplace(s,arg0,arg1);
654 case "search": return JSRegexp.stringSearch(s,arg0);
655 case "split": return JSRegexp.stringSplit(s,arg0,arg1,alength);
656 case "toLowerCase": return s.toLowerCase();
657 case "toUpperCase": return s.toUpperCase();
658 case "toString": return s;
660 int a = alength >= 1 ? JS.toInt(arg0) : 0;
661 int b = alength >= 2 ? JS.toInt(arg1) : slength;
662 if (a < 0) a = slength + a;
663 if (b < 0) b = slength + b;
666 if (a > slength) a = slength;
667 if (b > slength) b = slength;
668 if (a > b) return "";
669 return s.substring(a,b);
672 throw new JSExn("Attempted to call non-existent method: " + method);
675 static Object getFromPrimitive(Object o, Object key) throws JSExn {
676 boolean returnJS = false;
677 if (o instanceof Boolean) {
678 throw new JSExn("cannot call methods on Booleans");
679 } else if (o instanceof Number) {
680 if (key.equals("toPrecision") || key.equals("toExponential") || key.equals("toFixed"))
684 // the string stuff applies to everything
685 String s = o.toString();
687 // this is sort of ugly, but this list should never change
688 // These should provide a complete (enough) implementation of the ECMA-262 String object
691 case "length": return JS.N(s.length());
692 case "substring": returnJS = true; break;
693 case "charAt": returnJS = true; break;
694 case "charCodeAt": returnJS = true; break;
695 case "concat": returnJS = true; break;
696 case "indexOf": returnJS = true; break;
697 case "lastIndexOf": returnJS = true; break;
698 case "match": returnJS = true; break;
699 case "replace": returnJS = true; break;
700 case "seatch": returnJS = true; break;
701 case "slice": returnJS = true; break;
702 case "split": returnJS = true; break;
703 case "toLowerCase": returnJS = true; break;
704 case "toUpperCase": returnJS = true; break;
705 case "toString": returnJS = true; break;
706 case "substr": returnJS = true; break;
710 final Object target = o;
711 final String method = key.toString();
713 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
714 if (nargs > 2) throw new JSExn("cannot call that method with that many arguments");
715 return callMethodOnPrimitive(target, method, a0, a1, a2, rest, nargs);
722 private static class Stub extends JS {
723 private Object method;
725 public Stub(JS obj, Object method) { this.obj = obj; this.method = method; }
726 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
727 return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs);