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