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