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