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