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