trim down public api
[org.ibex.core.git] / src / org / ibex / js / Interpreter.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.ibex.js;
3
4 import org.ibex.util.*;
5 import java.util.*;
6
7 /** Encapsulates a single JS interpreter (ie call stack) */
8 class Interpreter implements ByteCodes, Tokens {
9     private static final JS CASCADE = JSString.intern("cascade");
10     
11     // Thread-Interpreter Mapping /////////////////////////////////////////////////////////////////////////
12
13     static Interpreter current() { return (Interpreter)threadToInterpreter.get(Thread.currentThread()); }
14     private static Hashtable threadToInterpreter = new Hashtable();
15
16     
17     // Instance members and methods //////////////////////////////////////////////////////////////////////
18     
19     int pausecount;               ///< the number of times pause() has been invoked; -1 indicates unpauseable
20     JSFunction f = null;          ///< the currently-executing JSFunction
21     JSScope scope;                ///< the current top-level scope (LIFO stack via NEWSCOPE/OLDSCOPE)
22     final Stack stack = new Stack(); ///< the object stack
23     int pc = 0;                   ///< the program counter
24
25     Interpreter(JSFunction f, boolean pauseable, JSArgs args) {
26         this.f = f;
27         this.pausecount = pauseable ? 0 : -1;
28         this.scope = new JSScope(f.parentScope);
29         try {
30             stack.push(new CallMarker(null));    // the "root function returned" marker -- f==null
31             stack.push(args);
32         } catch(JSExn e) {
33             throw new Error("should never happen");
34         }
35     }
36     
37     Interpreter(Trap t, JS val, boolean pauseOnPut) {
38         this.pausecount = -1;
39         try {
40             setupTrap(t,val,new TrapMarker(null,t,val,pauseOnPut));
41         } catch(JSExn e) {
42             throw new Error("should never happen");
43         }
44     }
45     
46     /** this is the only synchronization point we need in order to be threadsafe */
47     synchronized JS resume() throws JSExn {
48         if(f == null) throw new RuntimeException("function already finished");
49         Thread t = Thread.currentThread();
50         Interpreter old = (Interpreter)threadToInterpreter.get(t);
51         threadToInterpreter.put(t, this);
52         try {
53             return run();
54         } finally {
55             if (old == null) threadToInterpreter.remove(t);
56             else threadToInterpreter.put(t, old);
57         }
58     }
59
60     static int getLine() {
61         Interpreter c = Interpreter.current();
62         return c == null || c.f == null || c.pc < 0 || c.pc >= c.f.size ? -1 : c.f.line[c.pc];
63     }
64
65     static String getSourceName() {
66         Interpreter c = Interpreter.current();
67         return c == null || c.f == null ? null : c.f.sourceName;
68     } 
69
70     private static JSExn je(String s) { return new JSExn(getSourceName() + ":" + getLine() + " " + s); }
71
72     private JS run() throws JSExn {
73
74         // if pausecount changes after a get/put/call, we know we've been paused
75         final int initialPauseCount = pausecount;
76
77         OUTER: for(;; pc++) {
78         try {
79             int op = f.op[pc];
80             Object arg = f.arg[pc];
81             if(op == FINALLY_DONE) {
82                 FinallyData fd = (FinallyData) stack.pop();
83                 if(fd == null) continue OUTER; // NOP
84                 if(fd.exn != null) throw fd.exn;
85                 op = fd.op;
86                 arg = fd.arg;
87             }
88             switch(op) {
89             case LITERAL: stack.push((JS)arg); break;
90             case OBJECT: stack.push(new JS.O()); break;
91             case ARRAY: stack.push(new JSArray(JS.toInt((JS)arg))); break;
92             case DECLARE: scope.declare((JS)(arg==null ? stack.peek() : arg)); if(arg != null) stack.push((JS)arg); break;
93             case TOPSCOPE: stack.push(scope); break;
94             case JT: if (JS.toBoolean(stack.pop())) pc += JS.toInt((JS)arg) - 1; break;
95             case JF: if (!JS.toBoolean(stack.pop())) pc += JS.toInt((JS)arg) - 1; break;
96             case JMP: pc += JS.toInt((JS)arg) - 1; break;
97             case POP: stack.pop(); break;
98             case SWAP: stack.swap(); break;
99             case DUP: stack.push(stack.peek()); break;
100             case NEWSCOPE: scope = new JSScope(scope); break;
101             case OLDSCOPE: scope = scope.getParentScope(); break;
102             case ASSERT: if (!JS.toBoolean(stack.pop())) throw je("ibex.assertion.failed"); break;
103             case BITNOT: stack.push(JS.N(~JS.toLong(stack.pop()))); break;
104             case BANG: stack.push(JS.B(!JS.toBoolean(stack.pop()))); break;
105             case NEWFUNCTION: stack.push(((JSFunction)arg)._cloneWithNewParentScope(scope)); break;
106             case LABEL: break;
107
108             case TYPEOF: {
109                 Object o = stack.pop();
110                 if (o == null) stack.push(null);
111                 else if (o instanceof JSString) stack.push(JS.S("string"));
112                 else if (o instanceof JSNumber.B) stack.push(JS.S("boolean"));
113                 else if (o instanceof JSNumber) stack.push(JS.S("number"));
114                 else stack.push(JS.S("object"));
115                 break;
116             }
117
118             case PUSHKEYS: {
119                 JS o = stack.peek();
120                 stack.push(o == null ? null : o.keys());
121                 break;
122             }
123
124             case LOOP:
125                 stack.push(new LoopMarker(pc, pc > 0 && f.op[pc - 1] == LABEL ? (String)f.arg[pc - 1] : (String)null, scope));
126                 stack.push(JS.T);
127                 break;
128
129             case BREAK:
130             case CONTINUE:
131                 while(!stack.empty()) {
132                     JS o = stack.pop();
133                     if (o instanceof CallMarker) je("break or continue not within a loop");
134                     if (o instanceof TryMarker) {
135                         if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
136                         stack.push(new FinallyData(op, arg));
137                         scope = ((TryMarker)o).scope;
138                         pc = ((TryMarker)o).finallyLoc - 1;
139                         continue OUTER;
140                     }
141                     if (o instanceof LoopMarker) {
142                         if (arg == null || arg.equals(((LoopMarker)o).label)) {
143                             int loopInstructionLocation = ((LoopMarker)o).location;
144                             int endOfLoop = JS.toInt((JS)f.arg[loopInstructionLocation]) + loopInstructionLocation;
145                             scope = ((LoopMarker)o).scope;
146                             if (op == CONTINUE) { stack.push(o); stack.push(JS.F); }
147                             pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
148                             continue OUTER;
149                         }
150                     }
151                 }
152                 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
153                                 getSourceName() + ":" + getLine());
154
155             case TRY: {
156                 int[] jmps = (int[]) arg;
157                 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
158                 // each can be < 0 if the specified block does not exist
159                 stack.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1], this));
160                 break;
161             }
162
163             case RETURN: {
164                 JS retval = stack.pop();
165                 while(!stack.empty()) {
166                     Object o = stack.pop();
167                     if (o instanceof TryMarker) {
168                         if(((TryMarker)o).finallyLoc < 0) continue;
169                         stack.push(retval); 
170                         stack.push(new FinallyData(RETURN));
171                         scope = ((TryMarker)o).scope;
172                         pc = ((TryMarker)o).finallyLoc - 1;
173                         continue OUTER;
174                     } else if (o instanceof CallMarker) {
175                         boolean didTrapPut = false;
176                         if (o instanceof TrapMarker) { // handles return component of a read trap
177                             TrapMarker tm = (TrapMarker) o;
178                             boolean cascade = tm.t.isWriteTrap() && !tm.cascadeHappened && !JS.toBoolean(retval);
179                             if(cascade) {
180                                 Trap t = tm.t.nextWriteTrap();
181                                 if(t == null && tm.t.target instanceof JS.Clone) {
182                                     t = ((JS.Clone)tm.t.target).clonee.getTrap(tm.t.key);
183                                     if(t != null) t = t.writeTrap();
184                                 }
185                                 if(t != null) {
186                                     tm.t = t; // we reuse the old trap marker
187                                     setupTrap(t,tm.val,tm);
188                                     pc--; // we increment it on the next iter
189                                     continue OUTER;
190                                 } else {
191                                     didTrapPut = true;
192                                     if(!tm.pauseOnPut) tm.t.target.put(tm.t.key,tm.val);
193                                 }
194                             }
195                         }
196                         CallMarker cm = (CallMarker) o;
197                         scope = cm.scope;
198                         pc = cm.pc - 1;
199                         f = cm.f;
200                         if (didTrapPut) {
201                             if (((TrapMarker)cm).pauseOnPut) { pc++; return ((TrapMarker)cm).val; }
202                             if (pausecount > initialPauseCount) { pc++; return null; }   // we were paused
203                         } else {
204                             stack.push(retval);
205                         }
206                         if (f == null) return retval;
207                         continue OUTER;
208                     }
209                 }
210                 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
211             }
212
213             case PUT: {
214                 JS val = stack.pop();
215                 JS key = stack.pop();
216                 JS target = stack.peek();
217                 if (target == null) throw je("tried to put " + JS.debugToString(val) + " to the " + JS.debugToString(key) + " property on the null value");
218                 if (key == null) throw je("tried to assign \"" + JS.debugToString(val) + "\" to the null key");
219                 
220                 Trap t = null;
221                 TrapMarker tm = null;
222                 if(target instanceof JSScope && key.jsequals(CASCADE)) {
223                     CallMarker o = stack.findCall();
224                     if(o instanceof TrapMarker) {
225                         tm = (TrapMarker) o;
226                         target = tm.t.target;
227                         key = tm.t.key;
228                         tm.cascadeHappened = true;
229                         t = tm.t;
230                         if(t.isReadTrap()) throw new JSExn("can't do a write cascade in a read trap");
231                         t = t.nextWriteTrap();
232                     }
233                 }
234                 if(tm == null) { // not cascading
235                     t = target instanceof JSScope ? t = ((JSScope)target).top().getTrap(key) : target.getTrap(key);
236                     if(t != null) t = t.writeTrap();
237                 }
238                 if(t == null && target instanceof JS.Clone) {
239                     target = ((JS.Clone)target).clonee;
240                     t = target.getTrap(key);
241                     if(t != null) t = t.writeTrap();
242                 }
243
244                 stack.push(val);
245                 
246                 if(t != null) {
247                     setupTrap(t,val,new TrapMarker(this,t,val, tm != null && tm.pauseOnPut));
248                     pc--; // we increment later
249                     break;
250                 } else {
251                     if (tm != null && tm.pauseOnPut) { pc++; return val; }
252                     target.put(key,val);
253                     if (pausecount > initialPauseCount) { pc++; return null; }   // we were paused
254                     break;
255                 }
256             }
257
258             case GET:
259             case GET_PRESERVE: {
260                 JS target, key;
261                 if (op == GET) {
262                     key = arg == null ? stack.pop() : (JS)arg;
263                     target = stack.pop();
264                 } else {
265                     key = stack.pop();
266                     target = stack.peek();
267                     stack.push(key);
268                 }
269                 JS ret = null;
270                 if (key == null) throw je("tried to get the null key from " + target);
271                 if (target == null) throw je("tried to get property \"" + key + "\" from the null object");
272                 
273                 Trap t = null;
274                 TrapMarker tm = null;
275                 if(target instanceof JSScope && key.jsequals(CASCADE)) {
276                     CallMarker o = stack.findCall();
277                     if(o instanceof TrapMarker) {
278                         tm = (TrapMarker) o;
279                         target = tm.t.target;
280                         key = tm.t.key;
281                         t = tm.t;
282                         if(t.isWriteTrap()) throw new JSExn("can't do a read cascade in a write trap");
283                         t = t.nextReadTrap();
284                     }
285                 }
286                 if(tm == null) { // not cascading
287                     t = target instanceof JSScope ? t = ((JSScope)target).top().getTrap(key) : ((JS)target).getTrap(key);
288                     if(t != null) t = t.readTrap();
289                 }
290                 if(t == null && target instanceof JS.Clone) {
291                     target = ((JS.Clone)target).clonee;
292                     t = target.getTrap(key);
293                     if(t != null) t = t.readTrap();
294                 }
295                 
296                 if(t != null) {
297                     setupTrap(t,null,new TrapMarker(this,t,null));
298                     pc--; // we increment later
299                     break;
300                 } else {
301                     ret = target.get(key);
302                     if (pausecount > initialPauseCount) { pc++; return null; }   // we were paused
303                     if (ret == JS.METHOD) ret = new Stub(target, key);
304                     stack.push(ret);
305                     break;
306                 }
307             }
308             
309             case CALL: case CALLMETHOD: {
310                 int numArgs = JS.toInt((JS)arg);
311                 
312                 JS[] rest = numArgs > 3 ? new JS[numArgs - 3] : null;
313                 for(int i=numArgs - 1; i>2; i--) rest[i-3] = stack.pop();
314                 JS a2 = numArgs <= 2 ? null : stack.pop();
315                 JS a1 = numArgs <= 1 ? null : stack.pop();
316                 JS a0 = numArgs <= 0 ? null : stack.pop();
317                 
318                 JS method = null;
319                 JS ret = null;
320                 JS object = stack.pop();
321
322                 if (op == CALLMETHOD) {
323                     if (object == JS.METHOD) {
324                         method = stack.pop();
325                         object = stack.pop();
326                     } else if (object == null) {
327                         method = stack.pop();
328                         object = stack.pop();
329                         throw new JSExn("function '"+JS.debugToString(method)+"' not found in " + object.getClass().getName());
330                     } else {
331                         stack.pop();
332                         stack.pop();
333                     }
334                 }
335
336                 if (object instanceof JSFunction) {
337                     stack.push(new CallMarker(this));
338                     stack.push(new JSArgs(a0,a1,a2,rest,numArgs,object));
339                     f = (JSFunction)object;
340                     scope = new JSScope(f.parentScope);
341                     pc = -1;
342                     break;
343                 } else {
344                     JS c = (JS)object;
345                     ret = method == null ? c.call(a0, a1, a2, rest, numArgs) : c.callMethod(method, a0, a1, a2, rest, numArgs);
346                 }
347                 
348                 if (pausecount > initialPauseCount) { pc++; return null; }
349                 stack.push(ret);
350                 break;
351             }
352
353             case THROW:
354                 throw new JSExn(stack.pop(), this);
355
356                 /* FIXME GRAMMAR
357             case MAKE_GRAMMAR: {
358                 final Grammar r = (Grammar)arg;
359                 final JSScope final_scope = scope;
360                 Grammar r2 = new Grammar() {
361                         public int match(String s, int start, Hash v, JSScope scope) throws JSExn {
362                             return r.match(s, start, v, final_scope);
363                         }
364                         public int matchAndWrite(String s, int start, Hash v, JSScope scope, String key) throws JSExn {
365                             return r.matchAndWrite(s, start, v, final_scope, key);
366                         }
367                         public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
368                             Hash v = new Hash();
369                             r.matchAndWrite((String)a0, 0, v, final_scope, "foo");
370                             return v.get("foo");
371                         }
372                     };
373                 Object obj = stack.pop();
374                 if (obj != null && obj instanceof Grammar) r2 = new Grammar.Alternative((Grammar)obj, r2);
375                 stack.push(r2);
376                 break;
377             }
378                 */
379             case ADD_TRAP: case DEL_TRAP: {
380                 JS val = stack.pop();
381                 JS key = stack.pop();
382                 JS js = stack.peek();
383                 // A trap addition/removal
384                 if(!(val instanceof JSFunction)) throw new JSExn("tried to add/remove a non-function trap");
385                 if(js instanceof JSScope) {
386                     JSScope s = (JSScope) js;
387                     while(s.getParentScope() != null) {
388                         if(s.has(key)) throw new JSExn("cannot trap a variable that isn't at the top level scope");
389                         s = s.getParentScope();
390                     }
391                     js = s;
392                 }
393                 if(op == ADD_TRAP) js.addTrap(key, (JSFunction)val);
394                 else js.delTrap(key, (JSFunction)val);
395                 break;
396             }
397
398             case ADD: {
399                 int count = ((JSNumber)arg).toInt();
400                 if(count < 2) throw new Error("this should never happen");
401                 if(count == 2) {
402                     // common case
403                     JS right = stack.pop();
404                     JS left = stack.pop();
405                     JS ret;
406                     if(left instanceof JSString || right instanceof JSString)
407                         ret = JS.S(JS.toString(left).concat(JS.toString(right)));
408                     else if(left instanceof JSNumber.D || right instanceof JSNumber.D)
409                         ret = JS.N(JS.toDouble(left) + JS.toDouble(right));
410                     else {
411                         long l = JS.toLong(left) + JS.toLong(right);
412                         if(l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) ret = JS.N(l);
413                         ret = JS.N((int)l);
414                     }
415                     stack.push(ret);
416                 } else {
417                     JS[] args = new JS[count];
418                     while(--count >= 0) args[count] = stack.pop();
419                     if(args[0] instanceof JSString) {
420                         StringBuffer sb = new StringBuffer(64);
421                         for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
422                         stack.push(JS.S(sb.toString()));
423                     } else {
424                         int numStrings = 0;
425                         for(int i=0;i<args.length;i++) if(args[i] instanceof JSString) numStrings++;
426                         if(numStrings == 0) {
427                             double d = 0.0;
428                             for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
429                             stack.push(JS.N(d));
430                         } else {
431                             int i=0;
432                             StringBuffer sb = new StringBuffer(64);
433                             if(!(args[0] instanceof JSString || args[1] instanceof JSString)) {
434                                 double d=0.0;
435                                 do {
436                                     d += JS.toDouble(args[i++]);
437                                 } while(!(args[i] instanceof JSString));
438                                 sb.append(JS.toString(JS.N(d)));
439                             }
440                             while(i < args.length) sb.append(JS.toString(args[i++]));
441                             stack.push(JS.S(sb.toString()));
442                         }
443                     }
444                 }
445                 break;
446             }
447
448             default: {
449                 JS right = stack.pop();
450                 JS left = stack.pop();
451                 switch(op) {
452                         
453                 case BITOR: stack.push(JS.N(JS.toLong(left) | JS.toLong(right))); break;
454                 case BITXOR: stack.push(JS.N(JS.toLong(left) ^ JS.toLong(right))); break;
455                 case BITAND: stack.push(JS.N(JS.toLong(left) & JS.toLong(right))); break;
456
457                 case SUB: stack.push(JS.N(JS.toDouble(left) - JS.toDouble(right))); break;
458                 case MUL: stack.push(JS.N(JS.toDouble(left) * JS.toDouble(right))); break;
459                 case DIV: stack.push(JS.N(JS.toDouble(left) / JS.toDouble(right))); break;
460                 case MOD: stack.push(JS.N(JS.toDouble(left) % JS.toDouble(right))); break;
461                         
462                 case LSH: stack.push(JS.N(JS.toLong(left) << JS.toLong(right))); break;
463                 case RSH: stack.push(JS.N(JS.toLong(left) >> JS.toLong(right))); break;
464                 case URSH: stack.push(JS.N(JS.toLong(left) >>> JS.toLong(right))); break;
465                         
466                 //#repeat </<=/>/>= LT/LE/GT/GE
467                 case LT: {
468                     if(left instanceof JSString && right instanceof JSString)
469                         stack.push(JS.B(JS.toString(left).compareTo(JS.toString(right)) < 0));
470                     else
471                         stack.push(JS.B(JS.toDouble(left) < JS.toDouble(right)));
472                 }
473                 //#end
474                     
475                 case EQ:
476                 case NE: {
477                     boolean ret;
478                     if(left == null && right == null) ret = true;
479                     else if(left == null || right == null) ret = false;
480                     else ret = left.jsequals(right);
481                     stack.push(JS.B(op == EQ ? ret : !ret)); break;
482                 }
483
484                 default: throw new Error("unknown opcode " + op);
485                 } }
486             }
487
488         } catch(JSExn e) {
489             catchException(e);
490             pc--; // it'll get incremented on the next iteration
491         } // end try/catch
492         } // end for
493     }
494     
495     /** tries to find a handler withing the call chain for this exception
496         if a handler is found the interpreter is setup to call the exception handler
497         if a handler is not found the exception is thrown
498     */
499     void catchException(JSExn e) throws JSExn {
500         while(!stack.empty()) {
501             JS o = stack.pop();
502             if (o instanceof CatchMarker || o instanceof TryMarker) {
503                 boolean inCatch = o instanceof CatchMarker;
504                 if(inCatch) {
505                     o = stack.pop();
506                     if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
507                 }
508                 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
509                     // run the catch block, this will implicitly run the finally block, if it exists
510                     stack.push(o);
511                     stack.push(catchMarker);
512                     stack.push(e.getObject());
513                     f = ((TryMarker)o).f;
514                     scope = ((TryMarker)o).scope;
515                     pc = ((TryMarker)o).catchLoc;
516                     return;
517                 } else {
518                     stack.push(new FinallyData(e));
519                     f = ((TryMarker)o).f;
520                     scope = ((TryMarker)o).scope;
521                     pc = ((TryMarker)o).finallyLoc;
522                     return;
523                 }
524             }
525         }
526         throw e;
527     }
528
529     void setupTrap(Trap t, JS val, CallMarker cm) throws JSExn {
530         stack.push(cm);
531         stack.push(t.isWriteTrap() ? new JSArgs(val,t.f) : new JSArgs(t.f));
532         f = t.f;
533         scope = new TrapScope(t.f.parentScope,t);
534         pc = 0;
535     }
536
537
538     // Markers //////////////////////////////////////////////////////////////////////
539
540     static class Marker extends JS {
541         public JS get(JS key) throws JSExn { throw new Error("this should not be accessible from a script"); }
542         public void put(JS key, JS val) throws JSExn { throw new Error("this should not be accessible from a script"); }
543         public String coerceToString() { throw new Error("this should not be accessible from a script"); }
544         public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn { throw new Error("this should not be accessible from a script"); }
545     }
546     
547     static class CallMarker extends Marker {
548         final int pc;
549         final JSScope scope;
550         final JSFunction f;
551         public CallMarker(Interpreter cx) {
552             pc = cx == null ? -1 : cx.pc + 1;
553             scope = cx == null ? null : cx.scope;
554             f = cx == null ? null : cx.f;
555         }
556     }
557     
558     static class TrapMarker extends CallMarker {
559         Trap t;
560         JS val;
561         boolean cascadeHappened;
562         final boolean pauseOnPut;
563         public TrapMarker(Interpreter cx, Trap t, JS val) { this(cx,t,val,false); } 
564         public TrapMarker(Interpreter cx, Trap t, JS val, boolean pauseOnPut) {
565             super(cx);
566             this.t = t;
567             this.val = val;
568             this.pauseOnPut = pauseOnPut;
569         }
570     }
571     
572     static class CatchMarker extends Marker { }
573     private static CatchMarker catchMarker = new CatchMarker();
574     
575     static class LoopMarker extends Marker {
576         final public int location;
577         final public String label;
578         final public JSScope scope;
579         public LoopMarker(int location, String label, JSScope scope) {
580             this.location = location;
581             this.label = label;
582             this.scope = scope;
583         }
584     }
585     static class TryMarker extends Marker {
586         final public int catchLoc;
587         final public int finallyLoc;
588         final public JSScope scope;
589         final public JSFunction f;
590         public TryMarker(int catchLoc, int finallyLoc, Interpreter cx) {
591             this.catchLoc = catchLoc;
592             this.finallyLoc = finallyLoc;
593             this.scope = cx.scope;
594             this.f = cx.f;
595         }
596     }
597     static class FinallyData extends Marker {
598         final public int op;
599         final public Object arg;
600         final public JSExn exn;
601         public FinallyData(int op) { this(op,null); }
602         public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; this.exn = null; }
603         public FinallyData(JSExn exn) { this.exn = exn; this.op = -1; this.arg = null; } // Just throw this exn
604     }
605
606     static class TrapScope extends JSScope {
607         private Trap t;
608         public TrapScope(JSScope parent, Trap t) {
609             super(parent); this.t = t;
610         }
611         public JS get(JS key) throws JSExn {
612             //#jswitch(key)
613             case "trapee": return t.target;
614             case "callee": return t.f;
615             case "trapname": return t.key;
616             //#end
617             return super.get(key);
618         }
619     }
620     
621     static class JSArgs extends JS {
622         private final JS a0;
623         private final JS a1;
624         private final JS a2;
625         private final JS[] rest;
626         private final int nargs;
627         private final JS callee;
628         
629         public JSArgs(JS callee) { this(null,null,null,null,0,callee); }
630         public JSArgs(JS a0, JS callee) { this(a0,null,null,null,1,callee); }
631         public JSArgs(JS a0, JS a1, JS a2, JS[] rest, int nargs, JS callee) {
632             this.a0 = a0; this.a1 = a1; this.a2 = a2;
633             this.rest = rest; this.nargs = nargs;
634             this.callee = callee;
635         }
636         
637         public JS get(JS key) throws JSExn {
638             if(JS.isInt(key)) {
639                 int n = JS.toInt(key);
640                 switch(n) {
641                     case 0: return a0;
642                     case 1: return a1;
643                     case 2: return a2;
644                     default: return n>= 0 && n < nargs ? rest[n-3] : null;
645                 }
646             }
647             //#jswitch(key)
648             case "callee": return callee;
649             case "length": return JS.N(nargs);
650             //#end
651             return super.get(key);
652         }
653     }
654
655     static class Stub extends JS {
656         private JS method;
657         JS obj;
658         public Stub(JS obj, JS method) { this.obj = obj; this.method = method; }
659         public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
660             return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs);
661         }
662     }
663     
664     static class Stack {
665         private static final int MAX_STACK_SIZE = 512;
666         private JS[] stack = new JS[64];
667         private int sp = 0;
668         
669         boolean empty() { return sp == 0; }
670         void push(JS o) throws JSExn { if(sp == stack.length) grow(); stack[sp++] = o; }
671         JS peek() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[sp-1]; }
672         final JS pop() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[--sp]; }
673         void swap() throws JSExn {
674             if(sp < 2) throw new JSExn("stack overflow");
675             JS tmp = stack[sp-2];
676             stack[sp-2] = stack[sp-1];
677             stack[sp-1] = tmp;
678         }
679         CallMarker findCall() {
680             for(int i=sp-1;i>=0;i--) if(stack[i] instanceof CallMarker) return (CallMarker) stack[i];
681             return null;
682         }
683         void grow() throws JSExn {
684             if(stack.length >= MAX_STACK_SIZE) throw new JSExn("Stack overflow");
685             JS[] stack2 = new JS[stack.length * 2];
686             System.arraycopy(stack,0,stack2,0,stack.length);
687         }       
688         
689         void backtrace(JSExn e) {
690             for(int i=sp-1;i>=0;i--) {
691                 if (stack[i] instanceof CallMarker) {
692                     CallMarker cm = (CallMarker)stack[i];
693                     if(cm.f == null) break;
694                     String s = cm.f.sourceName + ":" + cm.f.line[cm.pc-1];
695                     if(cm instanceof Interpreter.TrapMarker) 
696                         s += " (trap on " + JS.debugToString(((Interpreter.TrapMarker)cm).t.key) + ")";
697                     e.addBacktrace(s);
698                 }
699             }
700         }
701     }
702 }