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