359b844a9c51c1027d5e053b19061f8b98151aa2
[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 ASSIGN_SUB: case ASSIGN_ADD: {
393                 Object val = stack.pop();
394                 Object key = stack.pop();
395                 Object obj = stack.peek();
396                 if (val instanceof JSFunction && obj instanceof JS) {
397                     // A trap addition/removal
398                     JS js = obj instanceof JSScope ? ((JSScope)obj).top() : (JS) obj;
399                     if(op == ASSIGN_ADD) js.addTrap(key, (JSFunction)val);
400                     else js.delTrap(key, (JSFunction)val);
401                     pc += ((Integer)arg).intValue() - 1;
402                 } else {
403                     // The following setup is VERY important. The generated bytecode depends on the stack
404                     // being setup like this (top to bottom) KEY, OBJ, VAL, KEY, OBJ
405                     stack.push(key);
406                     stack.push(val);
407                     stack.push(obj);
408                     stack.push(key);
409                 }
410                 break;
411             }
412
413             case ADD: {
414                 int count = ((Number)arg).intValue();
415                 if(count < 2) throw new Error("this should never happen");
416                 if(count == 2) {
417                     // common case
418                     Object right = stack.pop();
419                     Object left = stack.pop();
420                     if(left instanceof String || right instanceof String)
421                         stack.push(JS.toString(left).concat(JS.toString(right)));
422                     else stack.push(JS.N(JS.toDouble(left) + JS.toDouble(right)));
423                 } else {
424                     Object[] args = new Object[count];
425                     while(--count >= 0) args[count] = stack.pop();
426                     if(args[0] instanceof String) {
427                         StringBuffer sb = new StringBuffer(64);
428                         for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
429                         stack.push(sb.toString());
430                     } else {
431                         int numStrings = 0;
432                         for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
433                         if(numStrings == 0) {
434                             double d = 0.0;
435                             for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
436                             stack.push(JS.N(d));
437                         } else {
438                             int i=0;
439                             StringBuffer sb = new StringBuffer(64);
440                             if(!(args[0] instanceof String || args[1] instanceof String)) {
441                                 double d=0.0;
442                                 do {
443                                     d += JS.toDouble(args[i++]);
444                                 } while(!(args[i] instanceof String));
445                                 sb.append(JS.toString(JS.N(d)));
446                             }
447                             while(i < args.length) sb.append(JS.toString(args[i++]));
448                             stack.push(sb.toString());
449                         }
450                     }
451                 }
452                 break;
453             }
454
455             default: {
456                 Object right = stack.pop();
457                 Object left = stack.pop();
458                 switch(op) {
459                         
460                 case BITOR: stack.push(JS.N(JS.toLong(left) | JS.toLong(right))); break;
461                 case BITXOR: stack.push(JS.N(JS.toLong(left) ^ JS.toLong(right))); break;
462                 case BITAND: stack.push(JS.N(JS.toLong(left) & JS.toLong(right))); break;
463
464                 case SUB: stack.push(JS.N(JS.toDouble(left) - JS.toDouble(right))); break;
465                 case MUL: stack.push(JS.N(JS.toDouble(left) * JS.toDouble(right))); break;
466                 case DIV: stack.push(JS.N(JS.toDouble(left) / JS.toDouble(right))); break;
467                 case MOD: stack.push(JS.N(JS.toDouble(left) % JS.toDouble(right))); break;
468                         
469                 case LSH: stack.push(JS.N(JS.toLong(left) << JS.toLong(right))); break;
470                 case RSH: stack.push(JS.N(JS.toLong(left) >> JS.toLong(right))); break;
471                 case URSH: stack.push(JS.N(JS.toLong(left) >>> JS.toLong(right))); break;
472                         
473                 case LT: case LE: case GT: case GE: {
474                     if (left == null) left = JS.N(0);
475                     if (right == null) right = JS.N(0);
476                     int result = 0;
477                     if (left instanceof String || right instanceof String) {
478                         result = left.toString().compareTo(right.toString());
479                     } else {
480                         result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
481                     }
482                     stack.push(JS.B((op == LT && result < 0) || (op == LE && result <= 0) ||
483                                (op == GT && result > 0) || (op == GE && result >= 0)));
484                     break;
485                 }
486                     
487                 case EQ:
488                 case NE: {
489                     Object l = left;
490                     Object r = right;
491                     boolean ret;
492                     if (l == null) { Object tmp = r; r = l; l = tmp; }
493                     if (l == null && r == null) ret = true;
494                     else if (r == null) ret = false; // l != null, so its false
495                     else if (l instanceof Boolean) ret = JS.B(JS.toBoolean(r)).equals(l);
496                     else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
497                     else if (l instanceof String) ret = r != null && l.equals(r.toString());
498                     else ret = l.equals(r);
499                     stack.push(JS.B(op == EQ ? ret : !ret)); break;
500                 }
501
502                 default: throw new Error("unknown opcode " + op);
503                 } }
504             }
505
506         } catch(JSExn e) {
507             if(f.op[pc] != FINALLY_DONE) e.addBacktrace(f.sourceName,f.line[pc]);
508             while(stack.size() > 0) {
509                 Object o = stack.pop();
510                 if (o instanceof CatchMarker || o instanceof TryMarker) {
511                     boolean inCatch = o instanceof CatchMarker;
512                     if(inCatch) {
513                         o = stack.pop();
514                         if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
515                     }
516                     if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
517                         // run the catch block, this will implicitly run the finally block, if it exists
518                         stack.push(o);
519                         stack.push(catchMarker);
520                         stack.push(e.getObject());
521                         f = ((TryMarker)o).f;
522                         scope = ((TryMarker)o).scope;
523                         pc = ((TryMarker)o).catchLoc - 1;
524                         continue OUTER;
525                     } else {
526                         stack.push(new FinallyData(e));
527                         f = ((TryMarker)o).f;
528                         scope = ((TryMarker)o).scope;
529                         pc = ((TryMarker)o).finallyLoc - 1;
530                         continue OUTER;
531                     }
532                 } else if(o instanceof CallMarker) {
533                     CallMarker cm = (CallMarker) o;
534                     if(cm.f == null)
535                         e.addBacktrace("<java>",0); // This might not even be worth mentioning
536                     else
537                         e.addBacktrace(cm.f.sourceName,cm.f.line[cm.pc-1]);
538                 }
539             }
540             throw e;
541         } // end try/catch
542         } // end for
543     }
544
545
546
547     // Markers //////////////////////////////////////////////////////////////////////
548
549     public static class CallMarker {
550         int pc;
551         JSScope scope;
552         JSFunction f;
553         public CallMarker(Interpreter cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
554     }
555     
556     public static class CatchMarker { public CatchMarker() { } }
557     private static CatchMarker catchMarker = new CatchMarker();
558     
559     public static class LoopMarker {
560         public int location;
561         public String label;
562         public JSScope scope;
563         public LoopMarker(int location, String label, JSScope scope) {
564             this.location = location;
565             this.label = label;
566             this.scope = scope;
567         }
568     }
569     public static class TryMarker {
570         public int catchLoc;
571         public int finallyLoc;
572         public JSScope scope;
573         public JSFunction f;
574         public TryMarker(int catchLoc, int finallyLoc, Interpreter cx) {
575             this.catchLoc = catchLoc;
576             this.finallyLoc = finallyLoc;
577             this.scope = cx.scope;
578             this.f = cx.f;
579         }
580     }
581     public static class FinallyData {
582         public int op;
583         public Object arg;
584         public JSExn exn;
585         public FinallyData(int op) { this(op,null); }
586         public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
587         public FinallyData(JSExn exn) { this.exn = exn; } // Just throw this exn
588     }
589
590
591     // Operations on Primitives //////////////////////////////////////////////////////////////////////
592
593     static Object callMethodOnPrimitive(Object o, Object method, Object arg0, Object arg1, Object arg2, Object[] rest, int alength) throws JSExn {
594         if (method == null || !(method instanceof String) || "".equals(method))
595             throw new JSExn("attempt to call a non-existant method on a primitive");
596
597         if (o instanceof Number) {
598             //#switch(method)
599             case "toFixed": throw new JSExn("toFixed() not implemented");
600             case "toExponential": throw new JSExn("toExponential() not implemented");
601             case "toPrecision": throw new JSExn("toPrecision() not implemented");
602             case "toString": {
603                 int radix = alength >= 1 ? JS.toInt(arg0) : 10;
604                 return Long.toString(((Number)o).longValue(),radix);
605             }
606             //#end
607         } else if (o instanceof Boolean) {
608             // No methods for Booleans
609             throw new JSExn("attempt to call a method on a Boolean");
610         }
611
612         String s = JS.toString(o);
613         int slength = s.length();
614         //#switch(method)
615         case "substring": {
616             int a = alength >= 1 ? JS.toInt(arg0) : 0;
617             int b = alength >= 2 ? JS.toInt(arg1) : slength;
618             if (a > slength) a = slength;
619             if (b > slength) b = slength;
620             if (a < 0) a = 0;
621             if (b < 0) b = 0;
622             if (a > b) { int tmp = a; a = b; b = tmp; }
623             return s.substring(a,b);
624         }
625         case "substr": {
626             int start = alength >= 1 ? JS.toInt(arg0) : 0;
627             int len = alength >= 2 ? JS.toInt(arg1) : Integer.MAX_VALUE;
628             if (start < 0) start = slength + start;
629             if (start < 0) start = 0;
630             if (len < 0) len = 0;
631             if (len > slength - start) len = slength - start;
632             if (len <= 0) return "";
633             return s.substring(start,start+len);
634         }
635         case "charAt": {
636             int p = alength >= 1 ? JS.toInt(arg0) : 0;
637             if (p < 0 || p >= slength) return "";
638             return s.substring(p,p+1);
639         }
640         case "charCodeAt": {
641             int p = alength >= 1 ? JS.toInt(arg0) : 0;
642             if (p < 0 || p >= slength) return JS.N(Double.NaN);
643             return JS.N(s.charAt(p));
644         }
645         case "concat": {
646             StringBuffer sb = new StringBuffer(slength*2).append(s);
647             for(int i=0;i<alength;i++) sb.append(i==0?arg0:i==1?arg1:i==2?arg2:rest[i-3]);
648             return sb.toString();
649         }
650         case "indexOf": {
651             String search = alength >= 1 ? arg0.toString() : "null";
652             int start = alength >= 2 ? JS.toInt(arg1) : 0;
653             // Java's indexOf handles an out of bounds start index, it'll return -1
654             return JS.N(s.indexOf(search,start));
655         }
656         case "lastIndexOf": {
657             String search = alength >= 1 ? arg0.toString() : "null";
658             int start = alength >= 2 ? JS.toInt(arg1) : 0;
659             // Java's indexOf handles an out of bounds start index, it'll return -1
660             return JS.N(s.lastIndexOf(search,start));            
661         }
662         case "match": return JSRegexp.stringMatch(s,arg0);
663         case "replace": return JSRegexp.stringReplace(s,arg0,arg1);
664         case "search": return JSRegexp.stringSearch(s,arg0);
665         case "split": return JSRegexp.stringSplit(s,arg0,arg1,alength);
666         case "toLowerCase": return s.toLowerCase();
667         case "toUpperCase": return s.toUpperCase();
668         case "toString": return s;
669         case "slice": {
670             int a = alength >= 1 ? JS.toInt(arg0) : 0;
671             int b = alength >= 2 ? JS.toInt(arg1) : slength;
672             if (a < 0) a = slength + a;
673             if (b < 0) b = slength + b;
674             if (a < 0) a = 0;
675             if (b < 0) b = 0;
676             if (a > slength) a = slength;
677             if (b > slength) b = slength;
678             if (a > b) return "";
679             return s.substring(a,b);
680         }
681         //#end
682         throw new JSExn("Attempted to call non-existent method: " + method);
683     }
684     
685     static Object getFromPrimitive(Object o, Object key) throws JSExn {
686         boolean returnJS = false;
687         if (o instanceof Boolean) {
688             throw new JSExn("cannot call methods on Booleans");
689         } else if (o instanceof Number) {
690             if (key.equals("toPrecision") || key.equals("toExponential") || key.equals("toFixed"))
691                 returnJS = true;
692         }
693         if (!returnJS) {
694             // the string stuff applies to everything
695             String s = o.toString();
696             
697             // this is sort of ugly, but this list should never change
698             // These should provide a complete (enough) implementation of the ECMA-262 String object
699
700             //#switch(key)
701             case "length": return JS.N(s.length());
702             case "substring": returnJS = true; break; 
703             case "charAt": returnJS = true; break; 
704             case "charCodeAt": returnJS = true; break; 
705             case "concat": returnJS = true; break; 
706             case "indexOf": returnJS = true; break; 
707             case "lastIndexOf": returnJS = true; break; 
708             case "match": returnJS = true; break; 
709             case "replace": returnJS = true; break; 
710             case "seatch": returnJS = true; break; 
711             case "slice": returnJS = true; break; 
712             case "split": returnJS = true; break; 
713             case "toLowerCase": returnJS = true; break; 
714             case "toUpperCase": returnJS = true; break; 
715             case "toString": returnJS = true; break; 
716             case "substr": returnJS = true; break;  
717            //#end
718         }
719         if (returnJS) {
720             final Object target = o;
721             final String method = key.toString();
722             return new JS() {
723                     public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
724                         if (nargs > 2) throw new JSExn("cannot call that method with that many arguments");
725                         return callMethodOnPrimitive(target, method, a0, a1, a2, rest, nargs);
726                     }
727             };
728         }
729         return null;
730     }
731
732     private static class Stub extends JS {
733         private Object method;
734         JS obj;
735         public Stub(JS obj, Object method) { this.obj = obj; this.method = method; }
736         public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
737             return ((JS)obj).callMethod(method, a0, a1, a2, rest, nargs);
738         }
739     }
740 }