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 revisionPrevious revision
Next revision
Previous revision
Next revisionBoth sides next revision
at:tutorial:reflection [2007/06/29 11:26] – * stijnmat:tutorial:reflection [2007/10/25 19:09] – slot tvcutsem
Line 1: Line 1:
 ====== Reflective Programming ====== ====== 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. +[[wp>Reflection_(computer_science)|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.+The reflective model of AmbientTalk is based on [[http://bracha.org/mirrors.pdf|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 ===== ===== Mirrors =====
-As we have already mentioned in the introduction, 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'slots, as is exemplified below.+As we have already mentioned in the introduction, 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'methods, as is exemplified below.
  
 <code> <code>
-def baseObject := object{ +>def mirrorOnOne := reflect1; 
-  def field := nil; +>><mirror on:1> 
-  def canonicalMethod() { nil } +>mirrorOnOne.listMethods(); 
-  def keywordedarg1 method: arg2 { nil } +>>[<native method:==>, <native method:+>,  
-}; +   <native method:<=>>, <native method:to:do:>, ...]
-def mirror := reflectbaseObject; +
-def slots := mirror.listSlots(); +
-slots.each: { | slot | system.println() };+
 </code> </code>
  
-The code excerpt presented above uses the mirror to //introspect// on an object and uses the ''listSlots'' meta-method to obtain 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+The code excerpt presented above uses the mirror to //introspect// on a natively implemented object (the number 1) and uses the ''listMethods'' meta-method. The result is table of the methods provided by this object, including the comparators ''=='' and ''<=>'', operations such as ''+'' and the enumeration construct ''to:do:''. Since the number 1 is a natively implemented objectall of its methods are provided with builtin implementations. This can be witnessed from the example since all methods are denoted to be native methods.
  
-In addition to allowing program to reason about the structure of its objectsmirrors can also be used to write operations such as message sending in a first-class manner. The following example uses this power to invoke zero-argument methodwhose name is specified at runtime by requesting input from the user+When reflecting upon user-defined objectwe can observe that every object has some implictly defined methods and fields, in addition to those which are defined when constructing the object. Every AmbientTalk object has ''super'' field as well as primitive implementations for the methods ''=='', ''new'' and ''init''. The primitive methods play somewhat peculiar role in an object since they are present in every objectyet they can be safely overridden without leading to a name clash (which normally occurs when one object attempts to define two methods with the same name).
  
 <code> <code>
-def invokeUserMethod(object) { +>def inspectable := object: {  
-  def userInput := read: (system.readln()); + def map(arg1, @restArgs) { restArgs.map(arg1); } }; 
-  // This example assumes that the user typed single symbol +>><object:4927258> 
-  (reflect: object).invoke(objectuserInput, []); +>def mirrorOnInspectable := reflectinspectable; 
-};+>><mirror on:<object:4927258>> 
 +>mirrorOnInspectable.listFields(
 +>>[<field:super>
 +>mirrorOnInspectable.listMethods() 
 +>>[<method:map>, <primitive method:new>,  
 +   <primitive method:init>, <primitive method:==>
 +>def method := mirrorOnInspectable.grabMethod(`map); 
 +>><method:map> 
 +>method.bodyExpression 
 +>>restArgs.map(arg1) 
 +</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.  
 + 
 +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 first-class manner. The following example shows how to select all zero-argument methods whose name starts with ''test'' and invoke them. 
 + 
 +<code> 
 +>def isTestMethod(meth) { 
 +   (meth.name.text ~= "test.*").and: 
 +   { meth.parameters == [] } }; 
 +>><closure:isTestMethod> 
 +>def retainTestMethods(obj) { 
 +   (reflect: obj).listMethods() 
 +     .filter: &isTestMethod }; 
 +>><closure:retainTestMethods> 
 +>def runTest(obj) { 
 +   retainTestMethods(obj).each: { | meth |  
 +     (reflect: obj).invoke(objmeth.name, []) } }
 +>><closure:runTest> 
 +>runTest(object: {def testOne() { system.println(`ok) }); 
 +ok 
 +>>nil
 </code> </code>
  
Line 34: Line 62:
  
 ===== 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 from. This can be performed using the ''mirror:'' language construct as follows.+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 tutorialwe 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.
  
 <code> <code>
Line 47: Line 75:
     } else: {     } else: {
       super^doesNotUnderstand(selector);       super^doesNotUnderstand(selector);
-    } +    }; 
-  }+  };
 } }
 </code> </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 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.+<note> **TODO** Add a word on **base** </note> 
 + 
 +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 protocol. Such 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.
  
 <code> <code>
Line 76: Line 106:
 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 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 **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-methodwhile ''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 ''listSlots'' meta-method used in previous examples is an element of this protocol.+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 **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 **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.
at/tutorial/reflection.txt · Last modified: 2010/11/16 16:32 by tvcutsem