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();
244 } else if (object == JSCallable.METHOD) {
245 method = cx.stack.pop();
246 object = cx.stack.pop();
249 if (object instanceof String || object instanceof Number || object instanceof Boolean) {
250 JSArray arguments = new JSArray();
251 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
252 ret = Internal.callMethodOnPrimitive(object, method, arguments);
254 } else if (object instanceof JSFunction) {
255 // FEATURE: use something similar to call0/call1/call2 here
256 JSArray arguments = new JSArray();
257 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
258 cx.stack.push(new CallMarker(cx));
259 cx.stack.push(arguments);
260 cx.f = (JSFunction)object;
261 cx.scope = new JSScope(cx.f.parentJSScope);
265 } else if (object instanceof JSCallable) {
266 JSCallable c = (JSCallable)object;
267 Object[] rest = numArgs > 3 ? new Object[numArgs - 3] : null;
268 for(int i=numArgs - 1; i>2; i--) rest[i-3] = cx.stack.pop();
269 Object a2 = numArgs <= 2 ? null : cx.stack.pop();
270 Object a1 = numArgs <= 1 ? null : cx.stack.pop();
271 Object a0 = numArgs <= 0 ? null : cx.stack.pop();
272 ret = c.callMethod(method, a0, a1, a2, rest, numArgs);
275 throw new JS.Exn("can't call a " + object.getClass().getName() + " @" + cx.pc + "\n" + cx.f.dump());
278 if (cx.pausecount > initialPauseCount) return null;
284 Object o = cx.stack.pop();
285 if(o instanceof JS.Exn) throw (JS.Exn)o;
289 case ASSIGN_SUB: case ASSIGN_ADD: {
290 Object val = cx.stack.pop();
291 Object old = cx.stack.pop();
292 Object key = cx.stack.pop();
293 Object obj = cx.stack.peek();
294 if (val instanceof JSFunction && obj instanceof JSScope) {
295 JSScope parent = (JSScope)obj;
296 while(parent.getParentJSScope() != null) parent = parent.getParentJSScope();
297 if (parent instanceof JSTrap.JSTrappable) {
298 JSTrap.JSTrappable b = (JSTrap.JSTrappable)parent;
299 if (op == ASSIGN_ADD) JSTrap.addTrap(b, key, (JSFunction)val);
300 else JSTrap.delTrap(b, key, (JSFunction)val);
301 // skip over the "normal" implementation of +=/-=
302 cx.pc += ((Integer)arg).intValue() - 1;
306 // use the "normal" implementation
314 int count = ((Number)arg).intValue();
315 if(count < 2) throw new Error("this should never happen");
318 Object right = cx.stack.pop();
319 Object left = cx.stack.pop();
320 if(left instanceof String || right instanceof String)
321 cx.stack.push(JS.toString(left).concat(JS.toString(right)));
322 else cx.stack.push(new Double(JS.toDouble(left) + JS.toDouble(right)));
324 Object[] args = new Object[count];
325 while(--count >= 0) args[count] = cx.stack.pop();
326 if(args[0] instanceof String) {
327 StringBuffer sb = new StringBuffer(64);
328 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
329 cx.stack.push(sb.toString());
332 for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
333 if(numStrings == 0) {
335 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
336 cx.stack.push(new Double(d));
339 StringBuffer sb = new StringBuffer(64);
340 if(!(args[0] instanceof String || args[1] instanceof String)) {
343 d += JS.toDouble(args[i++]);
344 } while(!(args[i] instanceof String));
345 sb.append(JS.toString(new Double(d)));
347 while(i < args.length) sb.append(JS.toString(args[i++]));
348 cx.stack.push(sb.toString());
356 Object right = cx.stack.pop();
357 Object left = cx.stack.pop();
360 case BITOR: cx.stack.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
361 case BITXOR: cx.stack.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
362 case BITAND: cx.stack.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
364 case SUB: cx.stack.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
365 case MUL: cx.stack.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
366 case DIV: cx.stack.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
367 case MOD: cx.stack.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
369 case LSH: cx.stack.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
370 case RSH: cx.stack.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
371 case URSH: cx.stack.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
373 case LT: case LE: case GT: case GE: {
374 if (left == null) left = new Integer(0);
375 if (right == null) right = new Integer(0);
377 if (left instanceof String || right instanceof String) {
378 result = left.toString().compareTo(right.toString());
380 result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
382 cx.stack.push(new Boolean((op == LT && result < 0) || (op == LE && result <= 0) ||
383 (op == GT && result > 0) || (op == GE && result >= 0)));
392 if (l == null) { Object tmp = r; r = l; l = tmp; }
393 if (l == null && r == null) ret = true;
394 else if (r == null) ret = false; // l != null, so its false
395 else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
396 else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
397 else if (l instanceof String) ret = r != null && l.equals(r.toString());
398 else ret = l.equals(r);
399 cx.stack.push(new Boolean(op == EQ ? ret : !ret)); break;
402 default: throw new Error("unknown opcode " + op);
407 while(cx.stack.size() > 0) {
408 Object o = cx.stack.pop();
409 if (o instanceof CatchMarker || o instanceof TryMarker) {
410 boolean inCatch = o instanceof CatchMarker;
413 if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
415 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
416 // run the catch block, this will implicitly run the finally block, if it exists
418 cx.stack.push(catchMarker);
419 cx.stack.push(e.getObject());
420 cx.scope = ((TryMarker)o).scope;
421 cx.pc = ((TryMarker)o).catchLoc - 1;
425 cx.stack.push(new FinallyData(THROW));
426 cx.scope = ((TryMarker)o).scope;
427 cx.pc = ((TryMarker)o).finallyLoc - 1;
431 // no handler found within this func
432 if(o instanceof CallMarker) throw e;
439 // Exception Stuff ////////////////////////////////////////////////////////////////
441 static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
442 static EvaluatorException ee(String s) {
443 throw new EvaluatorException(JSContext.getSourceName() + ":" + JSContext.getLine() + " " + s);
445 static JS.Exn je(String s) {
446 throw new JS.Exn(JSContext.getSourceName() + ":" + JSContext.getLine() + " " + s);
450 // Markers //////////////////////////////////////////////////////////////////////
452 public static class CallMarker {
456 public CallMarker(JSContext cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
459 public static class CatchMarker { public CatchMarker() { } }
460 private static CatchMarker catchMarker = new CatchMarker();
462 public static class LoopMarker {
465 public JSScope scope;
466 public LoopMarker(int location, String label, JSScope scope) {
467 this.location = location;
472 public static class TryMarker {
474 public int finallyLoc;
475 public JSScope scope;
476 public TryMarker(int catchLoc, int finallyLoc, JSScope scope) {
477 this.catchLoc = catchLoc;
478 this.finallyLoc = finallyLoc;
482 public static class FinallyData {
485 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
486 public FinallyData(int op) { this(op,null); }