PageRenderTime 22ms CodeModel.GetById 13ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/interpreter/tags/at2dist041108/src/edu/vub/at/objects/mirrors/NATIntrospectiveMirror.java

http://ambienttalk.googlecode.com/
Java | 251 lines | 94 code | 24 blank | 133 comment | 8 complexity | 8b5f17870b3486e06317149be9820316 MD5 | raw file
  1/**
  2 * AmbientTalk/2 Project
  3 * NATMirror.java created on Aug 13, 2006 at 10:09:29 AM
  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.mirrors;
 29
 30import edu.vub.at.actors.net.OBJNetwork;
 31import edu.vub.at.eval.Evaluator;
 32import edu.vub.at.exceptions.InterpreterException;
 33import edu.vub.at.exceptions.XArityMismatch;
 34import edu.vub.at.exceptions.XIllegalOperation;
 35import edu.vub.at.exceptions.XSelectorNotFound;
 36import edu.vub.at.exceptions.XTypeMismatch;
 37import edu.vub.at.objects.ATBoolean;
 38import edu.vub.at.objects.ATMethod;
 39import edu.vub.at.objects.ATObject;
 40import edu.vub.at.objects.ATTable;
 41import edu.vub.at.objects.coercion.NativeTypeTags;
 42import edu.vub.at.objects.grammar.ATSymbol;
 43import edu.vub.at.objects.natives.NATBoolean;
 44import edu.vub.at.objects.natives.NATByRef;
 45import edu.vub.at.objects.natives.NATNil;
 46import edu.vub.at.objects.natives.NATNumber;
 47import edu.vub.at.objects.natives.NATTable;
 48import edu.vub.at.objects.natives.NATText;
 49
 50/**
 51 * <p>NATIntrospectiveMirror is a default mirror to represent an ambienttalk object 
 52 * which is capable of offering the java meta-interface of any language value at the 
 53 * ambienttalk level. This allows introspection into the language value's internals
 54 * as well as invoking some meta-level operations on it. Technically, NATMirror is 
 55 * simply a wrapper object around an ambienttalk object which deifies (ups) methods 
 56 * invoked upon it.</p>
 57 * 
 58 * <p>Note that whereas the mirror can offer e.g. an apply method when reifying a 
 59 * closure, this does not affect its own meta-interface. A NATMirror is always an 
 60 * object and can thus not be applied at the ambienttalk level.</p>
 61 * 
 62 * Example:
 63 * <pre>
 64 * def clo := { | x | x * 2 };
 65 * def  m  := at.mirrors.Factory.createMirror(clo);
 66 * 
 67 * clo( 5 )     <i> => 10 (legal) </i>
 68 * m.apply([5]) <i> => 10 (legal) </i>
 69 * m( 5 )       <i> => error (Application expected a closure, given a mirror) </i>
 70 * </pre>
 71 * 
 72 * @author smostinc
 73 * @author tvcutsem
 74 */
 75
 76public class NATIntrospectiveMirror extends NATByRef {
 77
 78	/** the object reflected on. This object is NOT a NATMirage */
 79	private final ATObject principal_;
 80	
 81	/**
 82	 * Return a mirror on the given native or custom AmbientTalk object.
 83	 * 
 84	 * @param objectRepresentation the object to reflect upon
 85	 * @return either an introspective mirror (if the passed object is native), otherwise
 86	 * a custom intercessive mirror.
 87	 */
 88	public static final ATObject atValue(ATObject objectRepresentation) throws XTypeMismatch, XIllegalOperation {
 89		if (objectRepresentation.isMirage()) {
 90			ATObject mirror = objectRepresentation.asMirage().getMirror();
 91			if (mirror.equals(Evaluator.getNil())) {
 92				// this case is triggered if an introspective mirror is being created
 93				// for a new, empty, mirage object. Example:
 94				//   object: {} mirroredBy: (reflect: (object:{}))
 95				// (here, reflect: (object:{}) returns an introspective mirror)
 96				//
 97				// Since mirages must be mirrored by intercessive mirrors, we simply return
 98				// a new instance of the defaultMirror (since introspective mirrors
 99				// encapsulate 'default' semantics anyway)
100				return new NATMirrorRoot(objectRepresentation.asMirage());
101			} else {
102				return mirror;
103			}
104		} else {
105			return new NATIntrospectiveMirror(objectRepresentation);
106		}
107	}
108	
109	/**
110	 * An introspective mirror is a wrapper which forwards a deified (upped) version of invoked 
111	 * methods and field accesses to its principal. This principal is a Java object 
112	 * representing an ambienttalk object. The deificiation process implies that 
113	 * only the object's meta_level operations (implemented in Java) will be called
114	 * directly by the mirror.
115	 * 
116	 * @param representation - the object to reflect upon, which is *not* a NATMirage
117	 */
118	private NATIntrospectiveMirror(ATObject representation) {
119		principal_ = representation;
120	}
121	
122	public NATIntrospectiveMirror asNativeIntrospectiveMirror() {
123		return this;
124	}
125
126	public boolean isNativeIntrospectiveMirror() {
127		return true;
128	}
129
130	/**
131	 * This method is used to allow selecting the base field of an intercessive mirror using 
132	 * the reflective selection of fields. This method is never invoked directly by the 
133	 * implementation.
134	 * @return the base-level entity this mirror reflects on
135	 */
136	public ATObject base_base() {
137		return principal_;
138	}
139	
140	public int hashCode() { return principal_.hashCode(); }
141	
142	public ATBoolean base__opeql__opeql_(ATObject other) throws InterpreterException {
143		if (other.isNativeIntrospectiveMirror()) {
144			return NATBoolean.atValue(principal_.equals(other.asNativeIntrospectiveMirror().principal_));
145		} else {
146			return NATBoolean._FALSE_;
147		}
148	}
149	
150	/* ------------------------------------------
151	 * -- Slot accessing and mutating protocol --
152	 * ------------------------------------------ */
153
154    
155    public ATMethod meta_grabMethod(ATSymbol methodName) throws InterpreterException {
156        try {
157        	// try to find a meta_ method in the principal
158			return Reflection.downMetaLevelMethod(principal_, methodName);
159		} catch (XSelectorNotFound e) {
160			e.catchOnlyIfSelectorEquals(methodName);
161			// try to find a base_ method in the mirror
162			return super.meta_grabMethod(methodName);
163		}
164    }
165
166	/**
167	 * Listing the methods of a mirror requires us to list all of the meta_ methods
168	 * of the principal + all of the base_ methods of the mirror itself
169	 */
170    public ATTable meta_listMethods() throws InterpreterException {
171   	    ATMethod[] principalMetaMethods = Reflection.downMetaLevelMethods(principal_);
172   	    ATMethod[] mirrorBaseMethods = Reflection.downBaseLevelMethods(this);
173        return NATTable.atValue(NATTable.collate(principalMetaMethods, mirrorBaseMethods));
174    }
175	
176	/* ------------------------------------
177	 * -- Extension and cloning protocol --
178	 * ------------------------------------ */
179
180	/**
181	 * This method makes a new mirror object. However, since the link from a 
182	 * mirror to its base object is immutable, this results in contacting the mirror
183	 * factory, to create a (new) mirror for the requested object.
184	 * @param initargs  an ATObject[] containing as its first element the object that needs to be reflects upon
185	 * @return <b>another</b> (possibly new) mirror object 
186	 */
187	public ATObject meta_newInstance(ATTable initargs) throws InterpreterException {
188    	int len = initargs.base_length().asNativeNumber().javaValue;
189		if (len != 1)
190			throw new XArityMismatch("init method of mirror", 1, len);
191		ATObject reflectee = initargs.base_at(NATNumber.ONE);
192		return atValue(reflectee);
193	}
194	
195	/* ---------------------------------
196	 * -- Abstract Grammar Protocol   --
197	 * --------------------------------- */
198		
199	public NATText meta_print() throws InterpreterException {
200		return NATText.atValue("<mirror on:"+principal_.meta_print().javaValue+">");
201	}
202	
203    public ATTable meta_typeTags() throws InterpreterException {
204    	return NATTable.of(NativeTypeTags._MIRROR_);
205    }
206	
207	/**
208	 * OBSOLETE: introspective mirrors are now pass-by-reference.
209	 * This has the following repercussions:
210	 *  - when passing the mirror of an isolate, a remote ref to the mirror is passed instead.
211	 *    The isolate is not copied.
212	 *  - mirrors on far references can still be created, by passing the principal by ref
213	 *    and by reflecting on the obtained far reference
214	 * 
215	 * An introspective mirror is pass-by-copy.
216     * When an introspective mirror is deserialized, it will become a mirror on
217     * its deserialized principal. This means that, if the principal is passed
218     * by copy, the mirror will be a local mirror on the copy. If the principal is passed
219     * by reference, the mirror will be a local mirror on the far reference.
220	 */
221	/*public ATObject meta_resolve() throws InterpreterException {
222		if(principal_ instanceof NATMirage)
223			return ((NATMirage)principal_).getMirror();
224		else
225			return this;
226	}*/
227
228	/**
229	 * For mirrors, first try to find a <tt>meta_</tt> method in the principal.
230	 * If this fails, try to find a <tt>base_</tt> method in the introspective mirror itself.
231	 */
232	protected boolean hasLocalMethod(ATSymbol atSelector) throws InterpreterException {
233        return Reflection.upRespondsTo(principal_, Reflection.upMetaLevelSelector(atSelector)) ||
234               super.hasLocalMethod(atSelector);
235	}
236	
237	/**
238	 * For mirrors, first try to find a <tt>meta_</tt> method in the principal.
239	 * If this fails, try to find a <tt>base_</tt> method in the introspective mirror itself.
240	 */
241	protected ATMethod getLocalMethod(ATSymbol selector) throws InterpreterException {
242		try {
243			String methSelector = Reflection.upMetaLevelSelector(selector);
244			return Reflection.upMethodSelection(principal_, methSelector, selector);
245		} catch (XSelectorNotFound e) {
246			e.catchOnlyIfSelectorEquals(selector);
247			return super.getLocalMethod(selector);
248		}
249	}
250
251}