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