2003/11/17 02:59:34
[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 if (object == JSCallable.METHOD) {
245                     method = cx.stack.pop();
246                     object = cx.stack.pop();
247                 }
248
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);
253
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);
262                     cx.pc = -1;
263                     break;
264
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);
273
274                 } else {
275                     throw new JS.Exn("can't call a " + object.getClass().getName() + " @" + cx.pc + "\n" + cx.f.dump());
276
277                 }
278                 if (cx.pausecount > initialPauseCount) return null;
279                 cx.stack.push(ret);
280                 break;
281             }
282
283             case THROW: {
284                 Object o = cx.stack.pop();
285                 if(o instanceof JS.Exn) throw (JS.Exn)o;
286                 throw new JS.Exn(o);
287             }
288
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;
303                         break;
304                     }
305                 }
306                 // use the "normal" implementation
307                 cx.stack.push(key);
308                 cx.stack.push(old);
309                 cx.stack.push(val);
310                 break;
311             }
312
313             case ADD: {
314                 int count = ((Number)arg).intValue();
315                 if(count < 2) throw new Error("this should never happen");
316                 if(count == 2) {
317                     // common case
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)));
323                 } else {
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());
330                     } else {
331                         int numStrings = 0;
332                         for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
333                         if(numStrings == 0) {
334                             double d = 0.0;
335                             for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
336                             cx.stack.push(new Double(d));
337                         } else {
338                             int i=0;
339                             StringBuffer sb = new StringBuffer(64);
340                             if(!(args[0] instanceof String || args[1] instanceof String)) {
341                                 double d=0.0;
342                                 do {
343                                     d += JS.toDouble(args[i++]);
344                                 } while(!(args[i] instanceof String));
345                                 sb.append(JS.toString(new Double(d)));
346                             }
347                             while(i < args.length) sb.append(JS.toString(args[i++]));
348                             cx.stack.push(sb.toString());
349                         }
350                     }
351                 }
352                 break;
353             }
354
355             default: {
356                 Object right = cx.stack.pop();
357                 Object left = cx.stack.pop();
358                 switch(op) {
359                         
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;
363
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;
368                         
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;
372                         
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);
376                     int result = 0;
377                     if (left instanceof String || right instanceof String) {
378                         result = left.toString().compareTo(right.toString());
379                     } else {
380                         result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
381                     }
382                     cx.stack.push(new Boolean((op == LT && result < 0) || (op == LE && result <= 0) ||
383                                        (op == GT && result > 0) || (op == GE && result >= 0)));
384                     break;
385                 }
386                     
387                 case EQ:
388                 case NE: {
389                     Object l = left;
390                     Object r = right;
391                     boolean ret;
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;
400                 }
401
402                 default: throw new Error("unknown opcode " + op);
403                 } }
404             }
405
406         } catch(JS.Exn e) {
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;
411                     if(inCatch) {
412                         o = cx.stack.pop();
413                         if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
414                     }
415                     if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
416                         // run the catch block, this will implicitly run the finally block, if it exists
417                         cx.stack.push(o);
418                         cx.stack.push(catchMarker);
419                         cx.stack.push(e.getObject());
420                         cx.scope = ((TryMarker)o).scope;
421                         cx.pc = ((TryMarker)o).catchLoc - 1;
422                         continue OUTER;
423                     } else {
424                         cx.stack.push(e);
425                         cx.stack.push(new FinallyData(THROW));
426                         cx.scope = ((TryMarker)o).scope;
427                         cx.pc = ((TryMarker)o).finallyLoc - 1;
428                         continue OUTER;
429                     }
430                 }
431                 // no handler found within this func
432                 if(o instanceof CallMarker) throw e;
433             }
434             throw e;
435         } // end try/catch
436         } // end for
437     }
438
439     // Exception Stuff ////////////////////////////////////////////////////////////////
440
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);
444     }
445     static JS.Exn je(String s) {
446         throw new JS.Exn(JSContext.getSourceName() + ":" + JSContext.getLine() + " " + s);
447     }
448
449
450     // Markers //////////////////////////////////////////////////////////////////////
451
452     public static class CallMarker {
453         int pc;
454         JSScope scope;
455         JSFunction f;
456         public CallMarker(JSContext cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
457     }
458     
459     public static class CatchMarker { public CatchMarker() { } }
460     private static CatchMarker catchMarker = new CatchMarker();
461     
462     public static class LoopMarker {
463         public int location;
464         public String label;
465         public JSScope scope;
466         public LoopMarker(int location, String label, JSScope scope) {
467             this.location = location;
468             this.label = label;
469             this.scope = scope;
470         }
471     }
472     public static class TryMarker {
473         public int catchLoc;
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;
479             this.scope = scope;
480         }
481     }
482     public static class FinallyData {
483         public int op;
484         public Object arg;
485         public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
486         public FinallyData(int op) { this(op,null); }
487     }
488 }