81feec199093394a70e63231faf9b51d17edf3c8
[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 Object METHOD = new Object() { public String toString() { return "JS.METHOD"; } };
14     public final JS unclone() { return _unclone(); }
15     public final JS jsclone() throws JSExn { return new Clone(this); }
16
17     public Enumeration keys() throws JSExn { throw new JSExn("you can't enumerate the keys of this object (class=" + this.getClass().getName() +")"); }
18     public Object get(Object key) throws JSExn { return null; }
19     public void put(Object key, Object val) throws JSExn { throw new JSExn("this object is read only (class=" + this.getClass().getName() +")"); }
20         
21     public final boolean hasTrap(Object key) { return getTrap(key) != null; }
22     
23     public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
24         throw new JSExn("method not found (" + method + ")");
25     }    
26     
27     // FIXME: JSArgs objects, pointers into stack frame
28     public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
29         throw new JSExn("you cannot call this object (class=" + this.getClass().getName() +")");
30     }
31
32     Trap getTrap(Object key) { return null; }
33     void putTrap(Object key, Trap value) throws JSExn { throw new JSExn("traps cannot be placed on this object (class=" + this.getClass().getName() +")"); }
34     
35     public static class O extends JS {
36         private Hash entries;
37         
38         public Enumeration keys() throws JSExn { return entries == null ? emptyEnumeration : entries.keys(); }
39         public Object get(Object key) throws JSExn { return entries == null ? null : entries.get(key, null); }
40         public void put(Object key, Object val) throws JSExn { (entries==null?entries=new Hash():entries).put(key,null,val); }        
41
42         /** retrieve a trap from the entries hash */
43         final Trap getTrap(Object key) {
44             return entries == null ? null : (Trap)entries.get(key, Trap.class);
45         }
46         
47         /** retrieve a trap from the entries hash */
48         final void putTrap(Object key, Trap value) {
49             if (entries == null) entries = new Hash();
50             entries.put(key, Trap.class, value);
51         }    
52     }
53     
54     public static class BT extends O {
55         private BalancedTree bt;
56         private final BalancedTree bt() { if(bt != null) return bt; return bt = new BalancedTree(); }
57         public final void insertNode(int index, Object o) { bt().insertNode(index,o); }
58         public final void clear() { bt().clear(); }
59         public final Object getNode(int i) { return bt().getNode(i); }
60         public final int treeSize() { return bt().treeSize(); }
61         public final Object deleteNode(int i) { return bt().deleteNode(i); }
62         public final void replaceNode(int index, Object o) { bt().replaceNode(index,o); }
63         public final int indexNode(Object o) { return bt().indexNode(o); }
64     }
65     
66     JS _unclone() { return this; }
67     
68     public interface Cloneable { }
69     
70     public static class Clone extends JS.O implements Cloneable {
71         protected JS clonee;
72         JS _unclone() { return clonee.unclone(); }
73         public JS getClonee() { return clonee; }
74         public Clone(JS clonee) throws JSExn {
75             if(!(clonee instanceof Cloneable)) throw new JSExn("this object isn't cloneable");
76             this.clonee = clonee;
77         }
78         public boolean equals(Object o) {
79             if (!(o instanceof JS)) return false;
80             return unclone() == ((JS)o).unclone();
81         }
82         public Enumeration keys() throws JSExn { return clonee.keys(); }
83         public Object get(Object key) throws JSExn { return clonee.get(key); }
84         public void put(Object key, Object val) throws JSExn { clonee.put(key, val); }
85         public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
86             return clonee.callMethod(method, a0, a1, a2, rest, nargs);
87         }    
88         public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
89             return clonee.call(a0, a1, a2, rest, nargs);
90         }
91     }
92
93     // Static Interpreter Control Methods ///////////////////////////////////////////////////////////////
94
95     /** log a message with the current JavaScript sourceName/line */
96     public static void log(Object message) { info(message); }
97     public static void debug(Object message) { Log.debug(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
98     public static void info(Object message) { Log.info(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
99     public static void warn(Object message) { Log.warn(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
100     public static void error(Object message) { Log.error(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
101
102     public static class NotPauseableException extends Exception { NotPauseableException() { } }
103
104     /** returns a callback which will restart the context; expects a value to be pushed onto the stack when unpaused */
105     public static UnpauseCallback pause() throws NotPauseableException {
106         Interpreter i = Interpreter.current();
107         if (i.pausecount == -1) throw new NotPauseableException();
108         i.pausecount++;
109         return new JS.UnpauseCallback(i);
110     }
111
112     public static class UnpauseCallback implements Task {
113         Interpreter i;
114         UnpauseCallback(Interpreter i) { this.i = i; }
115         public void perform() throws JSExn { unpause(null); }
116         public void unpause(Object o) throws JSExn {
117             // FIXME: if o instanceof JSExn, throw it into the JSworld
118             i.stack.push(o);
119             i.resume();
120         }
121     }
122
123
124
125     // Static Helper Methods ///////////////////////////////////////////////////////////////////////////////////
126
127     /** coerce an object to a Boolean */
128     public static boolean toBoolean(Object o) {
129         if (o == null) return false;
130         if (o instanceof Boolean) return ((Boolean)o).booleanValue();
131         if (o instanceof Long) return ((Long)o).longValue() != 0;
132         if (o instanceof Integer) return ((Integer)o).intValue() != 0;
133         if (o instanceof Number) {
134             double d = ((Number) o).doubleValue();
135             // NOTE: d == d is a test for NaN. It should be faster than Double.isNaN()
136             return d != 0.0 && d == d;
137         }
138         if (o instanceof String) return ((String)o).length() != 0;
139         return true;
140     }
141
142     /** coerce an object to a Long */
143     public static long toLong(Object o) { return toNumber(o).longValue(); }
144
145     /** coerce an object to an Int */
146     public static int toInt(Object o) { return toNumber(o).intValue(); }
147
148     /** coerce an object to a Double */
149     public static double toDouble(Object o) { return toNumber(o).doubleValue(); }
150
151     /** coerce an object to a Number */
152     public static Number toNumber(Object o) {
153         if (o == null) return ZERO;
154         if (o instanceof Number) return ((Number)o);
155
156         // NOTE: There are about 3 pages of rules in ecma262 about string to number conversions
157         //       We aren't even close to following all those rules.  We probably never will be.
158         if (o instanceof String) try { return N((String)o); } catch (NumberFormatException e) { return N(Double.NaN); }
159         if (o instanceof Boolean) return ((Boolean)o).booleanValue() ? N(1) : ZERO;
160         throw new Error("toNumber() got object of type " + o.getClass().getName() + " which we don't know how to handle");
161     }
162
163     /** coerce an object to a String */
164     public static String toString(Object o) {
165         if(o == null) return "null";
166         if(o instanceof String) return (String) o;
167         if(o instanceof Integer || o instanceof Long || o instanceof Boolean) return o.toString();
168         if(o instanceof JSArray) return o.toString();
169         if(o instanceof JSDate) return o.toString();
170         if(o instanceof Double || o instanceof Float) {
171             double d = ((Number)o).doubleValue();
172             if((int)d == d) return Integer.toString((int)d);
173             return o.toString();
174         }
175         if (o instanceof JS) return ((JS)o).coerceToString();   // HACK for now, this will probably go away
176         throw new RuntimeException("can't coerce "+o+" [" + o.getClass().getName() + "] to type String.");
177     }
178
179     public String coerceToString() {
180         throw new RuntimeException("can't coerce "+this+" [" + getClass().getName() + "] to type String.");
181     }
182
183     // Instance Methods ////////////////////////////////////////////////////////////////////
184
185     public static final Integer ZERO = new Integer(0);
186  
187     // this gets around a wierd fluke in the Java type checking rules for ?..:
188     public static final Object T = Boolean.TRUE;
189     public static final Object F = Boolean.FALSE;
190
191     public static final Boolean B(boolean b) { return b ? Boolean.TRUE : Boolean.FALSE; }
192     public static final Boolean B(int i) { return i==0 ? Boolean.FALSE : Boolean.TRUE; }
193     public static final Number N(String s) { return s.indexOf('.') == -1 ? N(Integer.parseInt(s)) : new Double(s); }
194     public static final Number N(double d) { return (int)d == d ? N((int)d) : new Double(d); }
195     public static final Number N(long l) { return N((int)l); }
196
197     private static final Integer[] smallIntCache = new Integer[65535 / 4];
198     private static final Integer[] largeIntCache = new Integer[65535 / 4];
199     public static final Number N(int i) {
200         Integer ret = null;
201         int idx = i + smallIntCache.length / 2;
202         if (idx < smallIntCache.length && idx > 0) {
203             ret = smallIntCache[idx];
204             if (ret != null) return ret;
205         }
206         else ret = largeIntCache[Math.abs(idx % largeIntCache.length)];
207         if (ret == null || ret.intValue() != i) {
208             ret = new Integer(i);
209             if (idx < smallIntCache.length && idx > 0) smallIntCache[idx] = ret;
210             else largeIntCache[Math.abs(idx % largeIntCache.length)] = ret;
211         }
212         return ret;
213     }
214     
215     private static Enumeration emptyEnumeration = new Enumeration() {
216             public boolean hasMoreElements() { return false; }
217             public Object nextElement() { throw new NoSuchElementException(); }
218         };
219     
220     public static JS fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
221         return JSFunction._fromReader(sourceName, firstLine, sourceCode);
222     }
223
224     // HACK: caller can't know if the argument is a JSFunction or not...
225     public static JS cloneWithNewParentScope(JS j, JSScope s) {
226         return ((JSFunction)j)._cloneWithNewParentScope(s);
227     }
228
229
230     // Trap support //////////////////////////////////////////////////////////////////////////////
231
232     /** performs a put, triggering traps if present; traps are run in an unpauseable interpreter */
233     public void putAndTriggerTraps(Object key, Object value) throws JSExn {
234         Trap t = getTrap(key);
235         if (t != null) t.invoke(value);
236         else put(key, value);
237     }
238
239     /** performs a get, triggering traps if present; traps are run in an unpauseable interpreter */
240     public Object getAndTriggerTraps(Object key) throws JSExn {
241         Trap t = getTrap(key);
242         if (t != null) return t.invoke();
243         else return get(key);
244     }
245
246     /** adds a trap, avoiding duplicates */
247     protected final void addTrap(Object name, JSFunction f) throws JSExn {
248         if (f.numFormalArgs > 1) throw new JSExn("traps must take either one argument (write) or no arguments (read)");
249         boolean isRead = f.numFormalArgs == 0;
250         for(Trap t = getTrap(name); t != null; t = t.next) if (t.f == f) return;
251         putTrap(name, new Trap(this, name.toString(), f, (Trap)getTrap(name)));
252     }
253
254     /** deletes a trap, if present */
255     protected final void delTrap(Object name, JSFunction f) throws JSExn {
256         Trap t = (Trap)getTrap(name);
257         if (t == null) return;
258         if (t.f == f) { putTrap(t.name, t.next); return; }
259         for(; t.next != null; t = t.next) if (t.next.f == f) { t.next = t.next.next; return; }
260     }
261
262
263