PageRenderTime 68ms CodeModel.GetById 14ms app.highlight 48ms RepoModel.GetById 1ms app.codeStats 0ms

/interpreter/tags/at2dist030708/src/edu/vub/at/objects/symbiosis/JavaClass.java

http://ambienttalk.googlecode.com/
Java | 411 lines | 207 code | 44 blank | 160 comment | 23 complexity | fd1b2d6c9adf81109a354a342d64b0a5 MD5 | raw file
  1/**
  2 * AmbientTalk/2 Project
  3 * JavaClass.java created on 3-nov-2006 at 10:54:38
  4 * (c) Programming Technology Lab, 2006 - 2007
  5 * Authors: Tom Van Cutsem & Stijn Mostinckx
  6 * 
  7 * Permission is hereby granted, free of charge, to any person
  8 * obtaining a copy of this software and associated documentation
  9 * files (the "Software"), to deal in the Software without
 10 * restriction, including without limitation the rights to use,
 11 * copy, modify, merge, publish, distribute, sublicense, and/or
 12 * sell copies of the Software, and to permit persons to whom the
 13 * Software is furnished to do so, subject to the following
 14 * conditions:
 15 *
 16 * The above copyright notice and this permission notice shall be
 17 * included in all copies or substantial portions of the Software.
 18 *
 19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 20 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 21 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 22 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 23 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 24 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 25 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 26 * OTHER DEALINGS IN THE SOFTWARE.
 27 */
 28package edu.vub.at.objects.symbiosis;
 29
 30import edu.vub.at.exceptions.InterpreterException;
 31import edu.vub.at.exceptions.XArityMismatch;
 32import edu.vub.at.exceptions.XDuplicateSlot;
 33import edu.vub.at.exceptions.XTypeMismatch;
 34import edu.vub.at.exceptions.XUnassignableField;
 35import edu.vub.at.exceptions.XUndefinedSlot;
 36import edu.vub.at.objects.ATBoolean;
 37import edu.vub.at.objects.ATContext;
 38import edu.vub.at.objects.ATField;
 39import edu.vub.at.objects.ATMethod;
 40import edu.vub.at.objects.ATNil;
 41import edu.vub.at.objects.ATObject;
 42import edu.vub.at.objects.ATTable;
 43import edu.vub.at.objects.ATTypeTag;
 44import edu.vub.at.objects.coercion.NativeTypeTags;
 45import edu.vub.at.objects.grammar.ATSymbol;
 46import edu.vub.at.objects.mirrors.PrimitiveMethod;
 47import edu.vub.at.objects.mirrors.Reflection;
 48import edu.vub.at.objects.natives.NATBoolean;
 49import edu.vub.at.objects.natives.NATNumber;
 50import edu.vub.at.objects.natives.NATObject;
 51import edu.vub.at.objects.natives.NATTable;
 52import edu.vub.at.objects.natives.NATText;
 53import edu.vub.at.objects.natives.grammar.AGSymbol;
 54import edu.vub.at.util.logging.Logging;
 55
 56import java.lang.ref.SoftReference;
 57
 58import com.thoughtworks.xstream.core.util.ObjectIdDictionary;
 59
 60/**
 61 * A JavaClass instance represents a Java Class under symbiosis.
 62 * 
 63 * Java classes are treated as AmbientTalk 'singleton' objects:
 64 * 
 65 *  - cloning a Java class results in the same Java class instance
 66 *  - sending 'new' to a Java class invokes the constructor and returns a new instance of the class under symbiosis
 67 *  - all static fields and methods of the Java class are reflected under symbiosis as fields and methods of the AT object
 68 *  
 69 * A Java Class object that represents an interface can furthermore be used
 70 * as an AmbientTalk type. The type's name corresponds to the interface's full name.
 71 *  
 72 * JavaClass instances are pooled (on a per-actor basis): there should exist only one JavaClass instance
 73 * for each Java class loaded into the JVM. Because the JVM ensures that a Java class
 74 * can only be loaded once, we can use the Java class wrapped by the JavaClass instance
 75 * as a unique key to identify its corresponding JavaClass instance.
 76 *  
 77 * @author tvcutsem
 78 */
 79public final class JavaClass extends NATObject implements ATTypeTag {
 80	
 81	/**
 82	 * A thread-local hashmap pooling all of the JavaClass wrappers for
 83	 * the current actor, referring to them using SOFT references, such
 84	 * that unused wrappers can be GC-ed when running low on memory.
 85	 */
 86	private static final ThreadLocal _JAVACLASS_POOL_ = new ThreadLocal() {
 87        protected synchronized Object initialValue() {
 88            return new ObjectIdDictionary();
 89        }
 90	};
 91	
 92	/**
 93	 * Allocate a unique symbiont object for the given Java class.
 94	 */
 95	public static final JavaClass wrapperFor(Class c) {
 96		ObjectIdDictionary map = (ObjectIdDictionary) _JAVACLASS_POOL_.get();
 97		if (map.containsId(c)) {
 98			SoftReference ref = (SoftReference) map.lookupId(c);
 99			JavaClass cls = (JavaClass) ref.get();
100			if (cls != null) {
101				return cls;
102			} else {
103				map.removeId(c);
104				cls = new JavaClass(c);
105				map.associateId(c, new SoftReference(cls));
106				return cls;
107			}
108		} else {
109			JavaClass jc = new JavaClass(c);
110			map.associateId(c, new SoftReference(jc));
111			return jc;
112		}
113	}
114	
115	// primitive fields and method of a JavaClass wrapper
116	
117	private static final AGSymbol _PTS_NAME_ = AGSymbol.jAlloc("parentTypes");
118	private static final AGSymbol _TNM_NAME_ = AGSymbol.jAlloc("typeName");
119	
120	/** def isSubtypeOf(type) { nil } */
121	private static final PrimitiveMethod _PRIM_STP_ = new PrimitiveMethod(
122			AGSymbol.jAlloc("isSubtypeOf"), NATTable.atValue(new ATObject[] { AGSymbol.jAlloc("type")})) {
123      
124	    private static final long serialVersionUID = -6864350539143194204L;
125
126		public ATObject base_apply(ATTable arguments, ATContext ctx) throws InterpreterException {
127			if (!arguments.base_length().equals(NATNumber.ONE)) {
128				throw new XArityMismatch("isSubtypeOf", 1, arguments.base_length().asNativeNumber().javaValue);
129			}
130			return ctx.base_lexicalScope().asJavaClassUnderSymbiosis().base_isSubtypeOf(arguments.base_at(NATNumber.ONE).asTypeTag());
131		}
132	};
133	
134	private final Class wrappedClass_;
135	
136	/**
137	 * A JavaClass wrapping a class c is an object that has the lexical scope as its lexical parent
138	 * and has NIL as its dynamic parent.
139	 * 
140	 * If the JavaClass wraps a Java interface type, JavaClass instances are
141	 * also types.
142	 */
143	private JavaClass(Class wrappedClass) {
144		super(wrappedClass.isInterface() ?
145			  new ATTypeTag[] { NativeTypeTags._TYPETAG_, NativeTypeTags._ISOLATE_ } :
146			  NATObject._NO_TYPETAGS_);
147		wrappedClass_ = wrappedClass;
148		
149		/*
150		 * We install a JavaConstructor instead of the default primitive method such that it 
151		 * will be wrapped correctly (using a JavaClosure) which implies that it is possible 
152		 * to cast a constructor.
153		 */
154		try {
155			super.meta_addMethod(new JavaConstructor(wrappedClass_));
156		} catch (InterpreterException e) {
157			Logging.Actor_LOG.fatal("Error while initializing Java Class constructor: " + wrappedClass.getName(), e);
158		}
159		
160		// add the two fields and one method needed for an ATTypeTag
161		if (wrappedClass.isInterface()) {
162			Class[] extendedInterfaces = wrappedClass_.getInterfaces();
163			ATObject[] types = new ATObject[extendedInterfaces.length];
164			for (int i = 0; i < extendedInterfaces.length; i++) {
165				types[i] = JavaClass.wrapperFor(extendedInterfaces[i]);
166			}
167			
168			try {
169				super.meta_defineField(_PTS_NAME_, NATTable.atValue(types));
170				super.meta_defineField(_TNM_NAME_, AGSymbol.jAlloc(wrappedClass_.getName()));
171				super.meta_addMethod(_PRIM_STP_);
172			} catch (InterpreterException e) {
173				Logging.Actor_LOG.fatal("Error while initializing Java Class as type tag: " + wrappedClass.getName(), e);
174			}
175		}
176	}
177	
178	/** return the class object denoted by this AmbientTalk symbiont */
179	public Class getWrappedClass() { return wrappedClass_; }
180	
181	public boolean isJavaClassUnderSymbiosis() { return true; }
182	public JavaClass asJavaClassUnderSymbiosis() throws XTypeMismatch { return this; }
183	
184    public ATBoolean base__opeql__opeql_(ATObject comparand) throws InterpreterException {
185    	if (comparand.isJavaClassUnderSymbiosis()) {
186            return NATBoolean.atValue(wrappedClass_.equals(comparand.asJavaClassUnderSymbiosis().wrappedClass_));
187    	} else {
188    		return NATBoolean._FALSE_;
189    	}
190    }
191        
192    /**
193     * Fields can be defined within a symbiotic Java class object. They are added
194     * to its AmbientTalk symbiont, but only if they do not clash with already
195     * existing field names.
196     */
197    public ATNil meta_defineField(ATSymbol name, ATObject value) throws InterpreterException {
198        if (Symbiosis.hasField(wrappedClass_, Reflection.upSelector(name), true)) {
199    	    throw new XDuplicateSlot(name);
200        } else {
201    	    return super.meta_defineField(name, value);
202        }
203    }
204    
205	/**
206	 * Symbiotic Java class objects are singletons.
207	 */
208	public ATObject meta_clone() throws InterpreterException { return this; }
209	
210	/**
211	 * aJavaClass.new(@args) == invoke a Java constructor
212	 * AmbientTalk objects can add a custom new method to the class in order to intercept
213	 * instance creation. The original instance can then be performed by invoking the old new(@args).
214	 * 
215	 * For example, imagine we want to extend the class java.lang.Point with a 3D coordinate, e.g. a 'z' field:
216	 * <tt>
217	 * def Point := jlobby.java.awt.Point;
218	 * def oldnew := Point.new;
219	 * def Point.new(x,y,z) { // 'override' the new method
220	 *   def point := oldnew(x,y); // invokes the Java constructor
221	 *   def point.z := z; // adds a field dynamically to the new JavaObject wrapper
222	 *   point; // important! new should return the newly created instance
223	 * }
224	 * def mypoint := Point.new(1,2,3);
225	 * </tt>
226	 */
227    public ATObject meta_newInstance(ATTable initargs) throws InterpreterException {
228//    	return Symbiosis.symbioticInstanceCreation(wrappedClass_, initargs.asNativeTable().elements_);
229    	return Symbiosis.symbioticInstanceCreation(new JavaConstructor(wrappedClass_), initargs.asNativeTable().elements_);
230    }
231    
232    /**
233     * Methods can be added to a symbiotic Java class object provided they do not already
234     * exist in the Java class.
235     */
236    public ATNil meta_addMethod(ATMethod method) throws InterpreterException {
237        ATSymbol name = method.base_name();
238        if (Symbiosis.hasMethod(wrappedClass_, Reflection.upSelector(name), true)) {
239    	    throw new XDuplicateSlot(name);
240        } else {
241    	    return super.meta_addMethod(method);
242        }
243    }
244
245    /**
246     * Fields can be grabbed from a symbiotic Java class object. Fields that correspond
247     * to static fields in the Java class are returned as JavaField instances.
248     */
249    public ATField meta_grabField(ATSymbol fieldName) throws InterpreterException {
250        try {
251        	return new JavaField(null,
252        			             Symbiosis.getField(wrappedClass_, Reflection.upSelector(fieldName), true));
253        } catch(XUndefinedSlot e) {
254        	return super.meta_grabField(fieldName);
255        }
256    }
257
258    /**
259     * Methods can be grabbed from a symbiotic Java class object. Methods that correspond
260     * to static methods in the Java class are returned as JavaMethod instances.
261     */
262    public ATMethod meta_grabMethod(ATSymbol methodName) throws InterpreterException {
263        JavaMethod choices = Symbiosis.getMethods(wrappedClass_, Reflection.upSelector(methodName), true);
264        if (choices != null) {
265        	return choices;
266        } else {
267        	return super.meta_grabMethod(methodName);
268        }
269    }
270
271    /**
272     * Querying a symbiotic Java class object for its fields results in a table containing
273     * both 'native' static Java fields and the fields of its AT symbiont
274     */
275    public ATTable meta_listFields() throws InterpreterException {
276		// instance fields of the wrapped object's class
277		JavaField[] jFields = Symbiosis.getAllFields(null, wrappedClass_);
278        // fields of the AT symbiont
279    	ATObject[] symbiontFields = super.meta_listFields().asNativeTable().elements_;
280    	return NATTable.atValue(NATTable.collate(jFields, symbiontFields));
281    }
282
283    /**
284     * Querying a symbiotic Java class object for its methods results in a table containing
285     * both 'native' static Java methods and the methods of its AT symbiont
286     */
287    public ATTable meta_listMethods() throws InterpreterException {
288		// instance methods of the wrapped object's class
289		JavaMethod[] jMethods = Symbiosis.getAllMethods(wrappedClass_, true);
290        // methods of the AT symbiont
291		ATObject[] symbiontMethods = super.meta_listMethods().asNativeTable().elements_;
292		return NATTable.atValue(NATTable.collate(jMethods, symbiontMethods));
293    }
294
295	public ATBoolean meta_isCloneOf(ATObject original) throws InterpreterException {
296		return NATBoolean.atValue(this == original);
297	}
298	
299	public NATText meta_print() throws InterpreterException {
300		return NATText.atValue("<java:"+wrappedClass_.toString()+">");
301	}
302
303	/**
304	 * Java class wrappers may be passed by-copy since Java Class
305	 * objects are serializable. Upon deserialization however, the
306	 * class wrapper returned will be the one local to the receiving
307	 * actor.
308	 */
309	public ATObject meta_pass() throws InterpreterException {
310		return this;
311	}
312	
313	/**
314     * A Java Class object remains unique within an actor.
315     */
316    public ATObject meta_resolve() throws InterpreterException {
317    	return wrapperFor(wrappedClass_);
318    }
319    
320    /* ========================
321     * == ATTypeTag Interface ==
322     * ======================== */
323    
324    /**
325     * If this class represents an interface type, parentTypes
326     * are wrappers for all interfaces extended by this Java interface type
327     */
328	public ATTable base_superTypes() throws InterpreterException {
329		return super.impl_invokeAccessor(this, _PTS_NAME_, NATTable.EMPTY).asTable();
330	}
331
332	public ATSymbol base_typeName() throws InterpreterException {
333		return super.impl_invokeAccessor(this, _TNM_NAME_, NATTable.EMPTY).asSymbol();
334	}
335
336	/**
337	 * A Java interface type used as a type can only be a subtype of another
338	 * Java interface type used as a type, and only if this type is assignable
339	 * to the other type.
340	 */
341	public ATBoolean base_isSubtypeOf(ATTypeTag other) throws InterpreterException {
342		if (other instanceof JavaClass) {
343			JavaClass otherClass = (JavaClass) other;
344			// wrappedClass <: otherClass <=> otherClass >= wrappedClass
345			return NATBoolean.atValue(otherClass.wrappedClass_.isAssignableFrom(wrappedClass_));
346		} else {
347			return NATBoolean._FALSE_;
348		}
349	}
350	
351	/**
352	 * When a Java interface type is used to annotate a message, this does not lead to
353	 * any additional metadata being added to the message.
354	 */
355	public ATObject base_annotateMessage(ATObject originalMessage) { return originalMessage; }
356	
357	/**
358	 * When a Java interface type is used to annotate a message, this does not lead to
359	 * any additional metadata being added to the message.
360	 */
361	public ATMethod base_annotateMethod(ATMethod originalMethod) {	return originalMethod; }
362	
363	// IMPLEMENTATION INTERFACE
364	
365    /**
366     * A symbiotic Java class object has all of the public static fields
367     * of its Java class plus all of the fields defined in the AT symbiont.
368     */
369	protected boolean hasLocalField(ATSymbol atSelector) throws InterpreterException {
370		return Symbiosis.hasField(wrappedClass_, Reflection.upSelector(atSelector), true) ||
371			   super.hasLocalField(atSelector);
372	}
373
374	/**
375     * A symbiotic Java class object has all of the public static methods
376     * of its Java class plus all of the methods defined in the AT symbiont.
377     */
378	protected boolean hasLocalMethod(ATSymbol atSelector) throws InterpreterException {
379		return Symbiosis.hasMethod(wrappedClass_, Reflection.upSelector(atSelector), true) ||
380		       super.hasLocalMethod(atSelector);
381	}
382	
383	protected ATObject getLocalField(ATSymbol selector) throws InterpreterException {
384		try {
385			return Symbiosis.readField(null, wrappedClass_, Reflection.upSelector(selector));
386		} catch(XUndefinedSlot e) {
387			return super.getLocalField(selector);
388		}
389	}
390	
391	protected ATMethod getLocalMethod(ATSymbol methodName) throws InterpreterException {
392        JavaMethod choices = Symbiosis.getMethods(wrappedClass_, Reflection.upSelector(methodName), true);
393        if (choices != null) {
394        	return choices;
395        } else {
396        	return super.getLocalMethod(methodName);
397        }
398	}
399	
400	protected void setLocalField(ATSymbol selector, ATObject value) throws InterpreterException {
401		try {
402			Symbiosis.writeField(null, wrappedClass_, Reflection.upSelector(selector), value);
403		} catch(XUndefinedSlot e) {
404			super.setLocalField(selector, value);
405		} catch(XUnassignableField e) {
406			// field may have been final, in which case there 'is no such field'
407			super.setLocalField(selector, value);
408		}
409	}
410	
411}