PageRenderTime 50ms CodeModel.GetById 9ms app.highlight 34ms RepoModel.GetById 1ms app.codeStats 1ms

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

http://ambienttalk.googlecode.com/
Java | 418 lines | 220 code | 38 blank | 160 comment | 23 complexity | b4790d6ffedd3a29745aa79fc0becca9 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.actors.net.Logging;
 31import edu.vub.at.exceptions.InterpreterException;
 32import edu.vub.at.exceptions.XArityMismatch;
 33import edu.vub.at.exceptions.XDuplicateSlot;
 34import edu.vub.at.exceptions.XSelectorNotFound;
 35import edu.vub.at.exceptions.XTypeMismatch;
 36import edu.vub.at.exceptions.XUnassignableField;
 37import edu.vub.at.exceptions.XUndefinedField;
 38import edu.vub.at.objects.ATBoolean;
 39import edu.vub.at.objects.ATContext;
 40import edu.vub.at.objects.ATField;
 41import edu.vub.at.objects.ATMethod;
 42import edu.vub.at.objects.ATNil;
 43import edu.vub.at.objects.ATObject;
 44import edu.vub.at.objects.ATStripe;
 45import edu.vub.at.objects.ATTable;
 46import edu.vub.at.objects.coercion.NativeStripes;
 47import edu.vub.at.objects.grammar.ATSymbol;
 48import edu.vub.at.objects.mirrors.PrimitiveMethod;
 49import edu.vub.at.objects.mirrors.Reflection;
 50import edu.vub.at.objects.natives.NATBoolean;
 51import edu.vub.at.objects.natives.NATNil;
 52import edu.vub.at.objects.natives.NATNumber;
 53import edu.vub.at.objects.natives.NATObject;
 54import edu.vub.at.objects.natives.NATTable;
 55import edu.vub.at.objects.natives.NATText;
 56import edu.vub.at.objects.natives.grammar.AGSymbol;
 57
 58import java.lang.ref.SoftReference;
 59import java.util.HashMap;
 60
 61/**
 62 * A JavaClass instance represents a Java Class under symbiosis.
 63 * 
 64 * Java classes are treated as AmbientTalk 'singleton' objects:
 65 * 
 66 *  - cloning a Java class results in the same Java class instance
 67 *  - sending 'new' to a Java class invokes the constructor and returns a new instance of the class under symbiosis
 68 *  - all static fields and methods of the Java class are reflected under symbiosis as fields and methods of the AT object
 69 *  
 70 * A Java Class object that represents an interface can furthermore be used
 71 * as an AmbientTalk stripe. The stripe's name corresponds to the interface's full name.
 72 *  
 73 * JavaClass instances are pooled (on a per-actor basis): there should exist only one JavaClass instance
 74 * for each Java class loaded into the JVM. Because the JVM ensures that a Java class
 75 * can only be loaded once, we can use the Java class wrapped by the JavaClass instance
 76 * as a unique key to identify its corresponding JavaClass instance.
 77 *  
 78 * @author tvcutsem
 79 */
 80public final class JavaClass extends NATObject implements ATStripe {
 81	
 82	/**
 83	 * A thread-local hashmap pooling all of the JavaClass wrappers for
 84	 * the current actor, referring to them using SOFT references, such
 85	 * that unused wrappers can be GC-ed when running low on memory.
 86	 */
 87	private static final ThreadLocal _JAVACLASS_POOL_ = new ThreadLocal() {
 88        protected synchronized Object initialValue() {
 89            return new HashMap();
 90        }
 91	};
 92	
 93	public static final JavaClass wrapperFor(Class c) {
 94		HashMap map = (HashMap) _JAVACLASS_POOL_.get();
 95		if (map.containsKey(c)) {
 96			SoftReference ref = (SoftReference) map.get(c);
 97			JavaClass cls = (JavaClass) ref.get();
 98			if (cls != null) {
 99				return cls;
100			} else {
101				map.remove(c);
102				cls = new JavaClass(c);
103				map.put(c, new SoftReference(cls));
104				return cls;
105			}
106		} else {
107			JavaClass jc = new JavaClass(c);
108			map.put(c, new SoftReference(jc));
109			return jc;
110		}
111	}
112	
113	// primitive fields and method of a JavaClass wrapper
114	
115	private static final AGSymbol _PST_NAME_ = AGSymbol.jAlloc("parentStripes");
116	private static final AGSymbol _SNM_NAME_ = AGSymbol.jAlloc("stripeName");
117	
118	/** def isSubstripeOf(stripe) { nil } */
119	private static final PrimitiveMethod _PRIM_SST_ = new PrimitiveMethod(
120			AGSymbol.jAlloc("isSubstripeOf"), NATTable.atValue(new ATObject[] { AGSymbol.jAlloc("stripe")})) {
121		public ATObject base_apply(ATTable arguments, ATContext ctx) throws InterpreterException {
122			if (!arguments.base_getLength().equals(NATNumber.ONE)) {
123				throw new XArityMismatch("isSubstripeOf", 1, arguments.base_getLength().asNativeNumber().javaValue);
124			}
125			return ctx.base_getLexicalScope().asJavaClassUnderSymbiosis().base_isSubstripeOf(arguments.base_at(NATNumber.ONE).asStripe());
126		}
127	};
128	
129	private final Class wrappedClass_;
130	
131	/**
132	 * A JavaClass wrapping a class c is an object that has the lexical scope as its lexical parent
133	 * and has NIL as its dynamic parent.
134	 * 
135	 * If the JavaClass wraps a Java interface type, JavaClass instances are
136	 * also stripes.
137	 */
138	private JavaClass(Class wrappedClass) {
139		super(wrappedClass.isInterface() ?
140			  new ATStripe[] { NativeStripes._STRIPE_ } :
141			  NATObject._NO_STRIPES_);
142		wrappedClass_ = wrappedClass;
143		
144		// add the two fields and one method needed for an ATStripe
145		if (wrappedClass.isInterface()) {
146			Class[] extendedInterfaces = wrappedClass_.getInterfaces();
147			ATObject[] stripes = new ATObject[extendedInterfaces.length];
148			for (int i = 0; i < extendedInterfaces.length; i++) {
149				stripes[i] = JavaClass.wrapperFor(extendedInterfaces[i]);
150			}
151			
152			try {
153				super.meta_defineField(_PST_NAME_, NATTable.atValue(stripes));
154				super.meta_defineField(_SNM_NAME_, AGSymbol.jAlloc(wrappedClass_.getName()));
155				super.meta_addMethod(_PRIM_SST_);
156			} catch (InterpreterException e) {
157				Logging.Actor_LOG.fatal("Error while initializing Java Class as stripe: " + wrappedClass.getName(), e);
158			}
159		}
160	}
161	
162	public Class getWrappedClass() { return wrappedClass_; }
163	
164	public JavaClass asJavaClassUnderSymbiosis() throws XTypeMismatch { return this; }
165	
166	public boolean equals(Object other) {
167		return ((other instanceof JavaClass) &&
168				(wrappedClass_.equals(((JavaClass) other).wrappedClass_)));
169	}
170	
171    /* ------------------------------------------------------
172     * - Symbiotic implementation of the ATObject interface -
173     * ------------------------------------------------------ */
174    
175    /**
176     * When a method is invoked upon a symbiotic Java class object, the underlying static Java method
177     * with the same name as the AmbientTalk selector is invoked. Its arguments are converted
178     * into their Java equivalents. Conversely, the result of the method invocation is converted
179     * into an AmbientTalk object.
180     */
181    public ATObject meta_invoke(ATObject receiver, ATSymbol atSelector, ATTable arguments) throws InterpreterException {
182        try {
183			String jSelector = Reflection.upSelector(atSelector);
184			return Symbiosis.symbioticInvocation(
185					this, null, wrappedClass_, jSelector, arguments.asNativeTable().elements_);
186		} catch (XSelectorNotFound e) {
187			e.catchOnlyIfSelectorEquals(atSelector);
188    	    return super.meta_invoke(receiver, atSelector, arguments);
189		}
190    }
191    
192    /**
193     * A symbiotic Java class object responds to all of the public static selectors of its Java class
194     * plus all of the per-instance selectors added to its AmbientTalk symbiont.
195     */
196    public ATBoolean meta_respondsTo(ATSymbol atSelector) throws InterpreterException {
197    	String jSelector = Reflection.upSelector(atSelector);
198    	if (Symbiosis.hasMethod(wrappedClass_, jSelector, true) ||
199    	    Symbiosis.hasField(wrappedClass_, jSelector, true)) {
200    		return NATBoolean._TRUE_;
201    	} else {
202    		return super.meta_respondsTo(atSelector);
203    	}
204    }
205    
206    /**
207     * When selecting a field from a symbiotic Java class object, if the object's class
208     * has a static field with a matching selector, it is automatically read;
209     * if it has methods corresponding to the selector, they are returned in a JavaMethod wrapper,
210     * otherwise, the fields of its AT symbiont are checked.
211     */
212    public ATObject meta_select(ATObject receiver, ATSymbol selector) throws InterpreterException {
213    	String jSelector = Reflection.upSelector(selector);
214    	try {
215   			return Symbiosis.readField(null, wrappedClass_, jSelector);
216    	} catch(XUndefinedField e) {
217       	    JavaMethod choices = Symbiosis.getMethods(wrappedClass_, jSelector, true);
218       	    if (choices != null) {
219       	     	return new JavaClosure(this, choices);
220       	    } else {
221       	    	return super.meta_select(receiver, selector);
222       	    }
223    	}
224    }
225    
226    /**
227     * A variable lookup is resolved by first checking whether the Java object has an appropriate static
228     * field with a matching name. If so, that field's contents are returned. If not, the AT symbiont's
229     * fields are checked.
230     */
231    public ATObject meta_lookup(ATSymbol selector) throws InterpreterException {
232        try {
233        	String jSelector = Reflection.upSelector(selector);
234      	    return Symbiosis.readField(null, wrappedClass_, jSelector);
235        } catch(XUndefinedField e) {
236        	return super.meta_lookup(selector);  
237        }
238    }
239    
240    /**
241     * Fields can be defined within a symbiotic Java class object. They are added
242     * to its AmbientTalk symbiont, but only if they do not clash with already
243     * existing field names.
244     */
245    public ATNil meta_defineField(ATSymbol name, ATObject value) throws InterpreterException {
246        if (Symbiosis.hasField(wrappedClass_, Reflection.upSelector(name), true)) {
247    	    throw new XDuplicateSlot(XDuplicateSlot._FIELD_, name);
248        } else {
249    	    return super.meta_defineField(name, value);
250        }
251    }
252    
253    /**
254     * Variables can be assigned within a symbiotic Java class object if that class object
255     * has a mutable static field with a matching name. Variable assignment is first
256     * resolved in the Java object and afterwards in the AT symbiont.
257     */
258    public ATNil meta_assignVariable(ATSymbol name, ATObject value) throws InterpreterException {
259        try {
260        	String jSelector = Reflection.upSelector(name);
261        	Symbiosis.writeField(null, wrappedClass_, jSelector, value);
262        	return NATNil._INSTANCE_;
263		} catch (XUnassignableField e) {
264			return super.meta_assignVariable(name, value);
265		}
266    }
267    
268    /**
269     * Fields can be assigned within a symbiotic Java class object if that class
270     * has a mutable field with a matching name. Field assignment is first resolved
271     * in the Java object and afterwards in the AT symbiont.
272     */
273    public ATNil meta_assignField(ATObject receiver, ATSymbol name, ATObject value) throws InterpreterException {
274        try {
275     	    String jSelector = Reflection.upSelector(name);
276    	    Symbiosis.writeField(null, wrappedClass_, jSelector, value);
277    	    return NATNil._INSTANCE_;	
278		} catch (XUnassignableField e) {
279			return super.meta_assignField(receiver, name, value);
280		}
281    }
282    
283	/**
284	 * Symbiotic Java class objects are singletons.
285	 */
286	public ATObject meta_clone() throws InterpreterException { return this; }
287	
288	/**
289	 * aJavaClass.new(@args) == invoke a Java constructor
290	 * AmbientTalk objects can add a custom new method to the class in order to intercept
291	 * instance creation. The original instance can then be performed by invoking the old new(@args).
292	 * 
293	 * For example, imagine we want to extend the class java.lang.Point with a 3D coordinate, e.g. a 'z' field:
294	 * <tt>
295	 * def Point := jlobby.java.awt.Point;
296	 * def oldnew := Point.new;
297	 * def Point.new(x,y,z) { // 'override' the new method
298	 *   def point := oldnew(x,y); // invokes the Java constructor
299	 *   def point.z := z; // adds a field dynamically to the new JavaObject wrapper
300	 *   point; // important! new should return the newly created instance
301	 * }
302	 * def mypoint := Point.new(1,2,3);
303	 * </tt>
304	 */
305    public ATObject meta_newInstance(ATTable initargs) throws InterpreterException {
306    	return Symbiosis.symbioticInstanceCreation(wrappedClass_, initargs.asNativeTable().elements_);
307    }
308    
309    /**
310     * Methods can be added to a symbiotic Java class object provided they do not already
311     * exist in the Java class.
312     */
313    public ATNil meta_addMethod(ATMethod method) throws InterpreterException {
314        ATSymbol name = method.base_getName();
315        if (Symbiosis.hasMethod(wrappedClass_, Reflection.upSelector(name), true)) {
316    	    throw new XDuplicateSlot(XDuplicateSlot._METHOD_, name);
317        } else {
318    	    return super.meta_addMethod(method);
319        }
320    }
321
322    /**
323     * Fields can be grabbed from a symbiotic Java class object. Fields that correspond
324     * to static fields in the Java class are returned as JavaField instances.
325     */
326    public ATField meta_grabField(ATSymbol fieldName) throws InterpreterException {
327        try {
328        	return new JavaField(null,
329        			             Symbiosis.getField(wrappedClass_, Reflection.upSelector(fieldName), true));
330        } catch(XUndefinedField e) {
331        	return super.meta_grabField(fieldName);
332        }
333    }
334
335    /**
336     * Methods can be grabbed from a symbiotic Java class object. Methods that correspond
337     * to static methods in the Java class are returned as JavaMethod instances.
338     */
339    public ATMethod meta_grabMethod(ATSymbol methodName) throws InterpreterException {
340        JavaMethod choices = Symbiosis.getMethods(wrappedClass_, Reflection.upSelector(methodName), true);
341        if (choices != null) {
342        	return choices;
343        } else {
344        	return super.meta_grabMethod(methodName);
345        }
346    }
347
348    /**
349     * Querying a symbiotic Java class object for its fields results in a table containing
350     * both 'native' static Java fields and the fields of its AT symbiont
351     */
352    public ATTable meta_listFields() throws InterpreterException {
353		// instance fields of the wrapped object's class
354		JavaField[] jFields = Symbiosis.getAllFields(null, wrappedClass_);
355        // fields of the AT symbiont
356    	ATObject[] symbiontFields = super.meta_listFields().asNativeTable().elements_;
357    	return NATTable.atValue(NATTable.collate(jFields, symbiontFields));
358    }
359
360    /**
361     * Querying a symbiotic Java class object for its methods results in a table containing
362     * both 'native' static Java methods and the methods of its AT symbiont
363     */
364    public ATTable meta_listMethods() throws InterpreterException {
365		// instance methods of the wrapped object's class
366		JavaMethod[] jMethods = Symbiosis.getAllMethods(wrappedClass_, true);
367        // methods of the AT symbiont
368		ATObject[] symbiontMethods = super.meta_listMethods().asNativeTable().elements_;
369		return NATTable.atValue(NATTable.collate(jMethods, symbiontMethods));
370    }
371
372	public ATBoolean meta_isCloneOf(ATObject original) throws InterpreterException {
373		return NATBoolean.atValue(this == original);
374	}
375	
376	public NATText meta_print() throws InterpreterException {
377		return NATText.atValue("<java:"+wrappedClass_.toString()+">");
378	}
379
380	/**
381     * A Java Class object remains unique within an actor.
382     */
383    public ATObject meta_resolve() throws InterpreterException {
384    	return wrapperFor(wrappedClass_);
385    }
386    
387    /* ========================
388     * == ATStripe Interface ==
389     * ======================== */
390    
391    /**
392     * If this class represents an interface type, parentStripes
393     * are wrappers for all interfaces extended by this Java interface type
394     */
395	public ATTable base_getParentStripes() throws InterpreterException {
396		return super.meta_select(this, _PST_NAME_).asTable();
397	}
398
399	public ATSymbol base_getStripeName() throws InterpreterException {
400		return super.meta_select(this, _SNM_NAME_).asSymbol();
401	}
402
403	/**
404	 * A Java interface type used as a stripe can only be a substripe of another
405	 * Java interface type used as a stripe, and only if this type is assignable
406	 * to the other type.
407	 */
408	public ATBoolean base_isSubstripeOf(ATStripe other) throws InterpreterException {
409		if (other instanceof JavaClass) {
410			JavaClass otherClass = (JavaClass) other;
411			// wrappedClass <: otherClass <=> otherClass >= wrappedClass
412			return NATBoolean.atValue(otherClass.wrappedClass_.isAssignableFrom(wrappedClass_));
413		} else {
414			return NATBoolean._FALSE_;
415		}
416	}
417	
418}