2003/11/03 06:32:55
authormegacz <megacz@xwt.org>
Fri, 30 Jan 2004 07:40:53 +0000 (07:40 +0000)
committermegacz <megacz@xwt.org>
Fri, 30 Jan 2004 07:40:53 +0000 (07:40 +0000)
darcs-hash:20040130074053-2ba56-c8bfd5c149f765d5439fddfaaeca5a245cfb719f.gz

src/org/xwt/HTTP.java
src/org/xwt/Res.java
src/org/xwt/Template.java
src/org/xwt/Trap.java
src/org/xwt/XMLRPC.java
src/org/xwt/XWT.java
src/org/xwt/builtin/splash.xwt
src/org/xwt/js/Function.java [moved from src/org/xwt/js/CompiledFunctionImpl.java with 73% similarity]
src/org/xwt/js/JS.java

index 7295f1f..eca310f 100644 (file)
@@ -780,7 +780,7 @@ public class HTTP {
                     if (Log.on) Log.log(Proxy.class, script);
                 }
 
-                JS.CompiledFunction scr = JS.parse("PAC script at " + url, 0, new StringReader(script));
+                Function scr = JS.parse("PAC script at " + url, 0, new StringReader(script));
                 // FIXME
                 /*
                 scr.call(new JS.Array(), proxyAutoConfigRootScope);
index 399476b..954f290 100644 (file)
@@ -80,7 +80,7 @@ public abstract class Res extends JS {
         }
         if (url.startsWith("http://")) return new HTTP(url);
         if (url.startsWith("https://")) return new HTTP(url);
-        if (url.startsWith("cab:")) return new CAB(stringToRes(url.substring(4)));
+        if (url.startsWith("cab:")) return new Cab(stringToRes(url.substring(4)));
         if (url.startsWith("data:")) return new ByteArray(Base64.decode(url.substring(5)));
         if (url.startsWith("utf8:")) return new ByteArray(url.substring(5).getBytes());
         throw new JS.Exn("invalid resource specifier " + url);
@@ -145,6 +145,18 @@ public abstract class Res extends JS {
         }
     }
 
+    /** "unwrap" a Cab archive */
+    public static class Cab extends Res {
+        private Res parent;
+        Cab(Res parent) { this.parent = parent; }
+        public String getDescriptiveName() { return "cab[" + parent.getDescriptiveName() + "]"; }
+        public InputStream getInputStream(String path) throws IOException {
+            // FIXME: knownlength
+            if (path.startsWith("/")) path = path.substring(1);
+            return new org.xwt.translators.MSPack(parent.getInputStream()).getInputStream(path);
+        }
+    }
+
     /** the Builtin resource */
     public static class Builtin extends Res {
        public Builtin() { };
@@ -204,8 +216,8 @@ public abstract class Res extends JS {
     /** shadow resource which replaces the graft */
     public static class ProgressWatcher extends Res {
         final Res watchee;
-        JS.CompiledFunction callback;
-        ProgressWatcher(Res watchee, JS.CompiledFunction callback) { this.watchee = watchee; this.callback = callback; }
+        Function callback;
+        ProgressWatcher(Res watchee, Function callback) { this.watchee = watchee; this.callback = callback; }
         public String getDescriptiveName() { return watchee.getDescriptiveName(); }
         public InputStream getInputStream(String s) throws IOException {
             final InputStream is = watchee.getInputStream(s);
@@ -232,24 +244,6 @@ public abstract class Res extends JS {
         }
     }
 
-    /** unpacks a Microsoft CAB file (possibly embedded in another file; we scan for 'MSCF' */
-    public static class CAB extends Res {
-        private Res parent;
-        CAB(Res parent) { this.parent = parent; }
-        private int swap_endian(int i) {
-            return ((i & 0xff) << 24) | ((i & 0xff00) << 8) | ((i & 0xff0000) >>> 8) | (i >>> 24);
-        }
-        public InputStream getInputStream(String path) throws IOException {
-            try {
-               return org.xwt.util.CAB.getFileInputStream(parent.getInputStream(), 2, path);
-            } catch (EOFException eof) {
-               throw new JS.Exn("MSCF header tag not found in file");
-            } catch (IOException ioe) {
-               throw new JS.Exn("IOException while reading file");
-            }
-        }
-    }
-
     public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
         if (method.equals("getUTF")) {
             if (checkOnly) return Boolean.TRUE;
index bf88c4f..a81f150 100644 (file)
@@ -32,7 +32,7 @@ public class Template {
     private Vec children = new Vec();  ///< during XML parsing, this holds the list of currently-parsed children; null otherwise
     private int numunits = -1;         ///< see numUnits(); -1 means that this value has not yet been computed
 
-    private JS.CompiledFunction script = null;       ///< the script on this node
+    private Function script = null;       ///< the script on this node
     private String fileName = "unknown";             ///< the filename this node came from; used only for debugging
     private Vec preapply = new Vec();                ///< templates that should be preapplied (in the order of application)
 
@@ -40,7 +40,7 @@ public class Template {
     // Instance Members that are only meaningful on root Template //////////////////////////////////////
 
     private JS.Scope staticScope = null;             ///< the scope in which the static block is executed
-    private JS.CompiledFunction staticscript = null; ///< the script on the static node of this template, null already performed
+    private Function staticscript = null; ///< the script on the static node of this template, null already performed
 
 
     // Only used during parsing /////////////////////////////////////////////////////////////////
@@ -95,9 +95,9 @@ public class Template {
     JS.Scope getStatic() {
         if (staticScope == null) staticScope = new JS.Scope(null);
         if (staticscript == null) return staticScope;
-        JS.CompiledFunction temp = staticscript;
+        Function temp = staticscript;
         staticscript = null;
-        new JS.Context(temp, staticScope, null).resume(null);
+        new JS.Context(temp, staticScope).resume();
         return staticScope;
     }
     
@@ -126,7 +126,7 @@ public class Template {
             b.put(b.numChildren(), kid);
         }
 
-        if (script != null) new JS.Context(script, pis, null).resume(null);
+        if (script != null) new JS.Context(script, pis).resume();
 
         for(int i=0; keys != null && i<keys.length; i++)
             if (vals[i] instanceof String && ((String)vals[i]).charAt(0) == '$') b.put(keys[i], pis.get(vals[i]));
@@ -278,8 +278,8 @@ public class Template {
             }
         }
 
-        private JS.CompiledFunction parseScript(boolean isstatic) {
-            JS.CompiledFunction thisscript = null;
+        private Function parseScript(boolean isstatic) {
+            Function thisscript = null;
             try {
                 thisscript = JS.parse(t.fileName + (isstatic ? "._" : ""), t.content_start, new StringReader(t.content.toString()));
             } catch (IOException ioe) {
index ea2ea95..7d9dcc1 100644 (file)
@@ -16,14 +16,14 @@ public class Trap {
 
     // Static Data //////////////////////////////////////////////////////////////
 
-    private static JS.CompiledFunction cascadeHelper = null;
+    private static Function cascadeHelper = null;
     private static String cascadeHelperText =
         "return function(q) { var ret = arguments.doTrap;" +
         "if (ret != false && !arguments.didCascade) arguments.cascade = q; };";
     static {
         try {
             cascadeHelper = JS.parse("cascadeHelper", 1, new StringReader(cascadeHelperText));
-            cascadeHelper = (JS.CompiledFunction)new JS.Context(cascadeHelper, null, null).resume(null);
+            cascadeHelper = (Function)new JS.Context(cascadeHelper, null).resume();
         } catch (Exception e) {
             Log.log(Trap.class, e);
         }
@@ -52,7 +52,7 @@ public class Trap {
     private Box trapee = null;
 
     /** the function for this trap */
-    JS.CompiledFunction f = null;
+    Function f = null;
 
     /** the next trap down the trap stack */
     private Trap next = null;
@@ -69,7 +69,7 @@ public class Trap {
      *  @param name the name of the property to trap on
      *  @param f the function to place as a trap
      */
-    static void addTrap(Box trapee, Object name, JS.CompiledFunction f) {
+    static void addTrap(Box trapee, Object name, Function f) {
 
         // check if this script has already placed a trap on this property
         for(Trap t = (Trap)trapee.get(name, Trap.class); t != null; t = t.next)
@@ -86,7 +86,7 @@ public class Trap {
      *  @param name the name of the property to trap on
      *  @param f the function to remove
      */
-    static void delTrap(Box trapee, Object name, JS.CompiledFunction f) {
+    static void delTrap(Box trapee, Object name, Function f) {
         Trap t = (Trap)trapee.get(name, Trap.class);
         if (t.f == f) { trapee.put2(name, Trap.class, t.next); return; }
         for(; t.next != null; t = t.next)
@@ -97,7 +97,7 @@ public class Trap {
 
     // Instance Methods //////////////////////////////////////////////////////////////////////////
 
-    private Trap(Box b, String n, JS.CompiledFunction f, Trap nx)
+    private Trap(Box b, String n, Function f, Trap nx)
     { trapee = b; name = n; this.f = f; this.next = nx; }
 
     // Read Traps //////////////////////////////////////////////////////////////////////
index ac83249..e32f569 100644 (file)
@@ -359,17 +359,19 @@ class XMLRPC extends JS.Callable {
         return objects.elementAt(0);
     }
 
-    public final Object call(JS.Array args) throws JS.Exn {
-        try {
-            return call2(args);
-        } catch (IOException se) {
-            if (Log.on) Log.log(this, se);
-            throw new JS.Exn("socket exception: " + se);
-
-        } catch (JS.Exn jse) {
-            if (Log.on) Log.log(this, jse.toString());
-            throw jse;
-        }
+    public final Object call(final JS.Array args) throws JS.Exn {
+        final JS.Context cx = JS.Context.current();
+        Scheduler.add(new Scheduler.Task() { public void perform() {
+            Object ret;
+            try {
+                ret = call2(args);
+            } catch (IOException se) {
+                if (Log.on) Log.log(this, se);
+                throw new JS.Exn("socket exception: " + se);
+            }
+            cx.resume(ret);
+        } });
+        return JS.Context.pause;
     }
 
     /** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
index f51f4e6..0c01e67 100644 (file)
@@ -45,9 +45,9 @@ public final class XWT extends JS.Obj {
     }
 
     public Object put(Object name, final Object value) {
-        if (name.equals("thread") && value != null && (value instanceof JS.Callable || value instanceof JS.CompiledFunction)) {
+        if (name.equals("thread") && value != null && (value instanceof JS.Callable || value instanceof Function)) {
             Scheduler.add(new Scheduler.Task() { public void perform() {
-                new JS.Context((CompiledFunction)value, null, null).resume(null);
+                new JS.Context((Function)value, null).resume();
             } });
         } else if (name.equals("clipboard")) Platform.setClipBoard(value.toString());
         else if (name.equals("frame")) Platform.createSurface((Box)value, true, true);
@@ -84,9 +84,13 @@ public final class XWT extends JS.Obj {
             if (checkOnly) return Boolean.TRUE;
             return new Res.Zip((Res)args.elementAt(0));
 
+        } else if (method.equals("uncab")) {
+            if (checkOnly) return Boolean.TRUE;
+            return new Res.Cab((Res)args.elementAt(0));
+
         } else if (method.equals("watchProgress")) {
             if (checkOnly) return Boolean.TRUE;
-            return new Res.ProgressWatcher((Res)args.elementAt(0), (JS.CompiledFunction)args.elementAt(1));
+            return new Res.ProgressWatcher((Res)args.elementAt(0), (Function)args.elementAt(1));
 
         } else if (method.equals("yield")) {
             if (checkOnly) return Boolean.TRUE;
@@ -195,8 +199,9 @@ public final class XWT extends JS.Obj {
         final JS.Context jsthread = JS.Context.current();
         final long currentTime = System.currentTimeMillis();
         final Scheduler.Task task = new Scheduler.Task() { public void perform() {
+            // FIXME: don't busy-wait
             if (System.currentTimeMillis() - currentTime < i) Scheduler.add(this);
-            else jsthread.resume(null);
+            else jsthread.resume();
         } };
         Scheduler.add(task);
         return JS.Context.pause;
@@ -213,7 +218,7 @@ public final class XWT extends JS.Obj {
         }
         public Object get(Object key) {
             Object ret = super.get(key);
-            if(ret == null) ret = JS.Math.get(key);
+            if(ret == null) ret = org.xwt.js.Math.singleton.get(key);
             return ret;
         }
     }
index 6f44cca..f6737ed 100644 (file)
         }
 
         xwt.thread = function() {
-            $text.font = xwt.fonts.vera["Vera.ttf"];
-            $text.fontsize = 14;
+//            $text.font = xwt.fonts.vera["Vera.ttf"];
+            $text.font = xwt.uncab(xwt.load("http://master.dist.xwt.org/msfonts/arial32.exe"))["Arial.TTF"];
+            $text.fontsize = 18;
             $text.text = "downloading...";
             fill = xwt.org.xwt.builtin["splash.png"];
-            xwt.window = thisbox;
+            xwt.frame = thisbox;
             x = (xwt.screenWidth - width) / 2;
             y = (xwt.screenHeight - height) / 2;
             var origin = xwt.origin;
similarity index 73%
rename from src/org/xwt/js/CompiledFunctionImpl.java
rename to src/org/xwt/js/Function.java
index e4bbe0e..f31d0ff 100644 (file)
@@ -5,40 +5,27 @@ import org.xwt.util.*;
 import java.io.*;
 
 /** a JavaScript function, compiled into bytecode */
-class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
+public class Function extends JS.Obj implements ByteCodes, Tokens {
 
-    // Fields and Accessors ///////////////////////////////////////////////
-
-    /** the number of formal arguments */
-    int numFormalArgs = 20;
-
-    /** the source code file that this block was drawn from */
-     String sourceName;
-    public String getSourceName() throws JS.Exn { return sourceName; }
-    
-    /** the line numbers */
-     int[] line = new int[10];
-
-    /** the first line of this script */
-    private int firstLine = -1;
+    public int getNumFormalArgs() { return numFormalArgs; }
 
-    /** the instructions */
-     int[] op = new int[10];
 
-    /** the arguments to the instructions */
-     Object[] arg = new Object[10];
+    // Fields and Accessors ///////////////////////////////////////////////
 
-    /** the number of instruction/argument pairs */
-     int size = 0;
-    int size() { return size; }
+    int numFormalArgs = 0;         ///< the number of formal arguments
+    String sourceName;             ///< the source code file that this block was drawn from
+    int[] line = new int[10];      ///< the line numbers
+    private int firstLine = -1;    ///< the first line of this script
+    int[] op = new int[10];        ///< the instructions
+    Object[] arg = new Object[10]; ///< the arguments to the instructions
+    int size = 0;                  ///< the number of instruction/argument pairs
+    JS.Scope parentScope;          ///< the default scope to use as a parent scope when executing this
 
-    /** the scope in which this function was declared; by default this function is called in a fresh subscope of the parentScope */
-    JS.Scope parentScope;
 
     // Constructors ////////////////////////////////////////////////////////
 
-    private CompiledFunctionImpl cloneWithNewParentScope(JS.Scope s) throws IOException {
-        CompiledFunctionImpl ret = new JS.CompiledFunction(sourceName, firstLine, null, s);
+    private Function cloneWithNewParentScope(JS.Scope s) {
+        Function ret = new Function(sourceName, firstLine, s);
         // 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;
@@ -49,16 +36,20 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
         return ret;
     }
 
-    protected CompiledFunctionImpl(String sourceName, int firstLine, Reader sourceCode, JS.Scope parentScope) throws IOException {
+    private Function(String sourceName, int firstLine, JS.Scope parentScope) {
         this.sourceName = sourceName;
         this.firstLine = firstLine;
         this.parentScope = parentScope;
+    }
+
+    protected Function(String sourceName, int firstLine, Reader sourceCode, JS.Scope parentScope) throws IOException {
+        this(sourceName, firstLine, parentScope);
         if (sourceCode == null) return;
         Parser p = new Parser(sourceCode, sourceName, firstLine);
         while(true) {
-            int s = size();
+            int s = size;
             p.parseStatement(this, null);
-            if (s == size()) break;
+            if (s == size) break;
         }
         add(-1, LITERAL, null); 
         add(-1, RETURN);
@@ -73,9 +64,9 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
     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_) {
+    void paste(Function other) { for(int i=0; i<other.size; i++) add(other.line[i], other.op[i], other.arg[i]); }
+    Function add(int line, int op_) { return add(line, op_, null); }
+    Function add(int line, int op_, Object arg_) {
         if (size == op.length - 1) {
             int[] line2 = new int[op.length * 2]; System.arraycopy(this.line, 0, line2, 0, op.length); this.line = line2;
             Object[] arg2 = new Object[op.length * 2]; System.arraycopy(arg, 0, arg2, 0, arg.length); arg = arg2;
@@ -88,41 +79,33 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
         return this;
     }
     
-    public static int getLine(Context cx) {
-        if(cx.pc < 0 || cx.pc >= ((CompiledFunctionImpl)cx.f).size) return -1;
-        return ((CompiledFunctionImpl)cx.f).line[cx.pc];
-    }
-
 
     // Invoking the Bytecode ///////////////////////////////////////////////////////
 
     /** returns false if the thread has been paused */
-    static Object eval(final Context cx, Object pushFirst) throws JS.Exn {
-        cx.stack.push(pushFirst);
+    static Object eval(final Context cx) throws JS.Exn {
         OUTER: for(;; cx.pc++) {
         try {
-            if (cx.f == null) return cx.stack.pop();
-            if (cx.pc >= ((CompiledFunctionImpl)cx.f).size) return cx.stack.pop();
-            String label = null;
-            int curOP = cx.f.op[cx.pc];
-            Object curArg = cx.f.arg[cx.pc];
+            if (cx.f == null || cx.pc >= cx.f.size) return cx.stack.pop();
+            int op = cx.f.op[cx.pc];
+            Object arg = cx.f.arg[cx.pc];
             Object returnedFromJava = null;
             boolean checkReturnedFromJava = false;
-            if(curOP == FINALLY_DONE) {
+            if(op == FINALLY_DONE) {
                 FinallyData fd = (FinallyData) cx.stack.pop();
                 if(fd == null) continue OUTER; // NOP
-                curOP = fd.op;
-                curArg = fd.arg;
+                op = fd.op;
+                arg = fd.arg;
             }
-            switch(curOP) {
-            case LITERAL: cx.stack.push(curArg); break;
+            switch(op) {
+            case LITERAL: cx.stack.push(arg); break;
             case OBJECT: cx.stack.push(new JS.Obj()); break;
-            case ARRAY: cx.stack.push(new JS.Array(JS.toNumber(curArg).intValue())); break;
-            case DECLARE: cx.scope.declare((String)(curArg==null ? cx.stack.peek() : curArg)); if(curArg != null) cx.stack.push(curArg); break;
+            case ARRAY: cx.stack.push(new JS.Array(JS.toNumber(arg).intValue())); break;
+            case DECLARE: cx.scope.declare((String)(arg==null ? cx.stack.peek() : arg)); if(arg != null) cx.stack.push(arg); break;
             case TOPSCOPE: cx.stack.push(cx.scope); break;
-            case JT: if (JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(curArg).intValue() - 1; break;
-            case JF: if (!JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(curArg).intValue() - 1; break;
-            case JMP: cx.pc += JS.toNumber(curArg).intValue() - 1; break;
+            case JT: if (JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(arg).intValue() - 1; break;
+            case JF: if (!JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(arg).intValue() - 1; break;
+            case JMP: cx.pc += JS.toNumber(arg).intValue() - 1; break;
             case POP: cx.stack.pop(); break;
             case SWAP: { Object o1 = cx.stack.pop(); Object o2 = cx.stack.pop(); cx.stack.push(o1); cx.stack.push(o2); break; }
             case DUP: cx.stack.push(cx.stack.peek()); break;
@@ -131,6 +114,8 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
             case ASSERT: if (!JS.toBoolean(cx.stack.pop())) throw je("assertion failed"); break;
             case BITNOT: cx.stack.push(new Long(~JS.toLong(cx.stack.pop()))); break;
             case BANG: cx.stack.push(new Boolean(!JS.toBoolean(cx.stack.pop()))); break;
+            case NEWFUNCTION: cx.stack.push(((Function)arg).cloneWithNewParentScope(cx.scope)); break;
+            case LABEL: break;
 
             case TYPEOF: {
                 Object o = cx.stack.pop();
@@ -143,15 +128,6 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
                 break;
             }
 
-            case NEWFUNCTION: {
-                try {
-                    cx.stack.push(((CompiledFunctionImpl)curArg).cloneWithNewParentScope(cx.scope));
-                } catch (IOException e) {
-                    throw new Error("this should never happen");
-                }
-                break;
-            }
-
             case PUSHKEYS: {
                 Object o = cx.stack.peek();
                 Object[] keys = ((JS)o).keys();
@@ -162,12 +138,11 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
                 break;
             }
 
-            case LABEL: break;
-            case LOOP: {
-                cx.stack.push(new LoopMarker(cx.pc, cx.pc > 0 && cx.f.op[cx.pc - 1] == LABEL ? (String)cx.f.arg[cx.pc - 1] : (String)null, cx.scope));
+            case LOOP:
+                cx.stack.push(new LoopMarker(cx.pc, cx.pc > 0 && cx.f.op[cx.pc - 1] == LABEL ?
+                                             (String)cx.f.arg[cx.pc - 1] : (String)null, cx.scope));
                 cx.stack.push(Boolean.TRUE);
                 break;
-            }
 
             case BREAK:
             case CONTINUE:
@@ -176,26 +151,27 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
                     if (o instanceof CallMarker) ee("break or continue not within a loop");
                     if (o instanceof TryMarker) {
                         if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
-                        cx.stack.push(new FinallyData(curOP, curArg));
+                        cx.stack.push(new FinallyData(op, arg));
                         cx.scope = ((TryMarker)o).scope;
                         cx.pc = ((TryMarker)o).finallyLoc - 1;
                         continue OUTER;
                     }
                     if (o instanceof LoopMarker) {
-                        if (curArg == null || curArg.equals(((LoopMarker)o).label)) {
+                        if (arg == null || arg.equals(((LoopMarker)o).label)) {
                             int loopInstructionLocation = ((LoopMarker)o).location;
                             int endOfLoop = ((Integer)cx.f.arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
                             cx.scope = ((LoopMarker)o).scope;
-                            if (curOP == CONTINUE) { cx.stack.push(o); cx.stack.push(Boolean.FALSE); }
-                            cx.pc = curOP == BREAK ? endOfLoop - 1 : loopInstructionLocation;
+                            if (op == CONTINUE) { cx.stack.push(o); cx.stack.push(Boolean.FALSE); }
+                            cx.pc = op == BREAK ? endOfLoop - 1 : loopInstructionLocation;
                             continue OUTER;
                         }
                     }
                 }
-                throw new Error("CONTINUE/BREAK invoked but couldn't find a LoopMarker at " + ((CompiledFunctionImpl)cx.f).sourceName + ":" + getLine(cx));
+                throw new Error("CONTINUE/BREAK invoked but couldn't find LoopMarker at " +
+                                cx.getSourceName() + ":" + cx.getLine());
 
             case TRY: {
-                int[] jmps = (int[]) curArg;
+                int[] jmps = (int[]) arg;
                 // 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
                 cx.stack.push(new TryMarker(jmps[0] < 0 ? -1 : cx.pc + jmps[0], jmps[1] < 0 ? -1 : cx.pc + jmps[1], cx.scope));
@@ -213,11 +189,10 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
                         cx.scope = ((TryMarker)o).scope;
                         cx.pc = ((TryMarker)o).finallyLoc - 1;
                         continue OUTER;
-                    }
-                    if (o instanceof CallMarker) {
+                    } else if (o instanceof CallMarker) {
                         cx.scope = ((CallMarker)o).scope;
                         cx.pc = ((CallMarker)o).pc;
-                        cx.f = (CompiledFunction)((CallMarker)o).f;
+                        cx.f = (Function)((CallMarker)o).f;
                         cx.stack.push(retval);
                         continue OUTER;
                     }
@@ -236,19 +211,16 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
                 if (key == null)
                     throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
                 returnedFromJava = ((JS)target).put(key, val);
-                if (returnedFromJava != null) {
-                    checkReturnedFromJava = true;
-                } else {
-                    cx.stack.push(val);
-                }
+                if (returnedFromJava != null) checkReturnedFromJava = true;
+                else cx.stack.push(val);
                 break;
             }
 
             case GET:
             case GET_PRESERVE: {
                 Object o, v;
-                if (curOP == GET) {
-                    v = curArg == null ? cx.stack.pop() : curArg;
+                if (op == GET) {
+                    v = arg == null ? cx.stack.pop() : arg;
                     o = cx.stack.pop();
                 } else {
                     v = cx.stack.pop();
@@ -258,67 +230,59 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
                 Object ret = null;
                 if (o == null) throw je("tried to get property \"" + v + "\" from the null value");
                 if (v == null) throw je("tried to get the null key from " + o);
-                if (o instanceof String || o instanceof Number || o instanceof Boolean)
+                if (o instanceof String || o instanceof Number || o instanceof Boolean) {
                     ret = Internal.getFromPrimitive(o,v);
-                else if (o instanceof JS) {
+                    cx.stack.push(ret);
+                    break;
+                } else if (o instanceof JS) {
                     returnedFromJava = ((JS)o).get(v);
                     checkReturnedFromJava = true;
                     break;
-                } else 
-                    throw je("tried to get property " + v + " from a " + o.getClass().getName());
-                cx.stack.push(ret);
-                break;
+                }
+                throw je("tried to get property " + v + " from a " + o.getClass().getName());
             }
             
-            case CALLMETHOD:
-            case CALL:
-            case CALL_REVERSED:
-            {
+            case CALL: case CALLMETHOD: case CALL_REVERSED: {
                 JS.Array arguments = new JS.Array();
-                int numArgs = JS.toNumber(curArg).intValue();
+                int numArgs = JS.toNumber(arg).intValue();
                 arguments.setSize(numArgs);
                 Object o = null;
-                if (curOP == CALL_REVERSED) o = cx.stack.pop();
+                if (op == CALL_REVERSED) o = cx.stack.pop();
                 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
-                if (curOP != CALL_REVERSED) o = cx.stack.pop();
+                if (op != CALL_REVERSED) o = cx.stack.pop();
                 if(o == null) throw je("attempted to call null");
                 Object ret;
 
-                if(curOP == CALLMETHOD) {
+                if(op == CALLMETHOD) {
                     Object method = o;
                     o = cx.stack.pop();
                     if(o instanceof String || o instanceof Number || o instanceof Boolean) {
                         ret = Internal.callMethodOnPrimitive(o,method,arguments);
                         cx.stack.push(ret);
                         cx.pc += 2;  // skip the GET and CALL
-                        break;
                     } else if (o instanceof JS && ((JS)o).callMethod(method, arguments, true) == Boolean.TRUE) {
                         returnedFromJava = ((JS)o).callMethod(method, arguments, false);
                         checkReturnedFromJava = true;
                         cx.pc += 2;  // skip the GET and CALL
-                        break;
                     } else {
                         // put the args back on the stack and let the GET followed by CALL happen
                         for(int j=0; j<numArgs; j++) cx.stack.push(arguments.elementAt(j));
                         cx.stack.push(o);
                         cx.stack.push(method);
-                        break;
                     }
-                }
 
-                if (o instanceof CompiledFunctionImpl) {
+                } else if (o instanceof Function) {
                     cx.stack.push(new CallMarker(cx));
                     cx.stack.push(arguments);
-                    cx.f = (CompiledFunction)o;
-                    cx.scope = new FunctionScope("unknown", cx.f.parentScope);
+                    cx.f = (Function)o;
+                    cx.scope = new Scope(cx.f.parentScope);
                     cx.pc = -1;
-                    break;
                     
                 } else {
                     returnedFromJava = ((JS.Callable)o).call(arguments);
                     checkReturnedFromJava = true;
-                    break;
                 }
+                break;
             }
 
             case THROW: {
@@ -328,11 +292,11 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
             }
 
             case INC: case DEC: {
-                boolean isPrefix = JS.toBoolean(curArg);
+                boolean isPrefix = JS.toBoolean(arg);
                 Object key = cx.stack.pop();
                 JS obj = (JS)cx.stack.pop();
                 Number num = JS.toNumber(obj.get(key));
-                Number val = new Double(curOP == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
+                Number val = new Double(op == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
                 obj.put(key, val);
                 cx.stack.push(isPrefix ? val : num);
                 break;
@@ -343,20 +307,15 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
                 Object old = cx.stack.pop();
                 Object key = cx.stack.pop();
                 Object obj = cx.stack.peek();
-                if (val instanceof CompiledFunction) {
-                    if (obj instanceof JS.Scope) {
-                        JS.Scope parent = (JS.Scope)obj;
-                        while(parent.getParentScope() != null) parent = parent.getParentScope();
-                        if (parent instanceof org.xwt.Box) {
-                            if (curOP == ASSIGN_ADD) {
-                                ((org.xwt.Box)parent).addTrap(key, val);
-                            } else {
-                                ((org.xwt.Box)parent).delTrap(key, val);
-                            }
-                            // skip over the "normal" implementation of +=/-=
-                            cx.pc += ((Integer)curArg).intValue() - 1;
-                            break;
-                        }
+                if (val instanceof Function && obj instanceof JS.Scope) {
+                    JS.Scope parent = (JS.Scope)obj;
+                    while(parent.getParentScope() != null) parent = parent.getParentScope();
+                    if (parent instanceof org.xwt.Box) {
+                        org.xwt.Box b = (org.xwt.Box)parent;
+                        if (op == ASSIGN_ADD) b.addTrap(key, val); else b.delTrap(key, val);
+                        // skip over the "normal" implementation of +=/-=
+                        cx.pc += ((Integer)arg).intValue() - 1;
+                        break;
                     }
                 }
                 // use the "normal" implementation
@@ -367,13 +326,14 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
             }
 
             case ADD: {
-                int count = ((Number)curArg).intValue();
+                int count = ((Number)arg).intValue();
                 if(count < 2) throw new Error("this should never happen");
                 if(count == 2) {
                     // common case
                     Object right = cx.stack.pop();
                     Object left = cx.stack.pop();
-                    if(left instanceof String || right instanceof String) cx.stack.push(JS.toString(left).concat(JS.toString(right)));
+                    if(left instanceof String || right instanceof String)
+                        cx.stack.push(JS.toString(left).concat(JS.toString(right)));
                     else cx.stack.push(new Double(JS.toDouble(left) + JS.toDouble(right)));
                 } else {
                     Object[] args = new Object[count];
@@ -410,7 +370,7 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
             default: {
                 Object right = cx.stack.pop();
                 Object left = cx.stack.pop();
-                switch(curOP) {
+                switch(op) {
                         
                 case BITOR: cx.stack.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
                 case BITXOR: cx.stack.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
@@ -434,8 +394,8 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
                     } else {
                         result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
                     }
-                    cx.stack.push(new Boolean((curOP == LT && result < 0) || (curOP == LE && result <= 0) ||
-                                       (curOP == GT && result > 0) || (curOP == GE && result >= 0)));
+                    cx.stack.push(new Boolean((op == LT && result < 0) || (op == LE && result <= 0) ||
+                                       (op == GT && result > 0) || (op == GE && result >= 0)));
                     break;
                 }
                     
@@ -451,10 +411,10 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
                     else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
                     else if (l instanceof String) ret = r != null && l.equals(r.toString());
                     else ret = l.equals(r);
-                    cx.stack.push(new Boolean(curOP == EQ ? ret : !ret)); break;
+                    cx.stack.push(new Boolean(op == EQ ? ret : !ret)); break;
                 }
 
-                default: throw new Error("unknown opcode " + curOP);
+                default: throw new Error("unknown opcode " + op);
                 } }
             }
 
@@ -469,7 +429,7 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
                     cx.stack.push(new CallMarker(cx));
                     cx.stack.push(((JS.TailCall)returnedFromJava).args);
                     cx.f = ((JS.TailCall)returnedFromJava).func;
-                    cx.scope = new CompiledFunctionImpl.FunctionScope("unknown", cx.f.parentScope);
+                    cx.scope = new Scope(cx.f.parentScope);
                     cx.pc = -1;
                 } else {
                     cx.stack.push(returnedFromJava);
@@ -511,9 +471,11 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
         } // end for
     }
 
+
     // Debugging //////////////////////////////////////////////////////////////////////
 
-    public String toString() {
+    public String toString() { return "Function [" + sourceName + ":" + firstLine + "]"; }
+    public String dump() {
         StringBuffer sb = new StringBuffer(1024);
         sb.append("\n" + sourceName + ": " + firstLine + "\n");
         for (int i=0; i < size; i++) {
@@ -537,22 +499,15 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
         return sb.toString();
     } 
 
+
     // Exception Stuff ////////////////////////////////////////////////////////////////
 
     static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
     static EvaluatorException ee(String s) {
-        throw new EvaluatorException(JS.Context.getSourceName() + ":" + JS.Context.getLine() + " " + s);
+        throw new EvaluatorException(Context.getSourceName() + ":" + Context.getLine() + " " + s);
     }
     static JS.Exn je(String s) {
-        throw new JS.Exn(JS.Context.getSourceName() + ":" + JS.Context.getLine() + " " + s);
-    }
-
-    // FunctionScope /////////////////////////////////////////////////////////////////
-
-    static class FunctionScope extends JS.Scope {
-        String sourceName;
-        public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
-        public String getSourceName() { return sourceName; }
+        throw new JS.Exn(Context.getSourceName() + ":" + Context.getLine() + " " + s);
     }
 
 
@@ -561,7 +516,7 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
     public static class CallMarker {
         int pc;
         Scope scope;
-        CompiledFunctionImpl f;
+        Function f;
         public CallMarker(Context cx) { pc = cx.pc + 1; scope = cx.scope; f = cx.f; }
     }
     
@@ -596,7 +551,3 @@ class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
     }
 }
 
-/** this class exists solely to work around a GCJ bug */
-abstract class JSCallable extends JS.Callable {
-        public abstract Object call(JS.Array args) throws JS.Exn;
-}
index 94809b5..ba83b01 100644 (file)
@@ -19,8 +19,8 @@ public abstract class JS {
     // Public Helper Methods //////////////////////////////////////////////////////////////////////
 
     /** parse and compile a function */
-    public static CompiledFunction parse(String sourceName, int firstLine, Reader sourceCode) throws IOException {
-        return new CompiledFunction(sourceName, firstLine, sourceCode, null);
+    public static Function parse(String sourceName, int firstLine, Reader sourceCode) throws IOException {
+        return new Function(sourceName, firstLine, sourceCode, null);
     }
 
     /** coerce an object to a Boolean */
@@ -54,7 +54,8 @@ public abstract class JS {
 
         // NOTE: There are about 3 pages of rules in ecma262 about string to number conversions
         //       We aren't even close to following all those rules.  We probably never will be.
-        if (o instanceof String) try { return new Double((String)o); } catch (NumberFormatException e) { return new Double(Double.NaN); }
+        if (o instanceof String)
+            try { return new Double((String)o); } catch (NumberFormatException e) { return new Double(Double.NaN); }
         if (o instanceof Boolean) return ((Boolean)o).booleanValue() ? new Long(1) : new Long(0);
         if (o instanceof JS) return ((JS)o).coerceToNumber();
         throw new Error("toNumber() got object of type " + o.getClass().getName() + " which we don't know how to handle");
@@ -82,19 +83,14 @@ public abstract class JS {
     public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
        if (checkOnly) return Boolean.FALSE;
        Object o = get(method);
-       if(o instanceof JS.Callable) {
-           return ((JS.Callable)o).call(args);
-       } else if(o == null) {
-           throw new JS.Exn("Attempted to call non-existent method: " + method);
-       } else {
-           throw new JS.Exn("Attempted to call a non-method: " +method);
-       }
+       if (o instanceof JS.Callable) return ((JS.Callable)o).call(args);
+        else if (o == null) throw new JS.Exn("Attempted to call non-existent method: " + method);
+        else throw new JS.Exn("Attempted to call a non-function: " +method);
     }
     
-    public Number coerceToNumber() { return new Integer(0); }
+    public Number coerceToNumber() { throw new JS.Exn("tried to coerce a JavaScript object to a Number"); }
     public String coerceToString() { throw new JS.Exn("tried to coerce a JavaScript object to a String"); }
-    public boolean coerceToBoolean() { return true; }
-    
+    public boolean coerceToBoolean() { throw new JS.Exn("tried to coerce a JavaScript object to a Boolean"); }
     public String typeName() { return "object"; }
 
 
@@ -148,8 +144,7 @@ public abstract class JS {
     public static class Scope extends ScopeImpl { 
         public Scope(Scope parentScope) { this(parentScope, false); }
         public Scope(Scope parentScope, boolean sealed) { super(parentScope, sealed); }
-        /** transparent scopes are not returned by THIS */
-        public boolean isTransparent() { return super.isTransparent(); }
+        public boolean isTransparent() { return super.isTransparent(); }   //< transparent scopes are not returned by THIS
         public boolean has(Object key) { return super.has(key); }
         public Object get(Object key) { return super._get(key); }
         public Object put(Object key, Object val) { super._put(key, val); return null; }
@@ -193,70 +188,82 @@ public abstract class JS {
         }
     }
 
-    /** anything that is callable with the () operator */
+    /** anything that is callable with the () operator and wasn't compiled from JS code */
     public static abstract class Callable extends JS.Obj {
         public abstract Object call(JS.Array args) throws JS.Exn;
     }
 
-    /** a Callable which was compiled from JavaScript code */
-    public static class CompiledFunction extends CompiledFunctionImpl {
-        public int getNumFormalArgs() { return numFormalArgs; }
-        CompiledFunction(String sourceName, int firstLine, Reader sourceCode, Scope scope) throws IOException {
-            super(sourceName, firstLine, sourceCode, scope);
-        }
-    }
-    
     /** a scope that is populated with js objects and functions normally found in the global scope */
     public static class GlobalScope extends GlobalScopeImpl {
         public GlobalScope() { this(null); }
         public GlobalScope(JS.Scope parent) { super(parent); }
     }
 
-    public static final JS Math = new org.xwt.js.Math();
-
     public static class TailCall {
-        CompiledFunction func = null;
+        Function func = null;
         JS.Array args = null;
         public TailCall() { }
-        public TailCall set(CompiledFunction func) { this.func = func; this.args = new JS.Array(); return this; }
-        public TailCall set(CompiledFunction func, JS.Array args) { this.func = func; this.args = args; return this; }
+        public TailCall set(Function func) { this.func = func; this.args = new JS.Array(); return this; }
+        public TailCall set(Function func, JS.Array args) { this.func = func; this.args = args; return this; }
     }
  
-    /** encapsulates a single JavaScript thread; the JS.Context->java.lang.Thread mapping is 1:1 */
+    /** encapsulates the state of a JavaScript "thread" (ie stack) */
     public static class Context {
 
-        CompiledFunction f = null;
-        Vec stack = new Vec();
-        public Scope scope = null;
-        int pc = 0;
 
-        /** return this to signal a pause */
+        // Statics //////////////////////////////////////////////////////////////////////
+
+        /**
+         *  Return this from call/get/put in order to make the interpreter pause.  The interpreter will expect a value
+         *  (the return from the call or the get) to be pushed onto the stack when it is resumed.
+         */
         public static Object pause = new Object();
 
-        public static int getLine() { return current().f == null ? -1 : current().f.getLine(current()); }
-        public static String getSourceName() { return current().f == null ? null : current().f.getSourceName();  }
+        private int getLine_() { return current().f == null ? -1 : (pc < 0 || pc >= f.size) ? -1 : f.line[pc]; }
+        public static int getLine() { return current().getLine_(); }
+        public static String getSourceName() { return current().f == null ? null : current().f.sourceName; } 
+
+        /** fetches the currently-executing javascript function */
+        public static JS.Context current() { return (JS.Context)threadToContext.get(Thread.currentThread()); }
+        private static Hashtable threadToContext = new Hashtable();
 
-        public Context(CompiledFunction function, Scope scope, JS.Array args) {
-            if (scope == null) scope = new CompiledFunctionImpl.FunctionScope("unknown", function.parentScope);
-            if (args == null) args = new JS.Array();
-            stack.push(new CompiledFunctionImpl.CallMarker(this));
-            stack.push(args);
+
+        // Instance members and methods //////////////////////////////////////////////////////////////////////
+
+        /** the currently-executing Function */
+        Function f = null;
+
+        /** the currently-executing scope */
+        public Scope scope = null;  // FIXME: do we really need this?  the function should contain this info
+
+        /** the object stack */
+        Vec stack = new Vec();
+
+        /** the program counter */
+        int pc = 0;
+
+        public Context(Function function, Scope scope) {
+            if (scope == null) scope = new Scope(function.parentScope);
+            stack.push(new Function.CallMarker(this));
+            stack.push(new JS.Array());
             this.f = function;
             this.scope = scope;
         }
 
+        public Object resume() { return resume(null); }
         public Object resume(Object o) {
+            Thread t = Thread.currentThread();
+            Context old = (Context)threadToContext.get(t);
             try {
-                javaContextToJSContext.put(Thread.currentThread(), this);
-                return CompiledFunctionImpl.eval(this, o);
+                threadToContext.put(t, this);
+                stack.push(o);
+                return Function.eval(this);
             } finally {
-                javaContextToJSContext.remove(Thread.currentThread());
+                if (old == null) threadToContext.remove(t);
+                else threadToContext.put(t, old);
             }
         }
 
-        /** fetches the currently-executing javascript function */
-        public static JS.Context current() { return (JS.Context)javaContextToJSContext.get(Thread.currentThread()); }
-        private static Hashtable javaContextToJSContext = new Hashtable();
     }
 }