trim down public api
[org.ibex.core.git] / src / org / ibex / js / JS.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL] 
2 package org.ibex.js; 
3
4 import org.ibex.util.*; 
5 import java.io.*;
6 import java.util.*;
7
8 /** The minimum set of functionality required for objects which are manipulated by JavaScript */
9 public abstract class JS { 
10     public static final JS METHOD = new JS() { };
11     public final JS unclone() { return _unclone(); }
12     public final JS jsclone() throws JSExn { return new Clone(this); }
13
14     public JS.Enumeration keys() throws JSExn { throw new JSExn("you can't enumerate the keys of this object (class=" + getClass().getName() +")"); }
15     public JS get(JS key) throws JSExn { return null; }
16     public void put(JS key, JS val) throws JSExn { throw new JSExn("" + key + " is read only (class=" + getClass().getName() +")"); }
17     
18     public InputStream getInputStream() throws IOException {
19         throw new IOException("this object doesn't have a stream associated with it " + getClass().getName() + ")");
20     }
21         
22     public final boolean hasTrap(JS key) { return getTrap(key) != null; }
23     
24     public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
25         throw new JSExn("method not found (" + JS.debugToString(method) + ")");
26     }
27     
28     public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
29         throw new JSExn("you cannot call this object (class=" + this.getClass().getName() +")");
30     }
31     
32     public final boolean equals(Object o) { return this == o || ((o instanceof JS) && jsequals((JS)o)); }
33     
34     public final String toString() {
35         // Discourage people from using toString()
36         String s = "JS Object [class=" + getClass().getName() + "]";
37         String ext = extendedToString();
38         return ext == null ? s : s + " " + ext;
39     }
40     
41     // These are only used internally by org.ibex.js
42     Trap getTrap(JS key) { return null; }
43     void putTrap(JS key, Trap value) throws JSExn { throw new JSExn("traps cannot be placed on this object (class=" + this.getClass().getName() +")"); }
44     String coerceToString() throws JSExn { throw new JSExn("can't coerce to a string (class=" + getClass().getName() +")"); }
45     boolean jsequals(JS o) { return this == o; }
46     String extendedToString() { return null; }
47     
48     public static class O extends JS implements Cloneable {
49         private Hash entries;
50         
51         public Enumeration keys() throws JSExn { return entries == null ? (Enumeration)EMPTY_ENUMERATION : (Enumeration)new JavaEnumeration(null,entries.keys()); }
52         public JS get(JS key) throws JSExn { return entries == null ? null : (JS)entries.get(key, null); }
53         public void put(JS key, JS val) throws JSExn { (entries==null?entries=new Hash():entries).put(key,null,val); }        
54
55         /** retrieve a trap from the entries hash */
56         final Trap getTrap(JS key) {
57             return entries == null ? null : (Trap)entries.get(key, Trap.class);
58         }
59         
60         /** retrieve a trap from the entries hash */
61         final void putTrap(JS key, Trap value) {
62             if (entries == null) entries = new Hash();
63             entries.put(key, Trap.class, value);
64         }    
65     }
66     
67     public static class BT extends O {
68         private BalancedTree bt;
69         private final BalancedTree bt() { if(bt != null) return bt; return bt = new BalancedTree(); }
70         public final void insertNode(int index, Object o) { bt().insertNode(index,o); }
71         public final void clear() { bt().clear(); }
72         public final Object getNode(int i) { return bt().getNode(i); }
73         public final int treeSize() { return bt().treeSize(); }
74         public final Object deleteNode(int i) { return bt().deleteNode(i); }
75         public final void replaceNode(int index, Object o) { bt().replaceNode(index,o); }
76         public final int indexNode(Object o) { return bt().indexNode(o); }
77     }
78         
79     JS _unclone() { return this; }
80     
81     public interface Cloneable { }
82     
83     public static class Clone extends JS.O {
84         protected final JS clonee;
85         JS _unclone() { return clonee.unclone(); }
86         public JS getClonee() { return clonee; }
87         public Clone(JS clonee) throws JSExn {
88             if(!(clonee instanceof Cloneable)) throw new JSExn("" + clonee.getClass().getName() + " isn't cloneable");
89             this.clonee = clonee;
90         }
91         public boolean jsequals(JS o) { return unclone().jsequals(o.unclone()); }
92         public Enumeration keys() throws JSExn { return clonee.keys(); }
93         public JS get(JS key) throws JSExn { return clonee.getAndTriggerTraps(key); }
94         public void put(JS key, JS val) throws JSExn { clonee.putAndTriggerTraps(key, val); }
95         public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
96             return clonee.callMethod(method, a0, a1, a2, rest, nargs);
97         }
98         public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
99             return clonee.call(a0, a1, a2, rest, nargs);
100         }
101         public InputStream getInputStream() throws IOException { return clonee.getInputStream(); }
102     }
103     
104     public static abstract class Enumeration extends JS {
105         final Enumeration parent;
106         boolean done;
107         public Enumeration(Enumeration parent) { this.parent = parent; }
108         protected abstract boolean _hasMoreElements();
109         protected abstract JS _nextElement() throws JSExn;
110         
111         public final boolean hasMoreElements() {
112             if(!done && !_hasMoreElements()) done = true;
113             return !done ? true : parent != null ? parent.hasMoreElements() : false;
114         }
115         public final JS nextElement() throws JSExn { return !done ? _nextElement() : parent != null ? parent.nextElement() : null; }
116         
117         public JS get(JS key) throws JSExn {
118             //#jswitch(key)
119             case "hasMoreElements": return B(hasMoreElements());
120             case "nextElement": return nextElement();
121             //#end
122             return super.get(key);
123         }
124     }
125     public static class EmptyEnumeration extends Enumeration {
126         public EmptyEnumeration(Enumeration parent) { super(parent); }
127         protected boolean _hasMoreElements() { return false; }
128         protected JS _nextElement() { return null; }
129     }
130     public static class JavaEnumeration extends Enumeration {
131         private final java.util.Enumeration e;
132         public JavaEnumeration(Enumeration parent, java.util.Enumeration e) { super(parent); this.e = e; }
133         protected boolean _hasMoreElements() { return e.hasMoreElements(); }
134         protected JS _nextElement() { return (JS) e.nextElement(); }
135     }
136     
137     // Static Interpreter Control Methods ///////////////////////////////////////////////////////////////
138
139     /** log a message with the current JavaScript sourceName/line */
140     public static void log(Object message) { info(message); }
141     public static void debug(Object message) { Log.debug(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
142     public static void info(Object message) { Log.info(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
143     public static void warn(Object message) { Log.warn(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
144     public static void error(Object message) { Log.error(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
145
146     public static class NotPauseableException extends Exception { NotPauseableException() { } }
147
148     /** returns a callback which will restart the context; expects a value to be pushed onto the stack when unpaused */
149     public static UnpauseCallback pause() throws NotPauseableException {
150         Interpreter i = Interpreter.current();
151         if (i.pausecount == -1) throw new NotPauseableException();
152         boolean get;
153         switch(i.f.op[i.pc]) {
154             case Tokens.RETURN: case ByteCodes.PUT: get = false; break;
155             case ByteCodes.GET: case ByteCodes.CALL: get = true; break;
156             default: throw new Error("should never happen");
157         }
158         i.pausecount++;
159         return new JS.UnpauseCallback(i,get);
160     }
161
162     public static class UnpauseCallback implements Task {
163         private Interpreter i;
164         private boolean get;
165         UnpauseCallback(Interpreter i, boolean get) { this.i = i; this.get = get; }
166         public void perform() throws JSExn { unpause(); }
167         public JS unpause() throws JSExn { return unpause((JS)null); }
168         public JS unpause(JS o) throws JSExn {
169             if (o == JS.METHOD) throw new JSExn("can't return a method to a paused context");
170             if(get) i.stack.push(o);
171             return i.resume();
172         }
173         public JS unpause(JSExn e) throws JSExn {
174             i.catchException(e);
175             return i.resume();
176         }
177     }
178
179
180
181     // Static Helper Methods ///////////////////////////////////////////////////////////////////////////////////
182
183     /** coerce an object to a Boolean */
184     public static boolean toBoolean(JS o) {
185         if(o == null) return false;
186         if(o instanceof JSNumber) return ((JSNumber)o).toBoolean();
187         if(o instanceof JSString) return ((JSString)o).s.length() != 0;
188         return true;
189     }
190     //#repeat long/int/double/float toLong/toInt/toDouble/toFloat Long/Integer/Double/Float parseLong/parseInt/parseDouble/parseFloat
191     /** coerce an object to a Number */
192     public static long toLong(JS o) throws JSExn {
193         if(o == null) return 0;
194         if(o instanceof JSNumber) return ((JSNumber)o).toLong();
195         if(o instanceof JSString) return Long.parseLong(o.coerceToString());
196         throw new JSExn("can't coerce a " + o.getClass().getName() + " to a number");
197     }
198     //#end
199     
200     public static String toString(JS o) throws JSExn {
201         if(o == null) return "null";
202         return o.coerceToString();
203     }
204     
205     public static String debugToString(JS o) {
206         try { return toString(o); }
207         catch(JSExn e) { return o.toString(); }
208     }
209     
210     public static boolean isInt(JS o) {
211         if(o == null) return true;
212         if(o instanceof JSNumber.I) return true;
213         if(o instanceof JSNumber.B) return false;
214         if(o instanceof JSNumber) {
215             JSNumber n = (JSNumber) o;
216             return n.toInt() == n.toDouble();
217         }
218         if(o instanceof JSString) {
219             String s = ((JSString)o).s;
220             for(int i=0;i<s.length();i++)
221                 if(s.charAt(i) < '0' || s.charAt(i) > '9') return false;
222             return true;
223         }
224         return false;
225     }
226     
227     public static boolean isString(JS o) {
228         if(o instanceof JSString) return true;
229         return false;
230     }
231     
232     public static JS newArray() { return new JSArray(); }
233     public static JS newRegexp(JS pat, JS flags) throws JSExn { return new JSRegexp(pat,flags); }
234
235     // Instance Methods ////////////////////////////////////////////////////////////////////
236  
237     public final static JS NaN = new JSNumber.D(Double.NaN);
238     public final static JS ZERO = new JSNumber.I(0);
239     public final static JS ONE = new JSNumber.I(1);
240     public final static JS MATH = new JSMath();
241         
242     public static final JS T = new JSNumber.B(true);
243     public static final JS F = new JSNumber.B(false);
244
245     public static final JS B(boolean b) { return b ? T : F; }
246     public static final JS B(int i) { return i==0 ? F : T; }
247     
248     private static final int CACHE_SIZE = 65536 / 4; // must be a power of two
249     private static final JSString[] stringCache = new JSString[CACHE_SIZE];
250     public static final JS S(String s) {
251         if(s == null) return null;
252         int slot = s.hashCode()&(CACHE_SIZE-1);
253         JSString ret = stringCache[slot];
254         if(ret == null || !ret.s.equals(s)) stringCache[slot] = ret = new JSString(s);
255         return ret;
256     }
257     public static final JS S(String s, boolean intern) { return intern ? JSString.intern(s) : S(s); }
258
259     public static final JS N(double d) { return new JSNumber.D(d); }
260     public static final JS N(long l) { return new JSNumber.L(l); }
261     
262     public static final JS N(Number n) {
263         if(n instanceof Integer) return N(n.intValue());
264         if(n instanceof Long) return N(n.longValue());
265         return N(n.doubleValue());
266     }
267
268     private static final JSNumber.I[] smallIntCache = new JSNumber.I[CACHE_SIZE];
269     private static final JSNumber.I[] largeIntCache = new JSNumber.I[CACHE_SIZE];
270     public static final JS N(int i) {
271         JSNumber.I ret = null;
272         int idx = i + smallIntCache.length / 2;
273         if (idx < CACHE_SIZE && idx > 0) {
274             ret = smallIntCache[idx];
275             if (ret != null) return ret;
276         }
277         else ret = largeIntCache[Math.abs(idx % CACHE_SIZE)];
278         if (ret == null || ret.i != i) {
279             ret = new JSNumber.I(i);
280             if (idx < smallIntCache.length && idx > 0) smallIntCache[idx] = ret;
281             else largeIntCache[Math.abs(idx % CACHE_SIZE)] = ret;
282         }
283         return ret;
284     }
285     
286     private static Enumeration EMPTY_ENUMERATION = new EmptyEnumeration(null);
287     
288     public static JS fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
289         return JSFunction._fromReader(sourceName, firstLine, sourceCode);
290     }
291
292     // HACK: caller can't know if the argument is a JSFunction or not...
293     public static JS cloneWithNewParentScope(JS j, JSScope s) {
294         return ((JSFunction)j)._cloneWithNewParentScope(s);
295     }
296
297
298     // Trap support //////////////////////////////////////////////////////////////////////////////
299
300     /** performs a put, triggering traps if present; traps are run in an unpauseable interpreter */
301     public void putAndTriggerTraps(JS key, JS value) throws JSExn {
302         Trap t = getTrap(key);
303         if(t == null || (t = t.writeTrap()) == null) put(key,value);
304         else new Interpreter(t,value,false).resume();
305     }
306
307     /** performs a get, triggering traps if present; traps are run in an unpauseable interpreter */
308     public JS getAndTriggerTraps(JS key) throws JSExn {
309         Trap t = getTrap(key);
310         if (t == null || (t = t.readTrap()) == null) return get(key);
311         else return new Interpreter(t,null,false).resume();
312     }
313     
314     public JS justTriggerTraps(JS key, JS value) throws JSExn {
315         Trap t = getTrap(key);
316         if(t == null || (t = t.writeTrap()) == null) return value;
317         else return new Interpreter(t,value,true).resume();
318     }
319
320     /** adds a trap, avoiding duplicates */
321     final void addTrap(JS key, JSFunction f) throws JSExn {
322         if (f.numFormalArgs > 1) throw new JSExn("traps must take either one argument (write) or no arguments (read)");
323         boolean isRead = f.numFormalArgs == 0;
324         for(Trap t = getTrap(key); t != null; t = t.next) if (t.f == f) return;
325         putTrap(key, new Trap(this, key, f, (Trap)getTrap(key)));
326     }
327
328     /** deletes a trap, if present */
329     final void delTrap(JS key, JSFunction f) throws JSExn {
330         Trap t = (Trap)getTrap(key);
331         if (t == null) return;
332         if (t.f == f) { putTrap(t.target, t.next); return; }
333         for(; t.next != null; t = t.next) if (t.next.f == f) { t.next = t.next.next; return; }
334     }
335
336
337