minor bug fixes from moving interfaces
[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: " + Script.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: "+ Script.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         /** entries[index + 0] // key
173          *  entries[index + 1] // value
174          *  entries[index + 2] // trap
175          */
176         protected final int indexmultiple = 3;
177
178         protected void entryAdded(int p) {}
179         protected void entryUpdated(int p) {}
180         protected void entryRemoved(int p) {}
181
182         public Obj() { super(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: " + Script.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             if (val == null) entries[i + 1] = holder;
238             else entries[i + 1] = val;
239             return val;
240         }
241         public JS getAndTriggerTraps(JS key) throws JSExn {
242             Trap t = null; int i = indexOf(key);
243             if (i < 0) return null;
244             t = (Trap)entries[i + 2];
245             return t == null ? (JS)entries[i + 1] : (JS)new Interpreter(t, null, false).run(null);
246         }
247         public JS justTriggerTraps(JS key, JS val) throws JSExn {
248             Trap t = null; int i = indexOf(key);
249             if (i >= 0) t = (Trap)entries[i + 2];
250             if (t == null || (t = t.write()) == null) return val;
251             return (JS)new Interpreter(t, val, true).run(null);
252         }
253
254         public void addTrap(JS key, JS f) throws JSExn {
255             if (f.getFormalArgs() == null || f.getFormalArgs().length > 1) throw new JSExn(
256                 "traps must take either one argument (write) or no arguments (read)");
257             int i = indexOf(key); if (i < 0) i = put(i, key);
258             for (Trap t = (Trap)entries[i + 2]; t != null; t = t.next())
259                 if (t.function().equals(f)) return;
260             entries[i + 2] = new TrapHolder(this, key, f, (Trap)entries[i + 2]);
261         }
262
263         public void delTrap(JS key, JS f) throws JSExn {
264             int i = indexOf(key); if (i < 0) return;
265             Trap t = (Trap)entries[i + 2];
266             if (t.function().equals(f)) { entries[i + 2] = t.next(); return; }
267             for (; t.next() != null; t = t.next())
268                 if (t.next().function().equals(f)) { ((TrapHolder)t).next = t.next().next(); return; }
269         }
270
271         public Trap getTrap(JS key) throws JSExn {
272             int i = indexOf(key); return i < 0 ? null : (Trap)entries[i + 2];
273         }
274
275         public String coerceToString() { return "object"; }
276
277         private static final class Placeholder implements Serializable {}
278
279         private static final class TrapHolder implements Trap {
280             private final JS target, key, function;
281             private Trap next;
282             TrapHolder(JS t, JS k, JS f, Trap n) { target = t; key = k; function = f; next = n; }
283
284             public JS key() { return key; }
285             public JS target() { return target; }
286             public JS function() { return function; }
287
288             public boolean isReadTrap()  {
289                 return function.getFormalArgs() == null || function.getFormalArgs().length == 0; }
290             public boolean isWriteTrap() {
291                 return function.getFormalArgs() != null && function.getFormalArgs().length != 0; }
292
293             public Trap next() { return next; }
294             public Trap nextRead() {
295                 Trap t = next; while (t != null && t.isWriteTrap()) t = t.next(); return t; }
296             public Trap nextWrite() {
297                 Trap t = next; while (t != null && t.isReadTrap()) t = t.next(); return t; }
298             public Trap read() { return isReadTrap() ? this : nextRead(); }
299             public Trap write() { return isWriteTrap() ? this : nextWrite(); }
300         }
301     }
302
303     public interface Trap {
304         public JS key();
305         public JS target();
306         public JS function();
307         public boolean isReadTrap();
308         public boolean isWriteTrap();
309         public Trap next();
310         public Trap nextRead();
311         public Trap nextWrite();
312
313         public Trap read(); // FIXME reconsider these function names
314         public Trap write();
315     }
316
317     /** An empty class used for instanceof matching the result of JS.get()
318      *  to decide if the key is a method (to be called with JS.callMethod(). */
319     public static final class Method extends Immutable {}
320
321
322     public static abstract class Enumeration extends Immutable {
323         public static final Enumeration EMPTY = new Empty(null);
324
325         private final Enumeration parent;
326
327         public Enumeration(Enumeration parent) { this.parent = parent; }
328
329         protected abstract boolean _hasNext();
330         protected abstract JS _next() throws JSExn;
331
332         public final boolean hasNext() {
333             return _hasNext() || parent != null ? parent.hasNext() : false; }
334         public final JS next() throws JSExn {
335             if (_hasNext()) return _next();
336             if (parent == null) throw new NoSuchElementException("reached end of set");
337             return parent.next();
338         }
339
340         public JS get(JS key) throws JSExn {
341             //#switch(Script.str(key))
342             case "hasNext": return Script.B(hasNext());
343             case "next": return next();
344             //#end
345             return super.get(key);
346         }
347
348         public static final class Empty extends Enumeration {
349             public Empty(Enumeration parent) { super(parent); }
350             protected boolean _hasNext() { return false; }
351             protected JS _next() { throw new NoSuchElementException(); }
352         }
353
354         public static final class JavaIterator extends Enumeration {
355             private final Iterator i;
356             public JavaIterator(Enumeration parent, Iterator i) { super(parent); this.i = i; }
357             protected boolean _hasNext() { return i.hasNext(); }
358             protected JS _next() { return (JS)i.next(); }
359         }
360
361         public static final class RandomAccessList extends Enumeration {
362             private final List l;
363             private int pos = 0, size;
364             public RandomAccessList(Enumeration parent, List list) {
365                 super(parent); l = list; size = l.size(); }
366             protected boolean _hasNext() { return  pos < size; }
367             protected JS _next() { return (JS)l.get(pos++); }
368         }
369     }
370
371 }