/interpreter/tags/at2dist130208/src/edu/vub/at/objects/natives/NATObject.java

http://ambienttalk.googlecode.com/ · Java · 846 lines · 415 code · 99 blank · 332 comment · 54 complexity · b8893432be4a39a0ab83d26935e65f16 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.ATTable;
  48. import edu.vub.at.objects.ATTypeTag;
  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.ATMessageCreation;
  54. import edu.vub.at.objects.grammar.ATSplice;
  55. import edu.vub.at.objects.grammar.ATStatement;
  56. import edu.vub.at.objects.grammar.ATSymbol;
  57. import edu.vub.at.objects.grammar.ATUnquoteSplice;
  58. import edu.vub.at.objects.mirrors.NativeClosure;
  59. import edu.vub.at.objects.mirrors.PrimitiveMethod;
  60. import edu.vub.at.objects.natives.grammar.AGSplice;
  61. import edu.vub.at.objects.natives.grammar.AGSymbol;
  62. import edu.vub.at.util.logging.Logging;
  63. import java.io.IOException;
  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. private static final long serialVersionUID = -4475956316807558583L;
  116. public ATObject base_apply(ATTable arguments, ATContext ctx) throws InterpreterException {
  117. if (!arguments.base_length().equals(NATNumber.ONE)) {
  118. throw new XArityMismatch("==", 1, arguments.base_length().asNativeNumber().javaValue);
  119. }
  120. ATObject comparand = arguments.base_at(NATNumber.ONE);
  121. // make other object perform the actual pointer equality
  122. // if comparand is a proxy, it can delegate this request to its principal
  123. return comparand.impl_identityEquals(ctx.base_lexicalScope());
  124. }
  125. };
  126. /** def new(@initargs) { nil } */
  127. private static final PrimitiveMethod _PRIM_NEW_ = new PrimitiveMethod(
  128. _NEW_NAME_, NATTable.atValue(new ATObject[] { new AGSplice(AGSymbol.jAlloc("initargs")) })) {
  129. private static final long serialVersionUID = -5475956316807558583L;
  130. public ATObject base_apply(ATTable arguments, ATContext ctx) throws InterpreterException {
  131. return ctx.base_lexicalScope().base_new(arguments.asNativeTable().elements_);
  132. }
  133. };
  134. /** def init(@initargs) { nil } */
  135. private static final PrimitiveMethod _PRIM_INI_ = new PrimitiveMethod(
  136. _INI_NAME_, NATTable.atValue(new ATObject[] { new AGSplice(AGSymbol.jAlloc("initargs")) })) {
  137. private static final long serialVersionUID = -6475956316807558583L;
  138. public ATObject base_apply(ATTable arguments, ATContext ctx) throws InterpreterException {
  139. return ctx.base_lexicalScope().asAmbientTalkObject().prim_init(ctx.base_self(), arguments.asNativeTable().elements_);
  140. }
  141. };
  142. /**
  143. * Does the selector signify a 'primitive' method, present in each AmbientTalk object?
  144. */
  145. public static boolean isPrimitive(ATSymbol name) {
  146. return name.equals(_EQL_NAME_) || name.equals(_NEW_NAME_) || name.equals(_INI_NAME_);
  147. }
  148. // Auxiliary static methods to support the type of dynamic parent
  149. public static final boolean _IS_A_ = true;
  150. public static final boolean _SHARES_A_ = false;
  151. /**
  152. * This flag determines the type of parent pointer of this object. We distinguish two cases:
  153. * - 1: an is-a link, which results in a recursive cloning of the parent when this object is cloned.
  154. * - 0: a shares-a link, which ensures that clones of this object share the same parent.
  155. */
  156. private static final byte _ISAPARENT_FLAG_ = 1<<0;
  157. /**
  158. * This flag determines whether or not the field map of this object is shared by other objects:
  159. * - 1: the map is shared, so modifications must be performed on a copy
  160. * - 0: the map is not shared, modifications may be directly performed on it
  161. *
  162. * This flag is important for maintaining the semantics that clones are self-sufficient objects:
  163. * they share field names and methods only at the implementation-level.
  164. */
  165. private static final byte _SHARE_MAP_FLAG_ = 1<<1;
  166. /**
  167. * Similar to _SHARE_MAP_FLAG__ but for determining the shared status of the method dictionary.
  168. */
  169. private static final byte _SHARE_DCT_FLAG_ = 1<<2;
  170. /**
  171. * This flag determines whether or not the object is an isolate and hence pass-by-copy:
  172. * - 1: the object is an isolate, pass-by-copy and no lexical parent except for the root
  173. * - 0: the object is pass-by-reference and can have any lexical parent
  174. */
  175. private static final byte _IS_ISOLATE_FLAG_ = 1<<3;
  176. /**
  177. * An empty type tag array shared by those objects that do not have any type tags.
  178. */
  179. public static final ATTypeTag[] _NO_TYPETAGS_ = new ATTypeTag[0];
  180. /**
  181. * The flags of an AmbientTalk object encode the following boolean information:
  182. * Format: 0b0000idap where
  183. * p = parent flag: if set, dynamic parent is 'is-a' parent, otherwise 'shares-a' parent
  184. * a = shares map flag: if set, the map of this object is shared between clones
  185. * d = shares dictionary flag: if set, the method dictionary of this object is shared between clones
  186. * i = is isolate flag: if set, the object is passed by copy in inter-actor communication
  187. */
  188. private byte flags_;
  189. // inherited from NATCallframe:
  190. // private FieldMap variableMap_;
  191. // private Vector stateVector_;
  192. // private LinkedList customFields_;
  193. /**
  194. * The method dictionary of this object. It maps method selectors to ATMethod objects.
  195. */
  196. private MethodDictionary methodDictionary_;
  197. /**
  198. * The types with which this object has been tagged.
  199. */
  200. protected ATTypeTag[] typeTags_;
  201. /* ------------------
  202. * -- Constructors --
  203. * ------------------ */
  204. /**
  205. * Creates an object tagged with the at.types.Isolate type.
  206. * Such an object is called an isolate because:
  207. * - it has no access to an enclosing lexical scope (except for the root lexical scope)
  208. * - it can therefore be passed by copy
  209. */
  210. public static NATObject createIsolate() {
  211. return new NATObject(new ATTypeTag[] { NativeTypeTags._ISOLATE_ });
  212. }
  213. /**
  214. * Constructs a new AmbientTalk object whose lexical parent is the
  215. * global scope and whose dynamic parent is the dynamic root.
  216. */
  217. public NATObject() {
  218. this(Evaluator.getGlobalLexicalScope());
  219. }
  220. /**
  221. * Construct a new AmbientTalk object directly tagged with the given type tags.
  222. */
  223. public NATObject(ATTypeTag[] tags) {
  224. this(Evaluator.getGlobalLexicalScope(), tags);
  225. }
  226. /**
  227. * Constructs a new ambienttalk object parametrised by a lexical scope. The
  228. * object is thus not equipped with a pointer to a dynamic parent.
  229. * @param lexicalParent - the lexical scope in which the object's definition was nested
  230. */
  231. public NATObject(ATObject lexicalParent) {
  232. this(OBJNil._INSTANCE_, lexicalParent, _SHARES_A_);
  233. }
  234. /**
  235. * Constructs a new ambienttalk object parametrised by a lexical scope.
  236. * The object's dynamic parent is nil and is tagged with the given table of type tags
  237. */
  238. public NATObject(ATObject lexicalParent, ATTypeTag[] tags) {
  239. this(OBJNil._INSTANCE_, lexicalParent, _SHARES_A_, tags);
  240. }
  241. /**
  242. * Constructs a new ambienttalk object with the given dynamic parent.
  243. * The lexical parent is assumed to be the global scope.
  244. * @param dynamicParent - the dynamic parent of the new object
  245. * @param parentType - the type of parent link
  246. */
  247. public NATObject(ATObject dynamicParent, boolean parentType) {
  248. this(dynamicParent, Evaluator.getGlobalLexicalScope(), parentType);
  249. }
  250. /**
  251. * Constructs a new ambienttalk object based on a set of parent pointers.
  252. * The object has no types.
  253. * @param dynamicParent - the parent object of the newly created object
  254. * @param lexicalParent - the lexical scope in which the object's definition was nested
  255. * @param parentType - how this object extends its dynamic parent (is-a or shares-a)
  256. */
  257. public NATObject(ATObject dynamicParent, ATObject lexicalParent, boolean parentType) {
  258. this(dynamicParent, lexicalParent, parentType, _NO_TYPETAGS_);
  259. }
  260. /**
  261. * Constructs a new ambienttalk object based on a set of parent pointers.
  262. * The object is typed with the given types.
  263. * @param dynamicParent - the parent object of the newly created object
  264. * @param lexicalParent - the lexical scope in which the object's definition was nested
  265. * @param parentType - how this object extends its dynamic parent (is-a or shares-a)
  266. * @param tags - the type tags attached to this object
  267. */
  268. public NATObject(ATObject dynamicParent, ATObject lexicalParent, boolean parentType, ATTypeTag[] tags) {
  269. super(lexicalParent);
  270. // by default, an object has a shares-a parent, does not share its map
  271. // or dictionary and is no isolate, so all flags are set to 0
  272. flags_ = 0;
  273. typeTags_ = tags;
  274. methodDictionary_ = new MethodDictionary();
  275. // bind the dynamic parent to the field named 'super'
  276. // we don't pass via meta_defineField as this would trigger mirages too early
  277. variableMap_.put(_SUPER_NAME_);
  278. stateVector_.add(dynamicParent);
  279. // add ==, new and init to the method dictionary directly
  280. // we don't pass via meta_addMethod as this would trigger mirages too early
  281. methodDictionary_.put(_EQL_NAME_, _PRIM_EQL_);
  282. methodDictionary_.put(_NEW_NAME_, _PRIM_NEW_);
  283. methodDictionary_.put(_INI_NAME_, _PRIM_INI_);
  284. if (parentType) { // parentType == _IS_A_)
  285. // requested an 'is-a' parent
  286. setFlag(_ISAPARENT_FLAG_); // set is-a parent flag to 1
  287. }
  288. try {
  289. // if this object is tagged as at.types.Isolate, flag it as an isolate
  290. // we cannot perform 'this.meta_isTypedAs(ISOLATE)' because this would trigger mirages too early
  291. if (isLocallyTaggedAs(NativeTypeTags._ISOLATE_)
  292. || dynamicParent.meta_isTaggedAs(NativeTypeTags._ISOLATE_).asNativeBoolean().javaValue) {
  293. setFlag(_IS_ISOLATE_FLAG_);
  294. // isolates can only have the global lexical root as their lexical scope
  295. lexicalParent_ = Evaluator.getGlobalLexicalScope();
  296. }
  297. } catch (InterpreterException e) {
  298. // some custom type failed to match agains the Isolate type,
  299. // the object is not considered an Isolate
  300. Logging.Actor_LOG.error("Error testing for Isolate type, ignored:", e);
  301. }
  302. }
  303. /**
  304. * Constructs a new ambienttalk object as a clone of an existing object.
  305. *
  306. * The caller of this method *must* ensure that the shares flags are set.
  307. *
  308. * This constructor is responsible for manually re-initialising any custom field
  309. * objects, because the init method of such custom fields is parameterized by the
  310. * clone, which only comes into existence when this constructor runs.
  311. */
  312. protected NATObject(FieldMap map,
  313. Vector state,
  314. LinkedList originalCustomFields,
  315. MethodDictionary methodDict,
  316. ATObject dynamicParent,
  317. ATObject lexicalParent,
  318. byte flags,
  319. ATTypeTag[] types) throws InterpreterException {
  320. super(map, state, lexicalParent, null);
  321. methodDictionary_ = methodDict;
  322. flags_ = flags; //a cloned object inherits all flags from original
  323. // clone inherits all types (this implies that clones of isolates are also isolates)
  324. typeTags_ = types;
  325. // ==, new and init should already be present in the method dictionary
  326. // set the 'super' field to point to the new dynamic parent
  327. setLocalField(_SUPER_NAME_, dynamicParent);
  328. // re-initialize all custom fields
  329. if (originalCustomFields != null) {
  330. customFields_ = new LinkedList();
  331. Iterator it = originalCustomFields.iterator();
  332. while (it.hasNext()) {
  333. ATField field = (ATField) it.next();
  334. customFields_.add(field.base_new(new ATObject[] { this }).asField());
  335. }
  336. }
  337. }
  338. /**
  339. * Initialize a new AmbientTalk object with the given closure.
  340. *
  341. * The closure encapsulates:
  342. * - the code with which to initialize the object
  343. * - the lexical parent of the object (but that parent should already be set)
  344. * - the lexically inherited fields for the object (the parameters of the closure)
  345. */
  346. public void initializeWithCode(ATClosure code) throws InterpreterException {
  347. NATTable copiedBindings = Evaluator.evalMandatoryPars(
  348. code.base_method().base_parameters(),
  349. code.base_context());
  350. code.base_applyInScope(copiedBindings, this);
  351. }
  352. /**
  353. * Invoke NATObject's primitive implementation, such that Java invocations of this
  354. * method have the same behaviour as AmbientTalk invocations.
  355. */
  356. public ATObject base_init(ATObject[] initargs) throws InterpreterException {
  357. return this.prim_init(this, initargs);
  358. }
  359. /**
  360. * The primitive implementation of init in objects is to invoke the init
  361. * method of their parent.
  362. * @param self the object that originally received the 'init' message.
  363. *
  364. * def init(@args) {
  365. * super^init(@args)
  366. * }
  367. */
  368. private ATObject prim_init(ATObject self, ATObject[] initargs) throws InterpreterException {
  369. return base_super().meta_invoke(self, Evaluator._INIT_, NATTable.atValue(initargs));
  370. }
  371. public ATBoolean base__opeql__opeql_(ATObject comparand) throws InterpreterException {
  372. return this.meta_invoke(this, _EQL_NAME_, NATTable.of(comparand)).asBoolean();
  373. }
  374. /* ------------------------------------------
  375. * -- Slot accessing and mutating protocol --
  376. * ------------------------------------------ */
  377. /**
  378. * When a new field is defined in an object, it is important to check whether or not
  379. * the field map is shared between clones or not. If it is shared, the map must be cloned first.
  380. * @throws InterpreterException
  381. */
  382. public ATNil meta_defineField(ATSymbol name, ATObject value) throws InterpreterException {
  383. if (this.isFlagSet(_SHARE_MAP_FLAG_)) {
  384. // copy the variable map
  385. variableMap_ = variableMap_.copy();
  386. // set the 'shares map' flag to false
  387. unsetFlag(_SHARE_MAP_FLAG_);
  388. }
  389. return super.meta_defineField(name, value);
  390. }
  391. /* ------------------------------------
  392. * -- Extension and cloning protocol --
  393. * ------------------------------------ */
  394. /**
  395. * When cloning an object, it is first determined whether the parent
  396. * has to be shared by the clone, or whether the parent must also be cloned.
  397. * This depends on whether the dynamic parent is an 'is-a' parent or a 'shares-a'
  398. * parent. This is determined by the _ISAPARENT_FLAG_ object flag.
  399. *
  400. * A cloned object shares with its original both the variable map
  401. * (to avoid having to copy space for field names) and the method dictionary
  402. * (method bindings are constant and can hence be shared).
  403. *
  404. * Should either the original or the clone later modify the map or the dictionary
  405. * (at the meta-level), the map or dictionary will be copied first. Hence,
  406. * sharing between clones is an implementation-level optimization: clones
  407. * are completely self-sufficient and do not influence one another by meta-level operations.
  408. */
  409. public ATObject meta_clone() throws InterpreterException {
  410. ATObject dynamicParent;
  411. if(this.isFlagSet(_ISAPARENT_FLAG_)) {
  412. // IS-A Relation : clone the dynamic parent.
  413. dynamicParent = base_super().meta_clone();
  414. } else {
  415. // SHARES_A Relation : share the dynamic parent.
  416. dynamicParent = base_super();
  417. }
  418. // ! set the shares flags of this object *and* of its clone
  419. // both this object and the clone now share the map and method dictionary
  420. setFlag(_SHARE_DCT_FLAG_);
  421. setFlag(_SHARE_MAP_FLAG_);
  422. NATObject clone = this.createClone(variableMap_,
  423. (Vector) stateVector_.clone(), // shallow copy
  424. customFields_, // must be re-initialized by clone!
  425. methodDictionary_,
  426. dynamicParent,
  427. lexicalParent_,
  428. flags_, typeTags_);
  429. return clone;
  430. }
  431. /**
  432. * When new is invoked on an object's mirror, the object is first cloned
  433. * by the mirror, after which the method named 'init' is invoked on it.
  434. *
  435. * meta_newInstance(t) = base_init(t) o meta_clone
  436. *
  437. * Care should be taken that a shares-a child implements its own init method
  438. * which does NOT perform a super-send. If this is not the case, then it is
  439. * possible that a shared parent is accidentally re-initialized because a
  440. * sharing child is cloned via new.
  441. */
  442. public ATObject meta_newInstance(ATTable initargs) throws InterpreterException {
  443. ATObject clone = this.meta_clone();
  444. clone.meta_invoke(clone, Evaluator._INIT_, initargs);
  445. return clone;
  446. }
  447. public ATBoolean meta_isExtensionOfParent() throws InterpreterException {
  448. return NATBoolean.atValue(isFlagSet(_ISAPARENT_FLAG_));
  449. }
  450. /* ---------------------------------
  451. * -- Structural Access Protocol --
  452. * --------------------------------- */
  453. /**
  454. * When a method is added to an object, it is first checked whether the method does not
  455. * already exist. Also, care has to be taken that the method dictionary of an object
  456. * does not affect clones. Therefore, if the method dictionary is shared, a copy
  457. * of the dictionary is taken before adding the method.
  458. *
  459. * One exception to method addition are primitive methods: if the method added
  460. * would conflict with a primitive method, the primitive is replaced by the new
  461. * method instead.
  462. */
  463. public ATNil meta_addMethod(ATMethod method) throws InterpreterException {
  464. ATSymbol name = method.base_name();
  465. if (this.hasLocalField(name) || (this.hasLocalMethod(name) && !isPrimitive(name))) {
  466. throw new XDuplicateSlot(name);
  467. } else {
  468. // first check whether the method dictionary is shared
  469. if (this.isFlagSet(_SHARE_DCT_FLAG_)) {
  470. methodDictionary_ = (MethodDictionary) methodDictionary_.clone();
  471. this.unsetFlag(_SHARE_DCT_FLAG_);
  472. }
  473. methodDictionary_.put(name, method);
  474. }
  475. return OBJNil._INSTANCE_;
  476. }
  477. public ATMethod meta_grabMethod(ATSymbol selector) throws InterpreterException {
  478. ATMethod result = (ATMethod)methodDictionary_.get(selector);
  479. if(result == null) {
  480. throw new XSelectorNotFound(selector, this);
  481. } else {
  482. return result;
  483. }
  484. }
  485. public ATTable meta_listMethods() throws InterpreterException {
  486. Collection methods = methodDictionary_.values();
  487. return NATTable.atValue((ATObject[]) methods.toArray(new ATObject[methods.size()]));
  488. }
  489. public NATText meta_print() throws InterpreterException {
  490. if (typeTags_.length == 0) {
  491. return NATText.atValue("<object:"+this.hashCode()+">");
  492. } else {
  493. return NATText.atValue("<object:"+this.hashCode()+
  494. Evaluator.printElements(typeTags_, "[", ",", "]").javaValue+">");
  495. }
  496. }
  497. public boolean isCallFrame() {
  498. return false;
  499. }
  500. /* ---------------------
  501. * -- Mirror Fields --
  502. * --------------------- */
  503. // protected methods, may be adapted by extensions
  504. protected NATObject createClone(FieldMap map,
  505. Vector state,
  506. LinkedList originalCustomFields,
  507. MethodDictionary methodDict,
  508. ATObject dynamicParent,
  509. ATObject lexicalParent,
  510. byte flags,
  511. ATTypeTag[] types) throws InterpreterException {
  512. return new NATObject(map,
  513. state,
  514. originalCustomFields,
  515. methodDict,
  516. dynamicParent,
  517. lexicalParent,
  518. flags,
  519. types);
  520. }
  521. /* ----------------------------------
  522. * -- Object Relational Comparison --
  523. * ---------------------------------- */
  524. public ATBoolean meta_isCloneOf(ATObject original) throws InterpreterException {
  525. if(original instanceof NATObject) {
  526. MethodDictionary originalMethods = ((NATObject)original).methodDictionary_;
  527. FieldMap originalVariables = ((NATObject)original).variableMap_;
  528. return NATBoolean.atValue(
  529. methodDictionary_.isDerivedFrom(originalMethods) &
  530. variableMap_.isDerivedFrom(originalVariables));
  531. } else {
  532. return NATBoolean._FALSE_;
  533. }
  534. }
  535. public ATBoolean meta_isRelatedTo(final ATObject object) throws InterpreterException {
  536. return this.meta_isCloneOf(object).base_or_(
  537. new NativeClosure(this) {
  538. public ATObject base_apply(ATTable args) throws InterpreterException {
  539. return scope_.base_super().meta_isRelatedTo(object);
  540. }
  541. }).asBoolean();
  542. }
  543. /* ---------------------------------
  544. * -- Type Testing and Querying --
  545. * --------------------------------- */
  546. /**
  547. * Check whether one of the type tags of this object is a subtype of the given type.
  548. * If not, then delegate the query to the dynamic parent.
  549. */
  550. public ATBoolean meta_isTaggedAs(ATTypeTag type) throws InterpreterException {
  551. if (isLocallyTaggedAs(type)) {
  552. return NATBoolean._TRUE_;
  553. } else {
  554. // no type tags match, ask the parent
  555. return base_super().meta_isTaggedAs(type);
  556. }
  557. }
  558. /**
  559. * Return the type tags that were directly attached to this object.
  560. */
  561. public ATTable meta_typeTags() throws InterpreterException {
  562. // make a copy of the internal type tag array to ensure that the types
  563. // of the object are immutable. Tables allow assignment!
  564. if (typeTags_.length == 0) {
  565. return NATTable.EMPTY;
  566. } else {
  567. ATTypeTag[] types = new ATTypeTag[typeTags_.length];
  568. System.arraycopy(typeTags_, 0, types, 0, typeTags_.length);
  569. return NATTable.atValue(types);
  570. }
  571. }
  572. // NATObject has to duplicate the NATByCopy implementation
  573. // because NATObject inherits from NATByRef, and because Java has no
  574. // multiple inheritance to override that implementation with that of
  575. // NATByCopy if this object signifies an isolate.
  576. /**
  577. * An isolate object does not return a proxy representation of itself
  578. * during serialization, hence it is serialized itself. If the object
  579. * is not an isolate, invoke the default behaviour for by-reference objects
  580. */
  581. public ATObject meta_pass() throws InterpreterException {
  582. if (isFlagSet(_IS_ISOLATE_FLAG_)) {
  583. return this;
  584. } else {
  585. return super.meta_pass();
  586. }
  587. }
  588. /**
  589. * An isolate object represents itself upon deserialization.
  590. * If this object is not an isolate, the default behaviour for by-reference
  591. * objects is invoked.
  592. */
  593. public ATObject meta_resolve() throws InterpreterException {
  594. if (isFlagSet(_IS_ISOLATE_FLAG_)) {
  595. // re-bind to the new local global lexical root
  596. lexicalParent_ = Evaluator.getGlobalLexicalScope();
  597. return this;
  598. } else {
  599. return super.meta_resolve();
  600. }
  601. }
  602. /**
  603. * This Java serialization hook is overridden merely to provide clearer error messages
  604. * in the case of a failing deserialization.
  605. */
  606. private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
  607. try {
  608. in.defaultReadObject();
  609. } catch(ArrayStoreException e) {
  610. Logging.Actor_LOG.fatal("Failed to deserialize instance of " + this.getClass(), e);
  611. throw new IOException("Object deserialized as wrong type: " + e.getMessage()
  612. + ". Did you forget to make a type tag object an isolate?");
  613. }
  614. }
  615. /* ---------------------------------------
  616. * -- Conversion and Testing Protocol --
  617. * --------------------------------------- */
  618. public NATObject asAmbientTalkObject() { return this; }
  619. /**
  620. * ALL asXXX methods return a coercer object which returns a proxy of the correct interface that will 'down'
  621. * subsequent Java base-level invocations to the AmbientTalk level.
  622. *
  623. * Coercion only happens if the object is tagged with the correct type.
  624. */
  625. private Object coerce(ATTypeTag requiredType, Class providedInterface) throws InterpreterException {
  626. if (this.meta_isTaggedAs(requiredType).asNativeBoolean().javaValue) {
  627. return Coercer.coerce(this, providedInterface);
  628. } else {
  629. // if the object does not possess the right type tag, raise a type error
  630. throw new XTypeMismatch(providedInterface, this);
  631. }
  632. }
  633. public ATBoolean asBoolean() throws InterpreterException { return (ATBoolean) coerce(NativeTypeTags._BOOLEAN_, ATBoolean.class); }
  634. public ATClosure asClosure() throws InterpreterException { return (ATClosure) coerce(NativeTypeTags._CLOSURE_, ATClosure.class); }
  635. public ATField asField() throws InterpreterException { return (ATField) coerce(NativeTypeTags._FIELD_, ATField.class); }
  636. public ATMessage asMessage() throws InterpreterException { return (ATMessage) coerce(NativeTypeTags._MESSAGE_, ATMessage.class); }
  637. public ATMethod asMethod() throws InterpreterException { return (ATMethod) coerce(NativeTypeTags._METHOD_, ATMethod.class); }
  638. public ATHandler asHandler() throws InterpreterException { return (ATHandler) coerce(NativeTypeTags._HANDLER_, ATHandler.class); }
  639. public ATNumber asNumber() throws InterpreterException { return (ATNumber) coerce(NativeTypeTags._NUMBER_, ATNumber.class); }
  640. public ATTable asTable() throws InterpreterException { return (ATTable) coerce(NativeTypeTags._TABLE_, ATTable.class); }
  641. public ATAsyncMessage asAsyncMessage() throws InterpreterException { return (ATAsyncMessage) coerce(NativeTypeTags._ASYNCMSG_, ATAsyncMessage.class);}
  642. public ATActorMirror asActorMirror() throws InterpreterException { return (ATActorMirror) coerce(NativeTypeTags._ACTORMIRROR_, ATActorMirror.class); }
  643. public ATTypeTag asTypeTag() throws InterpreterException { return (ATTypeTag) coerce(NativeTypeTags._TYPETAG_, ATTypeTag.class); }
  644. public ATBegin asBegin() throws InterpreterException { return (ATBegin) coerce(NativeTypeTags._BEGIN_, ATBegin.class); }
  645. public ATStatement asStatement() throws InterpreterException { return (ATStatement) coerce(NativeTypeTags._STATEMENT_, ATStatement.class); }
  646. public ATUnquoteSplice asUnquoteSplice() throws InterpreterException { return (ATUnquoteSplice) coerce(NativeTypeTags._UQSPLICE_, ATUnquoteSplice.class); }
  647. public ATSymbol asSymbol() throws InterpreterException { return (ATSymbol) coerce(NativeTypeTags._SYMBOL_, ATSymbol.class); }
  648. public ATSplice asSplice() throws InterpreterException { return (ATSplice) coerce(NativeTypeTags._SPLICE_, ATSplice.class); }
  649. public ATDefinition asDefinition() throws InterpreterException { return (ATDefinition) coerce(NativeTypeTags._DEFINITION_, ATDefinition.class); }
  650. public ATMessageCreation asMessageCreation() throws InterpreterException { return (ATMessageCreation) coerce(NativeTypeTags._MSGCREATION_, ATMessageCreation.class); }
  651. // ALL isXXX methods return true (can be overridden by programmer-defined base-level methods)
  652. public boolean isAmbientTalkObject() { return true; }
  653. // objects can only be 'cast' to a native category if they are marked with
  654. // the appropriate native type
  655. public boolean isSplice() throws InterpreterException { return meta_isTaggedAs(NativeTypeTags._SPLICE_).asNativeBoolean().javaValue; }
  656. public boolean isSymbol() throws InterpreterException { return meta_isTaggedAs(NativeTypeTags._SYMBOL_).asNativeBoolean().javaValue; }
  657. public boolean isTable() throws InterpreterException { return meta_isTaggedAs(NativeTypeTags._TABLE_).asNativeBoolean().javaValue; }
  658. public boolean isUnquoteSplice() throws InterpreterException { return meta_isTaggedAs(NativeTypeTags._UQSPLICE_).asNativeBoolean().javaValue; }
  659. public boolean isTypeTag() throws InterpreterException { return meta_isTaggedAs(NativeTypeTags._TYPETAG_).asNativeBoolean().javaValue; }
  660. // private methods
  661. private boolean isFlagSet(byte flag) {
  662. return (flags_ & flag) != 0;
  663. }
  664. private void setFlag(byte flag) {
  665. flags_ = (byte) (flags_ | flag);
  666. }
  667. private void unsetFlag(byte flag) {
  668. flags_ = (byte) (flags_ & (~flag));
  669. }
  670. protected boolean hasLocalMethod(ATSymbol selector) throws InterpreterException {
  671. return methodDictionary_.containsKey(selector);
  672. }
  673. protected ATMethod getLocalMethod(ATSymbol selector) throws InterpreterException {
  674. ATMethod result = ((ATObject) methodDictionary_.get(selector)).asMethod();
  675. if(result == null) {
  676. throw new XSelectorNotFound(selector, this);
  677. } else {
  678. return result;
  679. }
  680. }
  681. /**
  682. * Performs a type test for this object locally.
  683. * @return whether this object is tagged with a particular type tag or not.
  684. */
  685. private boolean isLocallyTaggedAs(ATTypeTag tag) throws InterpreterException {
  686. for (int i = 0; i < typeTags_.length; i++) {
  687. if (typeTags_[i].base_isSubtypeOf(tag).asNativeBoolean().javaValue) {
  688. // if one type matches, return true
  689. return true;
  690. }
  691. }
  692. return false;
  693. }
  694. /**
  695. * Auxiliary method to access the fields of an object and all of its super-objects up to (but excluding) nil.
  696. * Overridden fields of parent objects are not included.
  697. */
  698. public static ATField[] listTransitiveFields(ATObject obj) throws InterpreterException {
  699. Vector fields = new Vector();
  700. HashSet encounteredNames = new HashSet(); // to filter duplicates
  701. for (; obj != OBJNil._INSTANCE_ ; obj = obj.base_super()) {
  702. ATObject[] localFields = obj.meta_listFields().asNativeTable().elements_;
  703. for (int i = 0; i < localFields.length; i++) {
  704. ATField field = localFields[i].asField();
  705. ATSymbol fieldName = field.base_name();
  706. if (!encounteredNames.contains(fieldName)) {
  707. fields.add(field);
  708. encounteredNames.add(fieldName);
  709. }
  710. }
  711. }
  712. return (ATField[]) fields.toArray(new ATField[fields.size()]);
  713. }
  714. /**
  715. * Auxiliary method to access the methods of an object and all of its super-objects up to (but excluding) nil.
  716. * Overridden methods of parent objects are not included.
  717. */
  718. public static ATMethod[] listTransitiveMethods(ATObject obj) throws InterpreterException {
  719. Vector methods = new Vector();
  720. HashSet encounteredNames = new HashSet(); // to filter duplicates
  721. for (; obj != OBJNil._INSTANCE_ ; obj = obj.base_super()) {
  722. // fast-path for native objects
  723. if (obj instanceof NATObject) {
  724. Collection localMethods = ((NATObject) obj).methodDictionary_.values();
  725. for (Iterator iter = localMethods.iterator(); iter.hasNext();) {
  726. ATMethod localMethod = (ATMethod) iter.next();
  727. ATSymbol methodName = localMethod.base_name();
  728. if (!encounteredNames.contains(methodName)) {
  729. methods.add(localMethod);
  730. encounteredNames.add(methodName);
  731. }
  732. }
  733. } else {
  734. ATObject[] localMethods = obj.meta_listMethods().asNativeTable().elements_;
  735. for (int i = 0; i < localMethods.length; i++) {
  736. ATMethod localMethod = localMethods[i].asMethod();
  737. ATSymbol methodName = localMethod.base_name();
  738. if (!encounteredNames.contains(methodName)) {
  739. methods.add(localMethod);
  740. encounteredNames.add(methodName);
  741. }
  742. }
  743. }
  744. }
  745. return (ATMethod[]) methods.toArray(new ATMethod[methods.size()]);
  746. }
  747. }