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