/interpreter/tags/at2-build190607/src/edu/vub/at/objects/natives/NATObject.java

http://ambienttalk.googlecode.com/ · Java · 948 lines · 443 code · 99 blank · 406 comment · 70 complexity · b3ec4a357f6bead64b4c738fcb7a9bbd MD5 · raw file

  1. /**
  2. * AmbientTalk/2 Project
  3. * NATObject.java created on Jul 13, 2006 at 3:52:15 PM
  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.actors.ATActorMirror;
  30. import edu.vub.at.actors.ATAsyncMessage;
  31. import edu.vub.at.eval.Evaluator;
  32. import edu.vub.at.exceptions.InterpreterException;
  33. import edu.vub.at.exceptions.XArityMismatch;
  34. import edu.vub.at.exceptions.XDuplicateSlot;
  35. import edu.vub.at.exceptions.XSelectorNotFound;
  36. import edu.vub.at.exceptions.XTypeMismatch;
  37. import edu.vub.at.objects.ATBoolean;
  38. import edu.vub.at.objects.ATClosure;
  39. import edu.vub.at.objects.ATContext;
  40. import edu.vub.at.objects.ATField;
  41. import edu.vub.at.objects.ATHandler;
  42. import edu.vub.at.objects.ATMessage;
  43. import edu.vub.at.objects.ATMethod;
  44. import edu.vub.at.objects.ATNil;
  45. import edu.vub.at.objects.ATNumber;
  46. import edu.vub.at.objects.ATObject;
  47. import edu.vub.at.objects.ATTypeTag;
  48. import edu.vub.at.objects.ATTable;
  49. import edu.vub.at.objects.coercion.Coercer;
  50. import edu.vub.at.objects.coercion.NativeTypeTags;
  51. import edu.vub.at.objects.grammar.ATBegin;
  52. import edu.vub.at.objects.grammar.ATDefinition;
  53. import edu.vub.at.objects.grammar.ATExpression;
  54. import edu.vub.at.objects.grammar.ATMessageCreation;
  55. import edu.vub.at.objects.grammar.ATSplice;
  56. import edu.vub.at.objects.grammar.ATStatement;
  57. import edu.vub.at.objects.grammar.ATSymbol;
  58. import edu.vub.at.objects.grammar.ATUnquoteSplice;
  59. import edu.vub.at.objects.mirrors.NativeClosure;
  60. import edu.vub.at.objects.mirrors.PrimitiveMethod;
  61. import edu.vub.at.objects.natives.grammar.AGSplice;
  62. import edu.vub.at.objects.natives.grammar.AGSymbol;
  63. import edu.vub.at.util.logging.Logging;
  64. import java.util.Collection;
  65. import java.util.HashSet;
  66. import java.util.Iterator;
  67. import java.util.LinkedList;
  68. import java.util.Vector;
  69. /**
  70. * Native implementation of a default ambienttalk object.
  71. * Although a native AmbientTalk object is implemented as a subtype of callframes,
  72. * the reality is that call frames are a special kind of object.
  73. * This is a pure form of implementation subclassing: we subclass NATCallframe only
  74. * for reusing the field definition/assignment protocol and for inheriting the
  75. * variable map, the state vector and the lexical parent.
  76. * <p>
  77. * NATObjects are one of the five native classes that (almost) fully implement the ATObject interface
  78. * (next to NATCallFrame, NATNil, NATMirage and JavaObject). The implementation is such that
  79. * a NATObject instance represents <b>both</b> a base-level AmbientTalk object, as well as a meta-level
  80. * AmbientTalk mirror on that object.
  81. *
  82. * An AmbientTalk base-level object has the following structure:
  83. * <ul>
  84. * <li> properties: a set of boolean flags denoting:
  85. * <ul>
  86. * <li> whether the dynamic parent is an IS_A or a SHARES_A parent
  87. * <li> whether the object shares its variable map with clones
  88. * <li> whether the object shares its method dictionary with clones
  89. * <li> whether the object is an isolate (i.e. pass-by-copy)
  90. * </ul>
  91. * <li> a variable map, mapping variable names to indices into the state vector
  92. * <li> a state vector, containing the field values of the object
  93. * <li> a linked list containing custom field objects
  94. * <li> a method dictionary, mapping selectors to methods
  95. * <li> a dynamic object parent, to delegate select and invoke operations
  96. * ( this parent slot is represented by a true AmbientTalk field, rather than by an instance variable )
  97. * <li> a lexical object parent, to support lexical scoping
  98. * <li> a table of type tags that were attached to this object (for classification purposes)
  99. * </ul>
  100. *
  101. * @author tvcutsem
  102. * @author smostinc
  103. */
  104. public class NATObject extends NATCallframe implements ATObject {
  105. // The name of the field that points to the dynamic parent
  106. public static final AGSymbol _SUPER_NAME_ = AGSymbol.jAlloc("super");
  107. // The names of the primitive methods
  108. public static final AGSymbol _EQL_NAME_ = AGSymbol.jAlloc("==");
  109. public static final AGSymbol _NEW_NAME_ = AGSymbol.jAlloc("new");
  110. public static final AGSymbol _INI_NAME_ = AGSymbol.jAlloc("init");
  111. // The primitive methods themselves
  112. /** def ==(comparand) { nil } */
  113. private static final PrimitiveMethod _PRIM_EQL_ = new PrimitiveMethod(
  114. _EQL_NAME_, NATTable.atValue(new ATObject[] { AGSymbol.jAlloc("comparand")})) {
  115. public ATObject base_apply(ATTable arguments, ATContext ctx) throws InterpreterException {
  116. if (!arguments.base_getLength().equals(NATNumber.ONE)) {
  117. throw new XArityMismatch("==", 1, arguments.base_getLength().asNativeNumber().javaValue);
  118. }
  119. // primitive implementation uses pointer equality (as dictated by NATNil)
  120. return NATBoolean.atValue(ctx.base_getLexicalScope() == arguments.base_at(NATNumber.ONE));
  121. }
  122. };
  123. /** def new(@initargs) { nil } */
  124. private static final PrimitiveMethod _PRIM_NEW_ = new PrimitiveMethod(
  125. _NEW_NAME_, NATTable.atValue(new ATObject[] { new AGSplice(AGSymbol.jAlloc("initargs")) })) {
  126. public ATObject base_apply(ATTable arguments, ATContext ctx) throws InterpreterException {
  127. return ctx.base_getLexicalScope().base_new(arguments.asNativeTable().elements_);
  128. }
  129. };
  130. /** def init(@initargs) { nil } */
  131. private static final PrimitiveMethod _PRIM_INI_ = new PrimitiveMethod(
  132. _INI_NAME_, NATTable.atValue(new ATObject[] { new AGSplice(AGSymbol.jAlloc("initargs")) })) {
  133. public ATObject base_apply(ATTable arguments, ATContext ctx) throws InterpreterException {
  134. return ctx.base_getLexicalScope().asAmbientTalkObject().prim_init(ctx.base_getSelf(), arguments.asNativeTable().elements_);
  135. }
  136. };
  137. /**
  138. * Does the selector signify a 'primitive' method, present in each AmbientTalk object?
  139. */
  140. public static boolean isPrimitive(ATSymbol name) {
  141. return name.equals(_EQL_NAME_) || name.equals(_NEW_NAME_) || name.equals(_INI_NAME_);
  142. }
  143. // Auxiliary static methods to support the type of dynamic parent
  144. public static final boolean _IS_A_ = true;
  145. public static final boolean _SHARES_A_ = false;
  146. /**
  147. * This flag determines the type of parent pointer of this object. We distinguish two cases:
  148. * - 1: an is-a link, which results in a recursive cloning of the parent when this object is cloned.
  149. * - 0: a shares-a link, which ensures that clones of this object share the same parent.
  150. */
  151. private static final byte _ISAPARENT_FLAG_ = 1<<0;
  152. /**
  153. * This flag determines whether or not the field map of this object is shared by other objects:
  154. * - 1: the map is shared, so modifications must be performed on a copy
  155. * - 0: the map is not shared, modifications may be directly performed on it
  156. *
  157. * This flag is important for maintaining the semantics that clones are self-sufficient objects:
  158. * they share field names and methods only at the implementation-level.
  159. */
  160. private static final byte _SHARE_MAP_FLAG_ = 1<<1;
  161. /**
  162. * Similar to _SHARE_MAP_FLAG__ but for determining the shared status of the method dictionary.
  163. */
  164. private static final byte _SHARE_DCT_FLAG_ = 1<<2;
  165. /**
  166. * This flag determines whether or not the object is an isolate and hence pass-by-copy:
  167. * - 1: the object is an isolate, pass-by-copy and no lexical parent except for the root
  168. * - 0: the object is pass-by-reference and can have any lexical parent
  169. */
  170. private static final byte _IS_ISOLATE_FLAG_ = 1<<3;
  171. /**
  172. * An empty type tag array shared by those objects that do not have any type tags.
  173. */
  174. public static final ATTypeTag[] _NO_TYPETAGS_ = new ATTypeTag[0];
  175. /**
  176. * The flags of an AmbientTalk object encode the following boolean information:
  177. * Format: 0b0000idap where
  178. * p = parent flag: if set, dynamic parent is 'is-a' parent, otherwise 'shares-a' parent
  179. * a = shares map flag: if set, the map of this object is shared between clones
  180. * d = shares dictionary flag: if set, the method dictionary of this object is shared between clones
  181. * i = is isolate flag: if set, the object is passed by copy in inter-actor communication
  182. */
  183. private byte flags_;
  184. // inherited from NATCallframe:
  185. // private FieldMap variableMap_;
  186. // private Vector stateVector_;
  187. // private LinkedList customFields_;
  188. /**
  189. * The method dictionary of this object. It maps method selectors to ATMethod objects.
  190. */
  191. private MethodDictionary methodDictionary_;
  192. /**
  193. * The types with which this object has been tagged.
  194. */
  195. protected ATTypeTag[] typeTags_;
  196. /* ------------------
  197. * -- Constructors --
  198. * ------------------ */
  199. /**
  200. * Creates an object tagged with the at.types.Isolate type.
  201. * Such an object is called an isolate because:
  202. * - it has no access to an enclosing lexical scope (except for the root lexical scope)
  203. * - it can therefore be passed by copy
  204. */
  205. public static NATObject createIsolate() {
  206. return new NATObject(new ATTypeTag[] { NativeTypeTags._ISOLATE_ });
  207. }
  208. /**
  209. * Constructs a new AmbientTalk object whose lexical parent is the
  210. * global scope and whose dynamic parent is the dynamic root.
  211. */
  212. public NATObject() {
  213. this(Evaluator.getGlobalLexicalScope());
  214. }
  215. public NATObject(ATTypeTag[] tags) {
  216. this(Evaluator.getGlobalLexicalScope(), tags);
  217. }
  218. /**
  219. * Constructs a new ambienttalk object parametrised by a lexical scope. The
  220. * object is thus not equipped with a pointer to a dynamic parent.
  221. * @param lexicalParent - the lexical scope in which the object's definition was nested
  222. */
  223. public NATObject(ATObject lexicalParent) {
  224. this(NATNil._INSTANCE_, lexicalParent, _SHARES_A_);
  225. }
  226. /**
  227. * Constructs a new ambienttalk object parametrised by a lexical scope.
  228. * The object's dynamic parent is nil and is tagged with the given table of type tags
  229. */
  230. public NATObject(ATObject lexicalParent, ATTypeTag[] tags) {
  231. this(NATNil._INSTANCE_, lexicalParent, _SHARES_A_, tags);
  232. }
  233. /**
  234. * Constructs a new ambienttalk object with the given dynamic parent.
  235. * The lexical parent is assumed to be the global scope.
  236. * @param dynamicParent - the dynamic parent of the new object
  237. * @param parentType - the type of parent link
  238. */
  239. public NATObject(ATObject dynamicParent, boolean parentType) {
  240. this(dynamicParent, Evaluator.getGlobalLexicalScope(), parentType);
  241. }
  242. /**
  243. * Constructs a new ambienttalk object based on a set of parent pointers.
  244. * The object has no types.
  245. * @param dynamicParent - the parent object of the newly created object
  246. * @param lexicalParent - the lexical scope in which the object's definition was nested
  247. * @param parentType - how this object extends its dynamic parent (is-a or shares-a)
  248. */
  249. public NATObject(ATObject dynamicParent, ATObject lexicalParent, boolean parentType) {
  250. this(dynamicParent, lexicalParent, parentType, _NO_TYPETAGS_);
  251. }
  252. /**
  253. * Constructs a new ambienttalk object based on a set of parent pointers.
  254. * The object is typed with the given types.
  255. * @param dynamicParent - the parent object of the newly created object
  256. * @param lexicalParent - the lexical scope in which the object's definition was nested
  257. * @param parentType - how this object extends its dynamic parent (is-a or shares-a)
  258. * @param tags - the type tags attached to this object
  259. */
  260. public NATObject(ATObject dynamicParent, ATObject lexicalParent, boolean parentType, ATTypeTag[] tags) {
  261. super(lexicalParent);
  262. // by default, an object has a shares-a parent, does not share its map
  263. // or dictionary and is no isolate, so all flags are set to 0
  264. flags_ = 0;
  265. typeTags_ = tags;
  266. methodDictionary_ = new MethodDictionary();
  267. // bind the dynamic parent to the field named 'super'
  268. // we don't pass via meta_defineField as this would trigger mirages too early
  269. variableMap_.put(_SUPER_NAME_);
  270. stateVector_.add(dynamicParent);
  271. // add ==, new and init to the method dictionary directly
  272. // we don't pass via meta_addMethod as this would trigger mirages too early
  273. methodDictionary_.put(_EQL_NAME_, _PRIM_EQL_);
  274. methodDictionary_.put(_NEW_NAME_, _PRIM_NEW_);
  275. methodDictionary_.put(_INI_NAME_, _PRIM_INI_);
  276. if (parentType) { // parentType == _IS_A_)
  277. // requested an 'is-a' parent
  278. setFlag(_ISAPARENT_FLAG_); // set is-a parent flag to 1
  279. }
  280. try {
  281. // if this object is tagged as at.types.Isolate, flag it as an isolate
  282. // we cannot perform 'this.meta_isTypedAs(ISOLATE)' because this would trigger mirages too early
  283. if (isLocallyTaggedAs(NativeTypeTags._ISOLATE_)
  284. || dynamicParent.meta_isTaggedAs(NativeTypeTags._ISOLATE_).asNativeBoolean().javaValue) {
  285. setFlag(_IS_ISOLATE_FLAG_);
  286. // isolates can only have the global lexical root as their lexical scope
  287. lexicalParent_ = Evaluator.getGlobalLexicalScope();
  288. }
  289. } catch (InterpreterException e) {
  290. // some custom type failed to match agains the Isolate type,
  291. // the object is not considered an Isolate
  292. Logging.Actor_LOG.error("Error testing for Isolate type, ignored:", e);
  293. }
  294. }
  295. /**
  296. * Constructs a new ambienttalk object as a clone of an existing object.
  297. *
  298. * The caller of this method *must* ensure that the shares flags are set.
  299. *
  300. * This constructor is responsible for manually re-initialising any custom field
  301. * objects, because the init method of such custom fields is parameterized by the
  302. * clone, which only comes into existence when this constructor runs.
  303. */
  304. protected NATObject(FieldMap map,
  305. Vector state,
  306. LinkedList originalCustomFields,
  307. MethodDictionary methodDict,
  308. ATObject dynamicParent,
  309. ATObject lexicalParent,
  310. byte flags,
  311. ATTypeTag[] types) throws InterpreterException {
  312. super(map, state, lexicalParent, null);
  313. methodDictionary_ = methodDict;
  314. flags_ = flags; //a cloned object inherits all flags from original
  315. // clone inherits all types (this implies that clones of isolates are also isolates)
  316. typeTags_ = types;
  317. // ==, new and init should already be present in the method dictionary
  318. // set the 'super' field to point to the new dynamic parent
  319. setLocalField(_SUPER_NAME_, dynamicParent);
  320. // re-initialize all custom fields
  321. if (originalCustomFields != null) {
  322. customFields_ = new LinkedList();
  323. Iterator it = originalCustomFields.iterator();
  324. while (it.hasNext()) {
  325. ATField field = (ATField) it.next();
  326. customFields_.add(field.base_new(new ATObject[] { this }).asField());
  327. }
  328. }
  329. }
  330. /**
  331. * Initialize a new AmbientTalk object with the given closure.
  332. *
  333. * The closure encapsulates:
  334. * - the code with which to initialize the object
  335. * - the lexical parent of the object (but that parent should already be set)
  336. * - the lexically inherited fields for the object (the parameters of the closure)
  337. */
  338. public void initializeWithCode(ATClosure code) throws InterpreterException {
  339. NATTable copiedBindings = Evaluator.evalMandatoryPars(
  340. code.base_getMethod().base_getParameters(),
  341. code.base_getContext());
  342. code.base_applyInScope(copiedBindings, this);
  343. }
  344. /**
  345. * Invoke NATObject's primitive implementation, such that Java invocations of this
  346. * method have the same behaviour as AmbientTalk invocations.
  347. */
  348. public ATObject base_init(ATObject[] initargs) throws InterpreterException {
  349. return this.prim_init(this, initargs);
  350. }
  351. /**
  352. * The primitive implementation of init in objects is to invoke the init
  353. * method of their parent.
  354. * @param self the object that originally received the 'init' message.
  355. *
  356. * def init(@args) {
  357. * super^init(@args)
  358. * }
  359. */
  360. private ATObject prim_init(ATObject self, ATObject[] initargs) throws InterpreterException {
  361. ATObject parent = base_getSuper();
  362. return parent.meta_invoke(self, Evaluator._INIT_, NATTable.atValue(initargs));
  363. }
  364. public ATBoolean base__opeql__opeql_(ATObject comparand) throws InterpreterException {
  365. return this.meta_invoke(this, _EQL_NAME_, NATTable.of(comparand)).asBoolean();
  366. }
  367. /* ------------------------------
  368. * -- Message Sending Protocol --
  369. * ------------------------------ */
  370. /**
  371. * Invocations on an object ( <tt>o.m( args )</tt> ) are handled by looking up the requested
  372. * selector in the dynamic parent chain of the receiver. This dynamic lookup process
  373. * yields exactly the same result as a selection (e.g. <tt>o.m</tt>). The result
  374. * ought to be a closure (a method and its corresponding evaluation context), which
  375. * is applied to the provided arguments.
  376. *
  377. * The code for meta_invoke is actually equivalent to
  378. * <pre>return this.meta_select(receiver, selector).asClosure().meta_apply(arguments);</pre>
  379. * but has a specialized implementation for performance reasons (no unnecessary closure is created)
  380. */
  381. public ATObject meta_invoke(ATObject receiver, ATSymbol selector, ATTable arguments) throws InterpreterException {
  382. if (this.hasLocalField(selector)) {
  383. return this.getLocalField(selector).asClosure().base_apply(arguments);
  384. } else if (this.hasLocalMethod(selector)) {
  385. // immediately execute the method in the context ctx where
  386. // ctx.scope = the implementing scope, being this object, under which an additional callframe will be inserted
  387. // ctx.self = the late bound receiver, being the passed receiver
  388. return this.getLocalMethod(selector).base_apply(arguments, new NATContext(this, receiver));
  389. } else {
  390. return base_getSuper().meta_invoke(receiver, selector, arguments);
  391. }
  392. }
  393. /**
  394. * An ambienttalk object can respond to a message if a corresponding field or method exists
  395. * either in the receiver object locally, or in one of its dynamic parents.
  396. */
  397. public ATBoolean meta_respondsTo(ATSymbol selector) throws InterpreterException {
  398. if (this.hasLocalField(selector) || this.hasLocalMethod(selector))
  399. return NATBoolean._TRUE_;
  400. else
  401. return base_getSuper().meta_respondsTo(selector);
  402. }
  403. /* ------------------------------------------
  404. * -- Slot accessing and mutating protocol --
  405. * ------------------------------------------ */
  406. /**
  407. * meta_select is used to evaluate code of the form <tt>o.m</tt>.
  408. *
  409. * To select a slot from an object:
  410. * - first, the list of fields of the current receiver ('this') is searched.
  411. * If a matching field exists, its value is returned.
  412. * - second, the list of methods of the current receiver is searched.
  413. * If a matching method exists, it is returned, but wrapped in a closure.
  414. * This wrapping is vital to ensure that the method is paired with the correct 'self'.
  415. * This 'self' does not necessarily equal 'this'.
  416. * - third, the search for the slot is carried out recursively in the dynamic parent.
  417. * As such, slot selection traverses the dynamic parent chain up to a dynamic root.
  418. * The dynamic root deals with an unbound slot by sending the 'doesNotUnderstand' message
  419. * to the original receiver.
  420. *
  421. * @param receiver the original receiver of the selection
  422. * @param selector the selector to look up
  423. * @return the value of the found field, or a closure wrapping a found method
  424. */
  425. public ATObject meta_select(ATObject receiver, ATSymbol selector) throws InterpreterException {
  426. if (this.hasLocalField(selector)) {
  427. return this.getLocalField(selector);
  428. } else if (this.hasLocalMethod(selector)) {
  429. // return a new closure (mth, ctx) where
  430. // mth = the method found in this object
  431. // ctx.scope = the implementing scope, being this object
  432. // ctx.self = the late bound receiver, being the passed receiver
  433. // ctx.super = the parent of the implementor
  434. return new NATClosure(this.getLocalMethod(selector), this, receiver);
  435. } else {
  436. return base_getSuper().meta_select(receiver, selector);
  437. }
  438. }
  439. /**
  440. * This method corresponds to code of the form ( x ) within the scope of this
  441. * object. It searches for the requested selector among the methods and fields
  442. * of the object and its dynamic parents.
  443. *
  444. * Overridden from NATCallframe to take methods into account as well.
  445. *
  446. * This method is used to evaluate code of the form <tt>selector</tt> within the scope
  447. * of this object. An object resolves such a lookup request as follows:
  448. * - If a field corresponding to the selector exists locally, the field's value is returned.
  449. * - If a method corresponding to the selector exists locally, the method is wrapped
  450. * using the current object itself as implementor AND as 'self'.
  451. * The reason for setting the closure's 'self' to the implementor is because a lookup can only
  452. * be initiated by the object itself or a lexically nested one. Lexical nesting, however, has
  453. * nothing to do with dynamic delegation, and it would be wrong to bind 'self' to a nested object
  454. * which need not be a dynamic child of the implementor.
  455. *
  456. * - Otherwise, the search continues recursively in the object's lexical parent.
  457. */
  458. public ATObject meta_lookup(ATSymbol selector) throws InterpreterException {
  459. if (this.hasLocalField(selector)) {
  460. return this.getLocalField(selector);
  461. } else if (this.hasLocalMethod(selector)) {
  462. // return a new closure (mth, ctx) where
  463. // mth = the method found in this object
  464. // ctx.scope = the implementing scope, being this object
  465. // ctx.self = the receiver, being in this case again the implementor
  466. return new NATClosure(this.getLocalMethod(selector),this, this);
  467. } else {
  468. return lexicalParent_.meta_lookup(selector);
  469. }
  470. }
  471. /**
  472. * When a new field is defined in an object, it is important to check whether or not
  473. * the field map is shared between clones or not. If it is shared, the map must be cloned first.
  474. * @throws InterpreterException
  475. */
  476. public ATNil meta_defineField(ATSymbol name, ATObject value) throws InterpreterException {
  477. if (this.isFlagSet(_SHARE_MAP_FLAG_)) {
  478. // copy the variable map
  479. variableMap_ = variableMap_.copy();
  480. // set the 'shares map' flag to false
  481. unsetFlag(_SHARE_MAP_FLAG_);
  482. }
  483. return super.meta_defineField(name, value);
  484. }
  485. /**
  486. * meta_assignField is used to evaluate code of the form <tt>o.m := v</tt>.
  487. *
  488. * To assign a field in an object:
  489. * - first, the list of fields of the current receiver ('this') is searched.
  490. * If a matching field exists, its value is set.
  491. * - If the field is not found, the search for the slot is carried out recursively in the dynamic parent.
  492. * As such, field assignment traverses the dynamic parent chain up to a dynamic root.
  493. * The dynamic root deals with an unbound field by throwing an error.
  494. * @param value the value to assign to the field
  495. * @param selector the field to assign
  496. *
  497. * @return NIL
  498. */
  499. public ATNil meta_assignField(ATObject receiver, ATSymbol selector, ATObject value) throws InterpreterException {
  500. if (this.setLocalField(selector, value)) {
  501. return NATNil._INSTANCE_;
  502. } else {
  503. return base_getSuper().meta_assignField(receiver, selector, value);
  504. }
  505. }
  506. /* ------------------------------------
  507. * -- Extension and cloning protocol --
  508. * ------------------------------------ */
  509. /**
  510. * When cloning an object, it is first determined whether the parent
  511. * has to be shared by the clone, or whether the parent must also be cloned.
  512. * This depends on whether the dynamic parent is an 'is-a' parent or a 'shares-a'
  513. * parent. This is determined by the _ISAPARENT_FLAG_ object flag.
  514. *
  515. * A cloned object shares with its original both the variable map
  516. * (to avoid having to copy space for field names) and the method dictionary
  517. * (method bindings are constant and can hence be shared).
  518. *
  519. * Should either the original or the clone later modify the map or the dictionary
  520. * (at the meta-level), the map or dictionary will be copied first. Hence,
  521. * sharing between clones is an implementation-level optimization: clones
  522. * are completely self-sufficient and do not influence one another by meta-level operations.
  523. */
  524. public ATObject meta_clone() throws InterpreterException {
  525. ATObject dynamicParent;
  526. if(this.isFlagSet(_ISAPARENT_FLAG_)) {
  527. // IS-A Relation : clone the dynamic parent.
  528. dynamicParent = base_getSuper().meta_clone();
  529. } else {
  530. // SHARES_A Relation : share the dynamic parent.
  531. dynamicParent = base_getSuper();
  532. }
  533. // ! set the shares flags of this object *and* of its clone
  534. // both this object and the clone now share the map and method dictionary
  535. setFlag(_SHARE_DCT_FLAG_);
  536. setFlag(_SHARE_MAP_FLAG_);
  537. NATObject clone = this.createClone(variableMap_,
  538. (Vector) stateVector_.clone(), // shallow copy
  539. customFields_, // must be re-initialized by clone!
  540. methodDictionary_,
  541. dynamicParent,
  542. lexicalParent_,
  543. flags_, typeTags_);
  544. return clone;
  545. }
  546. /**
  547. * When new is invoked on an object's mirror, the object is first cloned
  548. * by the mirror, after which the method named 'init' is invoked on it.
  549. *
  550. * meta_newInstance(t) = base_init(t) o meta_clone
  551. *
  552. * Care should be taken that a shares-a child implements its own init method
  553. * which does NOT perform a super-send. If this is not the case, then it is
  554. * possible that a shared parent is accidentally re-initialized because a
  555. * sharing child is cloned via new.
  556. */
  557. public ATObject meta_newInstance(ATTable initargs) throws InterpreterException {
  558. ATObject clone = this.meta_clone();
  559. clone.meta_invoke(clone, Evaluator._INIT_, initargs);
  560. return clone;
  561. }
  562. public ATBoolean meta_isExtensionOfParent() throws InterpreterException {
  563. return NATBoolean.atValue(isFlagSet(_ISAPARENT_FLAG_));
  564. }
  565. /* ---------------------------------
  566. * -- Structural Access Protocol --
  567. * --------------------------------- */
  568. /**
  569. * When a method is added to an object, it is first checked whether the method does not
  570. * already exist. Also, care has to be taken that the method dictionary of an object
  571. * does not affect clones. Therefore, if the method dictionary is shared, a copy
  572. * of the dictionary is taken before adding the method.
  573. *
  574. * One exception to method addition are primitive methods: if the method added
  575. * would conflict with a primitive method, the primitive is replaced by the new
  576. * method instead.
  577. */
  578. public ATNil meta_addMethod(ATMethod method) throws InterpreterException {
  579. ATSymbol name = method.base_getName();
  580. if (methodDictionary_.containsKey(name) && !isPrimitive(name)) {
  581. throw new XDuplicateSlot(name);
  582. } else {
  583. // first check whether the method dictionary is shared
  584. if (this.isFlagSet(_SHARE_DCT_FLAG_)) {
  585. methodDictionary_ = (MethodDictionary) methodDictionary_.clone();
  586. this.unsetFlag(_SHARE_DCT_FLAG_);
  587. }
  588. methodDictionary_.put(name, method);
  589. }
  590. return NATNil._INSTANCE_;
  591. }
  592. public ATMethod meta_grabMethod(ATSymbol selector) throws InterpreterException {
  593. ATMethod result = (ATMethod)methodDictionary_.get(selector);
  594. if(result == null) {
  595. throw new XSelectorNotFound(selector, this);
  596. } else {
  597. return result;
  598. }
  599. }
  600. public ATTable meta_listMethods() throws InterpreterException {
  601. Collection methods = methodDictionary_.values();
  602. return NATTable.atValue((ATObject[]) methods.toArray(new ATObject[methods.size()]));
  603. }
  604. public NATText meta_print() throws InterpreterException {
  605. if (typeTags_.length == 0) {
  606. return NATText.atValue("<object:"+this.hashCode()+">");
  607. } else {
  608. return NATText.atValue("<object:"+this.hashCode()+
  609. Evaluator.printElements(typeTags_, "[", ",", "]").javaValue+">");
  610. }
  611. }
  612. public boolean isCallFrame() {
  613. return false;
  614. }
  615. /* ---------------------
  616. * -- Mirror Fields --
  617. * --------------------- */
  618. // protected methods, may be adapted by extensions
  619. protected NATObject createClone(FieldMap map,
  620. Vector state,
  621. LinkedList originalCustomFields,
  622. MethodDictionary methodDict,
  623. ATObject dynamicParent,
  624. ATObject lexicalParent,
  625. byte flags,
  626. ATTypeTag[] types) throws InterpreterException {
  627. return new NATObject(map,
  628. state,
  629. originalCustomFields,
  630. methodDict,
  631. dynamicParent,
  632. lexicalParent,
  633. flags,
  634. types);
  635. }
  636. /* ----------------------------------
  637. * -- Object Relational Comparison --
  638. * ---------------------------------- */
  639. public ATBoolean meta_isCloneOf(ATObject original) throws InterpreterException {
  640. if(original instanceof NATObject) {
  641. MethodDictionary originalMethods = ((NATObject)original).methodDictionary_;
  642. FieldMap originalVariables = ((NATObject)original).variableMap_;
  643. return NATBoolean.atValue(
  644. methodDictionary_.isDerivedFrom(originalMethods) &
  645. variableMap_.isDerivedFrom(originalVariables));
  646. } else {
  647. return NATBoolean._FALSE_;
  648. }
  649. }
  650. public ATBoolean meta_isRelatedTo(final ATObject object) throws InterpreterException {
  651. return this.meta_isCloneOf(object).base_or_(
  652. new NativeClosure(this) {
  653. public ATObject base_apply(ATTable args) throws InterpreterException {
  654. return scope_.base_getSuper().meta_isRelatedTo(object);
  655. }
  656. }).asBoolean();
  657. }
  658. /* ---------------------------------
  659. * -- Type Testing and Querying --
  660. * --------------------------------- */
  661. /**
  662. * Check whether one of the type tags of this object is a subtype of the given type.
  663. * If not, then delegate the query to the dynamic parent.
  664. */
  665. public ATBoolean meta_isTaggedAs(ATTypeTag type) throws InterpreterException {
  666. if (isLocallyTaggedAs(type)) {
  667. return NATBoolean._TRUE_;
  668. } else {
  669. // no type tags match, ask the parent
  670. return base_getSuper().meta_isTaggedAs(type);
  671. }
  672. }
  673. /**
  674. * Return the type tags that were directly attached to this object.
  675. */
  676. public ATTable meta_getTypeTags() throws InterpreterException {
  677. // make a copy of the internal type tag array to ensure that the types
  678. // of the object are immutable. Tables allow assignment!
  679. if (typeTags_.length == 0) {
  680. return NATTable.EMPTY;
  681. } else {
  682. ATTypeTag[] types = new ATTypeTag[typeTags_.length];
  683. System.arraycopy(typeTags_, 0, types, 0, typeTags_.length);
  684. return NATTable.atValue(types);
  685. }
  686. }
  687. // NATObject has to duplicate the NATByCopy implementation
  688. // because NATObject inherits from NATByRef, and because Java has no
  689. // multiple inheritance to override that implementation with that of
  690. // NATByCopy if this object signifies an isolate.
  691. /**
  692. * An isolate object does not return a proxy representation of itself
  693. * during serialization, hence it is serialized itself. If the object
  694. * is not an isolate, invoke the default behaviour for by-reference objects
  695. */
  696. public ATObject meta_pass() throws InterpreterException {
  697. if (isFlagSet(_IS_ISOLATE_FLAG_)) {
  698. return this;
  699. } else {
  700. return super.meta_pass();
  701. }
  702. }
  703. /**
  704. * An isolate object represents itself upon deserialization.
  705. * If this object is not an isolate, the default behaviour for by-reference
  706. * objects is invoked.
  707. */
  708. public ATObject meta_resolve() throws InterpreterException {
  709. if (isFlagSet(_IS_ISOLATE_FLAG_)) {
  710. // re-bind to the new local global lexical root
  711. lexicalParent_ = Evaluator.getGlobalLexicalScope();
  712. return this;
  713. } else {
  714. return super.meta_resolve();
  715. }
  716. }
  717. /* ---------------------------------------
  718. * -- Conversion and Testing Protocol --
  719. * --------------------------------------- */
  720. public NATObject asAmbientTalkObject() { return this; }
  721. /**
  722. * ALL asXXX methods return a coercer object which returns a proxy of the correct interface that will 'down'
  723. * subsequent Java base-level invocations to the AmbientTalk level.
  724. *
  725. * Coercion only happens if the object is tagged with the correct type.
  726. */
  727. private Object coerce(ATTypeTag requiredType, Class providedInterface) throws InterpreterException {
  728. if (this.meta_isTaggedAs(requiredType).asNativeBoolean().javaValue) {
  729. return Coercer.coerce(this, providedInterface);
  730. } else {
  731. // if the object does not possess the right type tag, raise a type error
  732. throw new XTypeMismatch(providedInterface, this);
  733. }
  734. }
  735. public ATBoolean asBoolean() throws InterpreterException { return (ATBoolean) coerce(NativeTypeTags._BOOLEAN_, ATBoolean.class); }
  736. public ATClosure asClosure() throws InterpreterException { return (ATClosure) coerce(NativeTypeTags._CLOSURE_, ATClosure.class); }
  737. public ATField asField() throws InterpreterException { return (ATField) coerce(NativeTypeTags._FIELD_, ATField.class); }
  738. public ATMessage asMessage() throws InterpreterException { return (ATMessage) coerce(NativeTypeTags._MESSAGE_, ATMessage.class); }
  739. public ATMethod asMethod() throws InterpreterException { return (ATMethod) coerce(NativeTypeTags._METHOD_, ATMethod.class); }
  740. public ATHandler asHandler() throws InterpreterException { return (ATHandler) coerce(NativeTypeTags._HANDLER_, ATHandler.class); }
  741. public ATNumber asNumber() throws InterpreterException { return (ATNumber) coerce(NativeTypeTags._NUMBER_, ATNumber.class); }
  742. public ATTable asTable() throws InterpreterException { return (ATTable) coerce(NativeTypeTags._TABLE_, ATTable.class); }
  743. public ATAsyncMessage asAsyncMessage() throws InterpreterException { return (ATAsyncMessage) coerce(NativeTypeTags._ASYNCMSG_, ATAsyncMessage.class);}
  744. public ATActorMirror asActorMirror() throws InterpreterException { return (ATActorMirror) coerce(NativeTypeTags._ACTORMIRROR_, ATActorMirror.class); }
  745. public ATTypeTag asTypeTag() throws InterpreterException { return (ATTypeTag) coerce(NativeTypeTags._TYPETAG_, ATTypeTag.class); }
  746. public ATBegin asBegin() throws InterpreterException { return (ATBegin) coerce(NativeTypeTags._BEGIN_, ATBegin.class); }
  747. public ATStatement asStatement() throws InterpreterException { return (ATStatement) coerce(NativeTypeTags._STATEMENT_, ATStatement.class); }
  748. public ATUnquoteSplice asUnquoteSplice() throws InterpreterException { return (ATUnquoteSplice) coerce(NativeTypeTags._UQSPLICE_, ATUnquoteSplice.class); }
  749. public ATSymbol asSymbol() throws InterpreterException { return (ATSymbol) coerce(NativeTypeTags._SYMBOL_, ATSymbol.class); }
  750. public ATSplice asSplice() throws InterpreterException { return (ATSplice) coerce(NativeTypeTags._SPLICE_, ATSplice.class); }
  751. public ATDefinition asDefinition() throws InterpreterException { return (ATDefinition) coerce(NativeTypeTags._DEFINITION_, ATDefinition.class); }
  752. public ATMessageCreation asMessageCreation() throws InterpreterException { return (ATMessageCreation) coerce(NativeTypeTags._MSGCREATION_, ATMessageCreation.class); }
  753. // ALL isXXX methods return true (can be overridden by programmer-defined base-level methods)
  754. public boolean isAmbientTalkObject() { return true; }
  755. // objects can only be 'cast' to a native category if they are marked with
  756. // the appropriate native type
  757. public boolean isSplice() throws InterpreterException { return meta_isTaggedAs(NativeTypeTags._SPLICE_).asNativeBoolean().javaValue; }
  758. public boolean isSymbol() throws InterpreterException { return meta_isTaggedAs(NativeTypeTags._SYMBOL_).asNativeBoolean().javaValue; }
  759. public boolean isTable() throws InterpreterException { return meta_isTaggedAs(NativeTypeTags._TABLE_).asNativeBoolean().javaValue; }
  760. public boolean isUnquoteSplice() throws InterpreterException { return meta_isTaggedAs(NativeTypeTags._UQSPLICE_).asNativeBoolean().javaValue; }
  761. public boolean isTypeTag() throws InterpreterException { return meta_isTaggedAs(NativeTypeTags._TYPETAG_).asNativeBoolean().javaValue; }
  762. // private methods
  763. private boolean isFlagSet(byte flag) {
  764. return (flags_ & flag) != 0;
  765. }
  766. private void setFlag(byte flag) {
  767. flags_ = (byte) (flags_ | flag);
  768. }
  769. private void unsetFlag(byte flag) {
  770. flags_ = (byte) (flags_ & (~flag));
  771. }
  772. private boolean hasLocalMethod(ATSymbol selector) {
  773. return methodDictionary_.containsKey(selector);
  774. }
  775. private ATMethod getLocalMethod(ATSymbol selector) throws InterpreterException {
  776. ATMethod result = ((ATObject) methodDictionary_.get(selector)).asMethod();
  777. if(result == null) {
  778. throw new XSelectorNotFound(selector, this);
  779. } else {
  780. return result;
  781. }
  782. }
  783. /**
  784. * Performs a type test for this object locally.
  785. * @return whether this object is tagged with a particular type tag or not.
  786. */
  787. private boolean isLocallyTaggedAs(ATTypeTag tag) throws InterpreterException {
  788. for (int i = 0; i < typeTags_.length; i++) {
  789. if (typeTags_[i].base_isSubtypeOf(tag).asNativeBoolean().javaValue) {
  790. // if one type matches, return true
  791. return true;
  792. }
  793. }
  794. return false;
  795. }
  796. /**
  797. * Auxiliary method to access the fields of an object and all of its super-objects up to (but excluding) nil.
  798. * Overridden fields of parent objects are not included.
  799. */
  800. public static ATField[] listTransitiveFields(ATObject obj) throws InterpreterException {
  801. Vector fields = new Vector();
  802. HashSet encounteredNames = new HashSet(); // to filter duplicates
  803. for (; obj != NATNil._INSTANCE_ ; obj = obj.base_getSuper()) {
  804. ATObject[] localFields = obj.meta_listFields().asNativeTable().elements_;
  805. for (int i = 0; i < localFields.length; i++) {
  806. ATField field = localFields[i].asField();
  807. ATSymbol fieldName = field.base_getName();
  808. if (!encounteredNames.contains(fieldName)) {
  809. fields.add(field);
  810. encounteredNames.add(fieldName);
  811. }
  812. }
  813. }
  814. return (ATField[]) fields.toArray(new ATField[fields.size()]);
  815. }
  816. /**
  817. * Auxiliary method to access the methods of an object and all of its super-objects up to (but excluding) nil.
  818. * Overridden methods of parent objects are not included.
  819. */
  820. public static ATMethod[] listTransitiveMethods(ATObject obj) throws InterpreterException {
  821. Vector methods = new Vector();
  822. HashSet encounteredNames = new HashSet(); // to filter duplicates
  823. for (; obj != NATNil._INSTANCE_ ; obj = obj.base_getSuper()) {
  824. // fast-path for native objects
  825. if (obj instanceof NATObject) {
  826. Collection localMethods = ((NATObject) obj).methodDictionary_.values();
  827. for (Iterator iter = localMethods.iterator(); iter.hasNext();) {
  828. ATMethod localMethod = (ATMethod) iter.next();
  829. ATSymbol methodName = localMethod.base_getName();
  830. if (!encounteredNames.contains(methodName)) {
  831. methods.add(localMethod);
  832. encounteredNames.add(methodName);
  833. }
  834. }
  835. } else {
  836. ATObject[] localMethods = obj.meta_listMethods().asNativeTable().elements_;
  837. for (int i = 0; i < localMethods.length; i++) {
  838. ATMethod localMethod = localMethods[i].asMethod();
  839. ATSymbol methodName = localMethod.base_getName();
  840. if (!encounteredNames.contains(methodName)) {
  841. methods.add(localMethod);
  842. encounteredNames.add(methodName);
  843. }
  844. }
  845. }
  846. }
  847. return (ATMethod[]) methods.toArray(new ATMethod[methods.size()]);
  848. }
  849. }