User Tools

Site Tools


at:tutorial:reflection

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
at:tutorial:reflection [2008/09/15 17:25]
tvcutsem updated
at:tutorial:reflection [2010/11/16 16:32] (current)
tvcutsem
Line 4: Line 4:
  
 The reflective model of AmbientTalk is based on [[http://bracha.org/mirrors.pdf|mirrors]], meta-level objects which allow one to reflect on an object's 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. The reflective model of AmbientTalk is based on [[http://bracha.org/mirrors.pdf|mirrors]], meta-level objects which allow one to reflect on an object's 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 ===== ===== Mirrors =====
Line 22: Line 23:
 // request a mirror on p via the mirror factory // request a mirror on p via the mirror factory
 > def mirrorOnP := reflect: p; > def mirrorOnP := reflect: p;
->><mirror on:1>+>><mirror on:<object:2493837>{x,x:=,...}>
  
 >mirrorOnP.listSlots().map: {|slot| slot.name }; >mirrorOnP.listSlots().map: {|slot| slot.name };
Line 28: Line 29:
 </code> </code>
  
-The code excerpt presented above uses the mirror to //introspect// on an object and uses the ''listSlots'' meta-method. The result is a table of the slots (fields and methods) provided by this object. Notice that fields are represented as a combination of an accessor and a mutator method, conforming to the Uniform Access Principle as discussed in chapter 5. Also note that the object has a field called ''super'', although this field was not explicitly defined. In AmbientTalk, ''super'' is defined implicitly for every object.+The code excerpt presented above uses the mirror to //introspect// on an object and uses the ''listSlots'' meta-method. The result is a table of the slots (fields and methods) provided by this object. Notice that fields are represented as a combination of an accessor and a mutator method, conforming to the Uniform Access Principle as discussed in [[:at:tutorial:objects#uniform_access|chapter 5]]. Also note that the object has a field called ''super'', although this field was not explicitly defined. In AmbientTalk, ''super'' is defined implicitly for every object. The picture below gives an overview of the different objects involved in the actor. 
 + 
 +{{:at:tutorial:meta-1.jpg|:at:tutorial:meta-1.jpg}} 
 + 
 +The code excerpt below shows how one can add and remove slots to and from an object, and how one can explicitly access values and invoke methods upon an object, reflectively:
  
 <code> <code>
->def inspectable := object: {  +// let's add a z coordinate to our point 
- def map(arg1@restArgs) { restArgs.map(arg1); } }+def [zaccessor, zmutator] := lobby.at.lang.values.createFieldSlot(`z,0); 
->><obj:{super,super:=,map}> +// we only add the accessorso the slot is read-only 
->def mirrorOnInspectable := reflect: inspectable+mirrorOnP.addSlot(zaccessor)
->><mirror on:<obj:{super,super:=,map}>> +// let's test it
->mirrorOnInspectable.listFields() +p.z 
->>[<field:super>] +>> 
->mirrorOnInspectable.listMethods() +// we can also read slots reflectively
->>[<method:map>, <primitive method:new>,  +def x :=mirrorOnP.grabSlot(`x
-   <primitive method:init>, <primitive method:==>] +>> <accessor method for:x
->def method := mirrorOnInspectable.grabMethod(`map); +// and we can also invoke methods reflectively
->><method:map> +mirrorOnP.invoke(p, lobby.at.lang.values.createInvocation(`distanceToOrigin,[],[])); 
->method.bodyExpression +>> 3.605551275463989 
->>restArgs.map(arg1)+// finally, we can remove slots..
 +mirrorOnP.removeSlot(`z);
 </code> </code>
  
-Using a mirror on an object, it is possible to get access to a representation of the object's methods and fields, allowing the programmer to read the value of a field, or as is exemplified above inspect the body of a method. This type of reflection is quite useful to for instance construct an inspector for live AmbientTalk objects.  +The following example contains the core of a unit testing framework by showing how to select all zero-argument methods of an object whose name starts with ''test'' and invoke them.
- +
-In addition to allowing a program to reason about the structure of its objects, mirrors can also be used to perform operations such as method invocation in a first-class manner. The following example shows how to select all zero-argument methods whose name starts with ''test'' and invoke them.+
  
 <code> <code>
 >def isTestMethod(meth) { >def isTestMethod(meth) {
    (meth.name.text ~= "test.*").and:    (meth.name.text ~= "test.*").and:
-   { meth.parameters == [] } };+   { meth.parameters.length == } };
 >><closure:isTestMethod> >><closure:isTestMethod>
 >def retainTestMethods(obj) { >def retainTestMethods(obj) {
Line 62: Line 66:
 >def runTest(obj) { >def runTest(obj) {
    retainTestMethods(obj).each: { | meth |     retainTestMethods(obj).each: { | meth | 
-     (reflect: obj).invoke(obj, `(.#(meth.name)())) } };+     (reflect: obj).invoke(obj, lobby.at.lang.values.createInvocation(meth.name, [], [])) } };
 >><closure:runTest> >><closure:runTest>
 >runTest(object: {def testOne() { system.println(`ok) } }); >runTest(object: {def testOne() { system.println(`ok) } });
Line 69: Line 73:
 </code> </code>
  
-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.+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. To get a complete overview, try to inspect AmbientTalk's prototypical mirror, named ''defaultMirror'', e.g. by using introspection: 
 + 
 +<code> 
 +defaultMirror.listSlots.map: { |slot| slot.name } 
 +</code> 
 + 
 + 
 +A complete overview of all meta-operations will be presented near the end of this chapter.
  
 ===== Mirages ===== ===== 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 fromThis can be performed using the ''mirror:'' language construct as follows.+ 
 +Extending the AmbientTalk core language requires 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 can redefine the programming language's default semantics of the MOP, by means of mirages. 
 + 
 +As a simple example, we show how to trace all method calls made on an object. The first step is to define //mirror// object that encapsulates this logging behaviourA mirror object must implement the complete AmbientTalk MOP. To make it convenient to make small changes to the MOP, AmbientTalk provides the ''defaultMirror'', which encapsulates the default semantics. By selectively overriding this mirror's methods, we can make small adjustments to the language, e.g. as follows:
  
 <code> <code>
-def dynamicExtensionMirror := mirror: { +def createTracingMirror(baseObject) { 
-  def doesNotUnderstand(selector) { +  extenddefaultMirror.new(baseObject) with: { 
-    system.println("You selected a slot" + selector + "which does not exist in this object."); +    def invoke(slf, invocation) { 
-    system.println("You can provide a definition here or press enter to report this error."); +      system.println("invoked "+invocation.selector+" on "+baseObject); 
-    def input := system.readln(); +      super^invoke(slf, invocation); 
-    if: !( "" == input ) then: { +    } 
-      def definition := read: input; +  }
-      eval: definition in: base; +
-    } else: { +
-      super^doesNotUnderstand(selector); +
-    }; +
-  };+
 } }
 </code> </code>
  
-<note**TODO** Add a word on **base** </note>+The primitive ''mirror:'' is syntactic sugar for creating a new prototype that extends from the ''defaultMirror''. Thus, we could have also defined the tracing mirror as: 
 + 
 +<code> 
 +def TracingMirror := mirror: { 
 +  def invoke(slf, invocation) { 
 +    system.println("invoked "+invocation.selector+" on "+self.base); 
 +    super^invoke(slf, invocation); 
 +  } 
 +
 +</code>
  
-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 be used subsequently to create objects with an adapted meta-object protocolSuch objects are called **mirages** as they are not ordinary objects, but rather objects whose appearance and behaviour are defined by a custom mirror. Mirages are constructed using a variation on the ''object:'' constructor as is illustrated below.+The next step is to create objects whose method calls can be traced. These objects will require the above tracing mirror as their implicit mirrorWe call such objects with a custom implicit mirror **mirages**. Mirages are constructed using a variation on the ''object:'' constructor as is illustrated below.
  
 <code> <code>
 def mirage := object: { def mirage := object: {
-  def m() { self.x }; +  def foo() { 42 }; 
-} mirroredBy: dynamicExtensionMirror;+} mirroredBy:{ |emptyBase| createTracingMirror(emptyBase) };
 </code> </code>
  
-When invoking the method ''m'' on the mirage, ''doesNotUnderstand'' will be invoked with selector ''`x''since the object does not have 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 objectUsing the code from the previous section, the user can verify that the mirage object now sports both an ''x'' and an ''x:='' slot+In the code above, the closure passed to ''mirroredBy:'' is //mirror construction closure//. This closure is applied to a newempty mirage object and it is expected that it returns new mirror that reflects upon this mirageWhen the mirror is constructed, the object initialization closure is executed.
  
-<note> +Another alternative is to just pass a mirror prototype to ''object:mirroredBy:'', like so:
-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. +
-</note>+
  
-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.+<code> 
 +def mirage := object: { 
 +  def foo() { 42 }; 
 +} mirroredBy: TracingMirror; 
 +</code> 
 + 
 +The AmbientTalk VM will then call ''new'' on the ''TracingMirror'' prototype to create a new mirror for the given ''mirage'' object. 
 + 
 +When invoking the method ''foo'' on the mirage, ''invoke'' will be invoked on the tracing mirror, causing the following behaviour: 
 + 
 +<code> 
 +> mirage.foo(); 
 +invoked foo on <obj:6276614{foo,...}> 
 +>> 42 
 +</code> 
 + 
 +The picture below gives an overview of the different objects involved in the actor. 
 + 
 +{{:at:tutorial:meta-2.jpg|:at:tutorial:meta-2.jpg}} 
 + 
 +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 language construct which is conceived as a reflective extension to the language is that of future-type message passing. Futures are discussed in the next chapter of this tutorial.
  
 ===== The Metaobject Protocol ===== ===== 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 [[http://prog.vub.ac.be/amop/at2langref/edu/vub/at/objects/Object.html|language reference]], this section provides an overview of the various protocols.+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 [[http://soft.vub.ac.be/amop/at2langref/edu/vub/at/objects/MirrorRoot.html|language reference]], this section provides an overview of the various protocols
 + 
 +The **Message Invocation Protocol** consists of methods to deal with both synchronous and asynchronous method invocation. 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 picture below gives an overview of that protocol.
  
-The **Message Passing Protocol** consists of methods to deal with both synchronous and asynchronous message sendingIt 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.+{{:at:tutorial:msgReceptionProtocol.jpg?500|:at:tutorial:msgReceptionProtocol.jpg}}
  
-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 **Object Marshalling 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 dynamic access and modification to slots. For instance, ''o.x'' can be intercepted using the ''invokeField'' meta-method, while ''o.x := 5'' is trapped using ''invoke'' where the selector will equal ''x:=''. The **Slot Access and Modification Protocol** consists of operations which allow trapping both dynamic access and modification to slots. For instance, ''o.x'' can be intercepted using the ''invokeField'' meta-method, while ''o.x := 5'' is trapped using ''invoke'' where the selector will equal ''x:=''.
  
-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 ''listMethods'' and ''listFields'' meta-methods used in previous examples are elements of this protocol.+The **Structural Access Protocol** reifies the structure of an AmbientTalk objects as a collection of slot objects. It 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 example is a member 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 **Object 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 **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 **Type Tag Protocol** consists of the methods ''isTaggedAs'' and ''listTypeTags'', 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). ''listTypeTags'' 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.  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.1221492327.txt.gz · Last modified: 2008/09/15 17:26 (external edit)