User Tools

Site Tools


Sidebar

Jump to
AmbientTalk
CRIME
iScheme

at:tutorial:reflection

This is an old revision of the document!


Reflective Programming

Reflection is an integral part of the AmbientTalk programming language. Through the use of reflection, the core language can be extended with both programming support as well as new language constructs. Both examples require a different kind of reflective access. The introduction of programming support (e.g. to visualise AmbientTalk objects) relies on introspection, the ability for a program to inspect and reason about parts of its own state. This particular flavour of reflection is quite popular and is available in most contemporary programming languages. AmbientTalk goes beyond introspection and also allows objects to supply alternative semantics for the default meta-level operations. This particular form of reflection, called intercession, allows enriching AmbientTalk from within the language itself.

The reflective model of AmbientTalk is based on mirrors, meta-level objects which allow one to reflect on an objects state and behaviour. How to create such mirrors and how they can be used is demonstrated in the first part of the tutorial. The second part of the tutorial showcases how to construct mirages, objects which override the default meta-level operations with custom behaviour. This tutorial concludes with a brief overview of the meta-level operations which are offered by AmbientTalk mirrors.

Mirrors

AmbientTalk uses a mirror-based architecture to provide reflective access to its objects. The basic principle of a mirror-based architecture is that all reflective facilities are encapsulated in a mirror object which provides reflective access to precisely one object, its reflectee. Moreover, the mirror of the object is not directly accessible as a slot of the object. Instead, a separate factory must be used to create mirrors, which allows the program to hand out different mirrors according to the dynamic call chain, the requesting object etc. The factory can be used implicitly using the reflect: primitive. Once a mirror has been created, it can be used for instance to produce a listing of an object's slots, as is exemplified below.

def baseObject := object: {
  def field := nil;
  def canonicalMethod() { nil }
  def keyworded: arg1 method: arg2 { nil }
};
def mirror := reflect: baseObject;
def slots := mirror.listSlots();
slots.each: { | slot | system.println() };

The code excerpt presented above uses the mirror to introspect on an object and uses the listSlots meta-method to obtain a collection of the slots contained in this object, to wit field, field:=, canonicalMethod, keyworded:method: and the primitive slots ==, new and init which are implicitly present in every AmbientTalk object.

In addition to allowing a program to reason about the structure of its objects, mirrors can also be used to write operations such as message sending in a first-class manner. The following example uses this power to invoke a zero-argument method, whose name is specified at runtime by requesting input from the user.

def invokeUserMethod(object) {
  def userInput := read: (system.readln());
  // This example assumes that the user typed a single symbol
  (reflect: object).invoke(object, userInput, []);
};

This part of the tutorial has provided a basic feeling of how AmbientTalk's default mirrors can be created and the kind of power they offer. The default mirrors offer a much wider range of capabilities than those presented in this section, however. A complete overview of all meta-operations will be presented in the final chapter of this tutorial.

Mirages

Extending the AmbientTalk core language involves adding objects which have a different implementation for some of the default meta-operations. In this part of the tutorial we describe how a programmer could define objects which allow for the dynamic addition of unknown methods and fields. First of all, we need to create a mirror instance which we can use to create new objects from. This can be performed using the mirror: language construct as follows.

def dynamicExtensionMirror := mirror: {
  def doesNotUnderstand(selector) {
    system.println("You selected a slot" + selector + "which does not exist in this object.");
    system.println("You can provide a definition here or press enter to report this error.");
    def input := system.readln();
    if: !( "" == input ) then: {
      def definition := read: input;
      eval: definition in: base;
    } else: {
      super^doesNotUnderstand(selector);
    }
  }
}

This mirror overrides the default implementation of the meta-operation doesNotUnderstand to report that a slot was selected which did not exist. The user is then provided with an opportunity to provide the missing definition or pass this opportunity in which case the default behaviour is executed (i.e. an error is being reported). The mirror defined above can subsequently used to create objects with an adapted meta-object protocol. Such objects are called mirages as they are not ordinary objects, but rather objects whose appearance and behaviour is defined by a custom mirror. Mirages are constructed using a variation on the object: constructor as is illustrated below.

def mirage := object: {
  def m() { self.x };
} mirroredBy: dynamicExtensionMirror;

When invoking the method m on the mirage, doesNotUnderstand will be invoked with a selector `x, since the object does not have a slot with the request name. The user can mediate this oversight by typing def x := 5 at which point the slot will be added to the object. Using the code from the previous section, the user can verify that the mirage object now sports both an x and an x:= slot.

Note that the use of self.x in the above example is crucial as the doesNotUnderstand operation is not called when a lexical lookup fails.

Whereas the example provided above may seem a little contrived, the reflective capabilities of AmbientTalk allow it to be extended with many abstraction relating to distributed computing for mobile ad hoc networks (AmbientTalk's main domain of application). An example of a language construct which is conceived as a reflective extension to the language is for instance futures, which are discussed in the next chapter of this tutorial.

The Metaobject Protocol

The Meta-Object Protocol of AmbientTalk can be divided into a series of independent protocols. Whereas the full semantics and signature of the meta-methods can be found in the language reference, this section provides an overview of the various protocols.

The Message Passing Protocol consists of methods to deal with both synchronous and asynchronous message sending. It provides necessary hooks to intercept both the reception of asynchronous messages and the invocation of synchronous messages. Moreover, it provides a hook to intercept asynchronous messages being sent by the object, allowing the object to add additional metadata to the message. The invoke meta-method illustrated above is an example of a method belonging to this protocol.

The Object Passing Protocol consists of two methods pass and resolve, which allow an object to prescribe how it should be passed to other objects and how the object should subsequently be resolved upon arrival. The default semantics allow objects to be passed by copy if they are tagged with the Isolate type tag. Otherwise, objects are passed by handing out a far object reference.

The Slot Access and Modification Protocol consists of operations which allow trapping both access and modification to slots. These operations are further refined based on whether they transitively search the dynamic or lexical parent chain. For instance, for the lookup of a variable, lookup traverses the lexical chain whereas select (which requires an additional receiver parameter) traverses the dynamic parent chain.

The Structural Access Protocol consists of operations used list all available slots, get access to a first-class slot representation and to add new slots to an existing object. The listSlots meta-method used in previous examples is an element of this protocol.

The Instantiation Protocol consists of the clone and newInstance methods, which are implictly called when using base-level code of the form clone: object and object.new(@args) respectively. In the default implementation, newInstance calls clone() to create a clone of the current object, and subsequently invokes the base-level init method with the supplied arguments on the cloned object.

The Relational Testing Protocol consists of the methods isCloneOf and isRelatedTo which allow testing whether 2 objects are related through cloning or a combination of cloning and object extension. Note that these operators are not able to discern that objects were generated by the same constructor function or (by extension) the execution of identical code in different actors.

The Type Testing Protocol consists of the methods isTaggedAs and getTypeTags, the former of which tests whether an object is transitively tagged with a particular type (i.e. this operation considers type tags of parent objects). getTypeTags on the other hand returns only the type tags which were explicitly attributed to this object (i.e. it does not return type tags attributed to the parent objects).

The Evaluation Protocol ensures that any AmbientTalk object can be part of a parse tree, and therefore every object provides meaningful implementations of the eval and quote meta-operations. The eval operation is called when evaluating a parsetree and typically returns the evaluated object itself, except for explicit parse-tree elements such as definition and method invocations.

at/tutorial/reflection.1184312274.txt.gz · Last modified: 2007/07/13 09:41 (external edit)