2003/10/31 10:57:24
[org.ibex.core.git] / src / org / xwt / js / JS.java
index 11faeaa..ebd2e36 100644 (file)
@@ -6,235 +6,250 @@ import java.io.*;
 import java.util.*;
 
 /**
- *  The public API for the JS engine; JS itself is actually a class
- *  implementing the minimal amount of functionality for an Object
- *  which can be manipulated by JavaScript code.
+ *  The public API for the JS engine.  JS itself is actually a class
+ *  implementing the absolute minimal amount of functionality for an
+ *  Object which can be manipulated by JavaScript code.  The static
+ *  methods, fields, and inner classes of JS define the publicly
+ *  visible API for the XWT JavaScript engine; code outside this
+ *  package should never depend on anything not defined in this file.
  */
 public abstract class JS { 
 
 
-    // Static Methods //////////////////////////////////////////////////////////////////////
+    // Public Helper Methods //////////////////////////////////////////////////////////////////////
 
-    private static Hashtable currentFunction = new Hashtable();
-    public static Function getCurrentFunction() { return (Function)currentFunction.get(Thread.currentThread()); }
-    public static String getCurrentFunctionSourceName() { return getCurrentFunctionSourceName(Thread.currentThread()); }
-    public static String getFileAndLine() { return getCurrentFunctionSourceName() + ":" + getCurrentFunction().getLine(); }
-    public static String getCurrentFunctionSourceName(Thread t) {
-       Function f = (Function)currentFunction.get(t);
-       if (f == null) return "null";
-       return f.getSourceName();
+    /** parse and compile a function */
+    public static CompiledFunction parse(String sourceName, int firstLine, Reader sourceCode) throws IOException {
+        return new CompiledFunction(sourceName, firstLine, sourceCode, null);
     }
 
+    /** coerce an object to a Boolean */
     public static boolean toBoolean(Object o) {
-       if (o == null) return false;
-       if (o instanceof Boolean) return ((Boolean)o).booleanValue();
-       if (o instanceof Number) return o.equals(new Integer(0));
-       return true;
+        if (o == null) return false;
+        if (o instanceof Boolean) return ((Boolean)o).booleanValue();
+        if (o instanceof Long) return ((Long)o).longValue() != 0;
+        if (o instanceof Integer) return ((Integer)o).intValue() != 0;
+        if (o instanceof Number) {
+            double d = ((Number) o).doubleValue();
+            // NOTE: d == d is a test for NaN. It should be faster than Double.isNaN()
+            return d != 0.0 && d == d;
+        }
+        if (o instanceof String) return ((String)o).length() != 0;
+        return true;
     }
 
+    /** coerce an object to a Long */
     public static long toLong(Object o) { return toNumber(o).longValue(); }
+
+    /** coerce an object to an Int */
+    public static int toInt(Object o) { return toNumber(o).intValue(); }
+
+    /** coerce an object to a Double */
     public static double toDouble(Object o) { return toNumber(o).doubleValue(); }
-    public static Number toNumber(Object o) {
-       if (o == null) return new Long(0);
-       if (o instanceof Number) return ((Number)o);
-       if (o instanceof String) try { return new Double((String)o); } catch (NumberFormatException e) { return new Double(0); }
-       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");
-    }
 
+    /** coerce an object to a Number */
+    public static Number toNumber(Object o) {
+        if (o == null) return new Long(0);
+        if (o instanceof Number) return ((Number)o);
 
+        // 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 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");
+    }
+    
+    /** coerce an object to a String */
+    public static String toString(Object o) {
+        if(o == null) return "null";
+        if(o instanceof String) return (String) o;
+        if(o instanceof Integer || o instanceof Long || o instanceof Boolean) return o.toString();
+        if(o instanceof JS) return ((JS)o).coerceToString();
+        if(o instanceof Double || o instanceof Float) {
+            double d = ((Number)o).doubleValue();
+            if((int)d == d) return Integer.toString((int)d);
+            return o.toString();
+        }
+        return o.toString();
+    }
+    
     // Instance Methods ////////////////////////////////////////////////////////////////////
  
     public abstract Object get(Object key) throws JS.Exn; 
     public abstract void put(Object key, Object val) throws JS.Exn; 
     public abstract Object[] keys(); 
-
-    public Number coerceToNumber() { throw new Error("you cannot coerce a " + this.getClass().getName() + " into a Number"); }
-    public String coerceToString() { throw new Error("you cannot coerce a " + this.getClass().getName() + " into a String"); }
-    public boolean coerceToBoolean() { throw new Error("you cannot coerce a " + this.getClass().getName() + " into a Boolean"); }
+    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);
+       }
+    }
+    
+    public Number coerceToNumber() { return new Integer(0); }
+    public String coerceToString() { throw new JS.Exn("tried to coerce a JavaScript object to a String"); }
+    public boolean coerceToBoolean() { return true; }
+    
+    public String typeName() { return "object"; }
 
 
-    // Subclasses /////////////////////////////////////////////////////////////////////////
+    // Inner Classes /////////////////////////////////////////////////////////////////////////
 
-    /** A slightly more featureful version of JS */
+    /** A sensible implementation of the abstract methods in the JS class */
     public static class Obj extends JS {
-       private Hash entries = new Hash();
-       private boolean sealed = false;
-       public Obj() { this(false); }
-       public Obj(boolean sealed) { this.sealed = sealed; }
-       public void setSeal(boolean sealed) { this.sealed = sealed; }
-       public Object get(Object key) { return entries.get(key); }
-       public void put(Object key, Object val) { if (!sealed) entries.put(key, val); }
-       public Object[] keys() { return(entries.keys()); }
+        private Hash entries = null;
+        private boolean sealed = false;
+        public Obj() { this(false); }
+        public Obj(boolean sealed) { this.sealed = sealed; }
+        public void setSeal(boolean sealed) { this.sealed = sealed; }      ///< a sealed object cannot have its properties modified
+        public void put(Object key, Object val) { put(key, null, val); }
+        protected void put(Object key, Object key2, Object val) {
+            if (sealed) return;
+            if (entries == null) entries = new Hash();
+            entries.put(key, key2, val); }
+        public Object[] keys() { return entries == null ? new Object[0] : entries.keys(); }
+        public Object get(Object key) { return get(key, null); }
+        protected Object get(Object key, Object key2) {
+            if (entries == null) return null;
+            if(key2 == null && callMethod((String)key, null, true) == Boolean.TRUE)
+                return new Internal.CallableStub(this, key);
+            return entries.get(key, key2);
+        }
     }
 
-    /** An exception which can be thrown and caught by JavaScripts */
+    /** An exception which can be thrown and caught by JavaScript code */
     public static class Exn extends RuntimeException { 
-       private Object js = null; 
-       public Exn(Object js) { this.js = js; } 
-       public String toString() { return "JS.Exn: " + js; }
-       public String getMessage() { return toString(); }
-       public Object getObject() { return js; } 
+        private Object js = null; 
+        public Exn(Object js) { this.js = js; } 
+        public String toString() { return "JS.Exn: " + js; }
+        public String getMessage() { return toString(); }
+        public Object getObject() { return js; } 
     } 
 
-    /** A JavaScript Array */
-    public static class Array extends Obj {
-       private Vec vec = new Vec();
-       public Array() { }
-       public Array(int size) { vec.setSize(size); }
-       private static int intVal(Object o) {
-           if (o instanceof Number) {
-               int intVal = ((Number)o).intValue();
-               if (intVal == ((Number)o).doubleValue()) return intVal;
-               return Integer.MIN_VALUE;
-           }
-           if (!(o instanceof String)) return Integer.MIN_VALUE;
-           String s = (String)o;
-           for(int i=0; i<s.length(); i++) if (s.charAt(i) < '0' || s.charAt(i) > '9') return Integer.MIN_VALUE;
-           return Integer.parseInt(s);
-       }
-       public Object get(Object key) throws JS.Exn {
-           // FIXME: HACK!
-           if (key.equals("cascade")) return org.xwt.Trap.cascadeFunction;
-           if (key.equals("trapee")) return org.xwt.Trap.currentTrapee();
-           if (key.equals("length")) return new Long(vec.size());
-           int i = intVal(key);
-           if (i == Integer.MIN_VALUE) return super.get(key);
-           try {
-               return vec.elementAt(i);
-           } catch (ArrayIndexOutOfBoundsException e) {
-               return null;
-           }
-       }
-       public void put(Object key, Object val) {
-           if (key.equals("length")) vec.setSize(toNumber(val).intValue());
-           int i = intVal(key);
-           if (i == Integer.MIN_VALUE) super.put(key, val);
-           else {
-               if (i >= vec.size()) vec.setSize(i+1);
-               vec.setElementAt(val, i);
-           }
-       }
-       public Object[] keys() {
-           Object[] sup = super.keys();
-           Object[] ret = new Object[vec.size() + 1 + sup.length];
-           System.arraycopy(sup, 0, ret, vec.size(), sup.length);
-           for(int i=0; i<vec.size(); i++) ret[i] = new Integer(i);
-           ret[vec.size()] = "length";
-           return ret;
-       }
-       public void setSize(int i) { vec.setSize(i); }
-       public int length() { return vec.size(); }
-       public Object elementAt(int i) { return vec.elementAt(i); }
-       public void addElement(Object o) { vec.addElement(o); }
-       public void setElementAt(Object o, int i) { vec.setElementAt(o, i); }
+    /** The publicly-visible face of JavaScript Array objects */
+    public static class Array extends ArrayImpl {
+        public Array() { }
+        public Array(int size) { super(size); }
+        public void setSize(int i) { super.setSize(i); }
+        public int length() { return super.length(); }
+        public Object elementAt(int i) { return super.elementAt(i); }
+        public void addElement(Object o) { super.addElement(o); }
+        public void setElementAt(Object o, int i) { super.setElementAt(o, i); }
+        public Object get(Object key) { return super._get(key); }
+        public void put(Object key, Object val) { super._put(key, val); }
     }
 
-    /** Anything that is callable */
-    public static class Function extends Obj {
-       ByteCodeBlock bytecodes;
-       int line;
-       String sourceName;
-       Scope parentScope;
-       public Function(int line, String sourceName, ByteCodeBlock bytecodes, Scope parentScope) {
-           this.sourceName = sourceName;
-           this.line = line;
-           this.bytecodes = bytecodes;
-           this.parentScope = parentScope;
-       }
-       public Function cloneWithNewParentScope(Scope s) {
-           if (this.getClass() != Function.class)
-               throw new Error("org.xwt.js.JS.Function.cloneWithNewParentScope() is not valid for subclasses");
-           return new Function(line, sourceName, bytecodes, s);
-       }
-       public String getSourceName() throws JS.Exn { return sourceName; }
-       public int getLine() throws JS.Exn { return line; }
-       public Object _call(JS.Array args) throws JS.Exn, ByteCodeBlock.ControlTransferException {
-           if (bytecodes == null) throw new Error("tried to call() a JS.Function with bytecodes == null");
-           Context cx = Context.getContextForCurrentThread();
-           int size = cx.stack.size();
-           cx.stack.push(new Context.CallMarker());
-           cx.stack.push(args);
-           bytecodes.eval(args == null ? parentScope : new FunctionScope(sourceName, parentScope));
-           Object ret = cx.stack.pop();
-           if (cx.stack.size() > size) {
-               Log.log(this, "warning, stack grew by " + (cx.stack.size() - size) +
-                       " elements during call to " + getSourceName() + ":" + getLine());
-               Log.log(this, "top element is " + cx.stack.peek());
-           }
-           return ret;
-       }
-       public final Object call(JS.Array args) throws JS.Exn {
-           Function saved = (Function)currentFunction.get(Thread.currentThread());
-           if (!getSourceName().equals("java")) currentFunction.put(Thread.currentThread(), this);
-           try {
-               return _call(args);
-           } catch (ByteCodeBlock.ReturnException e) {  // ignore
-               return e.retval;
-           } catch (ByteCodeBlock.ControlTransferException e) {
-               throw new RuntimeException(getSourceName() + ":" + getLine() +
-                                          " error, ControlTransferException tried to leave a function");
-           } finally {
-               if (saved == null) currentFunction.remove(Thread.currentThread());
-               else currentFunction.put(Thread.currentThread(), saved);
-           }
-       }
+    /** Any object which becomes part of the scope chain must support this interface */ 
+    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 has(Object key) { return super.has(key); }
+        public Object get(Object key) { return super._get(key); }
+        public void put(Object key, Object val) { super._put(key, val); }
+        public void declare(String s) { super.declare(s); }
+    } 
+
+    /** the result of a graft */
+    public static class Graft extends JS {
+        private JS graftee;
+        private Object replaced_key;
+        private Object replaced_val;
+        public Graft(JS graftee, Object key, Object val) {
+            if (graftee instanceof Array) throw new JS.Exn("can't graft onto Arrays (yet)");
+            if (graftee instanceof Callable) throw new JS.Exn("can't graft onto Callables (yet)");
+            if (graftee instanceof Scope) throw new JS.Exn("can't graft onto Scopes (yet)");
+            this.graftee = graftee;
+            replaced_key = key;
+            replaced_val = val;
+        }
+        public boolean equals(Object o) { return (this == o || graftee.equals(o)); }
+        public int hashCode() { return graftee.hashCode(); }
+        public Object get(Object key) { return replaced_key.equals(key) ? replaced_val : graftee.get(key); }
+        public void put(Object key, Object val) { graftee.put(key, val); }
+        public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
+            if (!replaced_key.equals(method)) return graftee.callMethod(method, args, checkOnly);
+            if (replaced_val instanceof Callable) return checkOnly ? Boolean.TRUE : ((Callable)replaced_val).call(args);
+            if (checkOnly) return Boolean.FALSE;
+            throw new JS.Exn("attempt to call non-function");
+        }
+        public Number coerceToNumber() { return graftee.coerceToNumber(); }
+        public String coerceToString() { return graftee.coerceToString(); }
+        public boolean coerceToBoolean() { return graftee.coerceToBoolean(); }
+        public String typeName() { return graftee.typeName(); }
+        public Object[] keys() {
+            Object[] ret = graftee.keys();
+            for(int i=0; i<ret.length; i++) if (replaced_key.equals(ret[i])) return ret;
+            Object[] ret2 = new Object[ret.length + 1];
+            System.arraycopy(ret, 0, ret2, 0, ret.length);
+            ret2[ret2.length - 1] = replaced_key;
+            return ret2;
+        }
     }
 
-    public static Function parse(Reader r, String sourceName, int line) throws IOException {
-       ByteCodeBlock b = new ByteCodeBlock(line, sourceName);
-       Parser p = new Parser(r, sourceName, line);
-       try {
-           while(true) {
-               int size = b.size();
-               p.parseStatement(false, b);
-               if (size == b.size()) break;
-           }
-           b.add(Tokens.RETURN);
-           return new Function(line, sourceName, b, null);
-       } catch (Exception e) {
-           if (Log.on) Log.log(Parser.class, e);
-           return null;
-       }
+    /** anything that is callable with the () operator */
+    public static abstract class Callable extends JS.Obj {
+        public abstract Object call(JS.Array args) throws JS.Exn;
     }
 
-    /** Any object which becomes part of the scope chain must support this interface */ 
-    public static class Scope extends Obj { 
-       private Scope parentScope;
-       private static Object NULL = new Object();
-       public Scope(Scope parentScope) { this(parentScope, false); }
-       public Scope(Scope parentScope, boolean sealed) { super(sealed); this.parentScope = parentScope; }
-       public Scope getParentScope() { return parentScope; }
-
-       // transparent scopes are not returned by THIS
-       public boolean isTransparent() { return false; }
-
-       public boolean has(Object key) { return super.get(key) != null; }
-       public Object get(Object key) {
-           if (!has(key)) return parentScope == null ? null : getParentScope().get(key);
-           Object ret = super.get(key); return ret == NULL ? null : ret;
-       }
-       public void put(Object key, Object val) {
-           if (!has(key) && parentScope != null) getParentScope().put(key, val);
-           else super.put(key, val == null ? NULL : val);
-       }
-       public Object[] keys() { throw new Error("you can't enumerate the properties of a Scope"); }
-       public void declare(String s) {
-           if (isTransparent()) getParentScope().declare(s);
-           else super.put(s, NULL);
-       }
-    } 
+    /** 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();
  
-    private class FunctionScope extends JS.Scope {
-       String sourceName;
-       public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
-       public String getSourceName() { return sourceName; }
-       public Object get(Object key) throws JS.Exn {
-           if (key.equals("trapee")) return org.xwt.Trap.currentTrapee();
-           else if (key.equals("cascade")) return org.xwt.Trap.cascadeFunction;
-           return super.get(key);
-       }
+    /** encapsulates a single JavaScript thread; the JS.Thread->java.lang.Thread mapping is 1:1 */
+    public static class Thread {
+
+        CompiledFunction currentCompiledFunction = null;
+        Vec stack = new Vec();
+        public Scope scope = null;
+        int pc = 0;
+        boolean paused = false;
+
+        CompiledFunction tailCallFunction = null;
+        JS.Array tailCallArgs = null;
+
+        public Thread(CompiledFunction function) {
+            this(function, new CompiledFunctionImpl.FunctionScope("unknown", function.parentScope));
+        }
+        public Thread(CompiledFunction function, Scope scope) {
+            stack.push(new CompiledFunctionImpl.CallMarker(this));
+            stack.push(new JS.Array());
+            this.currentCompiledFunction = function;
+            this.scope = scope;
+        }
+
+        public void setTailCall(JS.CompiledFunction f, JS.Array args) { tailCallFunction = f; tailCallArgs = args; }
+
+        public static JS.Thread current() { return (JS.Thread)javaThreadToJSThread.get(java.lang.Thread.currentThread()); }
+
+        public Object resume() { bind(); paused = false; Object ret = CompiledFunctionImpl.eval(this); unbind(); return ret; }
+        public void pause() { paused = true; unbind(); }
+        public void bind() { javaThreadToJSThread.put(java.lang.Thread.currentThread(), this); }
+        public void unbind() { if (current() == this) javaThreadToJSThread.remove(java.lang.Thread.currentThread()); }
+        public int getLine() { return currentCompiledFunction == null ? -1 : currentCompiledFunction.getLine(this); }
+        public String getSourceName() { return currentCompiledFunction == null ? null : currentCompiledFunction.getSourceName();  }
+
+        /** fetches the currently-executing javascript function */
+        public JS.CompiledFunction getCurrentCompiledFunction() { return currentCompiledFunction; }
+        private static Hashtable javaThreadToJSThread = new Hashtable();
     }
 }