HACK introduce get() and put() calls in trap functions for subclasses
[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     /** Returns true if the specific key is found in this object. */
45     public boolean hasKey(JS key);
46
47     /** Put a value to the given key, calling any write traps that have
48      *  been placed on the key.
49      *
50      *  This function may block for an indeterminate amount of time.
51      *
52      *  Write traps may change the final value  before it is put, thus
53      *  be careful to read the latest value from this function's return
54      *  before doing any more work with it.
55      */
56     public JS putAndTriggerTraps(JS key, JS value) throws JSExn;
57
58     /** Gets the value for a given key, calling any read traps that have
59      *  been placed on the key.
60      *
61      *  This function may block for an indeterminate amount of time.
62      */
63     public JS getAndTriggerTraps(JS key) throws JSExn;
64
65     /** Calls the write traps placed on a given key with the given value
66      *  and returns the result without saving it to this object's key store. */
67     public JS justTriggerTraps(JS key, JS value) throws JSExn;
68
69     public void addTrap(JS key, JS function) throws JSExn;
70     public void delTrap(JS key, JS function) throws JSExn;
71     public Trap getTrap(JS key) throws JSExn;
72
73     // FIXME: consider renaming/removing these
74     public InputStream getInputStream() throws IOException, JSExn;
75     public JS unclone();
76     public String coerceToString();
77
78
79     // Implementations ////////////////////////////////////////////////////////
80
81     /** Provides the lightest possible implementation of JS, throwing
82      *  exceptions on every mutable operation. */
83     public static class Immutable implements JS {
84         private static final String[] emptystr = new String[0];
85
86         public JS unclone() { return this; }
87         public JS.Enumeration keys() throws JSExn { throw new JSExn(
88             "object has no key set, class ["+ getClass().getName() +"]"); }
89         public JS get(JS key) throws JSExn { return null; }
90         public void put(JS key, JS val) throws JSExn { throw new JSExn(
91             "'" + key + "' is read only on class ["+ getClass().getName() +"]"); }
92         public InputStream getInputStream() throws IOException, JSExn { throw new JSExn(
93             "object has not associated stream, class ["+ getClass().getName() +"]"); }
94
95         public boolean hasKey(JS key) { return false; }
96
97         public Object run(Object o) throws Exception { throw new JSExn(
98             "object cannot be called, class ["+ getClass().getName() +"]"); }
99         public void pause() { throw new NotPausableException(); }
100
101         public JS call(JS[] args) throws JSExn { throw new JSExn(
102             "object cannot be called, class ["+ getClass().getName() +"]"); }
103         public JS call(JS method, JS[] args) throws JSExn { throw new JSExn(
104             "method not found: " + JSU.str(method)); }
105         public String[] getFormalArgs() { return emptystr; }
106
107         public void declare(JS key) throws JSExn { throw new JSExn(
108             "object cannot declare key: "+ JSU.str(key)); }
109         public void undeclare(JS key) throws JSExn { } // FIXME throw error?
110
111         public JS putAndTriggerTraps(JS key, JS val) throws JSExn { throw new JSExn(
112             "'" + key + "' is trap read only on class ["+ getClass().getName() +"]"); }
113         public JS getAndTriggerTraps(JS key) throws JSExn { return null; } // FIXME throw errors?
114         public JS justTriggerTraps(JS key, JS value) throws JSExn { return null; }
115
116         public void addTrap(JS key, JS function) throws JSExn { throw new JSExn(
117             "'" + key + "' is not trappable on class ["+ getClass().getName() +"]"); }
118         public void delTrap(JS key, JS function) throws JSExn { throw new JSExn(
119             "'" + key + "' trap is read only on class ["+ getClass().getName() +"]"); }
120         public Trap getTrap(JS key) throws JSExn { throw new JSExn(
121             "'" + key + "' is not trappable on class ["+ getClass().getName() +"]"); }
122
123         public String coerceToString() { return "object"; }
124     }
125
126     public interface Cloneable {}
127
128     public static class Clone implements JS {
129         protected final JS clonee;
130         public Clone(JS clonee) throws JSExn {
131             if (!(clonee instanceof Cloneable)) throw new JSExn(
132                 clonee.getClass().getName() + " is not implement cloneable");
133             this.clonee = clonee;
134         }
135
136         public JS unclone() { return clonee.unclone(); }
137         public boolean equals(Object o) { return clonee.equals(o); }
138
139         public Enumeration keys() throws JSExn { return clonee.keys(); }
140         public JS get(JS k) throws JSExn { return clonee.get(k); }
141         public void put(JS k, JS v) throws JSExn { clonee.put(k, v); }
142         public InputStream getInputStream() throws IOException, JSExn {
143             return clonee.getInputStream(); }
144
145         public Object run(Object o) throws Exception { return clonee.run(o); }
146         public void pause() { clonee.pause(); }
147
148         public JS call(JS m, JS[] a) throws JSExn { return clonee.call(m, a); }
149         public JS call(JS[] a) throws JSExn { return clonee.call(a); }
150         public String[] getFormalArgs() { return clonee.getFormalArgs(); }
151
152         public boolean hasKey(JS k) { return clonee.hasKey(k); }
153
154         public JS putAndTriggerTraps(JS k, JS v) throws JSExn {
155             return clonee.putAndTriggerTraps(k, v); }
156         public JS getAndTriggerTraps(JS k) throws JSExn {
157             return clonee.getAndTriggerTraps(k); }
158         public JS justTriggerTraps(JS k, JS v) throws JSExn {
159             return clonee.justTriggerTraps(k, v); }
160
161         public void addTrap(JS k, JS f) throws JSExn { clonee.addTrap(k, f); }
162         public void delTrap(JS k, JS f) throws JSExn { clonee.delTrap(k, f); }
163         public Trap getTrap(JS k) throws JSExn { return clonee.getTrap(k); }
164
165         public String coerceToString() { return clonee.coerceToString(); }
166     }
167
168     public static class Obj extends Basket.Hash implements JS {
169         private static final String[] emptystr = new String[0];
170         private static final Placeholder holder = new Placeholder();
171
172         // HACK: this is hideously, disgustingly ugly.... we need N-ary Hash classes
173         /** entries[index + 0] // key
174          *  entries[index + 1] // value
175          *  entries[index + 2] // trap
176          */
177
178         protected void entryAdded(int p) {}
179         protected void entryUpdated(int p) {}
180         protected void entryRemoved(int p) {}
181
182         public Obj() { super(3, 4, 0.75F); }
183
184         public JS unclone() { return this; }
185         public InputStream getInputStream() throws IOException, JSExn { throw new JSExn(
186             "object has not associated stream, class ["+ getClass().getName() +"]"); }
187
188         public Object run(Object o) throws Exception { throw new JSExn(
189             "object cannot be called, class ["+ getClass().getName() +"]"); }
190         public void pause() { throw new NotPausableException(); }
191
192         public JS call(JS[] args) throws JSExn { throw new JSExn(
193             "object cannot be called, class ["+ getClass().getName() +"]"); }
194         public JS call(JS method, JS[] args) throws JSExn { throw new JSExn(
195             "method not found: " + JSU.str(method)); }
196         public String[] getFormalArgs() { return emptystr; }
197
198         public Enumeration keys() throws JSExn {
199             return new Enumeration(null) {
200                 private int dest = -1, next = -1;
201                 public boolean _hasNext() {
202                     for (int i = Math.max(0, dest); i < usedslots; i++)
203                         if (i > 0 ? entries[i * indexmultiple] != null : true &&
204                             entries[i * indexmultiple] != this) { next = i; return true; }
205                     return false;
206                 }
207                 public JS _next() throws JSExn {
208                     if (next < 0 && !hasNext()) throw new NoSuchElementException();
209                     int index = next; dest = next; next = -1;
210                     return (JS)entries[index * indexmultiple];
211                 }
212             };
213         }
214         public JS get(JS key) throws JSExn { int i = indexOf(key);
215             return i < 0 ? null : entries[i + 1] instanceof Placeholder ?  null : (JS)entries[i + 1]; }
216         public void put(JS key, JS val) throws JSExn {
217             // NOTE: only way value can be stored as null is using declare()
218             int dest = put(indexOf(key), key);
219             if (val == null) entries[dest + 1] = holder;
220             else entries[dest + 1] = val; }
221
222         public boolean hasKey(JS key) { return indexOf(key) >= 0; }
223         /*public boolean hasValue(JS key, JS value) {
224             int i = indexOf(key); return i >= 0 && entries[i + 1] != null; }
225         public boolean hasTrap(JS key, JS trap) {
226             int i = indexOf(key); return i >= 0 && entries[i + 2] != null; }*/
227
228         public void declare(JS key) throws JSExn { entries[put(indexOf(key), key) + 1] = null; }
229         public void undeclare(JS key) throws JSExn { remove(indexOf(key)); }
230
231         public JS putAndTriggerTraps(JS key, JS val) throws JSExn {
232             Trap t = null; int i = indexOf(key);
233             if (i >= 0) t = (Trap)entries[i + 2];
234             if (t != null && (t = t.write()) != null) {
235                 val = (JS)new Interpreter(t, val, false).run(null);
236             }
237             put(key, val); // HACK: necessary for subclasses overriding put()
238             /*if (i < 0) i = put(i, key);
239             if (val == null) entries[i + 1] = holder;
240             else entries[i + 1] = val;*/
241             return val;
242         }
243         public JS getAndTriggerTraps(JS key) throws JSExn {
244             Trap t = null; int i = indexOf(key);
245             if (i < 0) return get(key); // HACK: necessary for subclasses overriding get()
246             t = (Trap)entries[i + 2];
247             return t == null ? (JS)entries[i + 1] : (JS)new Interpreter(t, null, false).run(null);
248         }
249         public JS justTriggerTraps(JS key, JS val) throws JSExn {
250             Trap t = null; int i = indexOf(key);
251             if (i >= 0) t = (Trap)entries[i + 2];
252             if (t == null || (t = t.write()) == null) return val;
253             return (JS)new Interpreter(t, val, true).run(null);
254         }
255
256         public void addTrap(JS key, JS f) throws JSExn {
257             if (f.getFormalArgs() == null || f.getFormalArgs().length > 1) throw new JSExn(
258                 "traps must take either one argument (write) or no arguments (read)");
259             int i = indexOf(key); if (i < 0) i = put(i, key);
260             for (Trap t = (Trap)entries[i + 2]; t != null; t = t.next())
261                 if (t.function().equals(f)) return;
262             entries[i + 2] = new TrapHolder(this, key, f, (Trap)entries[i + 2]);
263         }
264
265         public void delTrap(JS key, JS f) throws JSExn {
266             int i = indexOf(key); if (i < 0) return;
267             Trap t = (Trap)entries[i + 2];
268             if (t.function().equals(f)) { entries[i + 2] = t.next(); return; }
269             for (; t.next() != null; t = t.next())
270                 if (t.next().function().equals(f)) { ((TrapHolder)t).next = t.next().next(); return; }
271         }
272
273         public Trap getTrap(JS key) throws JSExn {
274             int i = indexOf(key); return i < 0 ? null : (Trap)entries[i + 2];
275         }
276
277         public String coerceToString() { return "object"; }
278
279         private static final class Placeholder implements Serializable {}
280
281         private static final class TrapHolder implements Trap {
282             private final JS target, key, function;
283             private Trap next;
284             TrapHolder(JS t, JS k, JS f, Trap n) { target = t; key = k; function = f; next = n; }
285
286             public JS key() { return key; }
287             public JS target() { return target; }
288             public JS function() { return function; }
289
290             public boolean isReadTrap()  {
291                 return function.getFormalArgs() == null || function.getFormalArgs().length == 0; }
292             public boolean isWriteTrap() {
293                 return function.getFormalArgs() != null && function.getFormalArgs().length != 0; }
294
295             public Trap next() { return next; }
296             public Trap nextRead() {
297                 Trap t = next; while (t != null && t.isWriteTrap()) t = t.next(); return t; }
298             public Trap nextWrite() {
299                 Trap t = next; while (t != null && t.isReadTrap()) t = t.next(); return t; }
300             public Trap read() { return isReadTrap() ? this : nextRead(); }
301             public Trap write() { return isWriteTrap() ? this : nextWrite(); }
302         }
303     }
304
305     public interface Trap {
306         public JS key();
307         public JS target();
308         public JS function();
309         public boolean isReadTrap();
310         public boolean isWriteTrap();
311         public Trap next();
312         public Trap nextRead();
313         public Trap nextWrite();
314
315         public Trap read(); // FIXME reconsider these function names
316         public Trap write();
317     }
318
319     /** An empty class used for instanceof matching the result of JS.get()
320      *  to decide if the key is a method (to be called with JS.callMethod(). */
321     public static final class Method extends Immutable {}
322
323
324     public static abstract class Enumeration extends Immutable {
325         public static final Enumeration EMPTY = new Empty(null);
326
327         private final Enumeration parent;
328
329         public Enumeration(Enumeration parent) { this.parent = parent; }
330
331         protected abstract boolean _hasNext();
332         protected abstract JS _next() throws JSExn;
333
334         public final boolean hasNext() {
335             return _hasNext() || parent != null ? parent.hasNext() : false; }
336         public final JS next() throws JSExn {
337             if (_hasNext()) return _next();
338             if (parent == null) throw new NoSuchElementException("reached end of set");
339             return parent.next();
340         }
341
342         public JS get(JS key) throws JSExn {
343             //#switch(JSU.str(key))
344             case "hasNext": return JSU.B(hasNext());
345             case "next": return next();
346             //#end
347             return super.get(key);
348         }
349
350         public static final class Empty extends Enumeration {
351             public Empty(Enumeration parent) { super(parent); }
352             protected boolean _hasNext() { return false; }
353             protected JS _next() { throw new NoSuchElementException(); }
354         }
355
356         public static final class JavaIterator extends Enumeration {
357             private final Iterator i;
358             public JavaIterator(Enumeration parent, Iterator i) { super(parent); this.i = i; }
359             protected boolean _hasNext() { return i.hasNext(); }
360             protected JS _next() { return (JS)i.next(); }
361         }
362
363         public static final class RandomAccessList extends Enumeration {
364             private final List l;
365             private int pos = 0, size;
366             public RandomAccessList(Enumeration parent, List list) {
367                 super(parent); l = list; size = l.size(); }
368             protected boolean _hasNext() { return  pos < size; }
369             protected JS _next() { return (JS)l.get(pos++); }
370         }
371     }
372
373 }