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 public JS.Enumeration keys() throws JSExn { throw new JSExn("you can't enumerate the keys of this object (class=" + getClass().getName() +")"); }
18 public JS get(JS key) throws JSExn { return null; }
19 public void put(JS key, JS val) throws JSExn { throw new JSExn("" + key + " is read only (class=" + getClass().getName() +")"); }
21 public InputStream getInputStream() throws IOException {
22 throw new IOException("this object doesn't have a stream associated with it " + getClass().getName() + ")");
25 public final boolean hasTrap(JS key) { return getTrap(key) != null; }
27 public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
28 throw new JSExn("method not found (" + JS.debugToString(method) + ")");
31 public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
32 throw new JSExn("you cannot call this object (class=" + this.getClass().getName() +")");
35 public final boolean equals(Object o) { return this == o || ((o instanceof JS) && jsequals((JS)o)); }
37 // FIXME: Remove this, eventually
38 public final String toString() { throw new Error("you shouldn't use toString() on JS objects"); }
40 // These are only used internally by org.ibex.js
41 Trap getTrap(JS key) { return null; }
42 void putTrap(JS key, Trap value) throws JSExn { throw new JSExn("traps cannot be placed on this object (class=" + this.getClass().getName() +")"); }
43 String coerceToString() throws JSExn { throw new JSExn("can't coerce to a string (class=" + getClass().getName() +")"); }
44 String debugToString() { return "[class=" + getClass().getName() + "]"; }
45 boolean jsequals(JS o) { return this == o; }
47 public static class O extends JS {
50 public Enumeration keys() throws JSExn { return entries == null ? (Enumeration)EMPTY_ENUMERATION : (Enumeration)new JavaEnumeration(null,entries.keys()); }
51 public JS get(JS key) throws JSExn { return entries == null ? null : (JS)entries.get(key, null); }
52 public void put(JS key, JS val) throws JSExn { (entries==null?entries=new Hash():entries).put(key,null,val); }
54 /** retrieve a trap from the entries hash */
55 final Trap getTrap(JS key) {
56 return entries == null ? null : (Trap)entries.get(key, Trap.class);
59 /** retrieve a trap from the entries hash */
60 final void putTrap(JS key, Trap value) {
61 if (entries == null) entries = new Hash();
62 entries.put(key, Trap.class, value);
66 public static class BT extends O {
67 private BalancedTree bt;
68 private final BalancedTree bt() { if(bt != null) return bt; return bt = new BalancedTree(); }
69 public final void insertNode(int index, Object o) { bt().insertNode(index,o); }
70 public final void clear() { bt().clear(); }
71 public final Object getNode(int i) { return bt().getNode(i); }
72 public final int treeSize() { return bt().treeSize(); }
73 public final Object deleteNode(int i) { return bt().deleteNode(i); }
74 public final void replaceNode(int index, Object o) { bt().replaceNode(index,o); }
75 public final int indexNode(Object o) { return bt().indexNode(o); }
78 // FEATURE: JS.StringKeys
79 /* public static StringKeys extends JS {
80 public JS get(JS key) { return JS.isString(key) ? get(JS.toString(key) : null; }
84 JS _unclone() { return this; }
86 public interface Cloneable { }
88 public static class Clone extends JS.O implements Cloneable {
89 protected final JS clonee;
90 JS _unclone() { return clonee.unclone(); }
91 public JS getClonee() { return clonee; }
92 public Clone(JS clonee) throws JSExn {
93 if(!(clonee instanceof Cloneable)) throw new JSExn("" + clonee.getClass().getName() + " isn't cloneable");
96 public boolean jsequals(JS o) { return unclone().jsequals(o.unclone()); }
97 public Enumeration keys() throws JSExn { return clonee.keys(); }
98 public JS get(JS key) throws JSExn { return clonee.get(key); }
99 public void put(JS key, JS val) throws JSExn { clonee.put(key, val); }
100 public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
101 return clonee.callMethod(method, a0, a1, a2, rest, nargs);
103 public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
104 return clonee.call(a0, a1, a2, rest, nargs);
106 public InputStream getInputStream() throws IOException { return clonee.getInputStream(); }
109 public static abstract class Enumeration extends JS {
110 final Enumeration parent;
112 public Enumeration(Enumeration parent) { this.parent = parent; }
113 protected abstract boolean _hasMoreElements();
114 protected abstract JS _nextElement() throws JSExn;
116 public final boolean hasMoreElements() {
117 if(!done && !_hasMoreElements()) done = true;
118 return !done ? true : parent != null ? parent.hasMoreElements() : false;
120 public final JS nextElement() throws JSExn { return !done ? _nextElement() : parent != null ? parent.nextElement() : null; }
122 public JS get(JS key) throws JSExn {
123 //#switch(JS.toString(key))
124 case "hasMoreElements": return B(hasMoreElements());
125 case "nextElement": return nextElement();
127 return super.get(key);
130 public static class EmptyEnumeration extends Enumeration {
131 public EmptyEnumeration(Enumeration parent) { super(parent); }
132 protected boolean _hasMoreElements() { return false; }
133 protected JS _nextElement() { return null; }
135 public static class JavaEnumeration extends Enumeration {
136 private final java.util.Enumeration e;
137 public JavaEnumeration(Enumeration parent, java.util.Enumeration e) { super(parent); this.e = e; }
138 protected boolean _hasMoreElements() { return e.hasMoreElements(); }
139 protected JS _nextElement() { return (JS) e.nextElement(); }
142 // Static Interpreter Control Methods ///////////////////////////////////////////////////////////////
144 /** log a message with the current JavaScript sourceName/line */
145 public static void log(Object message) { info(message); }
146 public static void debug(Object message) { Log.debug(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
147 public static void info(Object message) { Log.info(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
148 public static void warn(Object message) { Log.warn(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
149 public static void error(Object message) { Log.error(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
151 public static class NotPauseableException extends Exception { NotPauseableException() { } }
153 /** returns a callback which will restart the context; expects a value to be pushed onto the stack when unpaused */
154 public static UnpauseCallback pause() throws NotPauseableException {
155 Interpreter i = Interpreter.current();
156 if (i.pausecount == -1) throw new NotPauseableException();
158 switch(i.f.op[i.pc]) {
159 case Tokens.RETURN: case ByteCodes.PUT: get = false; break;
160 case ByteCodes.GET: case ByteCodes.CALL: get = true; break;
161 default: throw new Error("should never happen");
164 return new JS.UnpauseCallback(i,get);
167 public static class UnpauseCallback implements Task {
168 private Interpreter i;
170 UnpauseCallback(Interpreter i, boolean get) { this.i = i; this.get = get; }
171 public void perform() throws JSExn { unpause(); }
172 public JS unpause() throws JSExn { return unpause((JS)null); }
173 public JS unpause(JS o) throws JSExn {
174 if (o == JS.METHOD) throw new JSExn("can't return a method to a paused context");
175 if(get) i.stack.push(o);
178 public JS unpause(JSExn e) throws JSExn {
186 // Static Helper Methods ///////////////////////////////////////////////////////////////////////////////////
188 /** coerce an object to a Boolean */
189 public static boolean toBoolean(JS o) {
190 if(o == null) return false;
191 if(o instanceof JSNumber) return ((JSNumber)o).toBoolean();
192 if(o instanceof JSString) return ((JSString)o).length() != 0;
195 //#repeat long/int/double/float toLong/toInt/toDouble/toFloat Long/Integer/Double/Float parseLong/parseInt/parseDouble/parseFloat
196 /** coerce an object to a Number */
197 public static long toLong(JS o) throws JSExn {
198 if(o == null) return 0;
199 if(o instanceof JSNumber) return ((JSNumber)o).toLong();
200 if(o instanceof JSString) return Long.parseLong(o.coerceToString());
201 throw new JSExn("can't coerce a " + o.getClass().getName() + " to a number");
205 public static String toString(JS o) throws JSExn {
206 if(o == null) return "null";
207 return o.coerceToString();
210 public static String debugToString(JS o) {
211 try { return toString(o); }
212 catch(JSExn e) { return o.debugToString(); }
215 public static boolean isInt(JS o) {
216 if(o == null) return true;
217 if(o instanceof JSNumber.I) return true;
218 if(o instanceof JSNumber.B) return false;
219 if(o instanceof JSNumber) {
220 JSNumber n = (JSNumber) o;
221 return n.toInt() == n.toDouble();
223 if(o instanceof JSString) {
224 String s = ((JSString)o).s;
225 for(int i=0;i<s.length();i++)
226 if(s.charAt(i) < '0' || s.charAt(i) > '9') return false;
232 public static boolean isString(JS o) {
233 if(o instanceof JSString) return true;
237 // Instance Methods ////////////////////////////////////////////////////////////////////
239 public final static JS NaN = new JSNumber.D(Double.NaN);
240 public final static JS ZERO = new JSNumber.I(0);
241 public final static JS ONE = new JSNumber.I(1);
243 public static final JS T = new JSNumber.B(true);
244 public static final JS F = new JSNumber.B(false);
246 public static final JS B(boolean b) { return b ? T : F; }
247 public static final JS B(int i) { return i==0 ? F : T; }
249 private static final int CACHE_SIZE = 65536 / 4; // must be a power of two
250 private static final JSString[] stringCache = new JSString[CACHE_SIZE];
251 public static final JS S(String s) {
252 if(s == null) return null;
253 int slot = s.hashCode()&(CACHE_SIZE-1);
254 JSString ret = stringCache[slot];
255 if(ret == null || !ret.s.equals(s)) stringCache[slot] = ret = new JSString(s);
259 public static final JS N(double d) { return new JSNumber.D(d); }
260 public static final JS N(long l) { return new JSNumber.L(l); }
262 public static final JS N(Number n) {
263 if(n instanceof Integer) return N(n.intValue());
264 if(n instanceof Long) return N(n.longValue());
265 return N(n.doubleValue());
268 private static final JSNumber.I[] smallIntCache = new JSNumber.I[CACHE_SIZE];
269 private static final JSNumber.I[] largeIntCache = new JSNumber.I[CACHE_SIZE];
270 public static final JS N(int i) {
271 JSNumber.I ret = null;
272 int idx = i + smallIntCache.length / 2;
273 if (idx < CACHE_SIZE && idx > 0) {
274 ret = smallIntCache[idx];
275 if (ret != null) return ret;
277 else ret = largeIntCache[Math.abs(idx % CACHE_SIZE)];
278 if (ret == null || ret.i != i) {
279 ret = new JSNumber.I(i);
280 if (idx < smallIntCache.length && idx > 0) smallIntCache[idx] = ret;
281 else largeIntCache[Math.abs(idx % CACHE_SIZE)] = ret;
286 private static Enumeration EMPTY_ENUMERATION = new EmptyEnumeration(null);
288 public static JS fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
289 return JSFunction._fromReader(sourceName, firstLine, sourceCode);
292 // HACK: caller can't know if the argument is a JSFunction or not...
293 public static JS cloneWithNewParentScope(JS j, JSScope s) {
294 return ((JSFunction)j)._cloneWithNewParentScope(s);
298 // Trap support //////////////////////////////////////////////////////////////////////////////
300 /** performs a put, triggering traps if present; traps are run in an unpauseable interpreter */
301 public void putAndTriggerTraps(JS key, JS value) throws JSExn {
302 Trap t = getTrap(key);
303 if (t != null) t.invoke(value);
304 else put(key, value);
307 /** performs a get, triggering traps if present; traps are run in an unpauseable interpreter */
308 public JS getAndTriggerTraps(JS key) throws JSExn {
309 Trap t = getTrap(key);
310 if (t != null) return t.invoke();
311 else return get(key);
314 /** adds a trap, avoiding duplicates */
315 final void addTrap(JS key, JSFunction f) throws JSExn {
316 if (f.numFormalArgs > 1) throw new JSExn("traps must take either one argument (write) or no arguments (read)");
317 boolean isRead = f.numFormalArgs == 0;
318 for(Trap t = getTrap(key); t != null; t = t.next) if (t.f == f) return;
319 putTrap(key, new Trap(this, key, f, (Trap)getTrap(key)));
322 /** deletes a trap, if present */
323 final void delTrap(JS key, JSFunction f) throws JSExn {
324 Trap t = (Trap)getTrap(key);
325 if (t == null) return;
326 if (t.f == f) { putTrap(t.name, t.next); return; }
327 for(; t.next != null; t = t.next) if (t.next.f == f) { t.next = t.next.next; return; }