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 JS METHOD = new JS() { };
14 public final JS unclone() { return _unclone(); }
15 public final JS jsclone() throws JSExn { return new Clone(this); }
17 // FEATURE: JSEnumeration
18 public Enumeration keys() throws JSExn { throw new JSExn("you can't enumerate the keys of this object (class=" + getClass().getName() +")"); }
19 public JS get(JS key) throws JSExn { return null; }
20 public void put(JS key, JS val) throws JSExn { throw new JSExn("" + key + " is read only (class=" + getClass().getName() +")"); }
22 public final boolean hasTrap(JS key) { return getTrap(key) != null; }
24 public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
25 throw new JSExn("method not found (" + JS.debugToString(method) + ")");
28 // FIXME: JSArgs objects, pointers into stack frame
29 public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
30 throw new JSExn("you cannot call this object (class=" + this.getClass().getName() +")");
33 public final boolean equals(Object o) { return this == o || ((o instanceof JS) && jsequals((JS)o)); }
35 // FIXME: Remove this, eventually
36 public final String toString() { throw new Error("you shouldn't use toString() on JS objects"); }
38 // These are only used internally by org.ibex.js
39 Trap getTrap(JS key) { return null; }
40 void putTrap(JS key, Trap value) throws JSExn { throw new JSExn("traps cannot be placed on this object (class=" + this.getClass().getName() +")"); }
41 String coerceToString() throws JSExn { throw new JSExn("can't coerce to a string (class=" + getClass().getName() +")"); }
42 boolean jsequals(JS o) { return this == o; }
44 public static class O extends JS {
47 public Enumeration keys() throws JSExn { return entries == null ? emptyEnumeration : entries.keys(); }
48 public JS get(JS key) throws JSExn { return entries == null ? null : (JS)entries.get(key, null); }
49 public void put(JS key, JS val) throws JSExn { (entries==null?entries=new Hash():entries).put(key,null,val); }
51 /** retrieve a trap from the entries hash */
52 final Trap getTrap(JS key) {
53 return entries == null ? null : (Trap)entries.get(key, Trap.class);
56 /** retrieve a trap from the entries hash */
57 final void putTrap(JS key, Trap value) {
58 if (entries == null) entries = new Hash();
59 entries.put(key, Trap.class, value);
63 public static class BT extends O {
64 private BalancedTree bt;
65 private final BalancedTree bt() { if(bt != null) return bt; return bt = new BalancedTree(); }
66 public final void insertNode(int index, Object o) { bt().insertNode(index,o); }
67 public final void clear() { bt().clear(); }
68 public final Object getNode(int i) { return bt().getNode(i); }
69 public final int treeSize() { return bt().treeSize(); }
70 public final Object deleteNode(int i) { return bt().deleteNode(i); }
71 public final void replaceNode(int index, Object o) { bt().replaceNode(index,o); }
72 public final int indexNode(Object o) { return bt().indexNode(o); }
75 // FEATURE: JS.StringKeys
76 /* public static StringKeys extends JS {
77 public JS get(JS key) { return JS.isString(key) ? get(JS.toString(key) : null; }
81 JS _unclone() { return this; }
83 public interface Cloneable { }
85 public static class Clone extends JS.O implements Cloneable {
86 protected final JS clonee;
87 JS _unclone() { return clonee.unclone(); }
88 public JS getClonee() { return clonee; }
89 public Clone(JS clonee) throws JSExn {
90 if(!(clonee instanceof Cloneable)) throw new JSExn("" + getClass().getName() + " isn't cloneable");
93 public boolean jsequals(JS o) { return unclone().jsequals(o.unclone()); }
94 public Enumeration keys() throws JSExn { return clonee.keys(); }
95 public JS get(JS key) throws JSExn { return clonee.get(key); }
96 public void put(JS key, JS val) throws JSExn { clonee.put(key, val); }
97 public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
98 return clonee.callMethod(method, a0, a1, a2, rest, nargs);
100 public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
101 return clonee.call(a0, a1, a2, rest, nargs);
105 // Static Interpreter Control Methods ///////////////////////////////////////////////////////////////
107 /** log a message with the current JavaScript sourceName/line */
108 public static void log(Object message) { info(message); }
109 public static void debug(Object message) { Log.debug(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
110 public static void info(Object message) { Log.info(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
111 public static void warn(Object message) { Log.warn(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
112 public static void error(Object message) { Log.error(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
114 public static class NotPauseableException extends Exception { NotPauseableException() { } }
116 /** returns a callback which will restart the context; expects a value to be pushed onto the stack when unpaused */
117 public static UnpauseCallback pause() throws NotPauseableException {
118 Interpreter i = Interpreter.current();
119 if (i.pausecount == -1) throw new NotPauseableException();
121 return new JS.UnpauseCallback(i);
124 public static class UnpauseCallback implements Task {
126 UnpauseCallback(Interpreter i) { this.i = i; }
127 public void perform() throws JSExn { unpause((JS)null); }
128 public void unpause(JS o) throws JSExn {
132 public void unpause(JSExn e) {
133 // FIXME: Throw the JSExn into the js world
134 throw new Error("Exception " + e + " thrown from background task");
140 // Static Helper Methods ///////////////////////////////////////////////////////////////////////////////////
142 /** coerce an object to a Boolean */
143 public static boolean toBoolean(JS o) {
144 if(o == null) return false;
145 if(o instanceof JSNumber) return ((JSNumber)o).toBoolean();
146 if(o instanceof JSString) return ((JSString)o).length() != 0;
149 //#repeat long/int/double/float toLong/toInt/toDouble/toFloat Long/Integer/Double/Float parseLong/parseInt/parseDouble/parseFloat
150 /** coerce an object to a Number */
151 public static long toLong(JS o) throws JSExn {
152 if(o == null) return 0;
153 if(o instanceof JSNumber) return ((JSNumber)o).toLong();
154 if(o instanceof JSString) return Long.parseLong(o.coerceToString());
155 throw new JSExn("can't coerce a " + o.getClass().getName() + " to a number");
159 public static String toString(JS o) throws JSExn {
160 if(o == null) return "null";
161 return o.coerceToString();
164 public static String debugToString(JS o) {
165 try { return toString(o); }
166 catch(JSExn e) { return "[class=" + o.getClass().getName() + "]"; }
169 public static boolean isInt(JS o) {
170 if(o == null) return true;
171 if(o instanceof JSNumber.I) return true;
172 if(o instanceof JSNumber.B) return false;
173 if(o instanceof JSNumber) {
174 JSNumber n = (JSNumber) o;
175 return n.toInt() == n.toDouble();
177 if(o instanceof JSString) {
178 String s = ((JSString)o).s;
179 for(int i=0;i<s.length();i++)
180 if(s.charAt(i) < '0' || s.charAt(i) > '9') return false;
186 public static boolean isString(JS o) {
187 if(o instanceof JSString) return true;
191 // Instance Methods ////////////////////////////////////////////////////////////////////
193 public final static JS NaN = new JSNumber.D(Double.NaN);
194 public final static JS ZERO = new JSNumber.I(0);
195 public final static JS ONE = new JSNumber.I(1);
197 public static final JS T = new JSNumber.B(true);
198 public static final JS F = new JSNumber.B(false);
200 public static final JS B(boolean b) { return b ? T : F; }
201 public static final JS B(int i) { return i==0 ? F : T; }
203 public static final JS S(String s) { return new JSString(s); }
205 public static final JS N(double d) { return new JSNumber.D(d); }
206 public static final JS N(long l) { return new JSNumber.L(l); }
208 public static final JS N(Number n) {
209 if(n instanceof Integer) return N(n.intValue());
210 if(n instanceof Long) return N(n.longValue());
211 return N(n.doubleValue());
214 private static final JSNumber.I[] smallIntCache = new JSNumber.I[65535 / 4];
215 private static final JSNumber.I[] largeIntCache = new JSNumber.I[65535 / 4];
216 public static final JS N(int i) {
217 JSNumber.I ret = null;
218 int idx = i + smallIntCache.length / 2;
219 if (idx < smallIntCache.length && idx > 0) {
220 ret = smallIntCache[idx];
221 if (ret != null) return ret;
223 else ret = largeIntCache[Math.abs(idx % largeIntCache.length)];
224 if (ret == null || ret.i != i) {
225 ret = new JSNumber.I(i);
226 if (idx < smallIntCache.length && idx > 0) smallIntCache[idx] = ret;
227 else largeIntCache[Math.abs(idx % largeIntCache.length)] = ret;
232 private static Enumeration emptyEnumeration = new Enumeration() {
233 public boolean hasMoreElements() { return false; }
234 public Object nextElement() { throw new NoSuchElementException(); }
237 public static JS fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
238 return JSFunction._fromReader(sourceName, firstLine, sourceCode);
241 // HACK: caller can't know if the argument is a JSFunction or not...
242 public static JS cloneWithNewParentScope(JS j, JSScope s) {
243 return ((JSFunction)j)._cloneWithNewParentScope(s);
247 // Trap support //////////////////////////////////////////////////////////////////////////////
249 /** performs a put, triggering traps if present; traps are run in an unpauseable interpreter */
250 public void putAndTriggerTraps(JS key, JS value) throws JSExn {
251 Trap t = getTrap(key);
252 if (t != null) t.invoke(value);
253 else put(key, value);
256 /** performs a get, triggering traps if present; traps are run in an unpauseable interpreter */
257 public JS getAndTriggerTraps(JS key) throws JSExn {
258 Trap t = getTrap(key);
259 if (t != null) return t.invoke();
260 else return get(key);
263 /** adds a trap, avoiding duplicates */
264 final void addTrap(JS key, JSFunction f) throws JSExn {
265 if (f.numFormalArgs > 1) throw new JSExn("traps must take either one argument (write) or no arguments (read)");
266 boolean isRead = f.numFormalArgs == 0;
267 for(Trap t = getTrap(key); t != null; t = t.next) if (t.f == f) return;
268 putTrap(key, new Trap(this, key, f, (Trap)getTrap(key)));
271 /** deletes a trap, if present */
272 final void delTrap(JS key, JSFunction f) throws JSExn {
273 Trap t = (Trap)getTrap(key);
274 if (t == null) return;
275 if (t.f == f) { putTrap(t.name, t.next); return; }
276 for(; t.next != null; t = t.next) if (t.next.f == f) { t.next = t.next.next; return; }