c9bcd737f68d1da2eb647b0b1f872ec52235e36d
[org.ibex.core.git] / src / org / xwt / js / Interpreter.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt.js;
3
4 import org.xwt.util.*;
5 import java.util.*;
6 import java.io.*;
7
8 class Interpreter implements ByteCodes, Tokens {
9
10     static Object eval(final JSContext cx) throws JS.Exn {
11         final int initialPauseCount = cx.pausecount;
12         OUTER: for(;; cx.pc++) {
13         try {
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
20                 op = fd.op;
21                 arg = fd.arg;
22             }
23             switch(op) {
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;
33             case SWAP: {
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);
39                 break; }
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;
47             case LABEL: break;
48
49             case TYPEOF: {
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");
57                 break;
58             }
59
60             case PUSHKEYS: {
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());
65                 cx.stack.push(a);
66                 break;
67             }
68
69             case LOOP:
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);
73                 break;
74
75             case BREAK:
76             case CONTINUE:
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;
85                         continue OUTER;
86                     }
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;
94                             continue OUTER;
95                         }
96                     }
97                 }
98                 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
99                                 cx.getSourceName() + ":" + cx.getLine());
100
101             case TRY: {
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));
106                 break;
107             }
108
109             case RETURN: {
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;
119                         continue OUTER;
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;
127                                 if (t == null) {
128                                     ((JS)ts.t.trapee).put(t.name, ts.val);
129                                     if (cx.pausecount > initialPauseCount) return null;   // we were paused
130                                 } else {
131                                     cx.stack.push(o);
132                                     JSArray args = new JSArray();
133                                     args.addElement(ts.val);
134                                     cx.stack.push(args);
135                                     cx.f = t.f;
136                                     cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, ts.val);
137                                     cx.pc = -1;
138                                     break;
139                                 }
140                             }
141                         }
142                         cx.scope = ((CallMarker)o).scope;
143                         cx.pc = ((CallMarker)o).pc;
144                         cx.f = (JSFunction)((CallMarker)o).f;
145                         cx.stack.push(retval);
146                         continue OUTER;
147                     }
148                 }
149                 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
150             }
151
152             case PUT: {
153                 Object val = cx.stack.pop();
154                 Object key = cx.stack.pop();
155                 Object target = cx.stack.peek();
156                 if (target == null)
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());
160                 if (key == null)
161                     throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
162                 JSTrap t = null;
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;
168                     t = ts.t.next;
169                     ts.cascadeHappened = true;
170                     while (t != null && t.f.numFormalArgs == 0) t = t.next;
171                     if (t == null) target = ts.t.trapee;
172                 }
173                 if (t != null) {
174                     cx.stack.push(new CallMarker(cx));
175                     JSArray args = new JSArray();
176                     args.addElement(val);
177                     cx.stack.push(args);
178                     cx.f = t.f;
179                     cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, val);
180                     cx.pc = -1;
181                     break;
182                 }
183                 ((JS)target).put(key, val);
184                 if (cx.pausecount > initialPauseCount) return null;   // we were paused
185                 cx.stack.push(val);
186                 break;
187             }
188
189             case GET:
190             case GET_PRESERVE: {
191                 Object o, v;
192                 if (op == GET) {
193                     v = arg == null ? cx.stack.pop() : arg;
194                     o = cx.stack.pop();
195                 } else {
196                     v = cx.stack.pop();
197                     o = cx.stack.peek();
198                     cx.stack.push(v);
199                 }
200                 Object ret = null;
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);
205                     cx.stack.push(ret);
206                     break;
207                 } else if (o instanceof JS) {
208                     JSTrap t = null;
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;
216                     }
217                     if (t != null) {
218                         cx.stack.push(new CallMarker(cx));
219                         JSArray args = new JSArray();
220                         cx.stack.push(args);
221                         cx.f = t.f;
222                         cx.scope = new JSTrap.JSTrapScope(cx.f.parentJSScope, t, null);
223                         ((JSTrap.JSTrapScope)cx.scope).cascadeHappened = true;
224                         cx.pc = -1;
225                         break;
226                     }
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
230                     cx.stack.push(ret);
231                     break;
232                 }
233                 throw je("tried to get property " + v + " from a " + o.getClass().getName());
234             }
235             
236             case CALL: case CALLMETHOD: {
237                 int numArgs = JS.toInt(arg);
238                 Object method = null;
239                 Object ret = null;
240                 Object object = cx.stack.pop();
241
242                 if (op == CALL) {
243                     object = cx.stack.pop();
244                 } else {
245                     if (object == JSCallable.METHOD) {
246                         method = cx.stack.pop();
247                         object = cx.stack.pop();
248                     } else {
249                         cx.stack.pop();
250                         cx.stack.pop();
251                     }
252                 }
253
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);
258
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);
267                     cx.pc = -1;
268                     break;
269
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);
278
279                 } else {
280                     throw new JS.Exn("can't call a " + object.getClass().getName() + " @" + cx.pc + "\n" + cx.f.dump());
281
282                 }
283                 if (cx.pausecount > initialPauseCount) return null;
284                 cx.stack.push(ret);
285                 break;
286             }
287
288             case THROW: {
289                 Object o = cx.stack.pop();
290                 if(o instanceof JS.Exn) throw (JS.Exn)o;
291                 throw new JS.Exn(o);
292             }
293
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;
308                         break;
309                     }
310                 }
311                 // use the "normal" implementation
312                 cx.stack.push(key);
313                 cx.stack.push(old);
314                 cx.stack.push(val);
315                 break;
316             }
317
318             case ADD: {
319                 int count = ((Number)arg).intValue();
320                 if(count < 2) throw new Error("this should never happen");
321                 if(count == 2) {
322                     // common case
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)));
328                 } else {
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());
335                     } else {
336                         int numStrings = 0;
337                         for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
338                         if(numStrings == 0) {
339                             double d = 0.0;
340                             for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
341                             cx.stack.push(new Double(d));
342                         } else {
343                             int i=0;
344                             StringBuffer sb = new StringBuffer(64);
345                             if(!(args[0] instanceof String || args[1] instanceof String)) {
346                                 double d=0.0;
347                                 do {
348                                     d += JS.toDouble(args[i++]);
349                                 } while(!(args[i] instanceof String));
350                                 sb.append(JS.toString(new Double(d)));
351                             }
352                             while(i < args.length) sb.append(JS.toString(args[i++]));
353                             cx.stack.push(sb.toString());
354                         }
355                     }
356                 }
357                 break;
358             }
359
360             default: {
361                 Object right = cx.stack.pop();
362                 Object left = cx.stack.pop();
363                 switch(op) {
364                         
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;
368
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;
373                         
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;
377                         
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);
381                     int result = 0;
382                     if (left instanceof String || right instanceof String) {
383                         result = left.toString().compareTo(right.toString());
384                     } else {
385                         result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
386                     }
387                     cx.stack.push(new Boolean((op == LT && result < 0) || (op == LE && result <= 0) ||
388                                        (op == GT && result > 0) || (op == GE && result >= 0)));
389                     break;
390                 }
391                     
392                 case EQ:
393                 case NE: {
394                     Object l = left;
395                     Object r = right;
396                     boolean ret;
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;
405                 }
406
407                 default: throw new Error("unknown opcode " + op);
408                 } }
409             }
410
411         } catch(JS.Exn e) {
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;
416                     if(inCatch) {
417                         o = cx.stack.pop();
418                         if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
419                     }
420                     if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
421                         // run the catch block, this will implicitly run the finally block, if it exists
422                         cx.stack.push(o);
423                         cx.stack.push(catchMarker);
424                         cx.stack.push(e.getObject());
425                         cx.scope = ((TryMarker)o).scope;
426                         cx.pc = ((TryMarker)o).catchLoc - 1;
427                         continue OUTER;
428                     } else {
429                         cx.stack.push(e);
430                         cx.stack.push(new FinallyData(THROW));
431                         cx.scope = ((TryMarker)o).scope;
432                         cx.pc = ((TryMarker)o).finallyLoc - 1;
433                         continue OUTER;
434                     }
435                 }
436                 // no handler found within this func
437                 if(o instanceof CallMarker) throw e;
438             }
439             throw e;
440         } // end try/catch
441         } // end for
442     }
443
444     // Exception Stuff ////////////////////////////////////////////////////////////////
445
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);
449     }
450     static JS.Exn je(String s) {
451         throw new JS.Exn(JSContext.getSourceName() + ":" + JSContext.getLine() + " " + s);
452     }
453
454
455     // Markers //////////////////////////////////////////////////////////////////////
456
457     public static class CallMarker {
458         int pc;
459         JSScope scope;
460         JSFunction f;
461         public CallMarker(JSContext cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
462     }
463     
464     public static class CatchMarker { public CatchMarker() { } }
465     private static CatchMarker catchMarker = new CatchMarker();
466     
467     public static class LoopMarker {
468         public int location;
469         public String label;
470         public JSScope scope;
471         public LoopMarker(int location, String label, JSScope scope) {
472             this.location = location;
473             this.label = label;
474             this.scope = scope;
475         }
476     }
477     public static class TryMarker {
478         public int catchLoc;
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;
484             this.scope = scope;
485         }
486     }
487     public static class FinallyData {
488         public int op;
489         public Object arg;
490         public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
491         public FinallyData(int op) { this(op,null); }
492     }
493 }