get rid of JS.BT
[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     JS _unclone() { return this; }
68     
69     public interface Cloneable { }
70     
71     public static class Clone extends JS.O {
72         protected final JS clonee;
73         JS _unclone() { return clonee.unclone(); }
74         public JS getClonee() { return clonee; }
75         public Clone(JS clonee) throws JSExn {
76             if(!(clonee instanceof Cloneable)) throw new JSExn("" + clonee.getClass().getName() + " isn't cloneable");
77             this.clonee = clonee;
78         }
79         public boolean jsequals(JS o) { return unclone().jsequals(o.unclone()); }
80         public Enumeration keys() throws JSExn { return clonee.keys(); }
81         public JS get(JS key) throws JSExn { return clonee.getAndTriggerTraps(key); }
82         public void put(JS key, JS val) throws JSExn { clonee.putAndTriggerTraps(key, val); }
83         public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
84             return clonee.callMethod(method, a0, a1, a2, rest, nargs);
85         }
86         public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
87             return clonee.call(a0, a1, a2, rest, nargs);
88         }
89         public InputStream getInputStream() throws IOException { return clonee.getInputStream(); }
90     }
91     
92     public static abstract class Enumeration extends JS {
93         final Enumeration parent;
94         boolean done;
95         public Enumeration(Enumeration parent) { this.parent = parent; }
96         protected abstract boolean _hasMoreElements();
97         protected abstract JS _nextElement() throws JSExn;
98         
99         public final boolean hasMoreElements() {
100             if(!done && !_hasMoreElements()) done = true;
101             return !done ? true : parent != null ? parent.hasMoreElements() : false;
102         }
103         public final JS nextElement() throws JSExn { return !done ? _nextElement() : parent != null ? parent.nextElement() : null; }
104         
105         public JS get(JS key) throws JSExn {
106             //#jswitch(key)
107             case "hasMoreElements": return B(hasMoreElements());
108             case "nextElement": return nextElement();
109             //#end
110             return super.get(key);
111         }
112     }
113     public static class EmptyEnumeration extends Enumeration {
114         public EmptyEnumeration(Enumeration parent) { super(parent); }
115         protected boolean _hasMoreElements() { return false; }
116         protected JS _nextElement() { return null; }
117     }
118     public static class JavaEnumeration extends Enumeration {
119         private final java.util.Enumeration e;
120         public JavaEnumeration(Enumeration parent, java.util.Enumeration e) { super(parent); this.e = e; }
121         protected boolean _hasMoreElements() { return e.hasMoreElements(); }
122         protected JS _nextElement() { return (JS) e.nextElement(); }
123     }
124     
125     // Static Interpreter Control Methods ///////////////////////////////////////////////////////////////
126
127     /** log a message with the current JavaScript sourceName/line */
128     public static void log(Object message) { info(message); }
129     public static void debug(Object message) { Log.debug(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
130     public static void info(Object message) { Log.info(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
131     public static void warn(Object message) { Log.warn(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
132     public static void error(Object message) { Log.error(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
133
134     public static class NotPauseableException extends Exception { NotPauseableException() { } }
135
136     /** returns a callback which will restart the context; expects a value to be pushed onto the stack when unpaused */
137     public static UnpauseCallback pause() throws NotPauseableException {
138         Interpreter i = Interpreter.current();
139         if (i.pausecount == -1) throw new NotPauseableException();
140         boolean get;
141         switch(i.f.op[i.pc]) {
142             case Tokens.RETURN: case ByteCodes.PUT: get = false; break;
143             case ByteCodes.GET: case ByteCodes.CALL: get = true; break;
144             default: throw new Error("should never happen");
145         }
146         i.pausecount++;
147         return new JS.UnpauseCallback(i,get);
148     }
149
150     public static class UnpauseCallback implements Task {
151         private Interpreter i;
152         private boolean get;
153         UnpauseCallback(Interpreter i, boolean get) { this.i = i; this.get = get; }
154         public void perform() throws JSExn { unpause(); }
155         public JS unpause() throws JSExn { return unpause((JS)null); }
156         public JS unpause(JS o) throws JSExn {
157             if (o == JS.METHOD) throw new JSExn("can't return a method to a paused context");
158             if(get) i.stack.push(o);
159             return i.resume();
160         }
161         public JS unpause(JSExn e) throws JSExn {
162             i.catchException(e);
163             return i.resume();
164         }
165     }
166
167
168
169     // Static Helper Methods ///////////////////////////////////////////////////////////////////////////////////
170
171     /** coerce an object to a Boolean */
172     public static boolean toBoolean(JS o) {
173         if(o == null) return false;
174         if(o instanceof JSNumber) return ((JSNumber)o).toBoolean();
175         if(o instanceof JSString) return ((JSString)o).s.length() != 0;
176         return true;
177     }
178     //#repeat long/int/double/float toLong/toInt/toDouble/toFloat Long/Integer/Double/Float parseLong/parseInt/parseDouble/parseFloat
179     /** coerce an object to a Number */
180     public static long toLong(JS o) throws JSExn {
181         if(o == null) return 0;
182         if(o instanceof JSNumber) return ((JSNumber)o).toLong();
183         if(o instanceof JSString) return Long.parseLong(o.coerceToString());
184         throw new JSExn("can't coerce a " + o.getClass().getName() + " to a number");
185     }
186     //#end
187     
188     public static String toString(JS o) throws JSExn {
189         if(o == null) return "null";
190         return o.coerceToString();
191     }
192     
193     public static String debugToString(JS o) {
194         try { return toString(o); }
195         catch(JSExn e) { return o.toString(); }
196     }
197     
198     public static boolean isInt(JS o) {
199         if(o == null) return true;
200         if(o instanceof JSNumber.I) return true;
201         if(o instanceof JSNumber.B) return false;
202         if(o instanceof JSNumber) {
203             JSNumber n = (JSNumber) o;
204             return n.toInt() == n.toDouble();
205         }
206         if(o instanceof JSString) {
207             String s = ((JSString)o).s;
208             for(int i=0;i<s.length();i++)
209                 if(s.charAt(i) < '0' || s.charAt(i) > '9') return false;
210             return true;
211         }
212         return false;
213     }
214     
215     public static boolean isString(JS o) {
216         if(o instanceof JSString) return true;
217         return false;
218     }
219     
220     public static JS newArray() { return new JSArray(); }
221     public static JS newRegexp(JS pat, JS flags) throws JSExn { return new JSRegexp(pat,flags); }
222
223     // Instance Methods ////////////////////////////////////////////////////////////////////
224  
225     public final static JS NaN = new JSNumber.D(Double.NaN);
226     public final static JS ZERO = new JSNumber.I(0);
227     public final static JS ONE = new JSNumber.I(1);
228     public final static JS MATH = new JSMath();
229         
230     public static final JS T = new JSNumber.B(true);
231     public static final JS F = new JSNumber.B(false);
232
233     public static final JS B(boolean b) { return b ? T : F; }
234     public static final JS B(int i) { return i==0 ? F : T; }
235     
236     private static final int CACHE_SIZE = 65536 / 4; // must be a power of two
237     private static final JSString[] stringCache = new JSString[CACHE_SIZE];
238     public static final JS S(String s) {
239         if(s == null) return null;
240         int slot = s.hashCode()&(CACHE_SIZE-1);
241         JSString ret = stringCache[slot];
242         if(ret == null || !ret.s.equals(s)) stringCache[slot] = ret = new JSString(s);
243         return ret;
244     }
245     public static final JS S(String s, boolean intern) { return intern ? JSString.intern(s) : S(s); }
246
247     public static final JS N(double d) { return new JSNumber.D(d); }
248     public static final JS N(long l) { return new JSNumber.L(l); }
249     
250     public static final JS N(Number n) {
251         if(n instanceof Integer) return N(n.intValue());
252         if(n instanceof Long) return N(n.longValue());
253         return N(n.doubleValue());
254     }
255
256     private static final JSNumber.I[] smallIntCache = new JSNumber.I[CACHE_SIZE];
257     private static final JSNumber.I[] largeIntCache = new JSNumber.I[CACHE_SIZE];
258     public static final JS N(int i) {
259         JSNumber.I ret = null;
260         int idx = i + smallIntCache.length / 2;
261         if (idx < CACHE_SIZE && idx > 0) {
262             ret = smallIntCache[idx];
263             if (ret != null) return ret;
264         }
265         else ret = largeIntCache[Math.abs(idx % CACHE_SIZE)];
266         if (ret == null || ret.i != i) {
267             ret = new JSNumber.I(i);
268             if (idx < smallIntCache.length && idx > 0) smallIntCache[idx] = ret;
269             else largeIntCache[Math.abs(idx % CACHE_SIZE)] = ret;
270         }
271         return ret;
272     }
273     
274     private static Enumeration EMPTY_ENUMERATION = new EmptyEnumeration(null);
275     
276     public static JS fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
277         return JSFunction._fromReader(sourceName, firstLine, sourceCode);
278     }
279
280     // HACK: caller can't know if the argument is a JSFunction or not...
281     public static JS cloneWithNewParentScope(JS j, JSScope s) {
282         return ((JSFunction)j)._cloneWithNewParentScope(s);
283     }
284
285
286     // Trap support //////////////////////////////////////////////////////////////////////////////
287
288     /** performs a put, triggering traps if present; traps are run in an unpauseable interpreter */
289     public void putAndTriggerTraps(JS key, JS value) throws JSExn {
290         Trap t = getTrap(key);
291         if(t == null || (t = t.writeTrap()) == null) put(key,value);
292         else new Interpreter(t,value,false).resume();
293     }
294
295     /** performs a get, triggering traps if present; traps are run in an unpauseable interpreter */
296     public JS getAndTriggerTraps(JS key) throws JSExn {
297         Trap t = getTrap(key);
298         if (t == null || (t = t.readTrap()) == null) return get(key);
299         else return new Interpreter(t,null,false).resume();
300     }
301     
302     public JS justTriggerTraps(JS key, JS value) throws JSExn {
303         Trap t = getTrap(key);
304         if(t == null || (t = t.writeTrap()) == null) return value;
305         else return new Interpreter(t,value,true).resume();
306     }
307
308     /** adds a trap, avoiding duplicates */
309     final void addTrap(JS key, JSFunction f) throws JSExn {
310         if (f.numFormalArgs > 1) throw new JSExn("traps must take either one argument (write) or no arguments (read)");
311         boolean isRead = f.numFormalArgs == 0;
312         for(Trap t = getTrap(key); t != null; t = t.next) if (t.f == f) return;
313         putTrap(key, new Trap(this, key, f, (Trap)getTrap(key)));
314     }
315
316     /** deletes a trap, if present */
317     final void delTrap(JS key, JSFunction f) throws JSExn {
318         Trap t = (Trap)getTrap(key);
319         if (t == null) return;
320         if (t.f == f) { putTrap(t.target, t.next); return; }
321         for(; t.next != null; t = t.next) if (t.next.f == f) { t.next = t.next.next; return; }
322     }
323
324
325