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