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