2003/10/15 21:43:01
[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 java.io.*;
6 import java.util.*;
7
8 /**
9  *  The public API for the JS engine.  JS itself is actually a class
10  *  implementing the absolute minimal amount of functionality for an
11  *  Object which can be manipulated by JavaScript code.  The static
12  *  methods, fields, and inner classes of JS define the publicly
13  *  visible API for the XWT JavaScript engine; code outside this
14  *  package should never depend on anything not defined in this file.
15  */
16 public abstract class JS { 
17
18
19     // Public Helper Methods //////////////////////////////////////////////////////////////////////
20
21     /** parse and compile a function */
22     public static CompiledFunction parse(String sourceName, int firstLine, Reader sourceCode) throws IOException {
23         return new CompiledFunction(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) try { return new Double((String)o); } catch (NumberFormatException e) { return new Double(Double.NaN); }
58         if (o instanceof Boolean) return ((Boolean)o).booleanValue() ? new Long(1) : new Long(0);
59         if (o instanceof JS) return ((JS)o).coerceToNumber();
60         throw new Error("toNumber() got object of type " + o.getClass().getName() + " which we don't know how to handle");
61     }
62     
63     /** coerce an object to a String */
64     public static String toString(Object o) {
65         if(o == null) return "null";
66         if(o instanceof String) return (String) o;
67         if(o instanceof Integer || o instanceof Long || o instanceof Boolean) return o.toString();
68         if(o instanceof JS) return ((JS)o).coerceToString();
69         if(o instanceof Double || o instanceof Float) {
70             double d = ((Number)o).doubleValue();
71             if((int)d == d) return Integer.toString((int)d);
72             return o.toString();
73         }
74         return o.toString();
75     }
76     
77     // Instance Methods ////////////////////////////////////////////////////////////////////
78  
79     public abstract Object get(Object key) throws JS.Exn; 
80     public abstract void put(Object key, Object val) throws JS.Exn; 
81     public abstract Object[] keys(); 
82     public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
83         if(checkOnly) return Boolean.FALSE;
84         Object o = get(method);
85         if(o instanceof JS.Callable) {
86             return ((JS.Callable)o).call(args);
87         } else if(o == null) {
88             throw new JS.Exn("Attempted to call non-existent method: " + method);
89         } else {
90             throw new JS.Exn("Attempted to call a non-method: " +method);
91         }
92     }
93     
94     public Number coerceToNumber() { return new Integer(0); }
95     public String coerceToString() { throw new JS.Exn("tried to coerce a JavaScript object to a String"); }
96     public boolean coerceToBoolean() { return true; }
97     
98     public String typeName() { return "object"; }
99
100
101     // Inner Classes /////////////////////////////////////////////////////////////////////////
102
103     /** A sensible implementation of the abstract methods in the JS class */
104     public static class Obj extends JS {
105         private Hash entries = null;
106         private boolean sealed = false;
107         public Obj() { this(false); }
108         public Obj(boolean sealed) { this.sealed = sealed; }
109         public void setSeal(boolean sealed) { this.sealed = sealed; }      ///< a sealed object cannot have its properties modified
110         public void put(Object key, Object val) { put(key, null, val); }
111         protected void put(Object key, Object key2, Object val) {
112             if (sealed) return;
113             if (entries == null) entries = new Hash();
114             entries.put(key, key2, val); }
115         public Object[] keys() { return entries == null ? new Object[0] : entries.keys(); }
116         public Object get(Object key) { return get(key, null); }
117         protected Object get(Object key, Object key2) {
118             if (entries == null) return null;
119             if(key2 == null && callMethod((String)key, null, true) == Boolean.TRUE)
120                 return new Internal.CallableStub(this, key);
121             return entries.get(key, key2);
122         }
123     }
124
125     /** An exception which can be thrown and caught by JavaScript code */
126     public static class Exn extends RuntimeException { 
127         private Object js = null; 
128         public Exn(Object js) { this.js = js; } 
129         public String toString() { return "JS.Exn: " + js; }
130         public String getMessage() { return toString(); }
131         public Object getObject() { return js; } 
132     } 
133
134     /** The publicly-visible face of JavaScript Array objects */
135     public static class Array extends ArrayImpl {
136         public Array() { }
137         public Array(int size) { super(size); }
138         public void setSize(int i) { super.setSize(i); }
139         public int length() { return super.length(); }
140         public Object elementAt(int i) { return super.elementAt(i); }
141         public void addElement(Object o) { super.addElement(o); }
142         public void setElementAt(Object o, int i) { super.setElementAt(o, i); }
143         public Object get(Object key) { return super._get(key); }
144         public void put(Object key, Object val) { super._put(key, val); }
145     }
146
147     /** Any object which becomes part of the scope chain must support this interface */ 
148     public static class Scope extends ScopeImpl { 
149         public Scope(Scope parentScope) { this(parentScope, false); }
150         public Scope(Scope parentScope, boolean sealed) { super(parentScope, sealed); }
151         /** transparent scopes are not returned by THIS */
152         public boolean isTransparent() { return super.isTransparent(); }
153         public boolean has(Object key) { return super.has(key); }
154         public Object get(Object key) { return super._get(key); }
155         public void put(Object key, Object val) { super._put(key, val); }
156         public void declare(String s) { super.declare(s); }
157     } 
158
159     /** the result of a graft */
160     public static class Graft extends JS {
161         private JS graftee;
162         private Object replaced_key;
163         private Object replaced_val;
164         public Graft(JS graftee, Object key, Object val) {
165             if (graftee instanceof Array) throw new JS.Exn("can't graft onto Arrays (yet)");
166             if (graftee instanceof Callable) throw new JS.Exn("can't graft onto Callables (yet)");
167             if (graftee instanceof Scope) throw new JS.Exn("can't graft onto Scopes (yet)");
168             this.graftee = graftee;
169             replaced_key = key;
170             replaced_val = val;
171         }
172         public boolean equals(Object o) { return (this == o || graftee.equals(o)); }
173         public int hashCode() { return graftee.hashCode(); }
174         public Object get(Object key) { return replaced_key.equals(key) ? replaced_val : graftee.get(key); }
175         public void put(Object key, Object val) { graftee.put(key, val); }
176         public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
177             if (!replaced_key.equals(method)) return graftee.callMethod(method, args, checkOnly);
178             if (replaced_val instanceof Callable) return checkOnly ? Boolean.TRUE : ((Callable)replaced_val).call(args);
179             if (checkOnly) return Boolean.FALSE;
180             throw new JS.Exn("attempt to call non-function");
181         }
182         public Number coerceToNumber() { return graftee.coerceToNumber(); }
183         public String coerceToString() { return graftee.coerceToString(); }
184         public boolean coerceToBoolean() { return graftee.coerceToBoolean(); }
185         public String typeName() { return graftee.typeName(); }
186         public Object[] keys() {
187             Object[] ret = graftee.keys();
188             for(int i=0; i<ret.length; i++) if (replaced_key.equals(ret[i])) return ret;
189             Object[] ret2 = new Object[ret.length + 1];
190             System.arraycopy(ret, 0, ret2, 0, ret.length);
191             ret2[ret2.length - 1] = replaced_key;
192             return ret2;
193         }
194     }
195
196     /** anything that is callable with the () operator */
197     public static abstract class Callable extends JS.Obj {
198         public abstract Object call(JS.Array args) throws JS.Exn;
199     }
200
201     /** a Callable which was compiled from JavaScript code */
202     public static class CompiledFunction extends CompiledFunctionImpl {
203         public int getNumFormalArgs() { return numFormalArgs; }
204         CompiledFunction(String sourceName, int firstLine, Reader sourceCode, Scope scope) throws IOException {
205             super(sourceName, firstLine, sourceCode, scope);
206         }
207     }
208     
209     /** a scope that is populated with js objects and functions normally found in the global scope */
210     public static class GlobalScope extends GlobalScopeImpl {
211         public GlobalScope() { this(null); }
212         public GlobalScope(JS.Scope parent) { super(parent); }
213     }
214
215     public static final JS Math = new org.xwt.js.Math();
216  
217     /** encapsulates a single JavaScript thread; the JS.Thread->java.lang.Thread mapping is 1:1 */
218     public static class Thread {
219
220         CompiledFunction currentCompiledFunction = null;
221         Vec stack = new Vec();
222         int pc;
223
224         /** binds this thread to the current Java Thread */
225         public void bindToCurrentJavaThread() { javaThreadToJSThread.put(java.lang.Thread.currentThread(), this); }
226
227         /** returns the line of code that is currently executing */
228         public int getLine() { return currentCompiledFunction == null ? -1 : currentCompiledFunction.getLine(pc); }
229
230         /** returns the name of the source code file which declared the currently executing function */
231         public String getSourceName() { return currentCompiledFunction == null ? null : currentCompiledFunction.getSourceName();  }
232
233         /** fetches the currently-executing javascript function */
234         public JS.CompiledFunction getCurrentCompiledFunction() { return currentCompiledFunction; }
235
236
237         // Statics ///////////////////////////////////////////////////////////////////////
238
239         private static Hashtable javaThreadToJSThread = new Hashtable();
240
241         /** returns the JS thread for a given Java thread, creating one if necessary */
242         public static JS.Thread fromJavaThread(java.lang.Thread t) {
243             JS.Thread ret = (JS.Thread)javaThreadToJSThread.get(t);
244             if (ret == null) {
245                 ret = new JS.Thread();
246                 ret.bindToCurrentJavaThread();
247             }
248             return ret;
249         }
250         
251         public static JS.Thread currentJSThread() {
252             return fromJavaThread(java.lang.Thread.currentThread());
253         }
254     }
255
256
257
258
259