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