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 JS _unclone() { return this; }
77 public interface Cloneable { }
79 public static class Clone extends JS.O implements Cloneable {
80 protected final JS clonee;
81 JS _unclone() { return clonee.unclone(); }
82 public JS getClonee() { return clonee; }
83 public Clone(JS clonee) throws JSExn {
84 if(!(clonee instanceof Cloneable)) throw new JSExn("" + getClass().getName() + " isn't cloneable");
87 public boolean jsequals(JS o) { return unclone().jsequals(o.unclone()); }
88 public Enumeration keys() throws JSExn { return clonee.keys(); }
89 public JS get(JS key) throws JSExn { return clonee.get(key); }
90 public void put(JS key, JS val) throws JSExn { clonee.put(key, val); }
91 public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
92 return clonee.callMethod(method, a0, a1, a2, rest, nargs);
94 public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
95 return clonee.call(a0, a1, a2, rest, nargs);
99 // Static Interpreter Control Methods ///////////////////////////////////////////////////////////////
101 /** log a message with the current JavaScript sourceName/line */
102 public static void log(Object message) { info(message); }
103 public static void debug(Object message) { Log.debug(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
104 public static void info(Object message) { Log.info(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
105 public static void warn(Object message) { Log.warn(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
106 public static void error(Object message) { Log.error(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
108 public static class NotPauseableException extends Exception { NotPauseableException() { } }
110 /** returns a callback which will restart the context; expects a value to be pushed onto the stack when unpaused */
111 public static UnpauseCallback pause() throws NotPauseableException {
112 Interpreter i = Interpreter.current();
113 if (i.pausecount == -1) throw new NotPauseableException();
115 return new JS.UnpauseCallback(i);
118 public static class UnpauseCallback implements Task {
120 UnpauseCallback(Interpreter i) { this.i = i; }
121 public void perform() throws JSExn { unpause((JS)null); }
122 public void unpause(JS o) throws JSExn {
126 public void unpause(JSExn e) {
127 // FIXME: Throw the JSExn into the js world
128 throw new Error("Exception " + e + " thrown from background task");
134 // Static Helper Methods ///////////////////////////////////////////////////////////////////////////////////
136 /** coerce an object to a Boolean */
137 public static boolean toBoolean(JS o) {
138 if(o == null) return false;
139 if(o instanceof JSNumber) return ((JSNumber)o).toBoolean();
140 if(o instanceof JSString) return ((JSString)o).length() != 0;
143 //#repeat long/int/double/float toLong/toInt/toDouble/toFloat Long/Integer/Double/Float parseLong/parseInt/parseDouble/parseFloat
144 /** coerce an object to a Number */
145 public static long toLong(JS o) throws JSExn {
146 if(o == null) return 0;
147 if(o instanceof JSNumber) return ((JSNumber)o).toLong();
148 if(o instanceof JSString) return Long.parseLong(o.coerceToString());
149 throw new JSExn("can't coerce a " + o.getClass().getName() + " to a number");
153 public static String toString(JS o) throws JSExn {
154 if(o == null) return "null";
155 return o.coerceToString();
158 public static String debugToString(JS o) {
159 try { return toString(o); }
160 catch(JSExn e) { return "[class=" + o.getClass().getName() + "]"; }
163 public static boolean isInt(JS o) {
164 if(o == null) return true;
165 if(o instanceof JSNumber.I) return true;
166 if(o instanceof JSNumber.B) return false;
167 if(o instanceof JSNumber) {
168 JSNumber n = (JSNumber) o;
169 return n.toInt() == n.toDouble();
171 if(o instanceof JSString) {
172 String s = ((JSString)o).s;
173 for(int i=0;i<s.length();i++)
174 if(s.charAt(i) < '0' || s.charAt(i) > '9') return false;
180 public static boolean isString(JS o) {
181 if(o instanceof JSString) return true;
185 // Instance Methods ////////////////////////////////////////////////////////////////////
187 public final static JS NaN = new JSNumber.D(Double.NaN);
188 public final static JS ZERO = new JSNumber.I(0);
189 public final static JS ONE = new JSNumber.I(1);
191 public static final JS T = new JSNumber.B(true);
192 public static final JS F = new JSNumber.B(false);
194 public static final JS B(boolean b) { return b ? T : F; }
195 public static final JS B(int i) { return i==0 ? F : T; }
197 public static final JS S(String s) { return new JSString(s); }
199 public static final JS N(double d) { return new JSNumber.D(d); }
200 public static final JS N(long l) { return new JSNumber.L(l); }
202 public static final JS N(Number n) {
203 if(n instanceof Integer) return N(n.intValue());
204 if(n instanceof Long) return N(n.longValue());
205 return N(n.doubleValue());
208 private static final JSNumber.I[] smallIntCache = new JSNumber.I[65535 / 4];
209 private static final JSNumber.I[] largeIntCache = new JSNumber.I[65535 / 4];
210 public static final JS N(int i) {
211 JSNumber.I ret = null;
212 int idx = i + smallIntCache.length / 2;
213 if (idx < smallIntCache.length && idx > 0) {
214 ret = smallIntCache[idx];
215 if (ret != null) return ret;
217 else ret = largeIntCache[Math.abs(idx % largeIntCache.length)];
218 if (ret == null || ret.i != i) {
219 ret = new JSNumber.I(i);
220 if (idx < smallIntCache.length && idx > 0) smallIntCache[idx] = ret;
221 else largeIntCache[Math.abs(idx % largeIntCache.length)] = ret;
226 private static Enumeration emptyEnumeration = new Enumeration() {
227 public boolean hasMoreElements() { return false; }
228 public Object nextElement() { throw new NoSuchElementException(); }
231 public static JS fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
232 return JSFunction._fromReader(sourceName, firstLine, sourceCode);
235 // HACK: caller can't know if the argument is a JSFunction or not...
236 public static JS cloneWithNewParentScope(JS j, JSScope s) {
237 return ((JSFunction)j)._cloneWithNewParentScope(s);
241 // Trap support //////////////////////////////////////////////////////////////////////////////
243 /** performs a put, triggering traps if present; traps are run in an unpauseable interpreter */
244 public void putAndTriggerTraps(JS key, JS value) throws JSExn {
245 Trap t = getTrap(key);
246 if (t != null) t.invoke(value);
247 else put(key, value);
250 /** performs a get, triggering traps if present; traps are run in an unpauseable interpreter */
251 public JS getAndTriggerTraps(JS key) throws JSExn {
252 Trap t = getTrap(key);
253 if (t != null) return t.invoke();
254 else return get(key);
257 /** adds a trap, avoiding duplicates */
258 final void addTrap(JS key, JSFunction f) throws JSExn {
259 if (f.numFormalArgs > 1) throw new JSExn("traps must take either one argument (write) or no arguments (read)");
260 boolean isRead = f.numFormalArgs == 0;
261 for(Trap t = getTrap(key); t != null; t = t.next) if (t.f == f) return;
262 putTrap(key, new Trap(this, key, f, (Trap)getTrap(key)));
265 /** deletes a trap, if present */
266 final void delTrap(JS key, JSFunction f) throws JSExn {
267 Trap t = (Trap)getTrap(key);
268 if (t == null) return;
269 if (t.f == f) { putTrap(t.name, t.next); return; }
270 for(; t.next != null; t = t.next) if (t.next.f == f) { t.next = t.next.next; return; }