2003/09/23 08:24:59
[org.ibex.core.git] / src / org / xwt / js / CompiledFunctionImpl.java
index 0f08f2b..9fe5435 100644 (file)
@@ -6,10 +6,13 @@ import java.io.*;
 
 // FIXME: could use some cleaning up
 /** a JavaScript function, compiled into bytecode */
-class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
+class CompiledFunctionImpl extends JS.Callable implements ByteCodes, Tokens {
 
     // Fields and Accessors ///////////////////////////////////////////////
 
+    /** the number of formal arguments */
+    int numFormalArgs = 0;
+
     /** the source code file that this block was drawn from */
     private String sourceName;
     public String getSourceName() throws JS.Exn { return sourceName; }
@@ -37,7 +40,12 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
 
     private CompiledFunctionImpl cloneWithNewParentScope(JS.Scope s) throws IOException {
         CompiledFunctionImpl ret = new JS.CompiledFunction(sourceName, firstLine, null, s);
-        ret.paste(this);
+        // Reuse the same op, arg, line, and size variables for the new "instance" of the function
+        // NOTE: Neither *this* function nor the new function should be modified after this call
+        ret.op = this.op;
+        ret.arg = this.arg;
+        ret.line = this.line;
+        ret.size = this.size;
         return ret;
     }
 
@@ -63,15 +71,18 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
         try {
             cx.currentCompiledFunction = (CompiledFunction)this;
             int size = cx.stack.size();
-            cx.stack.push(new CallMarker());
+            cx.stack.push(callMarker);
             cx.stack.push(args);
             eval(scope);
             Object ret = cx.stack.pop();
-            // FIXME: if we catch an exception in Java, JS won't notice and the stack will be messed up
             if (cx.stack.size() > size)
                 // this should never happen
-                throw new Error("ERROR: stack grew by " + (cx.stack.size() - size) + " elements during call");
+                throw new Error("ERROR: stack grew by " + (cx.stack.size() - size) + " elements during call at " + sourceName + ":" + firstLine);
             return ret;
+        } catch(Error e) {
+            // Unwind the stack
+            while(cx.stack.size() > 0) if(cx.stack.pop() instanceof CallMarker) throw e;
+            throw new Error("CallMarker not found on the stack"); // should never happen
         } finally {
             cx.currentCompiledFunction = saved;
         }
@@ -81,8 +92,10 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
     // Adding and Altering Bytecodes ///////////////////////////////////////////////////
 
     int get(int pos) { return op[pos]; }
+    Object getArg(int pos) { return arg[pos]; }
     void set(int pos, int op_, Object arg_) { op[pos] = op_; arg[pos] = arg_; }
     void set(int pos, Object arg_) { arg[pos] = arg_; }
+    int pop() { size--; arg[size] = null; return op[size]; }
     void paste(CompiledFunctionImpl other) { for(int i=0; i<other.size; i++) add(other.line[i], other.op[i], other.arg[i]); }
     CompiledFunctionImpl add(int line, int op_) { return add(line, op_, null); }
     CompiledFunctionImpl add(int line, int op_, Object arg_) {
@@ -112,13 +125,22 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
         int pc;
         int lastPC = -1;
         OUTER: for(pc=0; pc<size; pc++) {
+        try {
             String label = null;
             cx.pc = lastPC = pc;
-            switch(op[pc]) {
+            int curOP = op[pc];
+            Object curArg = arg[pc];
+            if(curOP == FINALLY_DONE) {
+                FinallyData fd = (FinallyData) t.pop();
+                if(fd == null) continue OUTER; // NOP
+                curOP = fd.op;
+                curArg = fd.arg;
+            }
+            switch(curOP) {
             case LITERAL: t.push(arg[pc]); break;
             case OBJECT: t.push(new JS.Obj()); break;
             case ARRAY: t.push(new JS.Array(JS.toNumber(arg[pc]).intValue())); break;
-            case DECLARE: s.declare((String)t.pop()); break;
+            case DECLARE: s.declare((String)(arg[pc]==null ? t.peek() : arg[pc])); if(arg[pc] != null) t.push(arg[pc]); break;
             case TOPSCOPE: t.push(s); break;
             case JT: if (JS.toBoolean(t.pop())) pc += JS.toNumber(arg[pc]).intValue() - 1; break;
             case JF: if (!JS.toBoolean(t.pop())) pc += JS.toNumber(arg[pc]).intValue() - 1; break;
@@ -126,8 +148,8 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
             case POP: t.pop(); break;
             case SWAP: { Object o1 = t.pop(); Object o2 = t.pop(); t.push(o1); t.push(o2); break; }
             case DUP: t.push(t.peek()); break;
-            case NEWSCOPE: /*s = new JS.Scope(s);*/ break;
-            case OLDSCOPE: /*s = s.getParentScope();*/ break;
+            case NEWSCOPE: s = new JS.Scope(s); break;
+            case OLDSCOPE: s = s.getParentScope(); break;
             case ASSERT: if (!JS.toBoolean(t.pop())) throw je("assertion failed"); break;
             case BITNOT: t.push(new Long(~JS.toLong(t.pop()))); break;
             case BANG: t.push(new Boolean(!JS.toBoolean(t.pop()))); break;
@@ -164,8 +186,7 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
 
             case LABEL: break;
             case LOOP: {
-                t.push(s);
-                t.push(new LoopMarker(pc, pc > 0 && op[pc - 1] == LABEL ? (String)arg[pc - 1] : (String)null));
+                t.push(new LoopMarker(pc, pc > 0 && op[pc - 1] == LABEL ? (String)arg[pc - 1] : (String)null,s));
                 t.push(Boolean.TRUE);
                 break;
             }
@@ -175,21 +196,31 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
                 while(t.size() > 0) {
                     Object o = t.pop();
                     if (o instanceof CallMarker) ee("break or continue not within a loop");
-                    if (o != null && o instanceof LoopMarker) {
-                        if (arg[pc] == null || arg[pc].equals(((LoopMarker)o).label)) {
+                    if (o instanceof TryMarker) {
+                        if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
+                        t.push(new FinallyData(curOP, curArg));
+                        s = ((TryMarker)o).scope;
+                        pc = ((TryMarker)o).finallyLoc - 1;
+                        continue OUTER;
+                    }
+                    if (o instanceof LoopMarker) {
+                        if (curArg == null || curArg.equals(((LoopMarker)o).label)) {
                             int loopInstructionLocation = ((LoopMarker)o).location;
                             int endOfLoop = ((Integer)arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
-                            s = (JS.Scope)t.pop();
-                            if (op[pc] == CONTINUE) { t.push(s); t.push(o); t.push(Boolean.FALSE); }
-                            pc = op[pc] == BREAK ? endOfLoop - 1 : loopInstructionLocation;
+                            s = ((LoopMarker)o).scope;
+                            if (curOP == CONTINUE) { t.push(o); t.push(Boolean.FALSE); }
+                            pc = curOP == BREAK ? endOfLoop - 1 : loopInstructionLocation;
                             continue OUTER;
                         }
                     }
                 }
-                throw new Error("CONTINUE/BREAK invoked but couldn't find a LoopMarker at " + sourceName + ":" + line);
+                throw new Error("CONTINUE/BREAK invoked but couldn't find a LoopMarker at " + sourceName + ":" + getLine(pc));
 
             case TRY: {
-                t.push(new TryMarker(pc + ((Integer)arg[pc]).intValue(), s));
+                int[] jmps = (int[]) arg[pc];
+                // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
+                // each can be < 0 if the specified block does not exist
+                t.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1],s));
                 break;
             }
 
@@ -197,7 +228,15 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
                 Object retval = t.pop();
                 while(t.size() > 0) {
                     Object o = t.pop();
-                    if (o != null && o instanceof CallMarker) {
+                    if (o instanceof TryMarker) {
+                        if(((TryMarker)o).finallyLoc < 0) continue;
+                        t.push(retval); 
+                        t.push(new FinallyData(RETURN));
+                        s = ((TryMarker)o).scope;
+                        pc = ((TryMarker)o).finallyLoc - 1;
+                        continue OUTER;
+                    }
+                    if (o instanceof CallMarker) {
                         t.push(retval);
                         return;
                     }
@@ -224,7 +263,7 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
             case GET_PRESERVE: {
                 Object o, v;
                 if (op[pc] == GET) {
-                    v = t.pop();
+                    v = arg[pc] == null ? t.pop() : arg[pc];
                     o = t.pop();
                 } else {
                     v = t.pop();
@@ -253,39 +292,27 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
                 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(t.pop(), j);
                 Object o = t.pop();
                 if(o == null) throw je("attempted to call null");
-                try {
-                    Object ret;
-                    if(op[pc] == CALLMETHOD) {
-                        Object method = o;
-                        o = t.pop();
-                        if(o instanceof String || o instanceof Number || o instanceof Boolean)
-                            ret = Internal.callMethodOnPrimitive(o,method,arguments);
-                        else if(o instanceof JS)
-                            ret = ((JS)o).callMethod(method,arguments,false);
-                        else
-                            throw new JS.Exn("Tried to call a method on an object that isn't a JS object");
-                    } else {                   
-                        ret = ((JS.Callable)o).call(arguments);
-                    }
-                    t.push(ret);
-                    break;
-                } catch (JS.Exn e) {
-                    t.push(e);
+                Object ret;
+                if(op[pc] == CALLMETHOD) {
+                    Object method = o;
+                    o = t.pop();
+                    if(o instanceof String || o instanceof Number || o instanceof Boolean)
+                        ret = Internal.callMethodOnPrimitive(o,method,arguments);
+                    else if(o instanceof JS)
+                        ret = ((JS)o).callMethod(method,arguments,false);
+                    else
+                        throw new JS.Exn("Tried to call a method on an object that isn't a JS object");
+                } else {                   
+                    ret = ((JS.Callable)o).call(arguments);
                 }
+                t.push(ret);
+                break;
             }
             // fall through if exception was thrown
             case THROW: {
-                Object exn = t.pop();
-                while(t.size() > 0) {
-                    Object o = t.pop();
-                    if (o instanceof TryMarker) {
-                        t.push(exn);
-                        pc = ((TryMarker)o).location - 1;
-                        s = ((TryMarker)o).scope;
-                        continue OUTER;
-                    }
-                }
-                throw new JS.Exn(exn);
+                Object o = t.pop();
+                if(o instanceof JS.Exn) throw (JS.Exn)o;
+                throw new JS.Exn(o);
             }
 
             case INC: case DEC: {
@@ -298,26 +325,72 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
                 t.push(isPrefix ? val : num);
                 break;
             }
+            
+            case ASSIGN_SUB: case ASSIGN_ADD: {
+                Object val = t.pop();
+                Object old = t.pop();
+                Object key = t.pop();
+                Object obj = t.peek();
+                if (obj instanceof org.xwt.Box && val instanceof CompiledFunction) {
+                    if (curOP == ASSIGN_ADD) {
+                        ((org.xwt.Box)obj).addTrap(key, val);
+                    } else {
+                        ((org.xwt.Box)obj).delTrap(key, val);
+                    }
+                    // skip over the "normal" implementation of +=/-=
+                    pc += ((Integer)arg[pc]).intValue() - 1;
+                } else {
+                    // use the "normal" implementation
+                    t.push(key);
+                    t.push(old);
+                    t.push(arg);
+                }
+                break;
+            }
+
+            case ADD: {
+                int count = ((Number)arg[pc]).intValue();
+                if(count < 2) throw new Error("this should never happen");
+                if(count == 2) {
+                    // common case
+                    Object right = t.pop();
+                    Object left = t.pop();
+                    if(left instanceof String || right instanceof String) t.push(JS.toString(left).concat(JS.toString(right)));
+                    else t.push(new Double(JS.toDouble(left) + JS.toDouble(right)));
+                } else {
+                    Object[] args = new Object[count];
+                    while(--count >= 0) args[count] = t.pop();
+                    if(args[0] instanceof String) {
+                        StringBuffer sb = new StringBuffer(64);
+                        for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
+                        t.push(sb.toString());
+                    } else {
+                        int numStrings = 0;
+                        for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
+                        if(numStrings == 0) {
+                            double d = 0.0;
+                            for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
+                            t.push(new Double(d));
+                        } else {
+                            double d=0.0;
+                            int i=0;
+                            do {
+                                d += JS.toDouble(args[i++]);
+                            } while(!(args[i] instanceof String));
+                            StringBuffer sb = new StringBuffer(64);
+                            sb.append(JS.toString(new Double(d)));
+                            while(i < args.length) sb.append(JS.toString(args[i++]));
+                            t.push(sb.toString());
+                        }
+                    }
+                }
+                break;
+            }
 
             default: {
                 Object right = t.pop();
                 Object left = t.pop();
                 switch(op[pc]) {
-
-                case ADD: {
-                    Object l = left;
-                    Object r = right;
-                    if (l instanceof String || r instanceof String) {
-                        if (l == null) l = "null";
-                        if (r == null) r = "null";
-                        if (l instanceof Number && ((Number)l).doubleValue() == ((Number)l).longValue())
-                            l = new Long(((Number)l).longValue());
-                        if (r instanceof Number && ((Number)r).doubleValue() == ((Number)r).longValue())
-                            r = new Long(((Number)r).longValue());
-                        t.push(l.toString() + r.toString()); break;
-                    }
-                    t.push(new Double(JS.toDouble(l) + JS.toDouble(r))); break;
-                }
                         
                 case BITOR: t.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
                 case BITXOR: t.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
@@ -364,7 +437,37 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
                 default: throw new Error("unknown opcode " + op[pc]);
                 } }
             }
-        }
+        } catch(JS.Exn e) {
+            while(t.size() > 0) {
+                Object o = t.pop();
+                if (o instanceof CatchMarker || o instanceof TryMarker) {
+                    boolean inCatch = o instanceof CatchMarker;
+                    if(inCatch) {
+                        o = t.pop();
+                        if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
+                    }
+                    if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
+                        // run the catch block, this will implicitly run the finally block, if it exists
+                        t.push(o);
+                        t.push(catchMarker);
+                        t.push(e.getObject());
+                        s = ((TryMarker)o).scope;
+                        pc = ((TryMarker)o).catchLoc - 1;
+                        continue OUTER;
+                    } else {
+                        t.push(e);
+                        t.push(new FinallyData(THROW));
+                        s = ((TryMarker)o).scope;
+                        pc = ((TryMarker)o).finallyLoc - 1;
+                        continue OUTER;
+                    }
+                }
+                // no handler found within this func
+                if(o instanceof CallMarker) throw e;
+            }
+            throw new Error("couldn't find a Try or Call Marker!");
+        } // end try/catch
+        } // end for
         // this should never happen, we will ALWAYS have a RETURN at the end of the func
         throw new Error("Just fell out of CompiledFunction::eval() loop. Last PC was " + lastPC);
     }
@@ -384,8 +487,11 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
             sb.append(" ");
             sb.append(arg[i] == null ? "(no arg)" : arg[i]);
             if((op[i] == JF || op[i] == JT || op[i] == JMP) && arg[i] != null && arg[i] instanceof Number) {
-                sb.append(" jump to ");
-                sb.append(i+((Number) arg[i]).intValue());
+                sb.append(" jump to ").append(i+((Number) arg[i]).intValue());
+            } else  if(op[i] == TRY) {
+                int[] jmps = (int[]) arg[i];
+                sb.append(" catch: ").append(jmps[0] < 0 ? "No catch block" : ""+(i+jmps[0]));
+                sb.append(" finally: ").append(jmps[1] < 0 ? "No finally block" : ""+(i+jmps[1]));
             }
             sb.append("\n");
         }
@@ -401,7 +507,7 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
 
     // FunctionScope /////////////////////////////////////////////////////////////////
 
-    private class FunctionScope extends JS.Scope {
+    private static class FunctionScope extends JS.Scope {
         String sourceName;
         public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
         public String getSourceName() { return sourceName; }
@@ -411,23 +517,37 @@ class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
     // Markers //////////////////////////////////////////////////////////////////////
 
     public static class CallMarker { public CallMarker() { } }
+    private static CallMarker callMarker = new CallMarker();
+    
+    public static class CatchMarker { public CatchMarker() { } }
+    private static CatchMarker catchMarker = new CatchMarker();
+    
     public static class LoopMarker {
         public int location;
         public String label;
-        public LoopMarker(int location, String label) {
+        public JS.Scope scope;
+        public LoopMarker(int location, String label, JS.Scope scope) {
             this.location = location;
             this.label = label;
+            this.scope = scope;
         }
     }
     public static class TryMarker {
-        public int location;
+        public int catchLoc;
+        public int finallyLoc;
         public JS.Scope scope;
-        public TryMarker(int location, JS.Scope scope) {
-            this.location = location;
+        public TryMarker(int catchLoc, int finallyLoc, JS.Scope scope) {
+            this.catchLoc = catchLoc;
+            this.finallyLoc = finallyLoc;
             this.scope = scope;
         }
     }
-
+    public static class FinallyData {
+        public int op;
+        public Object arg;
+        public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
+        public FinallyData(int op) { this(op,null); }
+    }
 }
 
 /** this class exists solely to work around a GCJ bug */