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