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