added CALLMETHOD case to JS.pause()
[org.ibex.js.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 java.io.*;
6 import java.util.*;
7
8 /** The minimum set of functionality required for objects which are manipulated by JavaScript */
9 public abstract class JS { 
10     public static final JS METHOD = new JS() { };
11
12     public JS.Enumeration keys() throws JSExn { throw new JSExn("you can't enumerate the keys of this object (class=" + getClass().getName() +")"); }
13     public JS get(JS key) throws JSExn { return null; }
14     public void put(JS key, JS val) throws JSExn { throw new JSExn("" + key + " is read only (class=" + getClass().getName() +")"); }
15     
16     public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
17         throw new JSExn("method not found (" + JS.debugToString(method) + ")");
18     }
19     public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
20         throw new JSExn("you cannot call this object (class=" + this.getClass().getName() +")");
21     }
22     public InputStream getInputStream() throws IOException {
23         throw new IOException("this object doesn't have a stream associated with it " + getClass().getName() + ")");
24     }
25     
26     public final JS unclone() { return _unclone(); }
27     public final JS jsclone() throws JSExn { return new Clone(this); }
28     public final boolean hasTrap(JS key) { return getTrap(key) != null; }
29     public final boolean equals(Object o) { return this == o || ((o instanceof JS) && jsequals((JS)o)); }
30     // Discourage people from using toString()
31     public final String toString() { return "JS Object [class=" + getClass().getName() + "]"; }
32     
33     // Package private methods
34     Trap getTrap(JS key) { return null; }
35     void putTrap(JS key, Trap value) throws JSExn { throw new JSExn("traps cannot be placed on this object (class=" + this.getClass().getName() +")"); }
36     String coerceToString() throws JSExn { throw new JSExn("can't coerce to a string (class=" + getClass().getName() +")"); }
37     boolean jsequals(JS o) { return this == o; }
38     JS _unclone() { return this; }
39         
40     public static class O extends JS implements Cloneable {
41         private Hash entries;
42         
43         public Enumeration keys() throws JSExn { return entries == null ? (Enumeration)EMPTY_ENUMERATION : (Enumeration)new JavaEnumeration(null,entries.keys()); }
44         public JS get(JS key) throws JSExn { return entries == null ? null : (JS)entries.get(key, null); }
45         public void put(JS key, JS val) throws JSExn { (entries==null?entries=new Hash():entries).put(key,null,val); }        
46
47         /** retrieve a trap from the entries hash */
48         final Trap getTrap(JS key) {
49             return entries == null ? null : (Trap)entries.get(key, Trap.class);
50         }
51         
52         /** retrieve a trap from the entries hash */
53         final void putTrap(JS key, Trap value) {
54             if (entries == null) entries = new Hash();
55             entries.put(key, Trap.class, value);
56         }    
57     }
58     
59     public interface Cloneable { }
60         
61     public static class Clone extends O {
62         protected final JS clonee;
63         public Clone(JS clonee) throws JSExn {
64             if(!(clonee instanceof Cloneable)) throw new JSExn("" + clonee.getClass().getName() + " isn't cloneable");
65             this.clonee = clonee;
66         }
67         JS _unclone() { return clonee.unclone(); }
68         boolean jsequals(JS o) { return clonee.jsequals(o); }
69         
70         public Enumeration keys() throws JSExn { return clonee.keys(); }
71         public final JS get(JS key) throws JSExn { return clonee.get(key); }
72         public final void put(JS key, JS val) throws JSExn { clonee.put(key,val); }
73         public final JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
74             return clonee.callMethod(method,a0,a1,a2,rest,nargs); 
75         }
76         public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
77             return clonee.call(a0, a1, a2, rest, nargs);
78         }
79         public InputStream getInputStream() throws IOException { return clonee.getInputStream(); }
80         // FIXME: This shouldn't be necessary (its for Ibex.Blessing)
81         public JS getClonee() { return clonee; }
82     }
83     
84     public static abstract class Enumeration extends JS {
85         final Enumeration parent;
86         boolean done;
87         public Enumeration(Enumeration parent) { this.parent = parent; }
88         protected abstract boolean _hasMoreElements();
89         protected abstract JS _nextElement() throws JSExn;
90         
91         public final boolean hasMoreElements() {
92             if(!done && !_hasMoreElements()) done = true;
93             return !done ? true : parent != null ? parent.hasMoreElements() : false;
94         }
95         public final JS nextElement() throws JSExn { return !done ? _nextElement() : parent != null ? parent.nextElement() : null; }
96         
97         public JS get(JS key) throws JSExn {
98             //#switch(JS.toString(key))
99             case "hasMoreElements": return B(hasMoreElements());
100             case "nextElement": return nextElement();
101             //#end
102             return super.get(key);
103         }
104     }
105
106     public static class EmptyEnumeration extends Enumeration {
107         public EmptyEnumeration(Enumeration parent) { super(parent); }
108         protected boolean _hasMoreElements() { return false; }
109         protected JS _nextElement() { return null; }
110     }
111     public static class JavaEnumeration extends Enumeration {
112         private final java.util.Enumeration e;
113         public JavaEnumeration(Enumeration parent, java.util.Enumeration e) { super(parent); this.e = e; }
114         protected boolean _hasMoreElements() { return e.hasMoreElements(); }
115         protected JS _nextElement() { return (JS) e.nextElement(); }
116     }
117     
118     // Static Interpreter Control Methods ///////////////////////////////////////////////////////////////
119
120     /** log a message with the current JavaScript sourceName/line */
121     public static void log(Object message) { info(message); }
122     public static void debug(Object message) { Log.debug(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
123     public static void info(Object message) { Log.info(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
124     public static void warn(Object message) { Log.warn(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
125     public static void error(Object message) { Log.error(Interpreter.getSourceName() + ":" + Interpreter.getLine(), message); }
126
127     public static class NotPauseableException extends Exception { NotPauseableException() { } }
128
129     /** returns a callback which will restart the context; expects a value to be pushed onto the stack when unpaused */
130     public static UnpauseCallback pause() throws NotPauseableException {
131         Interpreter i = Interpreter.current();
132         if (i.pausecount == -1) throw new NotPauseableException();
133         boolean get;
134         switch(i.f.op[i.pc]) {
135             case Tokens.RETURN: case ByteCodes.PUT: get = false; break;
136             case ByteCodes.GET: case ByteCodes.CALL: case ByteCodes.CALLMETHOD: get = true; break;
137             default: throw new Error("should never happen: i.f.op[i.pc] == " + i.f.op[i.pc]);
138         }
139         i.pausecount++;
140         return new JS.UnpauseCallback(i,get);
141     }
142
143     public static class UnpauseCallback implements Task {
144         private Interpreter i;
145         private boolean get;
146         UnpauseCallback(Interpreter i, boolean get) { this.i = i; this.get = get; }
147         public void perform() throws JSExn { unpause(); }
148         public JS unpause() throws JSExn { return unpause((JS)null); }
149         public JS unpause(JS o) throws JSExn {
150             if (o == JS.METHOD) throw new JSExn("can't return a method to a paused context");
151             if(get) i.stack.push(o);
152             return i.resume();
153         }
154         public JS unpause(JSExn e) throws JSExn {
155             i.catchException(e);
156             return i.resume();
157         }
158     }
159
160
161
162     // Static Helper Methods ///////////////////////////////////////////////////////////////////////////////////
163
164     /** coerce an object to a Boolean */
165     public static boolean toBoolean(JS o) {
166         if(o == null) return false;
167         if(o instanceof JSNumber) return ((JSNumber)o).toBoolean();
168         if(o instanceof JSString) return ((JSString)o).s.length() != 0;
169         return true;
170     }
171     //#repeat long/int/double/float toLong/toInt/toDouble/toFloat Long/Integer/Double/Float parseLong/parseInt/parseDouble/parseFloat
172     /** coerce an object to a Number */
173     public static long toLong(JS o) throws JSExn {
174         if(o == null) return 0;
175         if(o instanceof JSNumber) return ((JSNumber)o).toLong();
176         if(o instanceof JSString) return Long.parseLong(o.coerceToString());
177         throw new JSExn("can't coerce a " + o.getClass().getName() + " to a number");
178     }
179     //#end
180     
181     public static String toString(JS o) throws JSExn {
182         if(o == null) return "null";
183         return o.coerceToString();
184     }
185     
186     public static String debugToString(JS o) {
187         try { return toString(o); }
188         catch(JSExn e) { return o.toString(); }
189     }
190     
191     public static boolean isInt(JS o) {
192         if(o == null) return true;
193         if(o instanceof JSNumber.I) return true;
194         if(o instanceof JSNumber.B) return false;
195         if(o instanceof JSNumber) {
196             JSNumber n = (JSNumber) o;
197             return n.toInt() == n.toDouble();
198         }
199         if(o instanceof JSString) {
200             String s = ((JSString)o).s;
201             for(int i=0;i<s.length();i++)
202                 if(s.charAt(i) < '0' || s.charAt(i) > '9') return false;
203             return true;
204         }
205         return false;
206     }
207     
208     public static boolean isString(JS o) {
209         if(o instanceof JSString) return true;
210         return false;
211     }
212     
213     // Instance Methods ////////////////////////////////////////////////////////////////////
214  
215     public final static JS NaN = new JSNumber.D(Double.NaN);
216     public final static JS ZERO = new JSNumber.I(0);
217     public final static JS ONE = new JSNumber.I(1);
218     public final static JS MATH = new JSMath();
219         
220     public static final JS T = new JSNumber.B(true);
221     public static final JS F = new JSNumber.B(false);
222
223     public static final JS B(boolean b) { return b ? T : F; }
224     public static final JS B(int i) { return i==0 ? F : T; }
225     
226     private static final int CACHE_SIZE = 65536 / 4; // must be a power of two
227     private static final JSString[] stringCache = new JSString[CACHE_SIZE];
228     public static final JS S(String s) {
229         if(s == null) return null;
230         int slot = s.hashCode()&(CACHE_SIZE-1);
231         JSString ret = stringCache[slot];
232         if(ret == null || !ret.s.equals(s)) stringCache[slot] = ret = new JSString(s);
233         return ret;
234     }
235     public static final JS S(String s, boolean intern) { return intern ? JSString.intern(s) : S(s); }
236
237     public static final JS N(double d) { return new JSNumber.D(d); }
238     public static final JS N(long l) { return new JSNumber.L(l); }
239     
240     public static final JS N(Number n) {
241         if(n instanceof Integer) return N(n.intValue());
242         if(n instanceof Long) return N(n.longValue());
243         return N(n.doubleValue());
244     }
245
246     private static final JSNumber.I[] smallIntCache = new JSNumber.I[CACHE_SIZE];
247     private static final JSNumber.I[] largeIntCache = new JSNumber.I[CACHE_SIZE];
248     public static final JS N(int i) {
249         JSNumber.I ret = null;
250         int idx = i + smallIntCache.length / 2;
251         if (idx < CACHE_SIZE && idx > 0) {
252             ret = smallIntCache[idx];
253             if (ret != null) return ret;
254         }
255         else ret = largeIntCache[Math.abs(idx % CACHE_SIZE)];
256         if (ret == null || ret.i != i) {
257             ret = new JSNumber.I(i);
258             if (idx < smallIntCache.length && idx > 0) smallIntCache[idx] = ret;
259             else largeIntCache[Math.abs(idx % CACHE_SIZE)] = ret;
260         }
261         return ret;
262     }
263     
264     private static Enumeration EMPTY_ENUMERATION = new EmptyEnumeration(null);
265     
266     public static JS fromReader(String sourceName, int firstLine, Reader sourceCode) throws IOException {
267         return Parser.fromReader(sourceName, firstLine, sourceCode);
268     }
269
270     public static JS cloneWithNewGlobalScope(JS js, JS s) {
271         if(js instanceof JSFunction)
272             return ((JSFunction)js)._cloneWithNewParentScope(new JSScope.Top(s));
273         else
274             return js;
275     }
276
277
278     // Trap support //////////////////////////////////////////////////////////////////////////////
279
280     /** performs a put, triggering traps if present; traps are run in an unpauseable interpreter */
281     public final void putAndTriggerTraps(JS key, JS value) throws JSExn {
282         Trap t = getTrap(key);
283         if(t == null || (t = t.writeTrap()) == null) put(key,value);
284         else new Interpreter(t,value,false).resume();
285     }
286
287     /** performs a get, triggering traps if present; traps are run in an unpauseable interpreter */
288     public final JS getAndTriggerTraps(JS key) throws JSExn {
289         Trap t = getTrap(key);
290         if (t == null || (t = t.readTrap()) == null) return get(key);
291         else return new Interpreter(t,null,false).resume();
292     }
293     
294     public final JS justTriggerTraps(JS key, JS value) throws JSExn {
295         Trap t = getTrap(key);
296         if(t == null || (t = t.writeTrap()) == null) return value;
297         else return new Interpreter(t,value,true).resume();
298     }
299
300     /** adds a trap, avoiding duplicates */
301     // FIXME: This shouldn't be public, it is needed for a hack in Template.java
302     public void addTrap(JS key, JSFunction f) throws JSExn {
303         if (f.numFormalArgs > 1) throw new JSExn("traps must take either one argument (write) or no arguments (read)");
304         boolean isRead = f.numFormalArgs == 0;
305         for(Trap t = getTrap(key); t != null; t = t.next) if (t.f == f) return;
306         putTrap(key, new Trap(this, key, f, (Trap)getTrap(key)));
307     }
308
309     /** deletes a trap, if present */
310     // FIXME: This shouldn't be public, it is needed for a hack in Template.java
311     public void delTrap(JS key, JSFunction f) throws JSExn {
312         Trap t = (Trap)getTrap(key);
313         if (t == null) return;
314         if (t.f == f) { putTrap(t.target, t.next); return; }
315         for(; t.next != null; t = t.next) if (t.next.f == f) { t.next = t.next.next; return; }
316     }
317
318
319