automatically try call(JS[]) if method
[org.ibex.js.git] / src / org / ibex / js / JS.java
index a75bb27..a727048 100644 (file)
@@ -1,4 +1,7 @@
-// Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL] 
+// Copyright 2000-2005 the Contributors, as shown in the revision logs.
+// Licensed under the Apache Public Source License 2.0 ("the License").
+// You may not use this file except in compliance with the License.
+
 package org.ibex.js; 
 
 import org.ibex.util.*; 
@@ -6,314 +9,358 @@ import java.io.*;
 import java.util.*;
 
 /** The minimum set of functionality required for objects which are manipulated by JavaScript */
-public abstract class JS { 
-    public static final JS METHOD = new JS() { };
-
-    public JS.Enumeration keys() throws JSExn { throw new JSExn("you can't enumerate the keys of this object (class=" + getClass().getName() +")"); }
-    public JS get(JS key) throws JSExn { return null; }
-    public void put(JS key, JS val) throws JSExn { throw new JSExn("" + key + " is read only (class=" + getClass().getName() +")"); }
-    
-    public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
-        throw new JSExn("method not found (" + JS.debugToString(method) + ")");
-    }
-    public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
-        throw new JSExn("you cannot call this object (class=" + this.getClass().getName() +")");
-    }
-    public InputStream getInputStream() throws IOException {
-        throw new IOException("this object doesn't have a stream associated with it " + getClass().getName() + ")");
-    }
-    
-    public final JS unclone() { return _unclone(); }
-    public final JS jsclone() throws JSExn { return new Clone(this); }
-    public final boolean hasTrap(JS key) { return getTrap(key) != null; }
-    public final boolean equals(Object o) { return this == o || ((o instanceof JS) && jsequals((JS)o)); }
-    // Discourage people from using toString()
-    public final String toString() { return "JS Object [class=" + getClass().getName() + "]"; }
-    
-    // Package private methods
-    Trap getTrap(JS key) { return null; }
-    void putTrap(JS key, Trap value) throws JSExn { throw new JSExn("traps cannot be placed on this object (class=" + this.getClass().getName() +")"); }
-    String coerceToString() throws JSExn { throw new JSExn("can't coerce to a string (class=" + getClass().getName() +")"); }
-    boolean jsequals(JS o) { return this == o; }
-    JS _unclone() { return this; }
-        
-    public static class O extends JS implements Cloneable {
-        private Hash entries;
-        
-        public Enumeration keys() throws JSExn { return entries == null ? (Enumeration)EMPTY_ENUMERATION : (Enumeration)new JavaEnumeration(null,entries.keys()); }
-        public JS get(JS key) throws JSExn { return entries == null ? null : (JS)entries.get(key, null); }
-        public void put(JS key, JS val) throws JSExn { (entries==null?entries=new Hash():entries).put(key,null,val); }        
-
-        /** retrieve a trap from the entries hash */
-        final Trap getTrap(JS key) {
-            return entries == null ? null : (Trap)entries.get(key, Trap.class);
+public interface JS extends Pausable {
+
+    /** Returns an enumeration of the keys in this object. */
+    public JS.Enumeration keys() throws JSExn;
+
+    /** Return the value associated with the given key. */
+    public JS get(JS key) throws JSExn;
+
+    /** Store a specific value against the given key. */
+    public void put(JS key, JS value) throws JSExn;
+
+    /** Executes or unpauses the task, running it in a
+     *  <i>pausable</i> context. */
+    public Object run(Object o) throws Exception, AlreadyRunningException;
+
+    /** Pauses the running task at its convienience. */
+    public void pause() throws NotPausableException;
+
+    /** Calls a specific method with given arguments on this object.
+     *  An exception is thrown if there is no such method or the
+     *  arguments are invalid. */
+    public JS call(JS method, JS[] args) throws JSExn;
+
+    /** Calls this object with the given arguments, running it in an
+     *  <i>unpausable</i> context. An exception is thrown if this
+     *  object is not callable or the arguments are invalid. */
+    public JS call(JS[] args) throws JSExn;
+
+    /** Returns the names of the formal arguments, if any.
+     *  This function must never return a null object. */
+    public String[] getFormalArgs();
+
+    /** Put a value to the given key, calling any write traps that have
+     *  been placed on the key.
+     *
+     *  This function may block for an indeterminate amount of time.
+     *
+     *  Write traps may change the final value  before it is put, thus
+     *  be careful to read the latest value from this function's return
+     *  before doing any more work with it.
+     */
+    public JS putAndTriggerTraps(JS key, JS value) throws JSExn;
+
+    /** Gets the value for a given key, calling any read traps that have
+     *  been placed on the key.
+     *
+     *  This function may block for an indeterminate amount of time.
+     */
+    public JS getAndTriggerTraps(JS key) throws JSExn;
+
+    /** Calls the write traps placed on a given key with the given value
+     *  and returns the result without saving it to this object's key store. */
+    public JS justTriggerTraps(JS key, JS value) throws JSExn;
+
+    public void addTrap(JS key, JS function) throws JSExn;
+    public void delTrap(JS key, JS function) throws JSExn;
+    public Trap getTrap(JS key) throws JSExn;
+
+    // FIXME: consider renaming/removing these
+    public InputStream getInputStream() throws IOException, JSExn;
+    public JS unclone();
+    public String coerceToString();
+
+
+    // Implementations ////////////////////////////////////////////////////////
+
+    /** Provides the lightest possible implementation of JS, throwing
+     *  exceptions on every mutable operation. */
+    public static class Immutable implements JS {
+        private static final String[] emptystr = new String[0];
+
+        public JS unclone() { return this; }
+        public JS.Enumeration keys() throws JSExn { throw new JSExn(
+            "object has no key set, class ["+ getClass().getName() +"]"); }
+        public JS get(JS key) throws JSExn { return null; }
+        public void put(JS key, JS val) throws JSExn { throw new JSExn(
+            "'" + key + "' is read only on class ["+ getClass().getName() +"]"); }
+        public InputStream getInputStream() throws IOException, JSExn { throw new JSExn(
+            "object has not associated stream, class ["+ getClass().getName() +"]"); }
+
+        public Object run(Object o) throws Exception { throw new JSExn(
+            "object cannot be called, class ["+ getClass().getName() +"]"); }
+        public void pause() { throw new NotPausableException(); }
+
+        public JS call(JS[] args) throws JSExn { throw new JSExn( "object cannot be called, class ["+ getClass().getName() +"]"); }
+        public JS call(JS method, JS[] args) throws JSExn {
+            if (method == null) return call(args);
+            throw new JSExn("method not found: " + JSU.str(method) + " class="+this.getClass().getName());
         }
-        
-        /** retrieve a trap from the entries hash */
-        final void putTrap(JS key, Trap value) {
-            if (entries == null) entries = new Hash();
-            entries.put(key, Trap.class, value);
-        }    
+        public String[] getFormalArgs() { return emptystr; }
+
+        public void declare(JS key) throws JSExn { throw new JSExn(
+            "object cannot declare key: "+ JSU.str(key)); }
+        public void undeclare(JS key) throws JSExn { } // FIXME throw error?
+
+        public JS putAndTriggerTraps(JS key, JS val) throws JSExn { throw new JSExn(
+            "'" + key + "' is trap read only on class ["+ getClass().getName() +"]"); }
+        public JS getAndTriggerTraps(JS key) throws JSExn { return null; } // FIXME throw errors?
+        public JS justTriggerTraps(JS key, JS value) throws JSExn { return null; }
+
+        public void addTrap(JS key, JS function) throws JSExn { throw new JSExn(
+            "'" + key + "' is not trappable on class ["+ getClass().getName() +"]"); }
+        public void delTrap(JS key, JS function) throws JSExn { throw new JSExn(
+            "'" + key + "' trap is read only on class ["+ getClass().getName() +"]"); }
+        public Trap getTrap(JS key) throws JSExn { throw new JSExn(
+            "'" + key + "' is not trappable on class ["+ getClass().getName() +"]"); }
+
+        public String coerceToString() { return "object"; }
     }
-    
-    public interface Cloneable { }
-        
-    public static class Clone extends O {
+
+    public interface Cloneable {}
+
+    public static class Clone implements JS {
         protected final JS clonee;
         public Clone(JS clonee) throws JSExn {
-            if(!(clonee instanceof Cloneable)) throw new JSExn("" + clonee.getClass().getName() + " isn't cloneable");
+            if (!(clonee instanceof Cloneable)) throw new JSExn(
+                clonee.getClass().getName() + " is not implement cloneable");
             this.clonee = clonee;
         }
-        JS _unclone() { return clonee.unclone(); }
-        boolean jsequals(JS o) { return clonee.jsequals(o); }
-        
+
+        public JS unclone() { return clonee.unclone(); }
+        public boolean equals(Object o) { return clonee.equals(o); }
+
         public Enumeration keys() throws JSExn { return clonee.keys(); }
-        public final JS get(JS key) throws JSExn { return clonee.get(key); }
-        public final void put(JS key, JS val) throws JSExn { clonee.put(key,val); }
-        public final JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
-            return clonee.callMethod(method,a0,a1,a2,rest,nargs); 
+        public JS get(JS k) throws JSExn { return clonee.get(k); }
+        public void put(JS k, JS v) throws JSExn { clonee.put(k, v); }
+        public InputStream getInputStream() throws IOException, JSExn {
+            return clonee.getInputStream(); }
+
+        public Object run(Object o) throws Exception { return clonee.run(o); }
+        public void pause() { clonee.pause(); }
+
+        public JS call(JS m, JS[] a) throws JSExn { return clonee.call(m, a); }
+        public JS call(JS[] a) throws JSExn { return clonee.call(a); }
+        public String[] getFormalArgs() { return clonee.getFormalArgs(); }
+
+        public JS putAndTriggerTraps(JS k, JS v) throws JSExn {
+            return clonee.putAndTriggerTraps(k, v); }
+        public JS getAndTriggerTraps(JS k) throws JSExn {
+            return clonee.getAndTriggerTraps(k); }
+        public JS justTriggerTraps(JS k, JS v) throws JSExn {
+            return clonee.justTriggerTraps(k, v); }
+
+        public void addTrap(JS k, JS f) throws JSExn { clonee.addTrap(k, f); }
+        public void delTrap(JS k, JS f) throws JSExn { clonee.delTrap(k, f); }
+        public Trap getTrap(JS k) throws JSExn { return clonee.getTrap(k); }
+
+        public String coerceToString() { return clonee.coerceToString(); }
+    }
+
+    public static class Obj extends Basket.Hash implements JS {
+        private static final String[] emptystr = new String[0];
+        private static final Placeholder holder = new Placeholder();
+
+        // HACK: this is hideously, disgustingly ugly.... we need N-ary Hash classes
+        /** entries[index + 0] // key
+         *  entries[index + 1] // value
+         *  entries[index + 2] // trap
+         */
+
+        protected void entryAdded(int p) {}
+        protected void entryUpdated(int p) {}
+        protected void entryRemoved(int p) {}
+
+        public Obj() { super(3, 4, 0.75F); }
+
+        public JS unclone() { return this; }
+        public InputStream getInputStream() throws IOException, JSExn { throw new JSExn(
+            "object has not associated stream, class ["+ getClass().getName() +"]"); }
+
+        public Object run(Object o) throws Exception { throw new JSExn(
+            "object cannot be called, class ["+ getClass().getName() +"]"); }
+        public void pause() { throw new NotPausableException(); }
+
+        public JS call(JS[] args) throws JSExn { throw new JSExn(
+            "object cannot be called, class ["+ getClass().getName() +"]"); }
+        public JS call(JS method, JS[] args) throws JSExn { throw new JSExn(
+            "method not found: " + JSU.str(method)); }
+        public String[] getFormalArgs() { return emptystr; }
+
+        public Enumeration keys() throws JSExn {
+            return new Enumeration(null) {
+                private int dest = -1, next = -1;
+                public boolean _hasNext() {
+                    for (int i = Math.max(0, dest); i < usedslots; i++)
+                        if (i > 0 ? entries[i * indexmultiple] != null : true &&
+                            entries[i * indexmultiple] != this) { next = i; return true; }
+                    return false;
+                }
+                public JS _next() throws JSExn {
+                    if (next < 0 && !hasNext()) throw new NoSuchElementException();
+                    int index = next; dest = next; next = -1;
+                    return (JS)entries[index * indexmultiple];
+                }
+            };
         }
-        public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
-            return clonee.call(a0, a1, a2, rest, nargs);
+        public JS get(JS key) throws JSExn { int i = indexOf(key);
+            return i < 0 ? null : entries[i + 1] instanceof Placeholder ?  null : (JS)entries[i + 1]; }
+        public void put(JS key, JS val) throws JSExn {
+            // NOTE: only way value can be stored as null is using declare()
+            int dest = put(indexOf(key), key);
+            if (val == null) entries[dest + 1] = holder;
+            else entries[dest + 1] = val; }
+
+        /*public boolean hasValue(JS key, JS value) {
+            int i = indexOf(key); return i >= 0 && entries[i + 1] != null; }
+        public boolean hasTrap(JS key, JS trap) {
+            int i = indexOf(key); return i >= 0 && entries[i + 2] != null; }*/
+
+        public void declare(JS key) throws JSExn { entries[put(indexOf(key), key) + 1] = null; }
+        public void undeclare(JS key) throws JSExn { remove(indexOf(key)); }
+
+        public JS putAndTriggerTraps(JS key, JS val) throws JSExn {
+            Trap t = null; int i = indexOf(key);
+            if (i >= 0) t = (Trap)entries[i + 2];
+            if (t != null && (t = t.write()) != null) {
+                val = (JS)new Interpreter(t, val, false).run(null);
+            }
+            put(key, val); // HACK: necessary for subclasses overriding put()
+            /*if (i < 0) i = put(i, key);
+            if (val == null) entries[i + 1] = holder;
+            else entries[i + 1] = val;*/
+            return val;
         }
-        public InputStream getInputStream() throws IOException { return clonee.getInputStream(); }
-        // FIXME: This shouldn't be necessary (its for Ibex.Blessing)
-        public JS getClonee() { return clonee; }
-    }
-    
-    public static abstract class Enumeration extends JS {
-        final Enumeration parent;
-        boolean done;
-        public Enumeration(Enumeration parent) { this.parent = parent; }
-        protected abstract boolean _hasMoreElements();
-        protected abstract JS _nextElement() throws JSExn;
-        
-        public final boolean hasMoreElements() {
-            if(!done && !_hasMoreElements()) done = true;
-            return !done ? true : parent != null ? parent.hasMoreElements() : false;
+        public JS getAndTriggerTraps(JS key) throws JSExn {
+            Trap t = null; int i = indexOf(key);
+            if (i < 0) return get(key); // HACK: necessary for subclasses overriding get()
+            t = (Trap)entries[i + 2];
+            return t == null ? (JS)entries[i + 1] : (JS)new Interpreter(t, null, false).run(null);
         }
-        public final JS nextElement() throws JSExn { return !done ? _nextElement() : parent != null ? parent.nextElement() : null; }
-        
-        public JS get(JS key) throws JSExn {
-            //#switch(JS.toString(key))
-            case "hasMoreElements": return B(hasMoreElements());
-            case "nextElement": return nextElement();
-            //#end
-            return super.get(key);
+        public JS justTriggerTraps(JS key, JS val) throws JSExn {
+            Trap t = null; int i = indexOf(key);
+            if (i >= 0) t = (Trap)entries[i + 2];
+            if (t == null || (t = t.write()) == null) return val;
+            return (JS)new Interpreter(t, val, true).run(null);
         }
-    }
 
-    public static class EmptyEnumeration extends Enumeration {
-        public EmptyEnumeration(Enumeration parent) { super(parent); }
-        protected boolean _hasMoreElements() { return false; }
-        protected JS _nextElement() { return null; }
-    }
-    public static class JavaEnumeration extends Enumeration {
-        private final java.util.Enumeration e;
-        public JavaEnumeration(Enumeration parent, java.util.Enumeration e) { super(parent); this.e = e; }
-        protected boolean _hasMoreElements() { return e.hasMoreElements(); }
-        protected JS _nextElement() { return (JS) e.nextElement(); }
-    }
-    
-    // Static Interpreter Control Methods ///////////////////////////////////////////////////////////////
-
-    /** log a message with the current JavaScript sourceName/line */
-    public static void log(Object message) { info(message); }
-    public static void debug(Object message) { Log.debug(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
-    public static void info(Object message) { Log.info(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
-    public static void warn(Object message) { Log.warn(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
-    public static void error(Object message) { Log.error(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
-
-    public static class NotPauseableException extends Exception { NotPauseableException() { } }
-
-    /** returns a callback which will restart the context; expects a value to be pushed onto the stack when unpaused */
-    public static UnpauseCallback pause() throws NotPauseableException {
-        Interpreter i = Interpreter.current();
-        if (i.pausecount == -1) throw new NotPauseableException();
-        boolean get;
-        switch(i.f.op[i.pc]) {
-            case Tokens.RETURN: case ByteCodes.PUT: get = false; break;
-            case ByteCodes.GET: case ByteCodes.CALL: case ByteCodes.CALLMETHOD: get = true; break;
-            default: throw new Error("should never happen: i.f.op[i.pc] == " + i.f.op[i.pc]);
+        public void addTrap(JS key, JS f) throws JSExn {
+            if (f.getFormalArgs() == null || f.getFormalArgs().length > 1) throw new JSExn(
+                "traps must take either one argument (write) or no arguments (read)");
+            int i = indexOf(key); if (i < 0) i = put(i, key);
+            for (Trap t = (Trap)entries[i + 2]; t != null; t = t.next())
+                if (t.function().equals(f)) return;
+            entries[i + 2] = new TrapHolder(this, key, f, (Trap)entries[i + 2]);
         }
-        i.pausecount++;
-        return new JS.UnpauseCallback(i,get);
-    }
 
-    public static class UnpauseCallback implements Task {
-        private Interpreter i;
-        private boolean get;
-        UnpauseCallback(Interpreter i, boolean get) { this.i = i; this.get = get; }
-        public void perform() throws JSExn { unpause(); }
-        public JS unpause() throws JSExn { return unpause((JS)null); }
-        public JS unpause(JS o) throws JSExn {
-            if (o == JS.METHOD) throw new JSExn("can't return a method to a paused context");
-            if(get) i.stack.push(o);
-            return i.resume();
+        public void delTrap(JS key, JS f) throws JSExn {
+            int i = indexOf(key); if (i < 0) return;
+            Trap t = (Trap)entries[i + 2];
+            if (t.function().equals(f)) { entries[i + 2] = t.next(); return; }
+            for (; t.next() != null; t = t.next())
+                if (t.next().function().equals(f)) { ((TrapHolder)t).next = t.next().next(); return; }
         }
-        public JS unpause(JSExn e) throws JSExn {
-            i.catchException(e);
-            return i.resume();
+
+        public Trap getTrap(JS key) throws JSExn {
+            int i = indexOf(key); return i < 0 ? null : (Trap)entries[i + 2];
         }
-    }
 
+        public String coerceToString() { return "object"; }
 
+        private static final class Placeholder implements Serializable {}
 
-    // Static Helper Methods ///////////////////////////////////////////////////////////////////////////////////
+        private static final class TrapHolder implements Trap {
+            private final JS target, key, function;
+            private Trap next;
+            TrapHolder(JS t, JS k, JS f, Trap n) { target = t; key = k; function = f; next = n; }
 
-    /** coerce an object to a Boolean */
-    public static boolean toBoolean(JS o) {
-        if(o == null) return false;
-        if(o instanceof JSNumber) return ((JSNumber)o).toBoolean();
-        if(o instanceof JSString) return ((JSString)o).s.length() != 0;
-        return true;
-    }
-    //#repeat long/int/double/float toLong/toInt/toDouble/toFloat Long/Integer/Double/Float parseLong/parseInt/parseDouble/parseFloat
-    /** coerce an object to a Number */
-    public static long toLong(JS o) throws JSExn {
-        if(o == null) return 0;
-        if(o instanceof JSNumber) return ((JSNumber)o).toLong();
-        if(o instanceof JSString) return Long.parseLong(o.coerceToString());
-        throw new JSExn("can't coerce a " + o.getClass().getName() + " to a number");
-    }
-    //#end
-    
-    public static String toString(JS o) throws JSExn {
-        if(o == null) return "null";
-        return o.coerceToString();
-    }
-    
-    public static String debugToString(JS o) {
-        try { return toString(o); }
-        catch(JSExn e) { return o.toString(); }
-    }
-    
-    public static boolean isInt(JS o) {
-        if(o == null) return true;
-        if(o instanceof JSNumber.I) return true;
-        if(o instanceof JSNumber.B) return false;
-        if(o instanceof JSNumber) {
-            JSNumber n = (JSNumber) o;
-            return n.toInt() == n.toDouble();
-        }
-        if(o instanceof JSString) {
-            String s = ((JSString)o).s;
-            for(int i=0;i<s.length();i++)
-                if(s.charAt(i) < '0' || s.charAt(i) > '9') return false;
-            return true;
-        }
-        return false;
-    }
-    
-    public static boolean isString(JS o) {
-        if(o instanceof JSString) return true;
-        return false;
-    }
-    
-    // Instance Methods ////////////////////////////////////////////////////////////////////
-    public final static JS NaN = new JSNumber.D(Double.NaN);
-    public final static JS ZERO = new JSNumber.I(0);
-    public final static JS ONE = new JSNumber.I(1);
-    public final static JS MATH = new JSMath();
-        
-    public static final JS T = new JSNumber.B(true);
-    public static final JS F = new JSNumber.B(false);
-
-    public static final JS B(boolean b) { return b ? T : F; }
-    public static final JS B(int i) { return i==0 ? F : T; }
-    
-    private static final int CACHE_SIZE = 65536 / 4; // must be a power of two
-    private static final JSString[] stringCache = new JSString[CACHE_SIZE];
-    public static final JS S(String s) {
-        if(s == null) return null;
-        int slot = s.hashCode()&(CACHE_SIZE-1);
-        JSString ret = stringCache[slot];
-        if(ret == null || !ret.s.equals(s)) stringCache[slot] = ret = new JSString(s);
-        return ret;
-    }
-    public static final JS S(String s, boolean intern) { return intern ? JSString.intern(s) : S(s); }
-
-    public static final JS N(double d) { return new JSNumber.D(d); }
-    public static final JS N(long l) { return new JSNumber.L(l); }
-    
-    public static final JS N(Number n) {
-        if(n instanceof Integer) return N(n.intValue());
-        if(n instanceof Long) return N(n.longValue());
-        return N(n.doubleValue());
-    }
+            public JS key() { return key; }
+            public JS target() { return target; }
+            public JS function() { return function; }
 
-    private static final JSNumber.I[] smallIntCache = new JSNumber.I[CACHE_SIZE];
-    private static final JSNumber.I[] largeIntCache = new JSNumber.I[CACHE_SIZE];
-    public static final JS N(int i) {
-        JSNumber.I ret = null;
-        int idx = i + smallIntCache.length / 2;
-        if (idx < CACHE_SIZE && idx > 0) {
-            ret = smallIntCache[idx];
-            if (ret != null) return ret;
-        }
-        else ret = largeIntCache[Math.abs(idx % CACHE_SIZE)];
-        if (ret == null || ret.i != i) {
-            ret = new JSNumber.I(i);
-            if (idx < smallIntCache.length && idx > 0) smallIntCache[idx] = ret;
-            else largeIntCache[Math.abs(idx % CACHE_SIZE)] = ret;
+            public boolean isReadTrap()  {
+                return function.getFormalArgs() == null || function.getFormalArgs().length == 0; }
+            public boolean isWriteTrap() {
+                return function.getFormalArgs() != null && function.getFormalArgs().length != 0; }
+
+            public Trap next() { return next; }
+            public Trap nextRead() {
+                Trap t = next; while (t != null && t.isWriteTrap()) t = t.next(); return t; }
+            public Trap nextWrite() {
+                Trap t = next; while (t != null && t.isReadTrap()) t = t.next(); return t; }
+            public Trap read() { return isReadTrap() ? this : nextRead(); }
+            public Trap write() { return isWriteTrap() ? this : nextWrite(); }
         }
-        return ret;
-    }
-    
-    private static Enumeration EMPTY_ENUMERATION = new EmptyEnumeration(null);
-    
-    public static JS fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
-        return Parser.fromReader(sourceName, firstLine, sourceCode);
     }
 
-    public static JS cloneWithNewGlobalScope(JS js, JS s) {
-        if(js instanceof JSFunction)
-            return ((JSFunction)js)._cloneWithNewParentScope(new JSScope.Top(s));
-        else
-            return js;
+    public interface Trap {
+        public JS key();
+        public JS target();
+        public JS function();
+        public boolean isReadTrap();
+        public boolean isWriteTrap();
+        public Trap next();
+        public Trap nextRead();
+        public Trap nextWrite();
+
+        public Trap read(); // FIXME reconsider these function names
+        public Trap write();
     }
 
+    /** An empty class used for instanceof matching the result of JS.get()
+     *  to decide if the key is a method (to be called with JS.callMethod(). */
+    public static final class Method extends Immutable {}
 
-    // Trap support //////////////////////////////////////////////////////////////////////////////
 
-    /** performs a put, triggering traps if present; traps are run in an unpauseable interpreter */
-    public final void putAndTriggerTraps(JS key, JS value) throws JSExn {
-        Trap t = getTrap(key);
-        if(t == null || (t = t.writeTrap()) == null) put(key,value);
-        else new Interpreter(t,value,false).resume();
-    }
+    public static abstract class Enumeration extends Immutable {
+        public static final Enumeration EMPTY = new Empty(null);
 
-    /** performs a get, triggering traps if present; traps are run in an unpauseable interpreter */
-    public final JS getAndTriggerTraps(JS key) throws JSExn {
-        Trap t = getTrap(key);
-        if (t == null || (t = t.readTrap()) == null) return get(key);
-        else return new Interpreter(t,null,false).resume();
-    }
-    
-    public final JS justTriggerTraps(JS key, JS value) throws JSExn {
-        Trap t = getTrap(key);
-        if(t == null || (t = t.writeTrap()) == null) return value;
-        else return new Interpreter(t,value,true).resume();
-    }
+        private final Enumeration parent;
 
-    /** adds a trap, avoiding duplicates */
-    // FIXME: This shouldn't be public, it is needed for a hack in Template.java
-    public void addTrap(JS key, JSFunction f) throws JSExn {
-        if (f.numFormalArgs > 1) throw new JSExn("traps must take either one argument (write) or no arguments (read)");
-        boolean isRead = f.numFormalArgs == 0;
-        for(Trap t = getTrap(key); t != null; t = t.next) if (t.f == f) return;
-        putTrap(key, new Trap(this, key, f, (Trap)getTrap(key)));
-    }
+        public Enumeration(Enumeration parent) { this.parent = parent; }
 
-    /** deletes a trap, if present */
-    // FIXME: This shouldn't be public, it is needed for a hack in Template.java
-    public void delTrap(JS key, JSFunction f) throws JSExn {
-        Trap t = (Trap)getTrap(key);
-        if (t == null) return;
-        if (t.f == f) { putTrap(t.target, t.next); return; }
-        for(; t.next != null; t = t.next) if (t.next.f == f) { t.next = t.next.next; return; }
-    }
+        protected abstract boolean _hasNext();
+        protected abstract JS _next() throws JSExn;
+
+        public final boolean hasNext() {
+            return _hasNext() || parent != null ? parent.hasNext() : false; }
+        public final JS next() throws JSExn {
+            if (_hasNext()) return _next();
+            if (parent == null) throw new NoSuchElementException("reached end of set");
+            return parent.next();
+        }
 
+        public JS get(JS key) throws JSExn {
+            //#switch(JSU.str(key))
+            case "hasNext": return JSU.B(hasNext());
+            case "next": return next();
+            //#end
+            return super.get(key);
+        }
+
+        public static final class Empty extends Enumeration {
+            public Empty(Enumeration parent) { super(parent); }
+            protected boolean _hasNext() { return false; }
+            protected JS _next() { throw new NoSuchElementException(); }
+        }
+
+        public static final class JavaIterator extends Enumeration {
+            private final Iterator i;
+            public JavaIterator(Enumeration parent, Iterator i) { super(parent); this.i = i; }
+            protected boolean _hasNext() { return i.hasNext(); }
+            protected JS _next() { return (JS)i.next(); }
+        }
+
+        public static final class RandomAccessList extends Enumeration {
+            private final List l;
+            private int pos = 0, size;
+            public RandomAccessList(Enumeration parent, List list) {
+                super(parent); l = list; size = l.size(); }
+            protected boolean _hasNext() { return  pos < size; }
+            protected JS _next() { return (JS)l.get(pos++); }
+        }
+    }
 
-} 
+}