PageRenderTime 27ms CodeModel.GetById 10ms app.highlight 13ms RepoModel.GetById 1ms app.codeStats 0ms

/interpreter/tags/at2dist090708/src/edu/vub/at/objects/natives/NATCallframe.java

http://ambienttalk.googlecode.com/
Java | 357 lines | 196 code | 43 blank | 118 comment | 44 complexity | 5c8040f384d9456842659b6ce883172d MD5 | raw file
  1/**
  2 * AmbientTalk/2 Project
  3 * NATCallframe.java created on Jul 28, 2006 at 11:26:17 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.natives;
 29
 30import edu.vub.at.eval.Evaluator;
 31import edu.vub.at.exceptions.InterpreterException;
 32import edu.vub.at.exceptions.XDuplicateSlot;
 33import edu.vub.at.exceptions.XIllegalOperation;
 34import edu.vub.at.exceptions.XSelectorNotFound;
 35import edu.vub.at.exceptions.XUndefinedSlot;
 36import edu.vub.at.objects.ATBoolean;
 37import edu.vub.at.objects.ATField;
 38import edu.vub.at.objects.ATMethod;
 39import edu.vub.at.objects.ATNil;
 40import edu.vub.at.objects.ATObject;
 41import edu.vub.at.objects.ATTable;
 42import edu.vub.at.objects.grammar.ATSymbol;
 43
 44import java.util.Iterator;
 45import java.util.LinkedList;
 46import java.util.Vector;
 47
 48/**
 49 * NATCallframe is a native implementation of a callframe. A callframe differs from
 50 * an ordinary object in the following regards:
 51 * - it has no dynamic parent
 52 * - it treats method definition as the addition of a closure to its variables.
 53 * - it cannot be extended nor cloned
 54 * 
 55 * Callframes can be regarded as 'field-only' objects. Fields are implemented as follows:
 56 *  - native fields are implemented efficiently using a 'map': the map datastructure maps
 57 *    selectors to indices into a state vector, such that field names can be shared efficiently
 58 *    across clones.
 59 *  - custom fields are collected in a linked list. Their lookup and assignment is slower,
 60 *    and when an object is cloned, the custom field objects are re-instantiated.
 61 *    The new clone is passed as the sole argument to 'new'.
 62 * 
 63 * @author tvcutsem
 64 * @author smostinc
 65 */
 66public class NATCallframe extends NATByRef implements ATObject {
 67	
 68	protected FieldMap 		variableMap_;
 69	protected final Vector	stateVector_;
 70	
 71    /**
 72     * The lexical parent 'scope' of this call frame/object.
 73     * A lexical scope should never travel along with an object when it is serialized,
 74     * hence it is declared transient. Serializable isolate objects will have to reset
 75     * this field upon deserialization.
 76     */
 77	protected transient ATObject lexicalParent_;
 78	
 79	protected LinkedList customFields_;
 80	
 81	/**
 82	 * Default constructor: creates a new call frame with a given scope pointer.
 83	 */
 84	public NATCallframe(ATObject lexicalParent) {
 85		variableMap_   = new FieldMap();
 86		stateVector_   = new Vector();
 87		lexicalParent_ = lexicalParent;
 88		customFields_ = null;
 89	}
 90	
 91	/**
 92	 * Used internally for cloning a callframe/object.
 93	 */
 94	protected NATCallframe(FieldMap varMap, Vector stateVector, ATObject lexicalParent, LinkedList customFields) {
 95		variableMap_ = varMap;
 96		stateVector_ = stateVector;
 97		lexicalParent_ = lexicalParent;
 98		customFields_ = customFields;
 99	}
100	
101	/* ------------------------------------------
102	 * -- Slot accessing and mutating protocol --
103	 * ------------------------------------------ */
104
105	/**
106	 * A field can be added to either a call frame or an object.
107	 * In both cases, it is checked whether the field does not already exist.
108	 * If it does not, a new field is created and its value set to the given initial value.
109	 * @throws InterpreterException 
110	 */
111	public ATNil meta_defineField(ATSymbol name, ATObject value) throws InterpreterException {
112		if (this.hasLocalField(name) || this.hasLocalMethod(name)) {
113			// field already exists...
114			throw new XDuplicateSlot(name);			
115		} else {
116			boolean fieldAdded = variableMap_.put(name);
117			if (!fieldAdded) {
118				throw new RuntimeException("Assertion failed: field not added to map while not duplicate");
119			}
120			// field now defined, add its value to the state vector
121			stateVector_.add(value);
122		}
123		return Evaluator.getNil();
124	}
125
126	/* ------------------------------------
127	 * -- Extension and cloning protocol --
128	 * ------------------------------------ */
129
130	public ATObject meta_clone() throws InterpreterException {
131		throw new XIllegalOperation("Cannot clone a call frame, clone its owning object instead.");
132	}
133
134	public ATObject meta_newInstance(ATTable initargs) throws InterpreterException {
135		throw new XIllegalOperation("Cannot create a new instance of a call frame, new its owning object instead.");
136	}
137
138	/* ---------------------------------
139	 * -- Structural Access Protocol  --
140	 * --------------------------------- */
141	
142	public ATNil meta_addField(ATField field) throws InterpreterException {
143		// when adding a native field, revert to the more optimized implementation using the map
144		if (field.isNativeField()) {
145			return this.meta_defineField(field.base_name(), field.base_readField());
146		}
147		
148		ATSymbol name = field.base_name();
149		if (this.hasLocalField(name)) {
150			// field already exists...
151			throw new XDuplicateSlot(name);			
152		} else {
153			// add a clone of the field initialized with its new host
154			field = field.meta_newInstance(NATTable.of(this)).asField();
155			
156			// add the field to the list of custom fields, which is created lazily
157			if (customFields_ == null) {
158				customFields_ = new LinkedList();
159			}
160			// append the custom field object
161			customFields_.add(field);
162		}
163		return Evaluator.getNil();
164	}
165	
166	public ATNil meta_addMethod(ATMethod method) throws InterpreterException {
167		throw new XIllegalOperation("Cannot add method "+
168								   method.base_name().base_text().asNativeText().javaValue +
169				                    " to a call frame. Add it as a closure field instead.");
170	}
171	
172	public ATField meta_grabField(ATSymbol selector) throws InterpreterException {
173		if (this.hasLocalNativeField(selector)) {
174			return new NATField(selector, this);
175		} else {
176			ATField fld = this.getLocalCustomField(selector);
177			if (fld != null) {
178				return fld;
179			} else {
180				throw new XUndefinedSlot("field grabbed", selector.toString());
181			}
182		}
183	}
184
185	public ATMethod meta_grabMethod(ATSymbol selector) throws InterpreterException {
186		throw new XSelectorNotFound(selector, this);
187	}
188
189	public ATTable meta_listFields() throws InterpreterException {
190		ATObject[] nativeFields = new ATObject[stateVector_.size()];
191		ATSymbol[] fieldNames = variableMap_.listFields();
192		// native fields first
193		for (int i = 0; i < fieldNames.length; i++) {
194			nativeFields[i] = new NATField(fieldNames[i], this);
195		}
196		if (customFields_ == null) {
197			// no custom fields
198			return NATTable.atValue(nativeFields);
199		} else {
200			ATObject[] customFields = (ATObject[]) customFields_.toArray(new ATObject[customFields_.size()]);
201			return NATTable.atValue(NATTable.collate(nativeFields, customFields));
202		}
203	}
204
205	public ATTable meta_listMethods() throws InterpreterException {
206		return NATTable.EMPTY;
207	}
208	
209	public NATText meta_print() throws InterpreterException {
210		return NATText.atValue("<callframe>");
211	}
212	
213	/* ---------------------
214	 * -- Mirror Fields   --
215	 * --------------------- */
216	
217	/**
218	 * Auxiliary method to dynamically select the 'super' field from this object.
219	 * Note that this method is part of the base-level interface to an object.
220	 * 
221	 * Also note that this method performs the behaviour equivalent to evaluating
222	 * 'super' and not 'self.super', which could lead to infinite loops.
223	 */
224	public ATObject base_super() throws InterpreterException {
225		return this.impl_call(NATObject._SUPER_NAME_, NATTable.EMPTY);
226	};
227	
228	public ATObject impl_lexicalParent() throws InterpreterException {
229		return lexicalParent_;
230	}
231
232	/* --------------------------
233	 * -- Conversion Protocol  --
234	 * -------------------------- */
235	
236	public boolean isCallFrame() {
237		return true;
238	}
239	
240	public ATBoolean meta_isCloneOf(ATObject original) throws InterpreterException {
241		if(	(original instanceof NATCallframe) &
242			! (original instanceof NATObject)) {
243			FieldMap originalVariables = ((NATCallframe)original).variableMap_;
244			
245			return NATBoolean.atValue(
246					variableMap_.isDerivedFrom(originalVariables));
247		} else {
248			return NATBoolean._FALSE_;
249		}
250	}
251
252	public ATBoolean meta_isRelatedTo(ATObject object) throws InterpreterException {
253		return super.meta_isRelatedTo(object);
254	}
255	
256    /* -----------------------------
257     * -- Object Passing protocol --
258     * ----------------------------- */
259	
260	// protected methods, only to be used by NATCallframe and NATObject
261
262	protected boolean hasLocalField(ATSymbol selector) throws InterpreterException {
263		return hasLocalNativeField(selector) || hasLocalCustomField(selector);
264	}
265	
266	protected boolean hasLocalNativeField(ATSymbol selector) {
267		return variableMap_.get(selector) != -1;
268	}
269	
270	protected boolean hasLocalCustomField(ATSymbol selector) throws InterpreterException {
271		if (customFields_ == null) {
272			return false;
273		} else {
274			Iterator it = customFields_.iterator();
275			while (it.hasNext()) {
276				ATField field = (ATField) it.next();
277				if (field.base_name().equals(selector)) {
278					return true;
279				}
280			}
281			return false;
282		}
283	}
284	
285	/**
286	 * Reads out the value of either a native or a custom field.
287	 * @throws XSelectorNotFound if no native or custom field with the given name exists locally.
288	 */
289	protected ATObject getLocalField(ATSymbol selector) throws InterpreterException {
290		int index = variableMap_.get(selector);
291		if(index != -1) {
292			return (ATObject) (stateVector_.get(index));
293		} else {
294			ATField fld = getLocalCustomField(selector);
295			if (fld != null) {
296				return fld.base_readField();
297			} else {
298				throw new XSelectorNotFound(selector, this);
299			}
300		}
301	}
302	
303	/**
304	 * @return a custom field matching the given selector or null if such a field does not exist
305	 */
306	protected ATField getLocalCustomField(ATSymbol selector) throws InterpreterException {
307		if (customFields_ == null) {
308			return null;
309		} else {
310			Iterator it = customFields_.iterator();
311			while (it.hasNext()) {
312				ATField field = (ATField) it.next();
313				if (field.base_name().equals(selector)) {
314					return field;
315				}
316			}
317			return null;
318		}
319	}
320	
321	/**
322	 * Set a given field if it exists.
323	 */
324	protected void setLocalField(ATSymbol selector, ATObject value) throws InterpreterException {
325		int index = variableMap_.get(selector);
326		if(index != -1) {
327			// field exists, modify the state vector
328			stateVector_.set(index, value);
329			// ok
330		} else {
331			ATField fld = getLocalCustomField(selector);
332			if (fld != null) {
333				fld.base_writeField(value);
334				// ok
335			} else {
336				// fail
337				throw new XSelectorNotFound(selector, this);
338			}
339		}
340	}
341
342	/**
343	 * A call frame has no methods.
344	 */
345	protected boolean hasLocalMethod(ATSymbol atSelector) throws InterpreterException {
346        return false;
347	}
348	
349	/**
350	 * A call frame has no methods.
351	 */
352	protected ATMethod getLocalMethod(ATSymbol selector) throws InterpreterException {
353		throw new XSelectorNotFound(selector, this);
354	}
355
356	
357}