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