2003/05/03 03:18:55
[org.ibex.core.git] / src / org / xwt / js / JS.java
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL] 
2  
3 package org.xwt.js; 
4 import org.xwt.util.*; 
5  
6 /** all objects other than Strings and Numbers which are exposed to JS code must implement this interface */ 
7 public interface JS { 
8  
9     public Object get(Object key) throws JS.Exn; 
10     public Object put(Object key, Object val) throws JS.Exn; 
11     public Object[] enumerateProperties(); 
12     public String coerceToString() throws JS.Exn; 
13     public Num coerceToNumber() throws JS.Exn; 
14     public Object call(Object[] args) throws JS.Exn; 
15  
16     /** if JS calls a Java method, and the Java method throws an exception, it can only be caught by JS if it is a subclass of Exn. */ 
17     public static class Exn extends RuntimeException { 
18         private Object js = null; 
19         public Exn(Object js) { this.js = js; } 
20         public Object getObject() { return js; } 
21     } 
22  
23     /** Any object which becomes part of the scope chain must support this interface */ 
24     public static interface Scope extends JS { 
25         public boolean has(Object key); 
26         public void declare(String s);
27         public JS getParentScope(); 
28     } 
29  
30     /** A mutable, boxed numeric value.  These are recycled -- never duplicate references -- use duplicate() instead. */ 
31     public static class Num implements Cloneable, JS { 
32          
33         private Num() { } 
34          
35         public boolean isDouble = false; 
36         public long longVal = -1; 
37         public double doubleVal = -1; 
38          
39         private static Vec pool = new Vec(); 
40         public static synchronized void recycle(Num n) { pool.push(n); } 
41         public static synchronized Num getOne() { return (pool.size() > 0) ? (Num)pool.pop() : new Num(); } 
42          
43         public Num duplicate() { try { return (Num)clone(); } catch (CloneNotSupportedException c) { throw new Error(c); } } 
44  
45         public Object get(Object key) throws JS.Exn { return null; } 
46         public Object put(Object key, Object val) throws JS.Exn { throw new JS.Exn("attempt to set a property on a Number"); } 
47         public Object[] enumerateProperties() { return new Object[] { }; } 
48         public String coerceToString() throws JS.Exn { return isDouble ? String.valueOf(doubleVal) : String.valueOf(longVal); } 
49         public Num coerceToNumber() throws JS.Exn { return duplicate(); } 
50         public Object call(Object[] args) throws JS.Exn { throw new JS.Exn("attempt to apply the () operator to a Number"); } 
51          
52     } 
53