more optimal jsfunction calls
[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
11     public static boolean checkAssertions = false;
12
13     public static final JS METHOD = new JS() { };
14     public final JS unclone() { return _unclone(); }
15     public final JS jsclone() throws JSExn { return new Clone(this); }
16
17     // FEATURE: JSEnumeration
18     public Enumeration keys() throws JSExn { throw new JSExn("you can't enumerate the keys of this object (class=" + getClass().getName() +")"); }
19     public JS get(JS key) throws JSExn { return null; }
20     public void put(JS key, JS val) throws JSExn { throw new JSExn("" + key + " is read only (class=" + getClass().getName() +")"); }
21     
22     public InputStream getInputStream() throws IOException {
23         throw new IOException("this object doesn't have a stream associated with it " + getClass().getName() + ")");
24     }
25         
26     public final boolean hasTrap(JS key) { return getTrap(key) != null; }
27     
28     public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
29         throw new JSExn("method not found (" + JS.debugToString(method) + ")");
30     }
31     
32     // FIXME: JSArgs objects, pointers into stack frame
33     public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
34         throw new JSExn("you cannot call this object (class=" + this.getClass().getName() +")");
35     }
36     
37     public final boolean equals(Object o) { return this == o || ((o instanceof JS) && jsequals((JS)o)); }
38     
39     // FIXME: Remove this, eventually
40     public final String toString() { throw new Error("you shouldn't use toString() on JS objects"); }
41     
42     // These are only used internally by org.ibex.js
43     Trap getTrap(JS key) { return null; }
44     void putTrap(JS key, Trap value) throws JSExn { throw new JSExn("traps cannot be placed on this object (class=" + this.getClass().getName() +")"); }
45     String coerceToString() throws JSExn { throw new JSExn("can't coerce to a string (class=" + getClass().getName() +")"); }
46     boolean jsequals(JS o) { return this == o; }
47     
48     public static class O extends JS {
49         private Hash entries;
50         
51         public Enumeration keys() throws JSExn { return entries == null ? emptyEnumeration : 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     // FEATURE: JS.StringKeys
80     /* public static StringKeys extends JS {
81         public JS get(JS key) { return JS.isString(key) ? get(JS.toString(key) : null; }
82         ...
83     */
84     
85     JS _unclone() { return this; }
86     
87     public interface Cloneable { }
88     
89     public static class Clone extends JS.O implements Cloneable {
90         protected final JS clonee;
91         JS _unclone() { return clonee.unclone(); }
92         public JS getClonee() { return clonee; }
93         public Clone(JS clonee) throws JSExn {
94             if(!(clonee instanceof Cloneable)) throw new JSExn("" + clonee.getClass().getName() + " isn't cloneable");
95             this.clonee = clonee;
96         }
97         public boolean jsequals(JS o) { return unclone().jsequals(o.unclone()); }
98         public Enumeration keys() throws JSExn { return clonee.keys(); }
99         public JS get(JS key) throws JSExn { return clonee.get(key); }
100         public void put(JS key, JS val) throws JSExn { clonee.put(key, val); }
101         public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
102             return clonee.callMethod(method, a0, a1, a2, rest, nargs);
103         }
104         public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
105             return clonee.call(a0, a1, a2, rest, nargs);
106         }
107         public InputStream getInputStream() throws IOException { return clonee.getInputStream(); }
108     }
109     
110     // Static Interpreter Control Methods ///////////////////////////////////////////////////////////////
111
112     /** log a message with the current JavaScript sourceName/line */
113     public static void log(Object message) { info(message); }
114     public static void debug(Object message) { Log.debug(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
115     public static void info(Object message) { Log.info(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
116     public static void warn(Object message) { Log.warn(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
117     public static void error(Object message) { Log.error(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
118
119     public static class NotPauseableException extends Exception { NotPauseableException() { } }
120
121     /** returns a callback which will restart the context; expects a value to be pushed onto the stack when unpaused */
122     public static UnpauseCallback pause() throws NotPauseableException {
123         Interpreter i = Interpreter.current();
124         if (i.pausecount == -1) throw new NotPauseableException();
125         boolean get;
126         switch(i.f.op[i.pc]) {
127             case Tokens.RETURN: case ByteCodes.PUT: get = false; break;
128             case ByteCodes.GET: case ByteCodes.CALL: get = true; break;
129             default: throw new Error("should never happen");
130         }
131         i.pausecount++;
132         return new JS.UnpauseCallback(i,get);
133     }
134
135     public static class UnpauseCallback implements Task {
136         private Interpreter i;
137         private boolean get;
138         UnpauseCallback(Interpreter i, boolean get) { this.i = i; this.get = get; }
139         public void perform() throws JSExn { unpause(); }
140         public JS unpause() throws JSExn { return unpause((JS)null); }
141         public JS unpause(JS o) throws JSExn {
142             if (o == JS.METHOD) throw new JSExn("can't return a method to a paused context");
143             if(get) i.stack.push(o);
144             return i.resume();
145         }
146         public JS unpause(JSExn e) throws JSExn {
147             i.catchException(e);
148             return i.resume();
149         }
150     }
151
152
153
154     // Static Helper Methods ///////////////////////////////////////////////////////////////////////////////////
155
156     /** coerce an object to a Boolean */
157     public static boolean toBoolean(JS o) {
158         if(o == null) return false;
159         if(o instanceof JSNumber) return ((JSNumber)o).toBoolean();
160         if(o instanceof JSString) return ((JSString)o).length() != 0;
161         return true;
162     }
163     //#repeat long/int/double/float toLong/toInt/toDouble/toFloat Long/Integer/Double/Float parseLong/parseInt/parseDouble/parseFloat
164     /** coerce an object to a Number */
165     public static long toLong(JS o) throws JSExn {
166         if(o == null) return 0;
167         if(o instanceof JSNumber) return ((JSNumber)o).toLong();
168         if(o instanceof JSString) return Long.parseLong(o.coerceToString());
169         throw new JSExn("can't coerce a " + o.getClass().getName() + " to a number");
170     }
171     //#end
172     
173     public static String toString(JS o) throws JSExn {
174         if(o == null) return "null";
175         return o.coerceToString();
176     }
177     
178     public static String debugToString(JS o) {
179         try { return toString(o); }
180         catch(JSExn e) { return "[class=" + o.getClass().getName() + "]"; }
181     }
182     
183     public static boolean isInt(JS o) {
184         if(o == null) return true;
185         if(o instanceof JSNumber.I) return true;
186         if(o instanceof JSNumber.B) return false;
187         if(o instanceof JSNumber) {
188             JSNumber n = (JSNumber) o;
189             return n.toInt() == n.toDouble();
190         }
191         if(o instanceof JSString) {
192             String s = ((JSString)o).s;
193             for(int i=0;i<s.length();i++)
194                 if(s.charAt(i) < '0' || s.charAt(i) > '9') return false;
195             return true;
196         }
197         return false;
198     }
199     
200     public static boolean isString(JS o) {
201         if(o instanceof JSString) return true;
202         return false;
203     }
204
205     // Instance Methods ////////////////////////////////////////////////////////////////////
206  
207     public final static JS NaN = new JSNumber.D(Double.NaN);
208     public final static JS ZERO = new JSNumber.I(0);
209     public final static JS ONE = new JSNumber.I(1);
210         
211     public static final JS T = new JSNumber.B(true);
212     public static final JS F = new JSNumber.B(false);
213
214     public static final JS B(boolean b) { return b ? T : F; }
215     public static final JS B(int i) { return i==0 ? F : T; }
216     
217     private static final int CACHE_SIZE = 65536 / 4; // must be a power of two
218     private static final JSString[] stringCache = new JSString[CACHE_SIZE];
219     public static final JS S(String s)  {
220         if(s == null) return null;
221         int slot = s.hashCode()&(CACHE_SIZE-1);
222         JSString ret = stringCache[slot];
223         if(ret == null || !ret.s.equals(s)) stringCache[slot] = ret = new JSString(s);
224         return ret;
225     }
226
227     public static final JS N(double d) { return new JSNumber.D(d); }
228     public static final JS N(long l) { return new JSNumber.L(l); }
229     
230     public static final JS N(Number n) {
231         if(n instanceof Integer) return N(n.intValue());
232         if(n instanceof Long) return N(n.longValue());
233         return N(n.doubleValue());
234     }
235
236     private static final JSNumber.I[] smallIntCache = new JSNumber.I[CACHE_SIZE];
237     private static final JSNumber.I[] largeIntCache = new JSNumber.I[CACHE_SIZE];
238     public static final JS N(int i) {
239         JSNumber.I ret = null;
240         int idx = i + smallIntCache.length / 2;
241         if (idx < CACHE_SIZE && idx > 0) {
242             ret = smallIntCache[idx];
243             if (ret != null) return ret;
244         }
245         else ret = largeIntCache[Math.abs(idx % CACHE_SIZE)];
246         if (ret == null || ret.i != i) {
247             ret = new JSNumber.I(i);
248             if (idx < smallIntCache.length && idx > 0) smallIntCache[idx] = ret;
249             else largeIntCache[Math.abs(idx % CACHE_SIZE)] = ret;
250         }
251         return ret;
252     }
253     
254     private static Enumeration emptyEnumeration = new Enumeration() {
255             public boolean hasMoreElements() { return false; }
256             public Object nextElement() { throw new NoSuchElementException(); }
257         };
258     
259     public static JS fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
260         return JSFunction._fromReader(sourceName, firstLine, sourceCode);
261     }
262
263     // HACK: caller can't know if the argument is a JSFunction or not...
264     public static JS cloneWithNewParentScope(JS j, JSScope s) {
265         return ((JSFunction)j)._cloneWithNewParentScope(s);
266     }
267
268
269     // Trap support //////////////////////////////////////////////////////////////////////////////
270
271     /** performs a put, triggering traps if present; traps are run in an unpauseable interpreter */
272     public void putAndTriggerTraps(JS key, JS value) throws JSExn {
273         Trap t = getTrap(key);
274         if (t != null) t.invoke(value);
275         else put(key, value);
276     }
277
278     /** performs a get, triggering traps if present; traps are run in an unpauseable interpreter */
279     public JS getAndTriggerTraps(JS key) throws JSExn {
280         Trap t = getTrap(key);
281         if (t != null) return t.invoke();
282         else return get(key);
283     }
284
285     /** adds a trap, avoiding duplicates */
286     final void addTrap(JS key, JSFunction f) throws JSExn {
287         if (f.numFormalArgs > 1) throw new JSExn("traps must take either one argument (write) or no arguments (read)");
288         boolean isRead = f.numFormalArgs == 0;
289         for(Trap t = getTrap(key); t != null; t = t.next) if (t.f == f) return;
290         putTrap(key, new Trap(this, key, f, (Trap)getTrap(key)));
291     }
292
293     /** deletes a trap, if present */
294     final void delTrap(JS key, JSFunction f) throws JSExn {
295         Trap t = (Trap)getTrap(key);
296         if (t == null) return;
297         if (t.f == f) { putTrap(t.name, t.next); return; }
298         for(; t.next != null; t = t.next) if (t.next.f == f) { t.next = t.next.next; return; }
299     }
300
301
302