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