1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
8 class Interpreter implements ByteCodes, Tokens {
10 static Object eval(final JSContext cx) throws JS.Exn {
11 final int initialPauseCount = cx.pausecount;
12 OUTER: for(;; cx.pc++) {
14 if (cx.f == null || cx.pc >= cx.f.size) return cx.stack.pop();
15 int op = cx.f.op[cx.pc];
16 Object arg = cx.f.arg[cx.pc];
17 if(op == FINALLY_DONE) {
18 FinallyData fd = (FinallyData) cx.stack.pop();
19 if(fd == null) continue OUTER; // NOP
24 case LITERAL: cx.stack.push(arg); break;
25 case OBJECT: cx.stack.push(new JS()); break;
26 case ARRAY: cx.stack.push(new JSArray(JS.toNumber(arg).intValue())); break;
27 case DECLARE: cx.scope.declare((String)(arg==null ? cx.stack.peek() : arg)); if(arg != null) cx.stack.push(arg); break;
28 case TOPSCOPE: cx.stack.push(cx.scope); break;
29 case JT: if (JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(arg).intValue() - 1; break;
30 case JF: if (!JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(arg).intValue() - 1; break;
31 case JMP: cx.pc += JS.toNumber(arg).intValue() - 1; break;
32 case POP: cx.stack.pop(); break;
34 int depth = (arg == null ? 1 : JS.toInt(arg));
35 Object save = cx.stack.elementAt(cx.stack.size() - 1);
36 for(int i=cx.stack.size() - 1; i > cx.stack.size() - 1 - depth; i--)
37 cx.stack.setElementAt(cx.stack.elementAt(i-1), i);
38 cx.stack.setElementAt(save, cx.stack.size() - depth - 1);
40 case DUP: cx.stack.push(cx.stack.peek()); break;
41 case NEWSCOPE: cx.scope = new JSScope(cx.scope); break;
42 case OLDSCOPE: cx.scope = cx.scope.getParentJSScope(); break;
43 case ASSERT: if (!JS.toBoolean(cx.stack.pop())) throw je("assertion failed"); break;
44 case BITNOT: cx.stack.push(new Long(~JS.toLong(cx.stack.pop()))); break;
45 case BANG: cx.stack.push(new Boolean(!JS.toBoolean(cx.stack.pop()))); break;
46 case NEWFUNCTION: cx.stack.push(((JSFunction)arg).cloneWithNewParentJSScope(cx.scope)); break;
50 Object o = cx.stack.pop();
51 if (o == null) cx.stack.push(null);
52 else if (o instanceof JS) cx.stack.push(((JS)o).typeName());
53 else if (o instanceof String) cx.stack.push("string");
54 else if (o instanceof Number) cx.stack.push("number");
55 else if (o instanceof Boolean) cx.stack.push("boolean");
56 else cx.stack.push("unknown");
61 Object o = cx.stack.peek();
62 Enumeration e = ((JS)o).keys();
63 JSArray a = new JSArray();
64 while(e.hasMoreElements()) a.addElement(e.nextElement());
70 cx.stack.push(new LoopMarker(cx.pc, cx.pc > 0 && cx.f.op[cx.pc - 1] == LABEL ?
71 (String)cx.f.arg[cx.pc - 1] : (String)null, cx.scope));
72 cx.stack.push(Boolean.TRUE);
77 while(cx.stack.size() > 0) {
78 Object o = cx.stack.pop();
79 if (o instanceof CallMarker) ee("break or continue not within a loop");
80 if (o instanceof TryMarker) {
81 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
82 cx.stack.push(new FinallyData(op, arg));
83 cx.scope = ((TryMarker)o).scope;
84 cx.pc = ((TryMarker)o).finallyLoc - 1;
87 if (o instanceof LoopMarker) {
88 if (arg == null || arg.equals(((LoopMarker)o).label)) {
89 int loopInstructionLocation = ((LoopMarker)o).location;
90 int endOfLoop = ((Integer)cx.f.arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
91 cx.scope = ((LoopMarker)o).scope;
92 if (op == CONTINUE) { cx.stack.push(o); cx.stack.push(Boolean.FALSE); }
93 cx.pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
98 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
99 cx.getSourceName() + ":" + cx.getLine());
102 int[] jmps = (int[]) arg;
103 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
104 // each can be < 0 if the specified block does not exist
105 cx.stack.push(new TryMarker(jmps[0] < 0 ? -1 : cx.pc + jmps[0], jmps[1] < 0 ? -1 : cx.pc + jmps[1], cx.scope));
110 Object retval = cx.stack.pop();
111 while(cx.stack.size() > 0) {
112 Object o = cx.stack.pop();
113 if (o instanceof TryMarker) {
114 if(((TryMarker)o).finallyLoc < 0) continue;
115 cx.stack.push(retval);
116 cx.stack.push(new FinallyData(RETURN));
117 cx.scope = ((TryMarker)o).scope;
118 cx.pc = ((TryMarker)o).finallyLoc - 1;
120 } else if (o instanceof CallMarker) {
121 if (cx.scope instanceof JSTrap.JSTrapScope) {
122 JSTrap.JSTrapScope ts = (JSTrap.JSTrapScope)cx.scope;
123 if (!ts.cascadeHappened) {
124 ts.cascadeHappened = true;
125 JSTrap t = ts.t.next;
126 while (t != null && t.f.numFormalArgs == 0) t = t.next;
128 ((JS)ts.t.trapee).put(t.name, ts.val);
129 if (cx.pausecount > initialPauseCount) return null; // we were paused
132 JSArray args = new JSArray();
133 args.addElement(ts.val);
136 cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, ts.val);
142 cx.scope = ((CallMarker)o).scope;
143 cx.pc = ((CallMarker)o).pc;
144 cx.f = (JSFunction)((CallMarker)o).f;
145 cx.stack.push(retval);
149 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
153 Object val = cx.stack.pop();
154 Object key = cx.stack.pop();
155 Object target = cx.stack.peek();
157 throw je("tried to put a value to the " + key + " property on the null value");
158 if (!(target instanceof JS))
159 throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
161 throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
163 if (target instanceof JSTrap.JSTrappable) {
164 t = ((JSTrap.JSTrappable)target).getTrap(val);
165 while (t != null && t.f.numFormalArgs == 0) t = t.next;
166 } else if (target instanceof JSTrap.JSTrapScope && key.equals("cascade")) {
167 JSTrap.JSTrapScope ts = (JSTrap.JSTrapScope)target;
169 ts.cascadeHappened = true;
170 while (t != null && t.f.numFormalArgs == 0) t = t.next;
171 if (t == null) target = ts.t.trapee;
174 cx.stack.push(new CallMarker(cx));
175 JSArray args = new JSArray();
176 args.addElement(val);
179 cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, val);
183 ((JS)target).put(key, val);
184 if (cx.pausecount > initialPauseCount) return null; // we were paused
193 v = arg == null ? cx.stack.pop() : arg;
201 if (v == null) throw je("tried to get the null key from " + o);
202 if (o == null) throw je("tried to get property \"" + v + "\" from the null value @" + cx.pc + "\n" + cx.f.dump());
203 if (o instanceof String || o instanceof Number || o instanceof Boolean) {
204 ret = Internal.getFromPrimitive(o,v);
207 } else if (o instanceof JS) {
209 if (o instanceof JSTrap.JSTrappable) {
210 t = ((JSTrap.JSTrappable)o).getTrap(v);
211 while (t != null && t.f.numFormalArgs != 0) t = t.next;
212 } else if (o instanceof JSTrap.JSTrapScope && v.equals("cascade")) {
213 t = ((JSTrap.JSTrapScope)o).t.next;
214 while (t != null && t.f.numFormalArgs != 0) t = t.next;
215 if (t == null) o = ((JSTrap.JSTrapScope)o).t.trapee;
218 cx.stack.push(new CallMarker(cx));
219 JSArray args = new JSArray();
222 cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, null);
223 ((JSTrap.JSTrapScope)cx.scope).cascadeHappened = true;
227 ret = ((JS)o).get(v);
228 if (ret == JSCallable.METHOD) ret = new Internal.JSCallableStub((JS)o, v);
229 if (cx.pausecount > initialPauseCount) return null; // we were paused
233 throw je("tried to get property " + v + " from a " + o.getClass().getName());
236 case CALL: case CALLMETHOD: {
237 int numArgs = JS.toInt(arg);
238 Object method = null;
240 Object object = cx.stack.pop();
243 object = cx.stack.pop();
245 if (object == JSCallable.METHOD) {
246 method = cx.stack.pop();
247 object = cx.stack.pop();
254 if (object instanceof String || object instanceof Number || object instanceof Boolean) {
255 JSArray arguments = new JSArray();
256 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
257 ret = Internal.callMethodOnPrimitive(object, method, arguments);
259 } else if (object instanceof JSFunction) {
260 // FEATURE: use something similar to call0/call1/call2 here
261 JSArray arguments = new JSArray();
262 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
263 cx.stack.push(new CallMarker(cx));
264 cx.stack.push(arguments);
265 cx.f = (JSFunction)object;
266 cx.scope = new JSScope(cx.f.parentJSScope);
270 } else if (object instanceof JSCallable) {
271 JSCallable c = (JSCallable)object;
272 Object[] rest = numArgs > 3 ? new Object[numArgs - 3] : null;
273 for(int i=numArgs - 1; i>2; i--) rest[i-3] = cx.stack.pop();
274 Object a2 = numArgs <= 2 ? null : cx.stack.pop();
275 Object a1 = numArgs <= 1 ? null : cx.stack.pop();
276 Object a0 = numArgs <= 0 ? null : cx.stack.pop();
277 ret = method == null ? c.call(a0, a1, a2, rest, numArgs) : c.callMethod(method, a0, a1, a2, rest, numArgs);
280 throw new JS.Exn("can't call a " + object.getClass().getName() + " @" + cx.pc + "\n" + cx.f.dump());
283 if (cx.pausecount > initialPauseCount) return null;
289 Object o = cx.stack.pop();
290 if(o instanceof JS.Exn) throw (JS.Exn)o;
294 case ASSIGN_SUB: case ASSIGN_ADD: {
295 Object val = cx.stack.pop();
296 Object old = cx.stack.pop();
297 Object key = cx.stack.pop();
298 Object obj = cx.stack.peek();
299 if (val instanceof JSFunction && obj instanceof JSScope) {
300 JSScope parent = (JSScope)obj;
301 while(parent.getParentJSScope() != null) parent = parent.getParentJSScope();
302 if (parent instanceof JSTrap.JSTrappable) {
303 JSTrap.JSTrappable b = (JSTrap.JSTrappable)parent;
304 if (op == ASSIGN_ADD) JSTrap.addTrap(b, key, (JSFunction)val);
305 else JSTrap.delTrap(b, key, (JSFunction)val);
306 // skip over the "normal" implementation of +=/-=
307 cx.pc += ((Integer)arg).intValue() - 1;
311 // use the "normal" implementation
319 int count = ((Number)arg).intValue();
320 if(count < 2) throw new Error("this should never happen");
323 Object right = cx.stack.pop();
324 Object left = cx.stack.pop();
325 if(left instanceof String || right instanceof String)
326 cx.stack.push(JS.toString(left).concat(JS.toString(right)));
327 else cx.stack.push(new Double(JS.toDouble(left) + JS.toDouble(right)));
329 Object[] args = new Object[count];
330 while(--count >= 0) args[count] = cx.stack.pop();
331 if(args[0] instanceof String) {
332 StringBuffer sb = new StringBuffer(64);
333 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
334 cx.stack.push(sb.toString());
337 for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
338 if(numStrings == 0) {
340 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
341 cx.stack.push(new Double(d));
344 StringBuffer sb = new StringBuffer(64);
345 if(!(args[0] instanceof String || args[1] instanceof String)) {
348 d += JS.toDouble(args[i++]);
349 } while(!(args[i] instanceof String));
350 sb.append(JS.toString(new Double(d)));
352 while(i < args.length) sb.append(JS.toString(args[i++]));
353 cx.stack.push(sb.toString());
361 Object right = cx.stack.pop();
362 Object left = cx.stack.pop();
365 case BITOR: cx.stack.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
366 case BITXOR: cx.stack.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
367 case BITAND: cx.stack.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
369 case SUB: cx.stack.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
370 case MUL: cx.stack.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
371 case DIV: cx.stack.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
372 case MOD: cx.stack.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
374 case LSH: cx.stack.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
375 case RSH: cx.stack.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
376 case URSH: cx.stack.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
378 case LT: case LE: case GT: case GE: {
379 if (left == null) left = new Integer(0);
380 if (right == null) right = new Integer(0);
382 if (left instanceof String || right instanceof String) {
383 result = left.toString().compareTo(right.toString());
385 result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
387 cx.stack.push(new Boolean((op == LT && result < 0) || (op == LE && result <= 0) ||
388 (op == GT && result > 0) || (op == GE && result >= 0)));
397 if (l == null) { Object tmp = r; r = l; l = tmp; }
398 if (l == null && r == null) ret = true;
399 else if (r == null) ret = false; // l != null, so its false
400 else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
401 else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
402 else if (l instanceof String) ret = r != null && l.equals(r.toString());
403 else ret = l.equals(r);
404 cx.stack.push(new Boolean(op == EQ ? ret : !ret)); break;
407 default: throw new Error("unknown opcode " + op);
412 while(cx.stack.size() > 0) {
413 Object o = cx.stack.pop();
414 if (o instanceof CatchMarker || o instanceof TryMarker) {
415 boolean inCatch = o instanceof CatchMarker;
418 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
420 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
421 // run the catch block, this will implicitly run the finally block, if it exists
423 cx.stack.push(catchMarker);
424 cx.stack.push(e.getObject());
425 cx.scope = ((TryMarker)o).scope;
426 cx.pc = ((TryMarker)o).catchLoc - 1;
430 cx.stack.push(new FinallyData(THROW));
431 cx.scope = ((TryMarker)o).scope;
432 cx.pc = ((TryMarker)o).finallyLoc - 1;
436 // no handler found within this func
437 if(o instanceof CallMarker) throw e;
444 // Exception Stuff ////////////////////////////////////////////////////////////////
446 static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
447 static EvaluatorException ee(String s) {
448 throw new EvaluatorException(JSContext.getSourceName() + ":" + JSContext.getLine() + " " + s);
450 static JS.Exn je(String s) {
451 throw new JS.Exn(JSContext.getSourceName() + ":" + JSContext.getLine() + " " + s);
455 // Markers //////////////////////////////////////////////////////////////////////
457 public static class CallMarker {
461 public CallMarker(JSContext cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
464 public static class CatchMarker { public CatchMarker() { } }
465 private static CatchMarker catchMarker = new CatchMarker();
467 public static class LoopMarker {
470 public JSScope scope;
471 public LoopMarker(int location, String label, JSScope scope) {
472 this.location = location;
477 public static class TryMarker {
479 public int finallyLoc;
480 public JSScope scope;
481 public TryMarker(int catchLoc, int finallyLoc, JSScope scope) {
482 this.catchLoc = catchLoc;
483 this.finallyLoc = finallyLoc;
487 public static class FinallyData {
490 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
491 public FinallyData(int op) { this(op,null); }