automatically try call(JS[]) if method
[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 { throw new JSExn(
113             "'" + key + "' is not trappable on class ["+ getClass().getName() +"]"); }
114         public void delTrap(JS key, JS function) throws JSExn { throw new JSExn(
115             "'" + key + "' trap is read only on class ["+ getClass().getName() +"]"); }
116         public Trap getTrap(JS key) throws JSExn { throw new JSExn(
117             "'" + key + "' is not trappable on class ["+ getClass().getName() +"]"); }
118
119         public String coerceToString() { return "object"; }
120     }
121
122     public interface Cloneable {}
123
124     public static class Clone implements JS {
125         protected final JS clonee;
126         public Clone(JS clonee) throws JSExn {
127             if (!(clonee instanceof Cloneable)) throw new JSExn(
128                 clonee.getClass().getName() + " is not implement cloneable");
129             this.clonee = clonee;
130         }
131
132         public JS unclone() { return clonee.unclone(); }
133         public boolean equals(Object o) { return clonee.equals(o); }
134
135         public Enumeration keys() throws JSExn { return clonee.keys(); }
136         public JS get(JS k) throws JSExn { return clonee.get(k); }
137         public void put(JS k, JS v) throws JSExn { clonee.put(k, v); }
138         public InputStream getInputStream() throws IOException, JSExn {
139             return clonee.getInputStream(); }
140
141         public Object run(Object o) throws Exception { return clonee.run(o); }
142         public void pause() { clonee.pause(); }
143
144         public JS call(JS m, JS[] a) throws JSExn { return clonee.call(m, a); }
145         public JS call(JS[] a) throws JSExn { return clonee.call(a); }
146         public String[] getFormalArgs() { return clonee.getFormalArgs(); }
147
148         public JS putAndTriggerTraps(JS k, JS v) throws JSExn {
149             return clonee.putAndTriggerTraps(k, v); }
150         public JS getAndTriggerTraps(JS k) throws JSExn {
151             return clonee.getAndTriggerTraps(k); }
152         public JS justTriggerTraps(JS k, JS v) throws JSExn {
153             return clonee.justTriggerTraps(k, v); }
154
155         public void addTrap(JS k, JS f) throws JSExn { clonee.addTrap(k, f); }
156         public void delTrap(JS k, JS f) throws JSExn { clonee.delTrap(k, f); }
157         public Trap getTrap(JS k) throws JSExn { return clonee.getTrap(k); }
158
159         public String coerceToString() { return clonee.coerceToString(); }
160     }
161
162     public static class Obj extends Basket.Hash implements JS {
163         private static final String[] emptystr = new String[0];
164         private static final Placeholder holder = new Placeholder();
165
166         // HACK: this is hideously, disgustingly ugly.... we need N-ary Hash classes
167         /** entries[index + 0] // key
168          *  entries[index + 1] // value
169          *  entries[index + 2] // trap
170          */
171
172         protected void entryAdded(int p) {}
173         protected void entryUpdated(int p) {}
174         protected void entryRemoved(int p) {}
175
176         public Obj() { super(3, 4, 0.75F); }
177
178         public JS unclone() { return this; }
179         public InputStream getInputStream() throws IOException, JSExn { throw new JSExn(
180             "object has not associated stream, class ["+ getClass().getName() +"]"); }
181
182         public Object run(Object o) throws Exception { throw new JSExn(
183             "object cannot be called, class ["+ getClass().getName() +"]"); }
184         public void pause() { throw new NotPausableException(); }
185
186         public JS call(JS[] args) throws JSExn { throw new JSExn(
187             "object cannot be called, class ["+ getClass().getName() +"]"); }
188         public JS call(JS method, JS[] args) throws JSExn { throw new JSExn(
189             "method not found: " + JSU.str(method)); }
190         public String[] getFormalArgs() { return emptystr; }
191
192         public Enumeration keys() throws JSExn {
193             return new Enumeration(null) {
194                 private int dest = -1, next = -1;
195                 public boolean _hasNext() {
196                     for (int i = Math.max(0, dest); i < usedslots; i++)
197                         if (i > 0 ? entries[i * indexmultiple] != null : true &&
198                             entries[i * indexmultiple] != this) { next = i; return true; }
199                     return false;
200                 }
201                 public JS _next() throws JSExn {
202                     if (next < 0 && !hasNext()) throw new NoSuchElementException();
203                     int index = next; dest = next; next = -1;
204                     return (JS)entries[index * indexmultiple];
205                 }
206             };
207         }
208         public JS get(JS key) throws JSExn { int i = indexOf(key);
209             return i < 0 ? null : entries[i + 1] instanceof Placeholder ?  null : (JS)entries[i + 1]; }
210         public void put(JS key, JS val) throws JSExn {
211             // NOTE: only way value can be stored as null is using declare()
212             int dest = put(indexOf(key), key);
213             if (val == null) entries[dest + 1] = holder;
214             else entries[dest + 1] = val; }
215
216         /*public boolean hasValue(JS key, JS value) {
217             int i = indexOf(key); return i >= 0 && entries[i + 1] != null; }
218         public boolean hasTrap(JS key, JS trap) {
219             int i = indexOf(key); return i >= 0 && entries[i + 2] != null; }*/
220
221         public void declare(JS key) throws JSExn { entries[put(indexOf(key), key) + 1] = null; }
222         public void undeclare(JS key) throws JSExn { remove(indexOf(key)); }
223
224         public JS putAndTriggerTraps(JS key, JS val) throws JSExn {
225             Trap t = null; int i = indexOf(key);
226             if (i >= 0) t = (Trap)entries[i + 2];
227             if (t != null && (t = t.write()) != null) {
228                 val = (JS)new Interpreter(t, val, false).run(null);
229             }
230             put(key, val); // HACK: necessary for subclasses overriding put()
231             /*if (i < 0) i = put(i, key);
232             if (val == null) entries[i + 1] = holder;
233             else entries[i + 1] = val;*/
234             return val;
235         }
236         public JS getAndTriggerTraps(JS key) throws JSExn {
237             Trap t = null; int i = indexOf(key);
238             if (i < 0) return get(key); // HACK: necessary for subclasses overriding get()
239             t = (Trap)entries[i + 2];
240             return t == null ? (JS)entries[i + 1] : (JS)new Interpreter(t, null, false).run(null);
241         }
242         public JS justTriggerTraps(JS key, JS val) throws JSExn {
243             Trap t = null; int i = indexOf(key);
244             if (i >= 0) t = (Trap)entries[i + 2];
245             if (t == null || (t = t.write()) == null) return val;
246             return (JS)new Interpreter(t, val, true).run(null);
247         }
248
249         public void addTrap(JS key, JS f) throws JSExn {
250             if (f.getFormalArgs() == null || f.getFormalArgs().length > 1) throw new JSExn(
251                 "traps must take either one argument (write) or no arguments (read)");
252             int i = indexOf(key); if (i < 0) i = put(i, key);
253             for (Trap t = (Trap)entries[i + 2]; t != null; t = t.next())
254                 if (t.function().equals(f)) return;
255             entries[i + 2] = new TrapHolder(this, key, f, (Trap)entries[i + 2]);
256         }
257
258         public void delTrap(JS key, JS f) throws JSExn {
259             int i = indexOf(key); if (i < 0) return;
260             Trap t = (Trap)entries[i + 2];
261             if (t.function().equals(f)) { entries[i + 2] = t.next(); return; }
262             for (; t.next() != null; t = t.next())
263                 if (t.next().function().equals(f)) { ((TrapHolder)t).next = t.next().next(); return; }
264         }
265
266         public Trap getTrap(JS key) throws JSExn {
267             int i = indexOf(key); return i < 0 ? null : (Trap)entries[i + 2];
268         }
269
270         public String coerceToString() { return "object"; }
271
272         private static final class Placeholder implements Serializable {}
273
274         private static final class TrapHolder implements Trap {
275             private final JS target, key, function;
276             private Trap next;
277             TrapHolder(JS t, JS k, JS f, Trap n) { target = t; key = k; function = f; next = n; }
278
279             public JS key() { return key; }
280             public JS target() { return target; }
281             public JS function() { return function; }
282
283             public boolean isReadTrap()  {
284                 return function.getFormalArgs() == null || function.getFormalArgs().length == 0; }
285             public boolean isWriteTrap() {
286                 return function.getFormalArgs() != null && function.getFormalArgs().length != 0; }
287
288             public Trap next() { return next; }
289             public Trap nextRead() {
290                 Trap t = next; while (t != null && t.isWriteTrap()) t = t.next(); return t; }
291             public Trap nextWrite() {
292                 Trap t = next; while (t != null && t.isReadTrap()) t = t.next(); return t; }
293             public Trap read() { return isReadTrap() ? this : nextRead(); }
294             public Trap write() { return isWriteTrap() ? this : nextWrite(); }
295         }
296     }
297
298     public interface Trap {
299         public JS key();
300         public JS target();
301         public JS function();
302         public boolean isReadTrap();
303         public boolean isWriteTrap();
304         public Trap next();
305         public Trap nextRead();
306         public Trap nextWrite();
307
308         public Trap read(); // FIXME reconsider these function names
309         public Trap write();
310     }
311
312     /** An empty class used for instanceof matching the result of JS.get()
313      *  to decide if the key is a method (to be called with JS.callMethod(). */
314     public static final class Method extends Immutable {}
315
316
317     public static abstract class Enumeration extends Immutable {
318         public static final Enumeration EMPTY = new Empty(null);
319
320         private final Enumeration parent;
321
322         public Enumeration(Enumeration parent) { this.parent = parent; }
323
324         protected abstract boolean _hasNext();
325         protected abstract JS _next() throws JSExn;
326
327         public final boolean hasNext() {
328             return _hasNext() || parent != null ? parent.hasNext() : false; }
329         public final JS next() throws JSExn {
330             if (_hasNext()) return _next();
331             if (parent == null) throw new NoSuchElementException("reached end of set");
332             return parent.next();
333         }
334
335         public JS get(JS key) throws JSExn {
336             //#switch(JSU.str(key))
337             case "hasNext": return JSU.B(hasNext());
338             case "next": return next();
339             //#end
340             return super.get(key);
341         }
342
343         public static final class Empty extends Enumeration {
344             public Empty(Enumeration parent) { super(parent); }
345             protected boolean _hasNext() { return false; }
346             protected JS _next() { throw new NoSuchElementException(); }
347         }
348
349         public static final class JavaIterator extends Enumeration {
350             private final Iterator i;
351             public JavaIterator(Enumeration parent, Iterator i) { super(parent); this.i = i; }
352             protected boolean _hasNext() { return i.hasNext(); }
353             protected JS _next() { return (JS)i.next(); }
354         }
355
356         public static final class RandomAccessList extends Enumeration {
357             private final List l;
358             private int pos = 0, size;
359             public RandomAccessList(Enumeration parent, List list) {
360                 super(parent); l = list; size = l.size(); }
361             protected boolean _hasNext() { return  pos < size; }
362             protected JS _next() { return (JS)l.get(pos++); }
363         }
364     }
365
366 }