b0d54e5242ec16674c2d4c282e3179685be4c7e5
[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 minimal amount of functionality for an Object
11  *  which can be manipulated by JavaScript code.
12  */
13 public abstract class JS { 
14
15
16     // Static Methods //////////////////////////////////////////////////////////////////////
17
18     private static Hashtable currentFunction = new Hashtable();
19     public static Function getCurrentFunction() { return (Function)currentFunction.get(Thread.currentThread()); }
20     public static String getCurrentFunctionSourceName() { return getCurrentFunctionSourceName(Thread.currentThread()); }
21     public static String getFileAndLine() { return getCurrentFunctionSourceName() + ":" + getCurrentFunction().getLine(); }
22     public static String getCurrentFunctionSourceName(Thread t) {
23         Function f = (Function)currentFunction.get(t);
24         if (f == null) return "null";
25         return f.getSourceName();
26     }
27
28     public static boolean toBoolean(Object o) {
29         if (o == null) return false;
30         if (o instanceof Boolean) return ((Boolean)o).booleanValue();
31         if (o instanceof Number) return o.equals(new Integer(0));
32         return true;
33     }
34
35     public static long toLong(Object o) { return toNumber(o).longValue(); }
36     public static double toDouble(Object o) { return toNumber(o).doubleValue(); }
37     public static Number toNumber(Object o) {
38         if (o == null) return new Long(0);
39         if (o instanceof Number) return ((Number)o);
40         if (o instanceof String) try { return new Double((String)o); } catch (NumberFormatException e) { return new Double(0); }
41         if (o instanceof Boolean) return ((Boolean)o).booleanValue() ? new Long(1) : new Long(0);
42         if (o instanceof JS) return ((JS)o).coerceToNumber();
43         throw new Error("toNumber() got object of type " + o.getClass().getName() + " which we don't know how to handle");
44     }
45
46
47     // Instance Methods ////////////////////////////////////////////////////////////////////
48  
49     public abstract Object get(Object key) throws JS.Exn; 
50     public abstract void put(Object key, Object val) throws JS.Exn; 
51     public abstract Object[] keys(); 
52
53     public Number coerceToNumber() { throw new Error("you cannot coerce a " + this.getClass().getName() + " into a Number"); }
54     public String coerceToString() { throw new Error("you cannot coerce a " + this.getClass().getName() + " into a String"); }
55     public boolean coerceToBoolean() { throw new Error("you cannot coerce a " + this.getClass().getName() + " into a Boolean"); }
56
57
58     // Subclasses /////////////////////////////////////////////////////////////////////////
59
60     /** A slightly more featureful version of JS */
61     public static class Obj extends JS {
62         private Hash entries = new Hash();
63         private boolean sealed = false;
64         public Obj() { this(false); }
65         public Obj(boolean sealed) { this.sealed = sealed; }
66         public void setSeal(boolean sealed) { this.sealed = sealed; }
67         public Object get(Object key) { return entries.get(key); }
68         public void put(Object key, Object val) { if (!sealed) entries.put(key, val); }
69         public Object[] keys() { return(entries.keys()); }
70     }
71
72     /** An exception which can be thrown and caught by JavaScripts */
73     public static class Exn extends RuntimeException { 
74         private Object js = null; 
75         public Exn(Object js) { this.js = js; } 
76         public String toString() { return "JS.Exn: " + js; }
77         public String getMessage() { return toString(); }
78         public Object getObject() { return js; } 
79     } 
80
81     /** A JavaScript Array */
82     public static class Array extends Obj {
83         private Vec vec = new Vec();
84         public Array() { }
85         public Array(int size) { vec.setSize(size); }
86         private static int intVal(Object o) {
87             if (o instanceof Number) {
88                 int intVal = ((Number)o).intValue();
89                 if (intVal == ((Number)o).doubleValue()) return intVal;
90                 return Integer.MIN_VALUE;
91             }
92             if (!(o instanceof String)) return Integer.MIN_VALUE;
93             String s = (String)o;
94             for(int i=0; i<s.length(); i++) if (s.charAt(i) < '0' || s.charAt(i) > '9') return Integer.MIN_VALUE;
95             return Integer.parseInt(s);
96         }
97         public Object get(Object key) throws JS.Exn {
98             // FIXME: HACK!
99             if (key.equals("cascade")) return org.xwt.Trap.cascadeFunction;
100             if (key.equals("trapee")) return org.xwt.Trap.currentTrapee();
101             if (key.equals("length")) return new Long(vec.size());
102             int i = intVal(key);
103             if (i == Integer.MIN_VALUE) return super.get(key);
104             try {
105                 return vec.elementAt(i);
106             } catch (ArrayIndexOutOfBoundsException e) {
107                 throw new JS.Exn(e.getMessage());
108             }
109         }
110         public void put(Object key, Object val) {
111             if (key.equals("length")) vec.setSize(toNumber(val).intValue());
112             int i = intVal(key);
113             if (i == Integer.MIN_VALUE) super.put(key, val);
114             else {
115                 if (i >= vec.size()) vec.setSize(i+1);
116                 vec.setElementAt(val, i);
117             }
118         }
119         public Object[] keys() {
120             Object[] sup = super.keys();
121             Object[] ret = new Object[vec.size() + 1 + sup.length];
122             System.arraycopy(sup, 0, ret, vec.size(), sup.length);
123             for(int i=0; i<vec.size(); i++) ret[i] = new Integer(i);
124             ret[vec.size()] = "length";
125             return ret;
126         }
127         public void setSize(int i) { vec.setSize(i); }
128         public int length() { return vec.size(); }
129         public Object elementAt(int i) { return vec.elementAt(i); }
130         public void addElement(Object o) { vec.addElement(o); }
131         public void setElementAt(Object o, int i) { vec.setElementAt(o, i); }
132     }
133
134     /** Anything that is callable */
135     public static class Function extends Obj {
136         ByteCodeBlock bytecodes;
137         int line;
138         String sourceName;
139         Scope parentScope;
140         public Function() { this(-1, "unknown", null, null); }
141         public Function(int line, String sourceName, ByteCodeBlock bytecodes, Scope parentScope) {
142             this.sourceName = sourceName;
143             this.line = line;
144             this.bytecodes = bytecodes;
145             this.parentScope = parentScope;
146         }
147         public String getSourceName() throws JS.Exn { return sourceName; }
148         public int getLine() throws JS.Exn { return line; }
149         public Object _call(JS.Array args) throws JS.Exn, ByteCodeBlock.ControlTransferException {
150             if (bytecodes == null) throw new Error("tried to call() a JS.Function with bytecodes == null");
151             Vec stack = new Vec();
152             stack.push(args);
153             return bytecodes.eval(new FunctionScope(sourceName, parentScope), stack);
154         }
155         public final Object call(JS.Array args) throws JS.Exn {
156             Function saved = (Function)currentFunction.get(Thread.currentThread());
157             currentFunction.put(Thread.currentThread(), this);
158             try {
159                 return _call(args);
160             } catch (ByteCodeBlock.ReturnException e) {  // ignore
161                 return e.retval;
162             } catch (ByteCodeBlock.ControlTransferException e) {
163                 throw new RuntimeException(getSourceName() + ":" + getLine() +
164                                            " error, ControlTransferException tried to leave a function");
165             } finally {
166                 if (saved == null) currentFunction.remove(Thread.currentThread());
167                 else currentFunction.put(Thread.currentThread(), saved);
168             }
169         }
170     }
171
172     public static class Script extends Function {
173         Vector e = null;
174         private Script(Vector e) { this.e = e; }
175         public String getSourceName() throws JS.Exn { return ((ByteCodeBlock)e.elementAt(0)).getSourceName(); }
176         public Object _call(JS.Array args) throws JS.Exn, ByteCodeBlock.ControlTransferException {
177             Scope rootScope = (Scope)args.elementAt(0);
178             for(int i=0; i<e.size(); i++) ((ByteCodeBlock)e.elementAt(i)).eval(rootScope, new Vec());
179             return null;
180         }
181         public static Script parse(Reader r, String sourceName, int line) throws IOException {
182             Parser p = new Parser(r, sourceName, line);
183             try {
184                 Vector exprs = new Vector();
185                 while(true) {
186                     ByteCodeBlock ret = p.parseStatement();
187                     if (ret == null) break;
188                     exprs.addElement(ret);
189                 }
190                 return new Script(exprs);
191             } catch (Exception e) {
192                 if (Log.on) Log.log(Parser.class, e);
193                 return null;
194             }
195         }
196     }
197
198     /** Any object which becomes part of the scope chain must support this interface */ 
199     public static class Scope extends Obj { 
200         private Scope parentScope;
201         private static Object NULL = new Object();
202         public Scope(Scope parentScope) { this(parentScope, false); }
203         public Scope(Scope parentScope, boolean sealed) { super(sealed); this.parentScope = parentScope; }
204         public Scope getParentScope() { return parentScope; }
205
206         // transparent scopes are not returned by THIS
207         public boolean isTransparent() { return false; }
208
209         public boolean has(Object key) { return super.get(key) != null; }
210         public Object get(Object key) {
211             if (!has(key)) return parentScope == null ? null : getParentScope().get(key);
212             Object ret = super.get(key); return ret == NULL ? null : ret;
213         }
214         public void put(Object key, Object val) {
215             if (!has(key) && parentScope != null) getParentScope().put(key, val);
216             else super.put(key, val == null ? NULL : val);
217         }
218         public Object[] keys() { throw new Error("you can't enumerate the properties of a Scope"); }
219         public void declare(String s) {
220             if (isTransparent()) getParentScope().declare(s);
221             else super.put(s, NULL);
222         }
223     } 
224  
225     private class FunctionScope extends JS.Scope {
226         String sourceName;
227         public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
228         public String getSourceName() { return sourceName; }
229         public Object get(Object key) throws JS.Exn {
230             if (key.equals("trapee")) return org.xwt.Trap.currentTrapee();
231             else if (key.equals("cascade")) return org.xwt.Trap.cascadeFunction;
232             return super.get(key);
233         }
234     }
235
236
237
238
239