added new invocation that does not create a call frame
[org.ibex.js.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
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     Vec stack = new Vec();        ///< the object stack
23     int pc = 0;                   ///< the program counter
24
25     Interpreter(JSFunction f, boolean pauseable, JSArray args) { this(f, pauseable, args, true); }
26     Interpreter(JSFunction f, boolean pauseable, JSArray args, boolean wrap) {
27         stack.push(new Interpreter.CallMarker(this));    // the "root function returned" marker -- f==null
28         this.f = f;
29         this.pausecount = pauseable ? 0 : -1;
30         this.scope = wrap ? new JSScope(f.parentScope) : f.parentScope;
31         stack.push(args);
32     }
33     
34     /** this is the only synchronization point we need in order to be threadsafe */
35     synchronized Object resume() throws JSExn {
36         Thread t = Thread.currentThread();
37         Interpreter old = (Interpreter)threadToInterpreter.get(t);
38         threadToInterpreter.put(t, this);
39         try {
40             return run();
41         } finally {
42             if (old == null) threadToInterpreter.remove(t);
43             else threadToInterpreter.put(t, old);
44         }
45     }
46
47     static int getLine() {
48         Interpreter c = Interpreter.current();
49         return c == null || c.f == null || c.pc < 0 || c.pc >= c.f.size ? -1 : c.f.line[c.pc];
50     }
51
52     static String getSourceName() {
53         Interpreter c = Interpreter.current();
54         return c == null || c.f == null ? null : c.f.sourceName;
55     } 
56
57     private static JSExn je(String s) { return new JSExn(getSourceName() + ":" + getLine() + " " + s); }
58
59     // FIXME: double check the trap logic
60     private Object run() throws JSExn {
61
62         // if pausecount changes after a get/put/call, we know we've been paused
63         final int initialPauseCount = pausecount;
64
65         OUTER: for(;; pc++) {
66         try {
67             if (f == null) return stack.pop();
68             int op = f.op[pc];
69             Object arg = f.arg[pc];
70             if(op == FINALLY_DONE) {
71                 FinallyData fd = (FinallyData) stack.pop();
72                 if(fd == null) continue OUTER; // NOP
73                 if(fd.exn != null) throw fd.exn;
74                 op = fd.op;
75                 arg = fd.arg;
76             }
77             switch(op) {
78             case LITERAL: stack.push(arg); break;
79             case OBJECT: stack.push(new JS()); break;
80             case ARRAY: stack.push(new JSArray(JS.toNumber(arg).intValue())); break;
81             case DECLARE: scope.declare((String)(arg==null ? stack.peek() : arg)); if(arg != null) stack.push(arg); break;
82             case TOPSCOPE: stack.push(scope); break;
83             case JT: if (JS.toBoolean(stack.pop())) pc += JS.toNumber(arg).intValue() - 1; break;
84             case JF: if (!JS.toBoolean(stack.pop())) pc += JS.toNumber(arg).intValue() - 1; break;
85             case JMP: pc += JS.toNumber(arg).intValue() - 1; break;
86             case POP: stack.pop(); break;
87             case SWAP: {
88                 int depth = (arg == null ? 1 : JS.toInt(arg));
89                 Object save = stack.elementAt(stack.size() - 1);
90                 for(int i=stack.size() - 1; i > stack.size() - 1 - depth; i--)
91                     stack.setElementAt(stack.elementAt(i-1), i);
92                 stack.setElementAt(save, stack.size() - depth - 1);
93                 break; }
94             case DUP: stack.push(stack.peek()); break;
95             case NEWSCOPE: scope = new JSScope(scope); break;
96             case OLDSCOPE: scope = scope.getParentScope(); break;
97             case ASSERT:
98                 if (JS.checkAssertions && !JS.toBoolean(stack.pop()))
99                     throw je("ibex.assertion.failed" /*FEATURE: line number*/); break;
100             case BITNOT: stack.push(JS.N(~JS.toLong(stack.pop()))); break;
101             case BANG: stack.push(JS.B(!JS.toBoolean(stack.pop()))); break;
102             case NEWFUNCTION: stack.push(((JSFunction)arg)._cloneWithNewParentScope(scope)); break;
103             case LABEL: break;
104
105             case TYPEOF: {
106                 Object o = stack.pop();
107                 if (o == null) stack.push(null);
108                 else if (o instanceof JS) stack.push("object");
109                 else if (o instanceof String) stack.push("string");
110                 else if (o instanceof Number) stack.push("number");
111                 else if (o instanceof Boolean) stack.push("boolean");
112                 else throw new Error("this should not happen");
113                 break;
114             }
115
116             case PUSHKEYS: {
117                 Object o = stack.peek();
118                 Enumeration e = ((JS)o).keys();
119                 JSArray a = new JSArray();
120                 while(e.hasMoreElements()) a.addElement(e.nextElement());
121                 stack.push(a);
122                 break;
123             }
124
125             case LOOP:
126                 stack.push(new LoopMarker(pc, pc > 0 && f.op[pc - 1] == LABEL ? (String)f.arg[pc - 1] : (String)null, scope));
127                 stack.push(Boolean.TRUE);
128                 break;
129
130             case BREAK:
131             case CONTINUE:
132                 while(stack.size() > 0) {
133                     Object o = stack.pop();
134                     if (o instanceof CallMarker) je("break or continue not within a loop");
135                     if (o instanceof TryMarker) {
136                         if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
137                         stack.push(new FinallyData(op, arg));
138                         scope = ((TryMarker)o).scope;
139                         pc = ((TryMarker)o).finallyLoc - 1;
140                         continue OUTER;
141                     }
142                     if (o instanceof LoopMarker) {
143                         if (arg == null || arg.equals(((LoopMarker)o).label)) {
144                             int loopInstructionLocation = ((LoopMarker)o).location;
145                             int endOfLoop = ((Integer)f.arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
146                             scope = ((LoopMarker)o).scope;
147                             if (op == CONTINUE) { stack.push(o); stack.push(Boolean.FALSE); }
148                             pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
149                             continue OUTER;
150                         }
151                     }
152                 }
153                 throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
154                                 getSourceName() + ":" + getLine());
155
156             case TRY: {
157                 int[] jmps = (int[]) arg;
158                 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
159                 // each can be < 0 if the specified block does not exist
160                 stack.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1], this));
161                 break;
162             }
163
164             case RETURN: {
165                 Object retval = stack.pop();
166                 while(stack.size() > 0) {
167                     Object o = stack.pop();
168                     if (o instanceof TryMarker) {
169                         if(((TryMarker)o).finallyLoc < 0) continue;
170                         stack.push(retval); 
171                         stack.push(new FinallyData(RETURN));
172                         scope = ((TryMarker)o).scope;
173                         pc = ((TryMarker)o).finallyLoc - 1;
174                         continue OUTER;
175                     } else if (o instanceof CallMarker) {
176                         if (scope instanceof Trap.TrapScope) { // handles return component of a read trap
177                             Trap.TrapScope ts = (Trap.TrapScope)scope;
178                             if (retval != null && retval instanceof Boolean && ((Boolean)retval).booleanValue())
179                                 ts.cascadeHappened = true;
180                             if (!ts.cascadeHappened) {
181                                 ts.cascadeHappened = true;
182                                 Trap t = ts.t.next;
183                                 while (t != null && t.f.numFormalArgs == 0) t = t.next;
184                                 if (t == null) {
185                                     ((JS)ts.t.trapee).put(ts.t.name, ts.val);
186                                     if (pausecount > initialPauseCount) { pc++; return null; }   // we were paused
187                                 } else {
188                                     stack.push(o);
189                                     JSArray args = new JSArray();
190                                     args.addElement(ts.val);
191                                     stack.push(args);
192                                     f = t.f;
193                                     scope = new Trap.TrapScope(f.parentScope, t, ts.val);
194                                     pc = -1;
195                                     continue OUTER;
196                                 }
197                             }
198                         }
199                         scope = ((CallMarker)o).scope;
200                         pc = ((CallMarker)o).pc - 1;
201                         f = (JSFunction)((CallMarker)o).f;
202                         stack.push(retval);
203                         continue OUTER;
204                     }
205                 }
206                 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
207             }
208
209             case PUT: {
210                 Object val = stack.pop();
211                 Object key = stack.pop();
212                 Object target = stack.peek();
213                 if (target == null)
214                     throw je("tried to put a value to the " + key + " property on the null value");
215                 if (!(target instanceof JS))
216                     throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
217                 if (key == null)
218                     throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
219
220                 Trap t = null;
221                 if (target instanceof JSScope && key.equals("cascade")) {
222                     Trap.TrapScope ts = null;
223                     JSScope p = (JSScope)target; // search the scope-path for the trap
224                     if (target instanceof Trap.TrapScope) {
225                         ts = (Trap.TrapScope)target;
226                     }
227                     else {
228                         while (ts == null && p.getParentScope() != null) {
229                             p = p.getParentScope();
230                             if (p instanceof Trap.TrapScope) {
231                                 ts = (Trap.TrapScope)p;
232                             }
233                         }
234                     }
235                     t = ts.t.next;
236                     ts.cascadeHappened = true;
237                     while (t != null && t.f.numFormalArgs == 0) t = t.next;
238                     if (t == null) { target = ts.t.trapee; key = ts.t.name; }
239
240                 } else if (target instanceof Trap.TrapScope && key.equals(((Trap.TrapScope)target).t.name)) {
241                     throw je("tried to put to " + key + " inside a trap it owns; use cascade instead"); 
242
243                 } else if (target instanceof JS) {
244                     if (target instanceof JSScope) {
245                         JSScope p = (JSScope)target; // search the scope-path for the trap
246                         t = p.getTrap(key);
247                         while (t == null && p.getParentScope() != null) { p = p.getParentScope(); t = p.getTrap(key); }
248                     } else {
249                         t = ((JS)target).getTrap(key);
250                     }
251                     while (t != null && t.f.numFormalArgs == 0) t = t.next; // find the first write trap
252                 }
253                 if (t != null) {
254                     stack.push(new CallMarker(this));
255                     JSArray args = new JSArray();
256                     args.addElement(val);
257                     stack.push(args);
258                     f = t.f;
259                     scope = new Trap.TrapScope(f.parentScope, t, val);
260                     pc = -1;
261                     break;
262                 }
263                 ((JS)target).put(key, val);
264                 if (pausecount > initialPauseCount) { pc++; return null; }   // we were paused
265                 stack.push(val);
266                 break;
267             }
268
269             case GET:
270             case GET_PRESERVE: {
271                 Object o, v;
272                 if (op == GET) {
273                     v = arg == null ? stack.pop() : arg;
274                     o = stack.pop();
275                 } else {
276                     v = stack.pop();
277                     o = stack.peek();
278                     stack.push(v);
279                 }
280                 Object ret = null;
281                 if (v == null) throw je("tried to get the null key from " + o);
282                 if (o == null) throw je("tried to get property \"" + v + "\" from the null object");
283                 if (o instanceof String || o instanceof Number || o instanceof Boolean) {
284                     ret = getFromPrimitive(o,v);
285                     stack.push(ret);
286                     break;
287                 } else if (o instanceof JS) {
288                     Trap t = null;
289                     if (o instanceof Trap.TrapScope && v.equals("cascade")) {
290                         t = ((Trap.TrapScope)o).t.next;
291                         while (t != null && t.f.numFormalArgs != 0) t = t.next;
292                         if (t == null) { v = ((Trap.TrapScope)o).t.name; o = ((Trap.TrapScope)o).t.trapee; }
293
294                     } else if (o instanceof JS) {
295                         if (o instanceof JSScope) {
296                             JSScope p = (JSScope)o; // search the scope-path for the trap
297                             t = p.getTrap(v);
298                             while (t == null && p.getParentScope() != null) { p = p.getParentScope(); t = p.getTrap(v); }
299                         } else {
300                             t = ((JS)o).getTrap(v);
301                         }
302                         while (t != null && t.f.numFormalArgs != 0) t = t.next; // get first read trap
303                     }
304                     if (t != null) {
305                         stack.push(new CallMarker(this));
306                         JSArray args = new JSArray();
307                         stack.push(args);
308                         f = t.f;
309                         scope = new Trap.TrapScope(f.parentScope, t, null);
310                         ((Trap.TrapScope)scope).cascadeHappened = true;
311                         pc = -1;
312                         break;
313                     }
314                     ret = ((JS)o).get(v);
315                     if (ret == JS.METHOD) ret = new Stub((JS)o, v);
316                     if (pausecount > initialPauseCount) { pc++; return null; }   // we were paused
317                     stack.push(ret);
318                     break;
319                 }
320                 throw je("tried to get property " + v + " from a " + o.getClass().getName());
321             }
322             
323             case CALL: case CALLMETHOD: {
324                 int numArgs = JS.toInt(arg);
325                 Object method = null;
326                 Object ret = null;
327                 Object object = stack.pop();
328
329                 if (op == CALLMETHOD) {
330                     if (object == JS.METHOD) {
331                         method = stack.pop();
332                         object = stack.pop();
333                     } else if (object == null) {
334                         Object name = stack.pop();
335                         stack.pop();
336                         throw new JSExn("function '"+name+"' not found");
337                     } else {
338                         stack.pop();
339                         stack.pop();
340                     }
341                 }
342                 Object[] rest = numArgs > 3 ? new Object[numArgs - 3] : null;
343                 for(int i=numArgs - 1; i>2; i--) rest[i-3] = stack.pop();
344                 Object a2 = numArgs <= 2 ? null : stack.pop();
345                 Object a1 = numArgs <= 1 ? null : stack.pop();
346                 Object a0 = numArgs <= 0 ? null : stack.pop();
347
348                 if (object instanceof String || object instanceof Number || object instanceof Boolean) {
349                     ret = callMethodOnPrimitive(object, method, a0, a1, a2, null, numArgs);
350
351                 } else if (object instanceof JSFunction) {
352                     // FIXME: use something similar to call0/call1/call2 here
353                     JSArray arguments = new JSArray();
354                     for(int i=0; i<numArgs; i++) arguments.addElement(i==0?a0:i==1?a1:i==2?a2:rest[i-3]);
355                     stack.push(new CallMarker(this));
356                     stack.push(arguments);
357                     f = (JSFunction)object;
358                     scope = new JSScope(f.parentScope);
359                     pc = -1;
360                     break;
361
362                 } else if (object instanceof JS) {
363                     JS c = (JS)object;
364                     ret = method == null ? c.call(a0, a1, a2, rest, numArgs) : c.callMethod(method, a0, a1, a2, rest, numArgs);
365
366                 } else {
367                     throw new JSExn("can't call a " + object + " @" + pc + "\n" + f.dump());
368
369                 }
370                 if (pausecount > initialPauseCount) { pc++; return null; }
371                 stack.push(ret);
372                 break;
373             }
374
375             case THROW:
376                 throw new JSExn(stack.pop(), stack, f, pc, scope);
377
378                 /* FIXME
379             case MAKE_GRAMMAR: {
380                 final Grammar r = (Grammar)arg;
381                 final JSScope final_scope = scope;
382                 Grammar r2 = new Grammar() {
383                         public int match(String s, int start, Hash v, JSScope scope) throws JSExn {
384                             return r.match(s, start, v, final_scope);
385                         }
386                         public int matchAndWrite(String s, int start, Hash v, JSScope scope, String key) throws JSExn {
387                             return r.matchAndWrite(s, start, v, final_scope, key);
388                         }
389                         public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
390                             Hash v = new Hash();
391                             r.matchAndWrite((String)a0, 0, v, final_scope, "foo");
392                             return v.get("foo");
393                         }
394                     };
395                 Object obj = stack.pop();
396                 if (obj != null && obj instanceof Grammar) r2 = new Grammar.Alternative((Grammar)obj, r2);
397                 stack.push(r2);
398                 break;
399             }
400                 */
401             case ADD_TRAP: case DEL_TRAP: {
402                 Object val = stack.pop();
403                 Object key = stack.pop();
404                 Object obj = stack.peek();
405                 // A trap addition/removal
406                 JS js = obj instanceof JSScope ? ((JSScope)obj).top() : (JS) obj;
407                 if(op == ADD_TRAP) js.addTrap(key, (JSFunction)val);
408                 else js.delTrap(key, (JSFunction)val);
409                 break;
410             }
411
412             case ASSIGN_SUB: case ASSIGN_ADD: {
413                 Object val = stack.pop();
414                 Object key = stack.pop();
415                 Object obj = stack.peek();
416                 // The following setup is VERY important. The generated bytecode depends on the stack
417                 // being setup like this (top to bottom) KEY, OBJ, VAL, KEY, OBJ
418                 stack.push(key);
419                 stack.push(val);
420                 stack.push(obj);
421                 stack.push(key);
422                 break;
423             }
424
425             case ADD: {
426                 int count = ((Number)arg).intValue();
427                 if(count < 2) throw new Error("this should never happen");
428                 if(count == 2) {
429                     // common case
430                     Object right = stack.pop();
431                     Object left = stack.pop();
432                     if(left instanceof String || right instanceof String)
433                         stack.push(JS.toString(left).concat(JS.toString(right)));
434                     else stack.push(JS.N(JS.toDouble(left) + JS.toDouble(right)));
435                 } else {
436                     Object[] args = new Object[count];
437                     while(--count >= 0) args[count] = stack.pop();
438                     if(args[0] instanceof String) {
439                         StringBuffer sb = new StringBuffer(64);
440                         for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
441                         stack.push(sb.toString());
442                     } else {
443                         int numStrings = 0;
444                         for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
445                         if(numStrings == 0) {
446                             double d = 0.0;
447                             for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
448                             stack.push(JS.N(d));
449                         } else {
450                             int i=0;
451                             StringBuffer sb = new StringBuffer(64);
452                             if(!(args[0] instanceof String || args[1] instanceof String)) {
453                                 double d=0.0;
454                                 do {
455                                     d += JS.toDouble(args[i++]);
456                                 } while(!(args[i] instanceof String));
457                                 sb.append(JS.toString(JS.N(d)));
458                             }
459                             while(i < args.length) sb.append(JS.toString(args[i++]));
460                             stack.push(sb.toString());
461                         }
462                     }
463                 }
464                 break;
465             }
466
467             default: {
468                 Object right = stack.pop();
469                 Object left = stack.pop();
470                 switch(op) {
471                         
472                 case BITOR: stack.push(JS.N(JS.toLong(left) | JS.toLong(right))); break;
473                 case BITXOR: stack.push(JS.N(JS.toLong(left) ^ JS.toLong(right))); break;
474                 case BITAND: stack.push(JS.N(JS.toLong(left) & JS.toLong(right))); break;
475
476                 case SUB: stack.push(JS.N(JS.toDouble(left) - JS.toDouble(right))); break;
477                 case MUL: stack.push(JS.N(JS.toDouble(left) * JS.toDouble(right))); break;
478                 case DIV: stack.push(JS.N(JS.toDouble(left) / JS.toDouble(right))); break;
479                 case MOD: stack.push(JS.N(JS.toDouble(left) % JS.toDouble(right))); break;
480                         
481                 case LSH: stack.push(JS.N(JS.toLong(left) << JS.toLong(right))); break;
482                 case RSH: stack.push(JS.N(JS.toLong(left) >> JS.toLong(right))); break;
483                 case URSH: stack.push(JS.N(JS.toLong(left) >>> JS.toLong(right))); break;
484                         
485                 case LT: case LE: case GT: case GE: {
486                     if (left == null) left = JS.N(0);
487                     if (right == null) right = JS.N(0);
488                     int result = 0;
489                     if (left instanceof String || right instanceof String) {
490                         result = left.toString().compareTo(right.toString());
491                     } else {
492                         result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
493                     }
494                     stack.push(JS.B((op == LT && result < 0) || (op == LE && result <= 0) ||
495                                (op == GT && result > 0) || (op == GE && result >= 0)));
496                     break;
497                 }
498                     
499                 case EQ:
500                 case NE: {
501                     Object l = left;
502                     Object r = right;
503                     boolean ret;
504                     if (l == null) { Object tmp = r; r = l; l = tmp; }
505                     if (l == null && r == null) ret = true;
506                     else if (r == null) ret = false; // l != null, so its false
507                     else if (l instanceof Boolean) ret = JS.B(JS.toBoolean(r)).equals(l);
508                     else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
509                     else if (l instanceof String) ret = r != null && l.equals(r.toString());
510                     else ret = l.equals(r);
511                     stack.push(JS.B(op == EQ ? ret : !ret)); break;
512                 }
513
514                 default: throw new Error("unknown opcode " + op);
515                 } }
516             }
517
518         } catch(JSExn e) {
519             while(stack.size() > 0) {
520                 Object o = stack.pop();
521                 if (o instanceof CatchMarker || o instanceof TryMarker) {
522                     boolean inCatch = o instanceof CatchMarker;
523                     if(inCatch) {
524                         o = stack.pop();
525                         if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
526                     }
527                     if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
528                         // run the catch block, this will implicitly run the finally block, if it exists
529                         stack.push(o);
530                         stack.push(catchMarker);
531                         stack.push(e.getObject());
532                         f = ((TryMarker)o).f;
533                         scope = ((TryMarker)o).scope;
534                         pc = ((TryMarker)o).catchLoc - 1;
535                         continue OUTER;
536                     } else {
537                         stack.push(new FinallyData(e));
538                         f = ((TryMarker)o).f;
539                         scope = ((TryMarker)o).scope;
540                         pc = ((TryMarker)o).finallyLoc - 1;
541                         continue OUTER;
542                     }
543                 }
544             }
545             throw e;
546         } // end try/catch
547         } // end for
548     }
549
550
551
552     // Markers //////////////////////////////////////////////////////////////////////
553
554     public static class CallMarker {
555         int pc;
556         JSScope scope;
557         JSFunction f;
558         public CallMarker(Interpreter cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
559     }
560     
561     public static class CatchMarker { }
562     private static CatchMarker catchMarker = new CatchMarker();
563     
564     public static class LoopMarker {
565         public int location;
566         public String label;
567         public JSScope scope;
568         public LoopMarker(int location, String label, JSScope scope) {
569             this.location = location;
570             this.label = label;
571             this.scope = scope;
572         }
573     }
574     public static class TryMarker {
575         public int catchLoc;
576         public int finallyLoc;
577         public JSScope scope;
578         public JSFunction f;
579         public TryMarker(int catchLoc, int finallyLoc, Interpreter cx) {
580             this.catchLoc = catchLoc;
581             this.finallyLoc = finallyLoc;
582             this.scope = cx.scope;
583             this.f = cx.f;
584         }
585     }
586     public static class FinallyData {
587         public int op;
588         public Object arg;
589         public JSExn exn;
590         public FinallyData(int op) { this(op,null); }
591         public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
592         public FinallyData(JSExn exn) { this.exn = exn; } // Just throw this exn
593     }
594
595
596     // Operations on Primitives //////////////////////////////////////////////////////////////////////
597
598     static Object callMethodOnPrimitive(Object o, Object method, Object arg0, Object arg1, Object arg2, Object[] rest, int alength) throws JSExn {
599         if (method == null || !(method instanceof String) || "".equals(method))
600             throw new JSExn("attempt to call a non-existant method on a primitive");
601
602         if (o instanceof Number) {
603             //#switch(method)
604             case "toFixed": throw new JSExn("toFixed() not implemented");
605             case "toExponential": throw new JSExn("toExponential() not implemented");
606             case "toPrecision": throw new JSExn("toPrecision() not implemented");
607             case "toString": {
608                 int radix = alength >= 1 ? JS.toInt(arg0) : 10;
609                 return Long.toString(((Number)o).longValue(),radix);
610             }
611             //#end
612         } else if (o instanceof Boolean) {
613             // No methods for Booleans
614             throw new JSExn("attempt to call a method on a Boolean");
615         }
616
617         String s = JS.toString(o);
618         int slength = s.length();
619         //#switch(method)
620         case "substring": {
621             int a = alength >= 1 ? JS.toInt(arg0) : 0;
622             int b = alength >= 2 ? JS.toInt(arg1) : slength;
623             if (a > slength) a = slength;
624             if (b > slength) b = slength;
625             if (a < 0) a = 0;
626             if (b < 0) b = 0;
627             if (a > b) { int tmp = a; a = b; b = tmp; }
628             return s.substring(a,b);
629         }
630         case "substr": {
631             int start = alength >= 1 ? JS.toInt(arg0) : 0;
632             int len = alength >= 2 ? JS.toInt(arg1) : Integer.MAX_VALUE;
633             if (start < 0) start = slength + start;
634             if (start < 0) start = 0;
635             if (len < 0) len = 0;
636             if (len > slength - start) len = slength - start;
637             if (len <= 0) return "";
638             return s.substring(start,start+len);
639         }
640         case "charAt": {
641             int p = alength >= 1 ? JS.toInt(arg0) : 0;
642             if (p < 0 || p >= slength) return "";
643             return s.substring(p,p+1);
644         }
645         case "charCodeAt": {
646             int p = alength >= 1 ? JS.toInt(arg0) : 0;
647             if (p < 0 || p >= slength) return JS.N(Double.NaN);
648             return JS.N(s.charAt(p));
649         }
650         case "concat": {
651             StringBuffer sb = new StringBuffer(slength*2).append(s);
652             for(int i=0;i<alength;i++) sb.append(i==0?arg0:i==1?arg1:i==2?arg2:rest[i-3]);
653             return sb.toString();
654         }
655         case "indexOf": {
656             String search = alength >= 1 ? arg0.toString() : "null";
657             int start = alength >= 2 ? JS.toInt(arg1) : 0;
658             // Java's indexOf handles an out of bounds start index, it'll return -1
659             return JS.N(s.indexOf(search,start));
660         }
661         case "lastIndexOf": {
662             String search = alength >= 1 ? arg0.toString() : "null";
663             int start = alength >= 2 ? JS.toInt(arg1) : 0;
664             // Java's indexOf handles an out of bounds start index, it'll return -1
665             return JS.N(s.lastIndexOf(search,start));            
666         }
667         case "match": return JSRegexp.stringMatch(s,arg0);
668         case "replace": return JSRegexp.stringReplace(s,arg0,arg1);
669         case "search": return JSRegexp.stringSearch(s,arg0);
670         case "split": return JSRegexp.stringSplit(s,arg0,arg1,alength);
671         case "toLowerCase": return s.toLowerCase();
672         case "toUpperCase": return s.toUpperCase();
673         case "toString": return s;
674         case "slice": {
675             int a = alength >= 1 ? JS.toInt(arg0) : 0;
676             int b = alength >= 2 ? JS.toInt(arg1) : slength;
677             if (a < 0) a = slength + a;
678             if (b < 0) b = slength + b;
679             if (a < 0) a = 0;
680             if (b < 0) b = 0;
681             if (a > slength) a = slength;
682             if (b > slength) b = slength;
683             if (a > b) return "";
684             return s.substring(a,b);
685         }
686         //#end
687         throw new JSExn("Attempted to call non-existent method: " + method);
688     }
689     
690     static Object getFromPrimitive(Object o, Object key) throws JSExn {
691         boolean returnJS = false;
692         if (o instanceof Boolean) {
693             throw new JSExn("Booleans do not have properties");
694         } else if (o instanceof Number) {
695             if (key.equals("toPrecision") || key.equals("toExponential") || key.equals("toFixed"))
696                 returnJS = true;
697         }
698         if (!returnJS) {
699             // the string stuff applies to everything
700             String s = o.toString();
701             
702             // this is sort of ugly, but this list should never change
703             // These should provide a complete (enough) implementation of the ECMA-262 String object
704
705             //#switch(key)
706             case "length": return JS.N(s.length());
707             case "substring": returnJS = true; break; 
708             case "charAt": returnJS = true; break; 
709             case "charCodeAt": returnJS = true; break; 
710             case "concat": returnJS = true; break; 
711             case "indexOf": returnJS = true; break; 
712             case "lastIndexOf": returnJS = true; break; 
713             case "match": returnJS = true; break; 
714             case "replace": returnJS = true; break; 
715             case "search": returnJS = true; break; 
716             case "slice": returnJS = true; break; 
717             case "split": returnJS = true; break; 
718             case "toLowerCase": returnJS = true; break; 
719             case "toUpperCase": returnJS = true; break; 
720             case "toString": returnJS = true; break; 
721             case "substr": returnJS = true; break;  
722            //#end
723         }
724         if (returnJS) {
725             final Object target = o;
726             final String method = key.toString();
727             return new JS() {
728                     public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
729                         if (nargs > 2) throw new JSExn("cannot call that method with that many arguments");
730                         return callMethodOnPrimitive(target, method, a0, a1, a2, rest, nargs);
731                     }
732             };
733         }
734         return null;
735     }
736
737     private static class Stub extends JS {
738         private Object method;
739         JS obj;
740         public Stub(JS obj, Object method) { this.obj = obj; this.method = method; }
741         public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
742             return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs);
743         }
744     }
745 }