79800fe2ed47cae34ae76666dbf5b9a6341d814a
[org.ibex.core.git] / src / org / xwt / js / JS.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL] 
2
3 package org.xwt.js; 
4 import org.xwt.util.*; 
5 import org.xwt.*; 
6 import java.io.*;
7 import java.util.*;
8
9 /**
10  *  The public API for the JS engine.  JS itself is actually a class
11  *  implementing the absolute minimal amount of functionality for an
12  *  Object which can be manipulated by JavaScript code.  The static
13  *  methods, fields, and inner classes of JS define the publicly
14  *  visible API for the XWT JavaScript engine; code outside this
15  *  package should never depend on anything not defined in this file.
16  */
17 public abstract class JS { 
18
19     // Public Helper Methods //////////////////////////////////////////////////////////////////////
20
21     /** parse and compile a function */
22     public static Function parse(String sourceName, int firstLine, Reader sourceCode) throws IOException {
23         return new Function(sourceName, firstLine, sourceCode, null);
24     }
25
26     /** coerce an object to a Boolean */
27     public static boolean toBoolean(Object o) {
28         if (o == null) return false;
29         if (o instanceof Boolean) return ((Boolean)o).booleanValue();
30         if (o instanceof Long) return ((Long)o).longValue() != 0;
31         if (o instanceof Integer) return ((Integer)o).intValue() != 0;
32         if (o instanceof Number) {
33             double d = ((Number) o).doubleValue();
34             // NOTE: d == d is a test for NaN. It should be faster than Double.isNaN()
35             return d != 0.0 && d == d;
36         }
37         if (o instanceof String) return ((String)o).length() != 0;
38         return true;
39     }
40
41     /** coerce an object to a Long */
42     public static long toLong(Object o) { return toNumber(o).longValue(); }
43
44     /** coerce an object to an Int */
45     public static int toInt(Object o) { return toNumber(o).intValue(); }
46
47     /** coerce an object to a Double */
48     public static double toDouble(Object o) { return toNumber(o).doubleValue(); }
49
50     /** coerce an object to a Number */
51     public static Number toNumber(Object o) {
52         if (o == null) return new Long(0);
53         if (o instanceof Number) return ((Number)o);
54
55         // NOTE: There are about 3 pages of rules in ecma262 about string to number conversions
56         //       We aren't even close to following all those rules.  We probably never will be.
57         if (o instanceof String)
58             try { return new Double((String)o); } catch (NumberFormatException e) { return new Double(Double.NaN); }
59         if (o instanceof Boolean) return ((Boolean)o).booleanValue() ? new Long(1) : new Long(0);
60         if (o instanceof JS) return ((JS)o).coerceToNumber();
61         throw new Error("toNumber() got object of type " + o.getClass().getName() + " which we don't know how to handle");
62     }
63     
64     /** coerce an object to a String */
65     public static String toString(Object o) {
66         if(o == null) return "null";
67         if(o instanceof String) return (String) o;
68         if(o instanceof Integer || o instanceof Long || o instanceof Boolean) return o.toString();
69         if(o instanceof JS) return ((JS)o).coerceToString();
70         if(o instanceof Double || o instanceof Float) {
71             double d = ((Number)o).doubleValue();
72             if((int)d == d) return Integer.toString((int)d);
73             return o.toString();
74         }
75         return o.toString();
76     }
77     
78     // Instance Methods ////////////////////////////////////////////////////////////////////
79  
80     public abstract Object get(Object key) throws JS.Exn; 
81     public abstract Object put(Object key, Object val) throws JS.Exn; 
82     public abstract Object[] keys(); 
83
84     public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
85         if(checkOnly) return Boolean.FALSE;
86         Object o = get(method);
87         if(o instanceof JS.Callable) {
88             return ((JS.Callable)o).call(args);
89         } else if(o == null) {
90             throw new JS.Exn("Attempted to call non-existent method: " + method);
91         } else {
92             throw new JS.Exn("Attempted to call a non-method: " +method);
93         }
94     }
95     
96     public Number coerceToNumber() { throw new JS.Exn("tried to coerce a JavaScript object to a Number"); }
97     public String coerceToString() { throw new JS.Exn("tried to coerce a JavaScript object to a String"); }
98     public boolean coerceToBoolean() { throw new JS.Exn("tried to coerce a JavaScript object to a Boolean"); }
99     public String typeName() { return "object"; }
100
101
102     // Inner Classes /////////////////////////////////////////////////////////////////////////
103
104     /** A sensible implementation of the abstract methods in the JS class */
105     public static class Obj extends JS {
106         // this gets around a wierd fluke in the Java type checking rules for ?..:
107         public static final Object T = Boolean.TRUE;
108         public static final Object F = Boolean.FALSE;
109         private Hash entries = null;
110         private boolean sealed = false;
111         public Obj() { this(false); }
112         public Obj(boolean sealed) { this.sealed = sealed; }
113         public void setSeal(boolean sealed) { this.sealed = sealed; }      ///< a sealed object cannot have its properties modified
114         public Object put(Object key, Object val) { put2(key, null, val); return null; }
115         protected void put2(Object key, Object key2, Object val) {
116             if (sealed) return;
117             if (entries == null) entries = new Hash();
118             entries.put(key, key2, val); }
119         public Object[] keys() { return entries == null ? new Object[0] : entries.keys(); }
120         public Object get(Object key) { return get(key, null); }
121         protected Object get(Object key, Object key2) {
122             if (entries == null) return null;
123             if(key2 == null && callMethod((String)key, null, true) == Boolean.TRUE)
124                 return new Internal.CallableStub(this, key);
125             return entries.get(key, key2);
126         }
127     }
128
129     /** An exception which can be thrown and caught by JavaScript code */
130     public static class Exn extends RuntimeException { 
131         private Object js = null; 
132         public Exn(Object js) { this.js = js; } 
133         public String toString() { return "JS.Exn: " + js; }
134         public String getMessage() { return toString(); }
135         public Object getObject() { return js; } 
136     } 
137
138     /** The publicly-visible face of JavaScript Array objects */
139     public static class Array extends ArrayImpl {
140         public Array() { }
141         public Array(int size) { super(size); }
142         public void setSize(int i) { super.setSize(i); }
143         public int length() { return super.length(); }
144         public Object elementAt(int i) { return super.elementAt(i); }
145         public void addElement(Object o) { super.addElement(o); }
146         public void setElementAt(Object o, int i) { super.setElementAt(o, i); }
147         public Object get(Object key) { return super._get(key); }
148         public Object put(Object key, Object val) { super._put(key, val); return null; }
149     }
150
151     /** Any object which becomes part of the scope chain must support this interface */ 
152     public static class Scope extends ScopeImpl { 
153         public Scope(Scope parentScope) { this(parentScope, false); }
154         public Scope(Scope parentScope, boolean sealed) { super(parentScope, sealed); }
155         public boolean has(Object key) { return super.has(key); }
156         public Object get(Object key) { return super._get(key); }
157         public Object put(Object key, Object val) { super._put(key, val); return null; }
158         public void declare(String s) { super.declare(s); }
159     } 
160
161     /** the result of a graft */
162     public static class Graft extends JS {
163         private JS graftee;
164         private Object replaced_key;
165         private Object replaced_val;
166         public Graft(JS graftee, Object key, Object val) {
167             if (graftee instanceof Array) throw new JS.Exn("can't graft onto Arrays (yet)");
168             if (graftee instanceof Callable) throw new JS.Exn("can't graft onto Callables (yet)");
169             if (graftee instanceof Scope) throw new JS.Exn("can't graft onto Scopes (yet)");
170             this.graftee = graftee;
171             replaced_key = key;
172             replaced_val = val;
173         }
174         public boolean equals(Object o) { return (this == o || graftee.equals(o)); }
175         public int hashCode() { return graftee.hashCode(); }
176         public Object get(Object key) { return replaced_key.equals(key) ? replaced_val : graftee.get(key); }
177         public Object put(Object key, Object val) { graftee.put(key, val); return null; }
178         public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
179             if (!replaced_key.equals(method)) return graftee.callMethod(method, args, checkOnly);
180             if (replaced_val instanceof Callable) return checkOnly ? Boolean.TRUE : ((Callable)replaced_val).call(args);
181             if (checkOnly) return Boolean.FALSE;
182             throw new JS.Exn("attempt to call non-function");
183         }
184         public Number coerceToNumber() { return graftee.coerceToNumber(); }
185         public String coerceToString() { return graftee.coerceToString(); }
186         public boolean coerceToBoolean() { return graftee.coerceToBoolean(); }
187         public String typeName() { return graftee.typeName(); }
188         public Object[] keys() {
189             Object[] ret = graftee.keys();
190             for(int i=0; i<ret.length; i++) if (replaced_key.equals(ret[i])) return ret;
191             Object[] ret2 = new Object[ret.length + 1];
192             System.arraycopy(ret, 0, ret2, 0, ret.length);
193             ret2[ret2.length - 1] = replaced_key;
194             return ret2;
195         }
196     }
197
198     /** anything that is callable with the () operator and wasn't compiled from JS code */
199     public static abstract class Callable extends JS.Obj {
200         public abstract Object call(JS.Array args) throws JS.Exn;
201     }
202
203     /** a scope that is populated with js objects and functions normally found in the global scope */
204     public static class GlobalScope extends GlobalScopeImpl {
205         public GlobalScope() { this(null); }
206         public GlobalScope(JS.Scope parent) { super(parent); }
207     }
208
209     public static class TailCall {
210         Function func = null;
211         JS.Array args = null;
212         public TailCall() { }
213         public TailCall set(Function func) { this.func = func; this.args = new JS.Array(); return this; }
214         public TailCall set(Function func, JS.Array args) { this.func = func; this.args = args; return this; }
215     }
216  
217     /** encapsulates the state of a JavaScript "thread" (ie stack) */
218     public static class Context {
219
220
221         // Statics //////////////////////////////////////////////////////////////////////
222
223         /**
224          *  Return this from call/get/put in order to make the interpreter pause.  The interpreter will expect a value
225          *  (the return from the call or the get) to be pushed onto the stack when it is resumed.
226          */
227         public static Object pause = new Object();
228
229         private int getLine_() { return current().f == null ? -1 : (pc < 0 || pc >= f.size) ? -1 : f.line[pc]; }
230         public static int getLine() { return current().getLine_(); }
231         public static String getSourceName() { return current().f == null ? null : current().f.sourceName; } 
232
233         /** fetches the currently-executing javascript function */
234         public static JS.Context current() { return (JS.Context)threadToContext.get(Thread.currentThread()); }
235         private static Hashtable threadToContext = new Hashtable();
236
237
238         // Instance members and methods //////////////////////////////////////////////////////////////////////
239
240         /** the currently-executing Function */
241         Function f = null;
242
243         /** the currently-executing scope */
244         public Scope scope = null;  // FIXME: do we really need this?  the function should contain this info
245
246         /** the object stack */
247         Vec stack = new Vec();
248
249         /** the program counter */
250         int pc = 0;
251
252         public Context(Function function, Scope scope) {
253             if (scope == null) scope = new Scope(function.parentScope);
254             stack.push(new Function.CallMarker(this));
255             stack.push(new JS.Array());
256             this.f = function;
257             this.scope = scope;
258         }
259
260         public Object resume() { return resume(null); }
261         public Object resume(Object o) {
262             Thread t = Thread.currentThread();
263             Context old = (Context)threadToContext.get(t);
264             try {
265                 threadToContext.put(t, this);
266                 stack.push(o);
267                 return Function.eval(this);
268             } finally {
269                 if (old == null) threadToContext.remove(t);
270                 else threadToContext.put(t, old);
271             }
272         }
273
274     }
275
276     public static void recurse(String indent, String name, Object o) {
277         if (!name.equals("")) name += " : ";
278
279         if (o == null) {
280             Log.logJS(indent + name + "<null>");
281
282         } else if (o instanceof JS.Array) {
283             Log.logJS(indent + name + "<array>");
284             JS.Array na = (JS.Array)o;
285             for(int i=0; i<na.length(); i++)
286                 recurse(indent + "  ", i + "", na.elementAt(i));
287
288         } else if (o instanceof JS) {
289             Log.logJS(indent + name + "<object>");
290             JS s = (JS)o;
291             Object[] keys = s.keys();
292             for(int i=0; i<keys.length; i++)
293                 if (keys[i] != null)
294                     recurse(indent + "  ", keys[i].toString(),
295                             (keys[i] instanceof Integer) ?
296                             s.get(((Integer)keys[i])) : s.get(keys[i].toString()));
297
298         } else {
299             Log.logJS(indent + name + o);
300
301         }
302     }
303
304
305
306
307
308