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