PageRenderTime 21ms CodeModel.GetById 2ms app.highlight 15ms RepoModel.GetById 1ms app.codeStats 0ms

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

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