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

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