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     JS _unclone() { return this; }
76     
77     public interface Cloneable { }
78     
79     public static class Clone extends JS.O implements Cloneable {
80         protected final JS clonee;
81         JS _unclone() { return clonee.unclone(); }
82         public JS getClonee() { return clonee; }
83         public Clone(JS clonee) throws JSExn {
84             if(!(clonee instanceof Cloneable)) throw new JSExn("" + getClass().getName() + " isn't cloneable");
85             this.clonee = clonee;
86         }
87         public boolean jsequals(JS o) { return unclone().jsequals(o.unclone()); }
88         public Enumeration keys() throws JSExn { return clonee.keys(); }
89         public JS get(JS key) throws JSExn { return clonee.get(key); }
90         public void put(JS key, JS val) throws JSExn { clonee.put(key, val); }
91         public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
92             return clonee.callMethod(method, a0, a1, a2, rest, nargs);
93         }
94         public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
95             return clonee.call(a0, a1, a2, rest, nargs);
96         }
97     }
98     
99     // Static Interpreter Control Methods ///////////////////////////////////////////////////////////////
100
101     /** log a message with the current JavaScript sourceName/line */
102     public static void log(Object message) { info(message); }
103     public static void debug(Object message) { Log.debug(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
104     public static void info(Object message) { Log.info(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
105     public static void warn(Object message) { Log.warn(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
106     public static void error(Object message) { Log.error(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
107
108     public static class NotPauseableException extends Exception { NotPauseableException() { } }
109
110     /** returns a callback which will restart the context; expects a value to be pushed onto the stack when unpaused */
111     public static UnpauseCallback pause() throws NotPauseableException {
112         Interpreter i = Interpreter.current();
113         if (i.pausecount == -1) throw new NotPauseableException();
114         i.pausecount++;
115         return new JS.UnpauseCallback(i);
116     }
117
118     public static class UnpauseCallback implements Task {
119         Interpreter i;
120         UnpauseCallback(Interpreter i) { this.i = i; }
121         public void perform() throws JSExn { unpause((JS)null); }
122         public void unpause(JS o) throws JSExn {
123             i.stack.push(o);
124             i.resume();
125         }
126         public void unpause(JSExn e) {
127             // FIXME: Throw the JSExn into the js world
128             throw new Error("Exception " + e + " thrown from background task");
129         }
130     }
131
132
133
134     // Static Helper Methods ///////////////////////////////////////////////////////////////////////////////////
135
136     /** coerce an object to a Boolean */
137     public static boolean toBoolean(JS o) {
138         if(o == null) return false;
139         if(o instanceof JSNumber) return ((JSNumber)o).toBoolean();
140         if(o instanceof JSString) return ((JSString)o).length() != 0;
141         return true;
142     }
143     //#repeat long/int/double/float toLong/toInt/toDouble/toFloat Long/Integer/Double/Float parseLong/parseInt/parseDouble/parseFloat
144     /** coerce an object to a Number */
145     public static long toLong(JS o) throws JSExn {
146         if(o == null) return 0;
147         if(o instanceof JSNumber) return ((JSNumber)o).toLong();
148         if(o instanceof JSString) return Long.parseLong(o.coerceToString());
149         throw new JSExn("can't coerce a " + o.getClass().getName() + " to a number");
150     }
151     //#end
152     
153     public static String toString(JS o) throws JSExn {
154         if(o == null) return "null";
155         return o.coerceToString();
156     }
157     
158     public static String debugToString(JS o) {
159         try { return toString(o); }
160         catch(JSExn e) { return "[class=" + o.getClass().getName() + "]"; }
161     }
162     
163     public static boolean isInt(JS o) {
164         if(o == null) return true;
165         if(o instanceof JSNumber.I) return true;
166         if(o instanceof JSNumber.B) return false;
167         if(o instanceof JSNumber) {
168             JSNumber n = (JSNumber) o;
169             return n.toInt() == n.toDouble();
170         }
171         if(o instanceof JSString) {
172             String s = ((JSString)o).s;
173             for(int i=0;i<s.length();i++)
174                 if(s.charAt(i) < '0' || s.charAt(i) > '9') return false;
175             return true;
176         }
177         return false;
178     }
179     
180     public static boolean isString(JS o) {
181         if(o instanceof JSString) return true;
182         return false;
183     }
184
185     // Instance Methods ////////////////////////////////////////////////////////////////////
186  
187     public final static JS NaN = new JSNumber.D(Double.NaN);
188     public final static JS ZERO = new JSNumber.I(0);
189     public final static JS ONE = new JSNumber.I(1);
190         
191     public static final JS T = new JSNumber.B(true);
192     public static final JS F = new JSNumber.B(false);
193
194     public static final JS B(boolean b) { return b ? T : F; }
195     public static final JS B(int i) { return i==0 ? F : T; }
196     
197     public static final JS S(String s) { return new JSString(s); }
198
199     public static final JS N(double d) { return new JSNumber.D(d); }
200     public static final JS N(long l) { return new JSNumber.L(l); }
201     
202     public static final JS N(Number n) {
203         if(n instanceof Integer) return N(n.intValue());
204         if(n instanceof Long) return N(n.longValue());
205         return N(n.doubleValue());
206     }
207
208     private static final JSNumber.I[] smallIntCache = new JSNumber.I[65535 / 4];
209     private static final JSNumber.I[] largeIntCache = new JSNumber.I[65535 / 4];
210     public static final JS N(int i) {
211         JSNumber.I ret = null;
212         int idx = i + smallIntCache.length / 2;
213         if (idx < smallIntCache.length && idx > 0) {
214             ret = smallIntCache[idx];
215             if (ret != null) return ret;
216         }
217         else ret = largeIntCache[Math.abs(idx % largeIntCache.length)];
218         if (ret == null || ret.i != i) {
219             ret = new JSNumber.I(i);
220             if (idx < smallIntCache.length && idx > 0) smallIntCache[idx] = ret;
221             else largeIntCache[Math.abs(idx % largeIntCache.length)] = ret;
222         }
223         return ret;
224     }
225     
226     private static Enumeration emptyEnumeration = new Enumeration() {
227             public boolean hasMoreElements() { return false; }
228             public Object nextElement() { throw new NoSuchElementException(); }
229         };
230     
231     public static JS fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
232         return JSFunction._fromReader(sourceName, firstLine, sourceCode);
233     }
234
235     // HACK: caller can't know if the argument is a JSFunction or not...
236     public static JS cloneWithNewParentScope(JS j, JSScope s) {
237         return ((JSFunction)j)._cloneWithNewParentScope(s);
238     }
239
240
241     // Trap support //////////////////////////////////////////////////////////////////////////////
242
243     /** performs a put, triggering traps if present; traps are run in an unpauseable interpreter */
244     public void putAndTriggerTraps(JS key, JS value) throws JSExn {
245         Trap t = getTrap(key);
246         if (t != null) t.invoke(value);
247         else put(key, value);
248     }
249
250     /** performs a get, triggering traps if present; traps are run in an unpauseable interpreter */
251     public JS getAndTriggerTraps(JS key) throws JSExn {
252         Trap t = getTrap(key);
253         if (t != null) return t.invoke();
254         else return get(key);
255     }
256
257     /** adds a trap, avoiding duplicates */
258     final void addTrap(JS key, JSFunction f) throws JSExn {
259         if (f.numFormalArgs > 1) throw new JSExn("traps must take either one argument (write) or no arguments (read)");
260         boolean isRead = f.numFormalArgs == 0;
261         for(Trap t = getTrap(key); t != null; t = t.next) if (t.f == f) return;
262         putTrap(key, new Trap(this, key, f, (Trap)getTrap(key)));
263     }
264
265     /** deletes a trap, if present */
266     final void delTrap(JS key, JSFunction f) throws JSExn {
267         Trap t = (Trap)getTrap(key);
268         if (t == null) return;
269         if (t.f == f) { putTrap(t.name, t.next); return; }
270         for(; t.next != null; t = t.next) if (t.next.f == f) { t.next = t.next.next; return; }
271     }
272
273
274