PageRenderTime 30ms CodeModel.GetById 9ms app.highlight 17ms RepoModel.GetById 1ms app.codeStats 0ms

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

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