ea12dfbe77fadd022a1e8cf8c594d3cd5a1d2885
[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         // FIXME: There are about 3 pages of rules in ecma262 about string to number conversions
55         // We aren't even close to following all those rules
56         if (o instanceof String) try { return new Double((String)o); } catch (NumberFormatException e) { return new Double(Double.NaN); }
57         if (o instanceof Boolean) return ((Boolean)o).booleanValue() ? new Long(1) : new Long(0);
58         if (o instanceof JS) return ((JS)o).coerceToNumber();
59         throw new Error("toNumber() got object of type " + o.getClass().getName() + " which we don't know how to handle");
60     }
61     
62     /** coerce an object to a String */
63     public static String toString(Object o) {
64         if(o == null) return "null";
65         if(o instanceof String) return (String) o;
66         if(o instanceof Integer || o instanceof Long || o instanceof Boolean) return o.toString();
67         if(o instanceof JS) return ((JS)o).coerceToString();
68         if(o instanceof Double || o instanceof Float) {
69             double d = ((Number)o).doubleValue();
70             if((int)d == d) return Integer.toString((int)d);
71             return o.toString();
72         }
73         return o.toString();
74     }
75     
76     // Instance Methods ////////////////////////////////////////////////////////////////////
77  
78     public abstract Object get(Object key) throws JS.Exn; 
79     public abstract void put(Object key, Object val) throws JS.Exn; 
80     public abstract Object[] keys(); 
81     public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
82         if(checkOnly) return Boolean.FALSE;
83         Object o = get(method);
84         if(o instanceof JS.Callable) {
85             return ((JS.Callable)o).call(args);
86         } else if(o == null) {
87             throw new JS.Exn("Attempted to call non-existent method: " + method);
88         } else {
89             throw new JS.Exn("Attempted to call a non-method: " +method);
90         }
91     }
92     
93     public Number coerceToNumber() { return new Integer(0); }
94     public String coerceToString() { throw new JS.Exn("tried to coerce a JavaScript object to a String"); }
95     public boolean coerceToBoolean() { return true; }
96     
97     public String typeName() { return "object"; }
98
99
100     // Inner Classes /////////////////////////////////////////////////////////////////////////
101
102     /** A sensible implementation of the abstract methods in the JS class */
103     public static class Obj extends JS {
104         private Hash entries = null;
105         private boolean sealed = false;
106         public Obj() { this(false); }
107         public Obj(boolean sealed) { this.sealed = sealed; }
108         public void setSeal(boolean sealed) { this.sealed = sealed; }      ///< a sealed object cannot have its properties modified
109         public void put(Object key, Object val) { put(key, null, val); }
110         protected void put(Object key, Object key2, Object val) {
111             if (sealed) return;
112             if (entries == null) entries = new Hash();
113             entries.put(key, key2, val); }
114         public Object[] keys() { return entries == null ? new Object[0] : entries.keys(); }
115         public Object get(Object key) { return get(key, null); }
116         protected Object get(Object key, Object key2) {
117             if (entries == null) return null;
118             if(key2 == null && callMethod((String)key, null, true) == Boolean.TRUE)
119                 return new Internal.CallableStub(this, key);
120             return entries.get(key, key2);
121         }
122     }
123
124     /** An exception which can be thrown and caught by JavaScript code */
125     public static class Exn extends RuntimeException { 
126         private Object js = null; 
127         public Exn(Object js) { this.js = js; } 
128         public String toString() { return "JS.Exn: " + js; }
129         public String getMessage() { return toString(); }
130         public Object getObject() { return js; } 
131     } 
132
133     /** The publicly-visible face of JavaScript Array objects */
134     public static class Array extends ArrayImpl {
135         public Array() { }
136         public Array(int size) { super(size); }
137         public void setSize(int i) { super.setSize(i); }
138         public int length() { return super.length(); }
139         public Object elementAt(int i) { return super.elementAt(i); }
140         public void addElement(Object o) { super.addElement(o); }
141         public void setElementAt(Object o, int i) { super.setElementAt(o, i); }
142         public Object get(Object key) { return super._get(key); }
143         public void put(Object key, Object val) { super._put(key, val); }
144     }
145
146     /** Any object which becomes part of the scope chain must support this interface */ 
147     public static class Scope extends ScopeImpl { 
148         public Scope(Scope parentScope) { this(parentScope, false); }
149         public Scope(Scope parentScope, boolean sealed) { super(parentScope, sealed); }
150         /** transparent scopes are not returned by THIS */
151         public boolean isTransparent() { return super.isTransparent(); }
152         public boolean has(Object key) { return super.has(key); }
153         public Object get(Object key) { return super._get(key); }
154         public void put(Object key, Object val) { super._put(key, val); }
155         public void declare(String s) { super.declare(s); }
156     } 
157
158     /** anything that is callable with the () operator */
159     public static abstract class Callable extends JS.Obj {
160         public abstract Object call(JS.Array args) throws JS.Exn;
161     }
162
163     /** a Callable which was compiled from JavaScript code */
164     public static class CompiledFunction extends CompiledFunctionImpl {
165         public int getNumFormalArgs() { return numFormalArgs; }
166         CompiledFunction(String sourceName, int firstLine, Reader sourceCode, Scope scope) throws IOException {
167             super(sourceName, firstLine, sourceCode, scope);
168         }
169     }
170     
171     /** a scope that is populated with js objects and functions normally found in the global scope */
172     public static class GlobalScope extends GlobalScopeImpl {
173         public GlobalScope() { this(null); }
174         public GlobalScope(JS.Scope parent) { super(parent); }
175     }
176
177     public static final JS Math = new org.xwt.js.Math();
178  
179     /** encapsulates a single JavaScript thread; the JS.Thread->java.lang.Thread mapping is 1:1 */
180     public static class Thread {
181
182         CompiledFunction currentCompiledFunction = null;
183         Vec stack = new Vec();
184         int pc;
185
186         /** binds this thread to the current Java Thread */
187         public void bindToCurrentJavaThread() { javaThreadToJSThread.put(java.lang.Thread.currentThread(), this); }
188
189         /** returns the line of code that is currently executing */
190         public int getLine() { return currentCompiledFunction == null ? -1 : currentCompiledFunction.getLine(pc); }
191
192         /** returns the name of the source code file which declared the currently executing function */
193         public String getSourceName() { return currentCompiledFunction == null ? null : currentCompiledFunction.getSourceName();  }
194
195         /** fetches the currently-executing javascript function */
196         public JS.CompiledFunction getCurrentCompiledFunction() { return currentCompiledFunction; }
197
198
199         // Statics ///////////////////////////////////////////////////////////////////////
200
201         private static Hashtable javaThreadToJSThread = new Hashtable();
202
203         /** returns the JS thread for a given Java thread, creating one if necessary */
204         public static JS.Thread fromJavaThread(java.lang.Thread t) {
205             JS.Thread ret = (JS.Thread)javaThreadToJSThread.get(t);
206             if (ret == null) {
207                 ret = new JS.Thread();
208                 ret.bindToCurrentJavaThread();
209             }
210             return ret;
211         }
212         
213         public static JS.Thread currentJSThread() {
214             return fromJavaThread(java.lang.Thread.currentThread());
215         }
216     }
217
218
219
220
221