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