1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
4 import org.ibex.util.*;
8 /** The minimum set of functionality required for objects which are manipulated by JavaScript */
9 public abstract class JS {
11 public static boolean checkAssertions = false;
13 public static final Object METHOD = new Object() { public String toString() { return "JS.METHOD"; } };
14 public final JS unclone() { return _unclone(); }
15 public final JS jsclone() throws JSExn { return new Clone(this); }
17 public Enumeration keys() throws JSExn { throw new JSExn("you can't enumerate the keys of this object (class=" + this.getClass().getName() +")"); }
18 public Object get(Object key) throws JSExn { return null; }
19 public void put(Object key, Object val) throws JSExn { throw new JSExn("this object is read only (class=" + this.getClass().getName() +")"); }
21 public final boolean hasTrap(Object key) { return getTrap(key) != null; }
23 public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
24 throw new JSExn("method not found (" + method + ")");
27 // FIXME: JSArgs objects, pointers into stack frame
28 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
29 throw new JSExn("you cannot call this object (class=" + this.getClass().getName() +")");
32 Trap getTrap(Object key) { return null; }
33 void putTrap(Object key, Trap value) throws JSExn { throw new JSExn("traps cannot be placed on this object (class=" + this.getClass().getName() +")"); }
35 public static class O extends JS {
38 public Enumeration keys() throws JSExn { return entries == null ? emptyEnumeration : entries.keys(); }
39 public Object get(Object key) throws JSExn { return entries == null ? null : entries.get(key, null); }
40 public void put(Object key, Object val) throws JSExn { (entries==null?entries=new Hash():entries).put(key,null,val); }
42 /** retrieve a trap from the entries hash */
43 final Trap getTrap(Object key) {
44 return entries == null ? null : (Trap)entries.get(key, Trap.class);
47 /** retrieve a trap from the entries hash */
48 final void putTrap(Object key, Trap value) {
49 if (entries == null) entries = new Hash();
50 entries.put(key, Trap.class, value);
54 public static class BT extends O {
55 private BalancedTree bt;
56 private final BalancedTree bt() { if(bt != null) return bt; return bt = new BalancedTree(); }
57 public final void insertNode(int index, Object o) { bt().insertNode(index,o); }
58 public final void clear() { bt().clear(); }
59 public final Object getNode(int i) { return bt().getNode(i); }
60 public final int treeSize() { return bt().treeSize(); }
61 public final Object deleteNode(int i) { return bt().deleteNode(i); }
62 public final void replaceNode(int index, Object o) { bt().replaceNode(index,o); }
63 public final int indexNode(Object o) { return bt().indexNode(o); }
66 JS _unclone() { return this; }
68 public interface Cloneable { }
70 public static class Clone extends JS.O implements Cloneable {
72 JS _unclone() { return clonee.unclone(); }
73 public JS getClonee() { return clonee; }
74 public Clone(JS clonee) throws JSExn {
75 if(!(clonee instanceof Cloneable)) throw new JSExn("this object isn't cloneable");
78 public boolean equals(Object o) {
79 if (!(o instanceof JS)) return false;
80 return unclone() == ((JS)o).unclone();
82 public Enumeration keys() throws JSExn { return clonee.keys(); }
83 public Object get(Object key) throws JSExn { return clonee.get(key); }
84 public void put(Object key, Object val) throws JSExn { clonee.put(key, val); }
85 public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
86 return clonee.callMethod(method, a0, a1, a2, rest, nargs);
88 public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
89 return clonee.call(a0, a1, a2, rest, nargs);
93 // Static Interpreter Control Methods ///////////////////////////////////////////////////////////////
95 /** log a message with the current JavaScript sourceName/line */
96 public static void log(Object message) { info(message); }
97 public static void debug(Object message) { Log.debug(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
98 public static void info(Object message) { Log.info(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
99 public static void warn(Object message) { Log.warn(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
100 public static void error(Object message) { Log.error(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
102 public static class NotPauseableException extends Exception { NotPauseableException() { } }
104 /** returns a callback which will restart the context; expects a value to be pushed onto the stack when unpaused */
105 public static UnpauseCallback pause() throws NotPauseableException {
106 Interpreter i = Interpreter.current();
107 if (i.pausecount == -1) throw new NotPauseableException();
109 return new JS.UnpauseCallback(i);
112 public static class UnpauseCallback implements Task {
114 UnpauseCallback(Interpreter i) { this.i = i; }
115 public void perform() throws JSExn { unpause(null); }
116 public void unpause(Object o) throws JSExn {
117 // FIXME: if o instanceof JSExn, throw it into the JSworld
125 // Static Helper Methods ///////////////////////////////////////////////////////////////////////////////////
127 /** coerce an object to a Boolean */
128 public static boolean toBoolean(Object o) {
129 if (o == null) return false;
130 if (o instanceof Boolean) return ((Boolean)o).booleanValue();
131 if (o instanceof Long) return ((Long)o).longValue() != 0;
132 if (o instanceof Integer) return ((Integer)o).intValue() != 0;
133 if (o instanceof Number) {
134 double d = ((Number) o).doubleValue();
135 // NOTE: d == d is a test for NaN. It should be faster than Double.isNaN()
136 return d != 0.0 && d == d;
138 if (o instanceof String) return ((String)o).length() != 0;
142 /** coerce an object to a Long */
143 public static long toLong(Object o) { return toNumber(o).longValue(); }
145 /** coerce an object to an Int */
146 public static int toInt(Object o) { return toNumber(o).intValue(); }
148 /** coerce an object to a Double */
149 public static double toDouble(Object o) { return toNumber(o).doubleValue(); }
151 /** coerce an object to a Number */
152 public static Number toNumber(Object o) {
153 if (o == null) return ZERO;
154 if (o instanceof Number) return ((Number)o);
156 // NOTE: There are about 3 pages of rules in ecma262 about string to number conversions
157 // We aren't even close to following all those rules. We probably never will be.
158 if (o instanceof String) try { return N((String)o); } catch (NumberFormatException e) { return N(Double.NaN); }
159 if (o instanceof Boolean) return ((Boolean)o).booleanValue() ? N(1) : ZERO;
160 throw new Error("toNumber() got object of type " + o.getClass().getName() + " which we don't know how to handle");
163 /** coerce an object to a String */
164 public static String toString(Object o) {
165 if(o == null) return "null";
166 if(o instanceof String) return (String) o;
167 if(o instanceof Integer || o instanceof Long || o instanceof Boolean) return o.toString();
168 if(o instanceof JSArray) return o.toString();
169 if(o instanceof JSDate) return o.toString();
170 if(o instanceof Double || o instanceof Float) {
171 double d = ((Number)o).doubleValue();
172 if((int)d == d) return Integer.toString((int)d);
175 if (o instanceof JS) return ((JS)o).coerceToString(); // HACK for now, this will probably go away
176 throw new RuntimeException("can't coerce "+o+" [" + o.getClass().getName() + "] to type String.");
179 public String coerceToString() {
180 throw new RuntimeException("can't coerce "+this+" [" + getClass().getName() + "] to type String.");
183 // Instance Methods ////////////////////////////////////////////////////////////////////
185 public static final Integer ZERO = new Integer(0);
187 // this gets around a wierd fluke in the Java type checking rules for ?..:
188 public static final Object T = Boolean.TRUE;
189 public static final Object F = Boolean.FALSE;
191 public static final Boolean B(boolean b) { return b ? Boolean.TRUE : Boolean.FALSE; }
192 public static final Boolean B(int i) { return i==0 ? Boolean.FALSE : Boolean.TRUE; }
193 public static final Number N(String s) { return s.indexOf('.') == -1 ? N(Integer.parseInt(s)) : new Double(s); }
194 public static final Number N(double d) { return (int)d == d ? N((int)d) : new Double(d); }
195 public static final Number N(long l) { return N((int)l); }
197 private static final Integer[] smallIntCache = new Integer[65535 / 4];
198 private static final Integer[] largeIntCache = new Integer[65535 / 4];
199 public static final Number N(int i) {
201 int idx = i + smallIntCache.length / 2;
202 if (idx < smallIntCache.length && idx > 0) {
203 ret = smallIntCache[idx];
204 if (ret != null) return ret;
206 else ret = largeIntCache[Math.abs(idx % largeIntCache.length)];
207 if (ret == null || ret.intValue() != i) {
208 ret = new Integer(i);
209 if (idx < smallIntCache.length && idx > 0) smallIntCache[idx] = ret;
210 else largeIntCache[Math.abs(idx % largeIntCache.length)] = ret;
215 private static Enumeration emptyEnumeration = new Enumeration() {
216 public boolean hasMoreElements() { return false; }
217 public Object nextElement() { throw new NoSuchElementException(); }
220 public static JS fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
221 return JSFunction._fromReader(sourceName, firstLine, sourceCode);
224 // HACK: caller can't know if the argument is a JSFunction or not...
225 public static JS cloneWithNewParentScope(JS j, JSScope s) {
226 return ((JSFunction)j)._cloneWithNewParentScope(s);
230 // Trap support //////////////////////////////////////////////////////////////////////////////
232 /** performs a put, triggering traps if present; traps are run in an unpauseable interpreter */
233 public void putAndTriggerTraps(Object key, Object value) throws JSExn {
234 Trap t = getTrap(key);
235 if (t != null) t.invoke(value);
236 else put(key, value);
239 /** performs a get, triggering traps if present; traps are run in an unpauseable interpreter */
240 public Object getAndTriggerTraps(Object key) throws JSExn {
241 Trap t = getTrap(key);
242 if (t != null) return t.invoke();
243 else return get(key);
246 /** adds a trap, avoiding duplicates */
247 protected final void addTrap(Object name, JSFunction f) throws JSExn {
248 if (f.numFormalArgs > 1) throw new JSExn("traps must take either one argument (write) or no arguments (read)");
249 boolean isRead = f.numFormalArgs == 0;
250 for(Trap t = getTrap(name); t != null; t = t.next) if (t.f == f) return;
251 putTrap(name, new Trap(this, name.toString(), f, (Trap)getTrap(name)));
254 /** deletes a trap, if present */
255 protected final void delTrap(Object name, JSFunction f) throws JSExn {
256 Trap t = (Trap)getTrap(name);
257 if (t == null) return;
258 if (t.f == f) { putTrap(t.name, t.next); return; }
259 for(; t.next != null; t = t.next) if (t.next.f == f) { t.next = t.next.next; return; }