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