fixes and additions to new js 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
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         i.pausecount++;
121         return new JS.UnpauseCallback(i);
122     }
123
124     public static class UnpauseCallback implements Task {
125         Interpreter i;
126         UnpauseCallback(Interpreter i) { this.i = i; }
127         public void perform() throws JSExn { unpause((JS)null); }
128         public void unpause(JS o) throws JSExn {
129             i.stack.push(o);
130             i.resume();
131         }
132         public void unpause(JSExn e) {
133             // FIXME: Throw the JSExn into the js world
134             throw new Error("Exception " + e + " thrown from background task");
135         }
136     }
137
138
139
140     // Static Helper Methods ///////////////////////////////////////////////////////////////////////////////////
141
142     /** coerce an object to a Boolean */
143     public static boolean toBoolean(JS o) {
144         if(o == null) return false;
145         if(o instanceof JSNumber) return ((JSNumber)o).toBoolean();
146         if(o instanceof JSString) return ((JSString)o).length() != 0;
147         return true;
148     }
149     //#repeat long/int/double/float toLong/toInt/toDouble/toFloat Long/Integer/Double/Float parseLong/parseInt/parseDouble/parseFloat
150     /** coerce an object to a Number */
151     public static long toLong(JS o) throws JSExn {
152         if(o == null) return 0;
153         if(o instanceof JSNumber) return ((JSNumber)o).toLong();
154         if(o instanceof JSString) return Long.parseLong(o.coerceToString());
155         throw new JSExn("can't coerce a " + o.getClass().getName() + " to a number");
156     }
157     //#end
158     
159     public static String toString(JS o) throws JSExn {
160         if(o == null) return "null";
161         return o.coerceToString();
162     }
163     
164     public static String debugToString(JS o) {
165         try { return toString(o); }
166         catch(JSExn e) { return "[class=" + o.getClass().getName() + "]"; }
167     }
168     
169     public static boolean isInt(JS o) {
170         if(o == null) return true;
171         if(o instanceof JSNumber.I) return true;
172         if(o instanceof JSNumber.B) return false;
173         if(o instanceof JSNumber) {
174             JSNumber n = (JSNumber) o;
175             return n.toInt() == n.toDouble();
176         }
177         if(o instanceof JSString) {
178             String s = ((JSString)o).s;
179             for(int i=0;i<s.length();i++)
180                 if(s.charAt(i) < '0' || s.charAt(i) > '9') return false;
181             return true;
182         }
183         return false;
184     }
185     
186     public static boolean isString(JS o) {
187         if(o instanceof JSString) return true;
188         return false;
189     }
190
191     // Instance Methods ////////////////////////////////////////////////////////////////////
192  
193     public final static JS NaN = new JSNumber.D(Double.NaN);
194     public final static JS ZERO = new JSNumber.I(0);
195     public final static JS ONE = new JSNumber.I(1);
196         
197     public static final JS T = new JSNumber.B(true);
198     public static final JS F = new JSNumber.B(false);
199
200     public static final JS B(boolean b) { return b ? T : F; }
201     public static final JS B(int i) { return i==0 ? F : T; }
202     
203     public static final JS S(String s) { return new JSString(s); }
204
205     public static final JS N(double d) { return new JSNumber.D(d); }
206     public static final JS N(long l) { return new JSNumber.L(l); }
207     
208     public static final JS N(Number n) {
209         if(n instanceof Integer) return N(n.intValue());
210         if(n instanceof Long) return N(n.longValue());
211         return N(n.doubleValue());
212     }
213
214     private static final JSNumber.I[] smallIntCache = new JSNumber.I[65535 / 4];
215     private static final JSNumber.I[] largeIntCache = new JSNumber.I[65535 / 4];
216     public static final JS N(int i) {
217         JSNumber.I ret = null;
218         int idx = i + smallIntCache.length / 2;
219         if (idx < smallIntCache.length && idx > 0) {
220             ret = smallIntCache[idx];
221             if (ret != null) return ret;
222         }
223         else ret = largeIntCache[Math.abs(idx % largeIntCache.length)];
224         if (ret == null || ret.i != i) {
225             ret = new JSNumber.I(i);
226             if (idx < smallIntCache.length && idx > 0) smallIntCache[idx] = ret;
227             else largeIntCache[Math.abs(idx % largeIntCache.length)] = ret;
228         }
229         return ret;
230     }
231     
232     private static Enumeration emptyEnumeration = new Enumeration() {
233             public boolean hasMoreElements() { return false; }
234             public Object nextElement() { throw new NoSuchElementException(); }
235         };
236     
237     public static JS fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
238         return JSFunction._fromReader(sourceName, firstLine, sourceCode);
239     }
240
241     // HACK: caller can't know if the argument is a JSFunction or not...
242     public static JS cloneWithNewParentScope(JS j, JSScope s) {
243         return ((JSFunction)j)._cloneWithNewParentScope(s);
244     }
245
246
247     // Trap support //////////////////////////////////////////////////////////////////////////////
248
249     /** performs a put, triggering traps if present; traps are run in an unpauseable interpreter */
250     public void putAndTriggerTraps(JS key, JS value) throws JSExn {
251         Trap t = getTrap(key);
252         if (t != null) t.invoke(value);
253         else put(key, value);
254     }
255
256     /** performs a get, triggering traps if present; traps are run in an unpauseable interpreter */
257     public JS getAndTriggerTraps(JS key) throws JSExn {
258         Trap t = getTrap(key);
259         if (t != null) return t.invoke();
260         else return get(key);
261     }
262
263     /** adds a trap, avoiding duplicates */
264     final void addTrap(JS key, JSFunction f) throws JSExn {
265         if (f.numFormalArgs > 1) throw new JSExn("traps must take either one argument (write) or no arguments (read)");
266         boolean isRead = f.numFormalArgs == 0;
267         for(Trap t = getTrap(key); t != null; t = t.next) if (t.f == f) return;
268         putTrap(key, new Trap(this, key, f, (Trap)getTrap(key)));
269     }
270
271     /** deletes a trap, if present */
272     final void delTrap(JS key, JSFunction f) throws JSExn {
273         Trap t = (Trap)getTrap(key);
274         if (t == null) return;
275         if (t.f == f) { putTrap(t.name, t.next); return; }
276         for(; t.next != null; t = t.next) if (t.next.f == f) { t.next = t.next.next; return; }
277     }
278
279
280