licensing update to APSL 2.0
[org.ibex.js.git] / src / org / ibex / js / Interpreter.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.js;
6
7 import org.ibex.util.*;
8 import java.util.*;
9
10 /** Encapsulates a single JS interpreter (ie call stack) */
11 class Interpreter implements ByteCodes, Tokens {
12     // Thread-Interpreter Mapping /////////////////////////////////////////////////////////////////////////
13
14     static Interpreter current() { return (Interpreter)threadToInterpreter.get(Thread.currentThread()); }
15     private static Hashtable threadToInterpreter = new Hashtable();
16
17     
18     // Instance members and methods //////////////////////////////////////////////////////////////////////
19     
20     int pausecount;               ///< the number of times pause() has been invoked; -1 indicates unpauseable
21     JSFunction f = null;          ///< the currently-executing JSFunction
22     JSScope scope;                ///< the current top-level scope (LIFO stack via NEWSCOPE/OLDSCOPE)
23     final Stack stack = new Stack(); ///< the object stack
24     int pc = 0;                   ///< the program counter
25
26     Interpreter(JSFunction f, boolean pauseable, JSArgs args) {
27         this.f = f;
28         this.pausecount = pauseable ? 0 : -1;
29         this.scope = f.parentScope;
30         try {
31             stack.push(new CallMarker(null));    // the "root function returned" marker -- f==null
32             stack.push(args);
33         } catch(JSExn e) {
34             throw new Error("should never happen");
35         }
36     }
37     
38     Interpreter(Trap t, JS val, boolean pauseOnPut) {
39         this.pausecount = -1;
40         try {
41             setupTrap(t,val,new TrapMarker(null,t,val,pauseOnPut));
42         } catch(JSExn e) {
43             throw new Error("should never happen");
44         }
45     }
46     
47     /** this is the only synchronization point we need in order to be threadsafe */
48     synchronized JS resume() throws JSExn {
49         if(f == null) throw new RuntimeException("function already finished");
50         if(scope == null) throw new RuntimeException("scope is null");
51         Thread t = Thread.currentThread();
52         Interpreter old = (Interpreter)threadToInterpreter.get(t);
53         threadToInterpreter.put(t, this);
54         try {
55             return run();
56         } finally {
57             if (old == null) threadToInterpreter.remove(t);
58             else threadToInterpreter.put(t, old);
59         }
60     }
61
62     static int getLine() {
63         Interpreter c = Interpreter.current();
64         return c == null || c.f == null || c.pc < 0 || c.pc >= c.f.size ? -1 : c.f.line[c.pc];
65     }
66
67     static String getSourceName() {
68         Interpreter c = Interpreter.current();
69         return c == null || c.f == null ? null : c.f.sourceName;
70     } 
71
72     private static JSExn je(String s) { return new JSExn(getSourceName() + ":" + getLine() + " " + s); }
73
74     private JS run() throws JSExn {
75
76         // if pausecount changes after a get/put/call, we know we've been paused
77         final int initialPauseCount = pausecount;
78
79         OUTER: for(;; pc++) {
80         try {
81             int op = f.op[pc];
82             Object arg = f.arg[pc];
83             if(op == FINALLY_DONE) {
84                 FinallyData fd = (FinallyData) stack.pop();
85                 if(fd == null) continue OUTER; // NOP
86                 if(fd.exn != null) throw fd.exn;
87                 op = fd.op;
88                 arg = fd.arg;
89             }
90             switch(op) {
91             case LITERAL: stack.push((JS)arg); break;
92             case OBJECT: stack.push(new JS.O()); break;
93             case ARRAY: stack.push(new JSArray(JS.toInt((JS)arg))); break;
94             //case DECLARE: scope.declare((JS)(arg==null ? stack.peek() : arg)); if(arg != null) stack.push((JS)arg); break;
95             case JT: if (JS.toBoolean(stack.pop())) pc += JS.toInt((JS)arg) - 1; break;
96             case JF: if (!JS.toBoolean(stack.pop())) pc += JS.toInt((JS)arg) - 1; break;
97             case JMP: pc += JS.toInt((JS)arg) - 1; break;
98             case POP: stack.pop(); break;
99             case SWAP: stack.swap(); break;
100             case DUP: stack.push(stack.peek()); break;
101             case NEWSCOPE: {
102                 int n = JS.toInt((JS)arg);
103                 scope = new JSScope(scope,(n>>>16)&0xffff,(n>>>0)&0xffff);
104                 break;
105             }
106             case OLDSCOPE: scope = scope.parent; break;
107             case GLOBALSCOPE: stack.push(scope.getGlobal()); break;
108             case SCOPEGET: stack.push(scope.get((JS)arg)); break;
109             case SCOPEPUT: scope.put((JS)arg,stack.peek()); break;
110             case ASSERT: if (!JS.toBoolean(stack.pop())) throw je("ibex.assertion.failed"); break;
111             case BITNOT: stack.push(JS.N(~JS.toLong(stack.pop()))); break;
112             case BANG: stack.push(JS.B(!JS.toBoolean(stack.pop()))); break;
113             case NEWFUNCTION: stack.push(((JSFunction)arg)._cloneWithNewParentScope(scope)); break;
114             case LABEL: break;
115
116             case TYPEOF: {
117                 Object o = stack.pop();
118                 if (o == null) stack.push(null);
119                 else if (o instanceof JSString) stack.push(JS.S("string"));
120                 else if (o instanceof JSNumber.B) stack.push(JS.S("boolean"));
121                 else if (o instanceof JSNumber) stack.push(JS.S("number"));
122                 else stack.push(JS.S("object"));
123                 break;
124             }
125
126             case PUSHKEYS: {
127                 JS o = stack.peek();
128                 stack.push(o == null ? null : o.keys());
129                 break;
130             }
131
132             case LOOP:
133                 stack.push(new LoopMarker(pc, pc > 0 && f.op[pc - 1] == LABEL ? (String)f.arg[pc - 1] : (String)null, scope));
134                 stack.push(JS.T);
135                 break;
136
137             case BREAK:
138             case CONTINUE:
139                 while(!stack.empty()) {
140                     JS o = stack.pop();
141                     if (o instanceof CallMarker) je("break or continue not within a loop");
142                     if (o instanceof TryMarker) {
143                         if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
144                         stack.push(new FinallyData(op, arg));
145                         scope = ((TryMarker)o).scope;
146                         pc = ((TryMarker)o).finallyLoc - 1;
147                         continue OUTER;
148                     }
149                     if (o instanceof LoopMarker) {
150                         if (arg == null || arg.equals(((LoopMarker)o).label)) {
151                             int loopInstructionLocation = ((LoopMarker)o).location;
152                             int endOfLoop = JS.toInt((JS)f.arg[loopInstructionLocation]) + loopInstructionLocation;
153                             scope = ((LoopMarker)o).scope;
154                             if (op == CONTINUE) { stack.push(o); stack.push(JS.F); }
155                             pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
156                             continue OUTER;
157                         }
158                     }
159                 }
160                 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
161                                 getSourceName() + ":" + getLine());
162
163             case TRY: {
164                 int[] jmps = (int[]) arg;
165                 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
166                 // each can be < 0 if the specified block does not exist
167                 stack.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1], this));
168                 break;
169             }
170
171             case RETURN: {
172                 JS retval = stack.pop();
173                 while(!stack.empty()) {
174                     Object o = stack.pop();
175                     if (o instanceof TryMarker) {
176                         if(((TryMarker)o).finallyLoc < 0) continue;
177                         stack.push(retval); 
178                         stack.push(new FinallyData(RETURN));
179                         scope = ((TryMarker)o).scope;
180                         pc = ((TryMarker)o).finallyLoc - 1;
181                         continue OUTER;
182                     } else if (o instanceof CallMarker) {
183                         boolean didTrapPut = false;
184                         if (o instanceof TrapMarker) { // handles return component of a write trap
185                             TrapMarker tm = (TrapMarker) o;
186                             boolean cascade = tm.t.isWriteTrap() && !tm.cascadeHappened && !JS.toBoolean(retval);
187                             if(cascade) {
188                                 Trap t = tm.t.nextWriteTrap();
189                                 if(t == null && tm.t.target instanceof JS.Clone) {
190                                     t = ((JS.Clone)tm.t.target).clonee.getTrap(tm.t.key);
191                                     if(t != null) t = t.writeTrap();
192                                 }
193                                 if(t != null) {
194                                     tm.t = t; // we reuse the old trap marker
195                                     setupTrap(t,tm.val,tm);
196                                     pc--; // we increment it on the next iter
197                                     continue OUTER;
198                                 } else {
199                                     didTrapPut = true;
200                                     if(!tm.pauseOnPut) tm.t.target.put(tm.t.key,tm.val);
201                                 }
202                             }
203                         }
204                         CallMarker cm = (CallMarker) o;
205                         scope = cm.scope;
206                         pc = cm.pc - 1;
207                         f = cm.f;
208                         if (didTrapPut) {
209                             if (((TrapMarker)cm).pauseOnPut) { pc++; return ((TrapMarker)cm).val; }
210                             if (pausecount > initialPauseCount) { pc++; return null; }   // we were paused
211                         } else {
212                             stack.push(retval);
213                         }
214                         if (f == null) return retval;
215                         continue OUTER;
216                     }
217                 }
218                 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
219             }
220                 
221             case CASCADE: {
222                 boolean write = JS.toBoolean((JS)arg);
223                 JS val = write ? stack.pop() : null;
224                 CallMarker o = stack.findCall();
225                 if(!(o instanceof TrapMarker)) throw new JSExn("tried to CASCADE while not in a trap");
226                 TrapMarker tm = (TrapMarker) o;
227                 JS key = tm.t.key;
228                 JS target = tm.t.target;
229                 if(tm.t.isWriteTrap() != write) throw new JSExn("tried to do a " + (write?"write":"read") + " cascade in a " + (write?"read":"write") + " trap");
230                 Trap t = write ? tm.t.nextWriteTrap() : tm.t.nextReadTrap();
231                 // FIXME: Doesn't handle multiple levels of clone's (probably can just make this a while loop)
232                 if(t == null && target instanceof JS.Clone) {
233                     target = ((JS.Clone)target).clonee;
234                     t = target.getTrap(key);
235                     if(t != null) t = write ? t.writeTrap() : t.readTrap();
236                 }
237                 if(write) {
238                     tm.cascadeHappened = true;
239                     stack.push(val);
240                 }
241                 if(t != null) {
242                     setupTrap(t,val,new TrapMarker(this,t,val,tm.pauseOnPut));
243                     pc--; // we increment later
244                 } else {
245                     if(write) {
246                         if (tm.pauseOnPut) { pc++; return val; }
247                         target.put(key,val);
248                     } else {
249                         JS ret = target.get(key);
250                         if (ret == JS.METHOD) ret = new Stub(target, key);
251                         stack.push(ret);                        
252                     }
253                     if (pausecount > initialPauseCount) { pc++; return null; }   // we were paused                    
254                 }
255                 break;
256             }
257                 
258             case PUT: {
259                 JS val = stack.pop();
260                 JS key = stack.pop();
261                 JS target = stack.peek();
262                 if (target == null) throw je("tried to put " + JS.debugToString(val) + " to the " + JS.debugToString(key) + " property on the null value");
263                 if (key == null) throw je("tried to assign \"" + JS.debugToString(val) + "\" to the null key");
264                 
265                 Trap t = target.getTrap(key);
266                 if(t != null) t = t.writeTrap();
267                 
268                 if(t == null && target instanceof JS.Clone) {
269                     target = ((JS.Clone)target).clonee;
270                     t = target.getTrap(key);
271                     if(t != null) t = t.writeTrap();
272                 }
273
274                 stack.push(val);
275                 
276                 if(t != null) {
277                     setupTrap(t,val,new TrapMarker(this,t,val));
278                     pc--; // we increment later
279                 } else {
280                     target.put(key,val);
281                     if (pausecount > initialPauseCount) { pc++; return null; }   // we were paused
282                 }
283                 break;
284             }
285
286             case GET:
287             case GET_PRESERVE: {
288                 JS target, key;
289                 if (op == GET) {
290                     key = arg == null ? stack.pop() : (JS)arg;
291                     target = stack.pop();
292                 } else {
293                     key = stack.pop();
294                     target = stack.peek();
295                     stack.push(key);
296                 }
297                 JS ret = null;
298                 if (key == null) throw je("tried to get the null key from " + JS.debugToString(target));
299                 if (target == null) throw je("tried to get property \"" + JS.debugToString(key) + "\" from the null object");
300                 
301                 Trap t = target.getTrap(key);
302                 if(t != null) t = t.readTrap();
303                 
304                 if(t == null && target instanceof JS.Clone) {
305                     target = ((JS.Clone)target).clonee;
306                     t = target.getTrap(key);
307                     if(t != null) t = t.readTrap();
308                 }
309                 
310                 if(t != null) {
311                     setupTrap(t,null,new TrapMarker(this,t,null));
312                     pc--; // we increment later
313                 } else {
314                     ret = target.get(key);
315                     if (pausecount > initialPauseCount) { pc++; return null; }   // we were paused
316                     if (ret == JS.METHOD) ret = new Stub(target, key);
317                     stack.push(ret);
318                 }
319                 break;
320             }
321             
322             case CALL: case CALLMETHOD: {
323                 int numArgs = JS.toInt((JS)arg);
324                 
325                 JS[] rest = numArgs > 3 ? new JS[numArgs - 3] : null;
326                 for(int i=numArgs - 1; i>2; i--) rest[i-3] = stack.pop();
327                 JS a2 = numArgs <= 2 ? null : stack.pop();
328                 JS a1 = numArgs <= 1 ? null : stack.pop();
329                 JS a0 = numArgs <= 0 ? null : stack.pop();
330                 
331                 JS method = null;
332                 JS ret = null;
333                 JS object = stack.pop();
334
335                 if (op == CALLMETHOD) {
336                     if (object == JS.METHOD) {
337                         method = stack.pop();
338                         object = stack.pop();
339                     } else if (object == null) {
340                         method = stack.pop();
341                         object = stack.pop();
342                         throw new JSExn("function '"+JS.debugToString(method)+"' not found in " + object.getClass().getName());
343                     } else {
344                         stack.pop();
345                         stack.pop();
346                     }
347                 }
348
349                 if (object instanceof JSFunction) {
350                     stack.push(new CallMarker(this));
351                     stack.push(new JSArgs(a0,a1,a2,rest,numArgs,object));
352                     f = (JSFunction)object;
353                     scope = f.parentScope;
354                     pc = -1;
355                     break;
356                 } else {
357                     JS c = (JS)object;
358                     ret = method == null ? c.call(a0, a1, a2, rest, numArgs) : c.callMethod(method, a0, a1, a2, rest, numArgs);
359                 }
360                 
361                 if (pausecount > initialPauseCount) { pc++; return null; }
362                 stack.push(ret);
363                 break;
364             }
365
366             case THROW:
367                 throw new JSExn(stack.pop(), this);
368
369                 /* FIXME GRAMMAR
370             case MAKE_GRAMMAR: {
371                 final Grammar r = (Grammar)arg;
372                 final JSScope final_scope = scope;
373                 Grammar r2 = new Grammar() {
374                         public int match(String s, int start, Hash v, JSScope scope) throws JSExn {
375                             return r.match(s, start, v, final_scope);
376                         }
377                         public int matchAndWrite(String s, int start, Hash v, JSScope scope, String key) throws JSExn {
378                             return r.matchAndWrite(s, start, v, final_scope, key);
379                         }
380                         public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
381                             Hash v = new Hash();
382                             r.matchAndWrite((String)a0, 0, v, final_scope, "foo");
383                             return v.get("foo");
384                         }
385                     };
386                 Object obj = stack.pop();
387                 if (obj != null && obj instanceof Grammar) r2 = new Grammar.Alternative((Grammar)obj, r2);
388                 stack.push(r2);
389                 break;
390             }
391                 */
392             case ADD_TRAP: case DEL_TRAP: {
393                 JS val = stack.pop();
394                 JS key = stack.pop();
395                 JS js = stack.peek();
396                 // A trap addition/removal
397                 if(!(val instanceof JSFunction)) throw new JSExn("tried to add/remove a non-function trap");
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(new TrapArgs(t,val));
537         f = t.f;
538         scope = f.parentScope;
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 TrapArgs extends JS {
612         private Trap t;
613         private JS val;
614         public TrapArgs(Trap t, JS val) { this.t = t; this.val = val; }
615         public JS get(JS key) throws JSExn {
616             if(JS.isInt(key) && JS.toInt(key) == 0) return val;
617             //#switch(JS.toString(key))
618             case "trapee": return t.target;
619             case "callee": return t.f;
620             case "trapname": return t.key;
621             case "length": return t.isWriteTrap() ? ONE : ZERO;
622             //#end
623             return super.get(key);
624         }
625     }
626     
627     static class JSArgs extends JS {
628         private final JS a0;
629         private final JS a1;
630         private final JS a2;
631         private final JS[] rest;
632         private final int nargs;
633         private final JS callee;
634         
635         public JSArgs(JS callee) { this(null,null,null,null,0,callee); }
636         public JSArgs(JS a0, JS callee) { this(a0,null,null,null,1,callee); }
637         public JSArgs(JS a0, JS a1, JS a2, JS[] rest, int nargs, JS callee) {
638             this.a0 = a0; this.a1 = a1; this.a2 = a2;
639             this.rest = rest; this.nargs = nargs;
640             this.callee = callee;
641         }
642         
643         public JS get(JS key) throws JSExn {
644             if(JS.isInt(key)) {
645                 int n = JS.toInt(key);
646                 switch(n) {
647                     case 0: return a0;
648                     case 1: return a1;
649                     case 2: return a2;
650                     default: return n>= 0 && n < nargs ? rest[n-3] : null;
651                 }
652             }
653             //#switch(JS.toString(key))
654             case "callee": return callee;
655             case "length": return JS.N(nargs);
656             //#end
657             return super.get(key);
658         }
659     }
660
661     static class Stub extends JS {
662         private JS method;
663         JS obj;
664         public Stub(JS obj, JS method) { this.obj = obj; this.method = method; }
665         public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
666             return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs);
667         }
668     }
669     
670     static class Stack {
671         private static final int MAX_STACK_SIZE = 512;
672         private JS[] stack = new JS[64];
673         private int sp = 0;
674         
675         boolean empty() { return sp == 0; }
676         void push(JS o) throws JSExn { if(sp == stack.length) grow(); stack[sp++] = o; }
677         JS peek() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[sp-1]; }
678         final JS pop() { if(sp == 0) throw new RuntimeException("Stack underflow"); return stack[--sp]; }
679         void swap() throws JSExn {
680             if(sp < 2) throw new JSExn("stack overflow");
681             JS tmp = stack[sp-2];
682             stack[sp-2] = stack[sp-1];
683             stack[sp-1] = tmp;
684         }
685         CallMarker findCall() {
686             for(int i=sp-1;i>=0;i--) if(stack[i] instanceof CallMarker) return (CallMarker) stack[i];
687             return null;
688         }
689         void grow() throws JSExn {
690             if(stack.length >= MAX_STACK_SIZE) throw new JSExn("Stack overflow");
691             JS[] stack2 = new JS[stack.length * 2];
692             System.arraycopy(stack,0,stack2,0,stack.length);
693         }       
694         
695         void backtrace(JSExn e) {
696             for(int i=sp-1;i>=0;i--) {
697                 if (stack[i] instanceof CallMarker) {
698                     CallMarker cm = (CallMarker)stack[i];
699                     if(cm.f == null) break;
700                     String s = cm.f.sourceName + ":" + cm.f.line[cm.pc-1];
701                     if(cm instanceof Interpreter.TrapMarker) 
702                         s += " (trap on " + JS.debugToString(((Interpreter.TrapMarker)cm).t.key) + ")";
703                     e.addBacktrace(s);
704                 }
705             }
706         }
707     }
708 }