purged JS.Obj <-> Basket.Hash incest
[org.ibex.js.git] / src / org / ibex / js / JS.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.js; 
6
7 import org.ibex.util.*; 
8 import java.io.*;
9 import java.util.*;
10
11 /** The minimum set of functionality required for objects which are manipulated by JavaScript */
12 public interface JS extends Pausable {
13
14     /** Returns an enumeration of the keys in this object. */
15     public JS.Enumeration keys() throws JSExn;
16
17     /** Return the value associated with the given key. */
18     public JS get(JS key) throws JSExn;
19
20     /** Store a specific value against the given key. */
21     public void put(JS key, JS value) throws JSExn;
22
23     /** Executes or unpauses the task, running it in a
24      *  <i>pausable</i> context. */
25     public Object run(Object o) throws Exception, AlreadyRunningException;
26
27     /** Pauses the running task at its convienience. */
28     public void pause() throws NotPausableException;
29
30     /** Calls a specific method with given arguments on this object.
31      *  An exception is thrown if there is no such method or the
32      *  arguments are invalid. */
33     public JS call(JS method, JS[] args) throws JSExn;
34
35     /** Calls this object with the given arguments, running it in an
36      *  <i>unpausable</i> context. An exception is thrown if this
37      *  object is not callable or the arguments are invalid. */
38     public JS call(JS[] args) throws JSExn;
39
40     /** Returns the names of the formal arguments, if any.
41      *  This function must never return a null object. */
42     public String[] getFormalArgs();
43
44     /** Put a value to the given key, calling any write traps that have
45      *  been placed on the key.
46      *
47      *  This function may block for an indeterminate amount of time.
48      *
49      *  Write traps may change the final value  before it is put, thus
50      *  be careful to read the latest value from this function's return
51      *  before doing any more work with it.
52      */
53     public JS putAndTriggerTraps(JS key, JS value) throws JSExn;
54
55     /** Gets the value for a given key, calling any read traps that have
56      *  been placed on the key.
57      *
58      *  This function may block for an indeterminate amount of time.
59      */
60     public JS getAndTriggerTraps(JS key) throws JSExn;
61
62     /** Calls the write traps placed on a given key with the given value
63      *  and returns the result without saving it to this object's key store. */
64     public JS justTriggerTraps(JS key, JS value) throws JSExn;
65
66     public void addTrap(JS key, JS function) throws JSExn;
67     public void delTrap(JS key, JS function) throws JSExn;
68     public Trap getTrap(JS key) throws JSExn;
69
70     // FIXME: consider renaming/removing these
71     public InputStream getInputStream() throws IOException, JSExn;
72     public JS unclone();
73     public String coerceToString();
74
75
76     // Implementations ////////////////////////////////////////////////////////
77
78     /** Provides the lightest possible implementation of JS, throwing
79      *  exceptions on every mutable operation. */
80     public static class Immutable implements JS {
81         private static final String[] emptystr = new String[0];
82
83         public JS unclone() { return this; }
84         public JS.Enumeration keys() throws JSExn { throw new JSExn(
85             "object has no key set, class ["+ getClass().getName() +"]"); }
86         public JS get(JS key) throws JSExn { return null; }
87         public void put(JS key, JS val) throws JSExn { throw new JSExn(
88             "'" + key + "' is read only on class ["+ getClass().getName() +"]"); }
89         public InputStream getInputStream() throws IOException, JSExn { throw new JSExn(
90             "object has not associated stream, class ["+ getClass().getName() +"]"); }
91
92         public Object run(Object o) throws Exception { throw new JSExn(
93             "object cannot be called, class ["+ getClass().getName() +"]"); }
94         public void pause() { throw new NotPausableException(); }
95
96         public JS call(JS[] args) throws JSExn { throw new JSExn( "object cannot be called, class ["+ getClass().getName() +"]"); }
97         public JS call(JS method, JS[] args) throws JSExn {
98             if (method == null) return call(args);
99             throw new JSExn("method not found: " + JSU.str(method) + " class="+this.getClass().getName());
100         }
101         public String[] getFormalArgs() { return emptystr; }
102
103         public void declare(JS key) throws JSExn { throw new JSExn(
104             "object cannot declare key: "+ JSU.str(key)); }
105         public void undeclare(JS key) throws JSExn { } // FIXME throw error?
106
107         public JS putAndTriggerTraps(JS key, JS val) throws JSExn { throw new JSExn(
108             "'" + key + "' is trap read only on class ["+ getClass().getName() +"]"); }
109         public JS getAndTriggerTraps(JS key) throws JSExn { return null; } // FIXME throw errors?
110         public JS justTriggerTraps(JS key, JS value) throws JSExn { return null; }
111
112         public void addTrap(JS key, JS function) throws JSExn {
113             Log.warn(this, "'" + JSU.str(key) + "' is not trappable on class ["+ getClass().getName() +"]"); }
114         public void delTrap(JS key, JS function) throws JSExn {
115             Log.warn(this, "'" + JSU.str(key) + "' trap is read only on class ["+ getClass().getName() +"]"); }
116         public Trap getTrap(JS key) throws JSExn {
117             //Log.warn(this, "'" + JSU.str(key) + "' is not trappable on class ["+ getClass().getName() +"]");
118             return null;
119         }
120
121         public String coerceToString() { return "object"; }
122     }
123
124     public interface Cloneable {}
125
126     public static class Clone implements JS {
127         protected final JS clonee;
128         public Clone(JS clonee) throws JSExn {
129             if (!(clonee instanceof Cloneable)) throw new JSExn(
130                 clonee.getClass().getName() + " is not implement cloneable");
131             this.clonee = clonee;
132         }
133
134         public JS unclone() { return clonee.unclone(); }
135         public boolean equals(Object o) { return clonee.equals(o); }
136
137         public Enumeration keys() throws JSExn { return clonee.keys(); }
138         public JS get(JS k) throws JSExn { return clonee.get(k); }
139         public void put(JS k, JS v) throws JSExn { clonee.put(k, v); }
140         public InputStream getInputStream() throws IOException, JSExn {
141             return clonee.getInputStream(); }
142
143         public Object run(Object o) throws Exception { return clonee.run(o); }
144         public void pause() { clonee.pause(); }
145
146         public JS call(JS m, JS[] a) throws JSExn { return clonee.call(m, a); }
147         public JS call(JS[] a) throws JSExn { return clonee.call(a); }
148         public String[] getFormalArgs() { return clonee.getFormalArgs(); }
149
150         public JS putAndTriggerTraps(JS k, JS v) throws JSExn {
151             return clonee.putAndTriggerTraps(k, v); }
152         public JS getAndTriggerTraps(JS k) throws JSExn {
153             return clonee.getAndTriggerTraps(k); }
154         public JS justTriggerTraps(JS k, JS v) throws JSExn {
155             return clonee.justTriggerTraps(k, v); }
156
157         public void addTrap(JS k, JS f) throws JSExn { clonee.addTrap(k, f); }
158         public void delTrap(JS k, JS f) throws JSExn { clonee.delTrap(k, f); }
159         public Trap getTrap(JS k) throws JSExn { return clonee.getTrap(k); }
160
161         public String coerceToString() { return clonee.coerceToString(); }
162     }
163
164     public static class Obj extends Basket.HashMap implements JS {
165         private static final String[] emptystr = new String[0];
166         private static final Placeholder holder = new Placeholder();
167
168         public Obj() { super(3, 4, 0.75F); }
169
170         public JS unclone() { return this; }
171         public InputStream getInputStream() throws IOException, JSExn { throw new JSExn(
172             "object has not associated stream, class ["+ getClass().getName() +"]"); }
173
174         public Object run(Object o) throws Exception { throw new JSExn(
175             "object cannot be called, class ["+ getClass().getName() +"]"); }
176         public void pause() { throw new NotPausableException(); }
177
178         public JS call(JS[] args) throws JSExn { throw new JSExn(
179             "object cannot be called, class ["+ getClass().getName() +"]"); }
180         public JS call(JS method, JS[] args) throws JSExn { throw new JSExn(
181             "method not found: " + JSU.str(method)); }
182         public String[] getFormalArgs() { return emptystr; }
183
184         public Enumeration keys() throws JSExn {
185             final Object[] keys = super.dumpkeys();
186             return new Enumeration(null) {
187                     private int cur = 0;
188                     public boolean _hasNext() { return cur < keys.length; }
189                     public JS _next() throws JSExn {
190                         if (cur >= keys.length) throw new NoSuchElementException();
191                         return (JS)keys[cur++];
192                     }
193                 };
194         }
195
196         public JS get(JS key) throws JSExn { return (JS)super.get(key, 0); }
197         public void put(JS key, JS val) throws JSExn { super.put(key, val, 0); }
198
199         /*public boolean hasValue(JS key, JS value) {
200             int i = indexOf(key); return i >= 0 && entries[i + 1] != null; }
201         public boolean hasTrap(JS key, JS trap) {
202             int i = indexOf(key); return i >= 0 && entries[i + 2] != null; }*/
203
204         public JS putAndTriggerTraps(JS key, JS val) throws JSExn {
205             Trap t = (Trap)super.get(key, 1);
206             if (t != null && (t = t.write()) != null)
207                 val = (JS)new Interpreter(t, val, false).run(null);
208             put(key, val); // HACK: necessary for subclasses overriding put()
209             /*if (i < 0) i = put(i, key);
210             if (val == null) entries[i + 1] = holder;
211             else entries[i + 1] = val;*/
212             return val;
213         }
214         public JS getAndTriggerTraps(JS key) throws JSExn {
215             Trap t = (Trap)super.get(key, 1);
216             return t == null ? (JS)super.get(key) : (JS)new Interpreter(t, null, false).run(null);
217         }
218         public JS justTriggerTraps(JS key, JS val) throws JSExn {
219             Trap t = (Trap)super.get(key, 1);
220             if (t == null || (t = t.write()) == null) return val;
221             return (JS)new Interpreter(t, val, true).run(null);
222         }
223
224         public void addTrap(JS key, JS f) throws JSExn {
225             if (f.getFormalArgs() == null || f.getFormalArgs().length > 1) throw new JSExn(
226                 "traps must take either one argument (write) or no arguments (read)");
227             for (Trap t = (Trap)super.get(key, 1); t != null; t = t.next())
228                 if (t.function().equals(f)) return;
229             super.put(key, new TrapHolder(this, key, f, (Trap)super.get(key, 1)), 1);
230         }
231
232         public void delTrap(JS key, JS f) throws JSExn {
233             Trap t = (Trap)super.get(key, 1);
234             if (t==null) return;
235             if (t.function().equals(f)) { super.put(key, t.next(), 2); return; }
236             for (; t.next() != null; t = t.next())
237                 if (t.next().function().equals(f)) { ((TrapHolder)t).next = t.next().next(); return; }
238         }
239
240         public Trap getTrap(JS key) throws JSExn { return (Trap)super.get(key, 1); }
241
242         public String coerceToString() { return "object"; }
243
244         private static final class Placeholder implements Serializable {}
245
246         private static final class TrapHolder implements Trap {
247             private final JS target, key, function;
248             private Trap next;
249             TrapHolder(JS t, JS k, JS f, Trap n) { target = t; key = k; function = f; next = n; }
250
251             public JS key() { return key; }
252             public JS target() { return target; }
253             public JS function() { return function; }
254
255             public boolean isReadTrap()  {
256                 return function.getFormalArgs() == null || function.getFormalArgs().length == 0; }
257             public boolean isWriteTrap() {
258                 return function.getFormalArgs() != null && function.getFormalArgs().length != 0; }
259
260             public Trap next() { return next; }
261             public Trap nextRead() {
262                 Trap t = next; while (t != null && t.isWriteTrap()) t = t.next(); return t; }
263             public Trap nextWrite() {
264                 Trap t = next; while (t != null && t.isReadTrap()) t = t.next(); return t; }
265             public Trap read() { return isReadTrap() ? this : nextRead(); }
266             public Trap write() { return isWriteTrap() ? this : nextWrite(); }
267         }
268     }
269
270     public interface Trap {
271         public JS key();
272         public JS target();
273         public JS function();
274         public boolean isReadTrap();
275         public boolean isWriteTrap();
276         public Trap next();
277         public Trap nextRead();
278         public Trap nextWrite();
279
280         public Trap read(); // FIXME reconsider these function names
281         public Trap write();
282     }
283
284     /** An empty class used for instanceof matching the result of JS.get()
285      *  to decide if the key is a method (to be called with JS.callMethod(). */
286     public static final class Method extends Immutable {}
287
288
289     public static abstract class Enumeration extends Immutable {
290         public static final Enumeration EMPTY = new Empty(null);
291
292         private final Enumeration parent;
293
294         public Enumeration(Enumeration parent) { this.parent = parent; }
295
296         protected abstract boolean _hasNext();
297         protected abstract JS _next() throws JSExn;
298
299         public final boolean hasNext() {
300             return _hasNext() || (parent != null ? parent.hasNext() : false); }
301         public final JS next() throws JSExn {
302             if (_hasNext()) return _next();
303             if (parent == null) throw new NoSuchElementException("reached end of set");
304             return parent.next();
305         }
306
307         public JS get(JS key) throws JSExn {
308             //#switch(JSU.str(key))
309             case "hasNext": return JSU.B(hasNext());
310             case "next": return next();
311             //#end
312             return super.get(key);
313         }
314
315         public static final class Empty extends Enumeration {
316             public Empty(Enumeration parent) { super(parent); }
317             protected boolean _hasNext() { return false; }
318             protected JS _next() { throw new NoSuchElementException(); }
319         }
320
321         public static final class JavaIterator extends Enumeration {
322             private final Iterator i;
323             public JavaIterator(Enumeration parent, Iterator i) { super(parent); this.i = i; }
324             protected boolean _hasNext() { return i.hasNext(); }
325             protected JS _next() { return (JS)i.next(); }
326         }
327
328         public static final class RandomAccessList extends Enumeration {
329             private final List l;
330             private int pos = 0, size;
331             public RandomAccessList(Enumeration parent, List list) {
332                 super(parent); l = list; size = l.size(); }
333             protected boolean _hasNext() { return  pos < size; }
334             protected JS _next() { return (JS)l.get(pos++); }
335         }
336     }
337
338 }