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