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