2003/06/09 06:38:36
[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                 return null;
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(int line, String sourceName, ByteCodeBlock bytecodes, Scope parentScope) {
141             this.sourceName = sourceName;
142             this.line = line;
143             this.bytecodes = bytecodes;
144             this.parentScope = parentScope;
145         }
146         public Function cloneWithNewParentScope(Scope s) {
147             if (this.getClass() != Function.class)
148                 throw new Error("org.xwt.js.JS.Function.cloneWithNewParentScope() is not valid for subclasses");
149             return new Function(line, sourceName, bytecodes, s);
150         }
151         public String getSourceName() throws JS.Exn { return sourceName; }
152         public int getLine() throws JS.Exn { return line; }
153         public Object _call(JS.Array args) throws JS.Exn, ByteCodeBlock.ControlTransferException {
154             if (bytecodes == null) throw new Error("tried to call() a JS.Function with bytecodes == null");
155             Vec stack = new Vec();
156             stack.push(args);
157             return bytecodes.eval(args == null ? parentScope : new FunctionScope(sourceName, parentScope), stack);
158         }
159         public final Object call(JS.Array args) throws JS.Exn {
160             Function saved = (Function)currentFunction.get(Thread.currentThread());
161             if (!getSourceName().equals("java")) currentFunction.put(Thread.currentThread(), this);
162             try {
163                 return _call(args);
164             } catch (ByteCodeBlock.ReturnException e) {  // ignore
165                 return e.retval;
166             } catch (ByteCodeBlock.ControlTransferException e) {
167                 throw new RuntimeException(getSourceName() + ":" + getLine() +
168                                            " error, ControlTransferException tried to leave a function");
169             } finally {
170                 if (saved == null) currentFunction.remove(Thread.currentThread());
171                 else currentFunction.put(Thread.currentThread(), saved);
172             }
173         }
174     }
175
176     public static Function parse(Reader r, String sourceName, int line) throws IOException {
177         ByteCodeBlock b = new ByteCodeBlock(line, sourceName);
178         Parser p = new Parser(r, sourceName, line);
179         try {
180             while(true) {
181                 int size = b.size();
182                 p.parseStatement(false, b);
183                 if (size == b.size()) break;
184             }
185             return new Function(line, sourceName, b, null);
186         } catch (Exception e) {
187             if (Log.on) Log.log(Parser.class, e);
188             return null;
189         }
190     }
191
192     /** Any object which becomes part of the scope chain must support this interface */ 
193     public static class Scope extends Obj { 
194         private Scope parentScope;
195         private static Object NULL = new Object();
196         public Scope(Scope parentScope) { this(parentScope, false); }
197         public Scope(Scope parentScope, boolean sealed) { super(sealed); this.parentScope = parentScope; }
198         public Scope getParentScope() { return parentScope; }
199
200         // transparent scopes are not returned by THIS
201         public boolean isTransparent() { return false; }
202
203         public boolean has(Object key) { return super.get(key) != null; }
204         public Object get(Object key) {
205             if (!has(key)) return parentScope == null ? null : getParentScope().get(key);
206             Object ret = super.get(key); return ret == NULL ? null : ret;
207         }
208         public void put(Object key, Object val) {
209             if (!has(key) && parentScope != null) getParentScope().put(key, val);
210             else super.put(key, val == null ? NULL : val);
211         }
212         public Object[] keys() { throw new Error("you can't enumerate the properties of a Scope"); }
213         public void declare(String s) {
214             if (isTransparent()) getParentScope().declare(s);
215             else super.put(s, NULL);
216         }
217     } 
218  
219     private class FunctionScope extends JS.Scope {
220         String sourceName;
221         public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
222         public String getSourceName() { return sourceName; }
223         public Object get(Object key) throws JS.Exn {
224             if (key.equals("trapee")) return org.xwt.Trap.currentTrapee();
225             else if (key.equals("cascade")) return org.xwt.Trap.cascadeFunction;
226             return super.get(key);
227         }
228     }
229
230
231
232
233