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