User Tools

Site Tools


at:tutorial:appendix

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:appendix [2008/07/10 16:24]
tvcutsem *
at:tutorial:appendix [2021/09/24 10:28] (current)
elisag [Dynamic Variables]
Line 1: Line 1:
-====== Appendix ======+====== Appendix: Libraries ======
  
-In the appendix, we explain useful libraries available to the AmbientTalk/2 programmer. These libraries provide abstractions ranging from traditional, established "collections" up to newly researched language constructs, such as "ambient references".+In the appendix, we explain useful libraries available to the AmbientTalk/2 programmer as part of the AmbientTalk standard library, also known as ''atlib''. These libraries provide abstractions ranging from traditional, established "collections" up to newly researched language constructs, such as "ambient references". 
 + 
 +The Ambientalk standard library (''atlib'') is part of the AmbientTalk/2 distribution. Note that the Intellij plugin already contains ''atlib''. If you would like to access the atlib source files, please visit the dedicated gitlab project [[ https://gitlab.soft.vub.ac.be/ambienttalk/atlib |here.]] 
  
 ===== Unit Testing Framework ===== ===== Unit Testing Framework =====
Line 27: Line 29:
 This will execute all ''test*'' methods in the given unit test (in an **undefined** order!), and print out which of the tests succeeded or failed. The ''runTest'' method can optionally take a "reporter" object as an argument, which can be used to implement a custom strategy for reporting success or failure of a unit test. The default reporter object is a text-based UI. This will execute all ''test*'' methods in the given unit test (in an **undefined** order!), and print out which of the tests succeeded or failed. The ''runTest'' method can optionally take a "reporter" object as an argument, which can be used to implement a custom strategy for reporting success or failure of a unit test. The default reporter object is a text-based UI.
  
-Like in JUnit and SUnit, it is possible to define two methods named ''setUp()'' and ''tearDown()'' that are invoked in between //each// individual ''test*'' method. Never rely on the lexical order of your unit test methods for the purposes of initialization, etc.! Unit test methods may be exacuted in an arbitrary order.+Like in JUnit and SUnit, it is possible to define two methods named ''setUp()'' and ''tearDown()'' that are invoked in between //each// individual ''test*'' method. Never rely on the lexical order of your unit test methods for the purposes of initialization, etc.! Unit test methods may be executed in an arbitrary order.
  
 ==== Assertions ==== ==== Assertions ====
Line 82: Line 84:
  
 It is also possible to use ''makeFuture()'' to create a fresh future explicitly within the unit test method, and to use the returned resolver to resolve the future at the appropriate time. It is also possible to use ''makeFuture()'' to create a fresh future explicitly within the unit test method, and to use the returned resolver to resolve the future at the appropriate time.
 +
 +<note tip>
 +See the [[distribution#take_offline_remote_objects|distributed programming]] chapter for details about how to simulate network disconnections in distributed unit tests.
 +</note>
  
 ==== Test Suites ==== ==== Test Suites ====
Line 386: Line 392:
 ===== Language Extensions ===== ===== Language Extensions =====
  
-The files in the ''at/lang'' directory define custom language features which mostly use AmbientTalk/2's reflective facilities to extend the language.+The files in the ''at/lang'' directory define custom language features which mostly use AmbientTalk/2's reflective facilities to extend the language. In what follows, we describe the most relevant ones
  
-==== Futures and Multifutures ==== 
  
-=== Futures ===+ 
 + 
 +=====Futures and Multifutures ===== 
 + 
 +==== Futures ====
  
 The module ''/.at.lang.futures'' provides support for futures. Futures have already been described as part of the [[:at:tutorial:actors#futures|concurrency]] section in the tutorial. The module ''/.at.lang.futures'' provides support for futures. Futures have already been described as part of the [[:at:tutorial:actors#futures|concurrency]] section in the tutorial.
Line 413: Line 422:
 </code> </code>
  
-Finally, the futures module also provides some auxiliary functions, of which ''group:'' is often a very useful one. The ''group:'' construct groups a table of futures into a single future which is resolved with a table of values or ruined with an exception:+The ''makeFuture'' function can also take a timeout. If a timeout is given it returns a returns a pair [leaseresolver]  where the lease timer gets immediately activated. If the future is not resolved within the given timeout, the lease expires and ruins the future with a ''TimeoutException''. Note that this means a lease will get parameter-passed rather than the future if given to other actors. 
 + 
 +=== Auxilary functions in the futures module ==== 
 + 
 +The futures module also provides some auxiliary functions, of which ''group:'' is often a very useful one. The ''group:'' construct groups a table of futures into a single future which is resolved with a table of values or ruined with an exception:
  
 <code> <code>
-when: (group: [ a<-m(), b<-n() ]) becomes: { |values|+when: (group: [ a<-m()@FutureMessage, b<-n()@FutureMessage ]) becomes: { |values|
   def [aResult, bResult] := values;   def [aResult, bResult] := values;
   ...   ...
Line 422: Line 435:
 </code> </code>
  
-=== Multifutures ===+Another useful auxilary function is ''future:'' construct which returns a future which is resolved with the value passed to the 'reply' closure: 
 + 
 +<code> 
 +future: { |return| 
 +  // some computation 
 +  return(val) 
 +
 +</code> 
 + 
 +This is actually equivalent to the slightly more verbose code: 
 + 
 +<code> 
 +def [fut,res] := makeFuture(); 
 +try: { // some computation 
 +  res.resolve(val); 
 +} catch: Exception using: { |e| res.ruin(e) } 
 +fut; 
 +</code> 
 + 
 +==== Multifutures ====
  
 The module ''/.at.lang.multifutures'' provides support for multifutures. A multifuture is a future that can be resolved multiple times. We distinguish between 'bounded multifutures', which can be resolved up to a maximum number and 'unbounded multifutures' which have no upper bound. The module ''/.at.lang.multifutures'' provides support for multifutures. A multifuture is a future that can be resolved multiple times. We distinguish between 'bounded multifutures', which can be resolved up to a maximum number and 'unbounded multifutures' which have no upper bound.
Line 463: Line 495:
 When the message sent to a multireference is annotated with @Due(t), the timeout is applied to the implicit multifuture, causing whenAll observers to trigger automatically. Note that the implicit multifuture of a multireference is bounded, so whenAll observers trigger automatically when all replies have been received. When the message sent to a multireference is annotated with @Due(t), the timeout is applied to the implicit multifuture, causing whenAll observers to trigger automatically. Note that the implicit multifuture of a multireference is bounded, so whenAll observers trigger automatically when all replies have been received.
  
-==== Dynamic Variables ====+ 
 +===== Leased Object References ===== 
 + 
 +The module ''/.at.lang.leasedrefs'' provides support for leased object references. Leased object references have already been described as part of the [[:at:tutorial:distribution#dealing_with_permanent_failures|distributed programing]] section in the tutorial. 
 + 
 +<note> 
 +The implementation of leased object references actually consists of two files: ''/.at.lang.leasedrefs'' and ''/at.lang.leasedrefstrait''. ''leasedrefstrait'' module implements the behaviour common to the different types of leased references. This module is imported in the ''leasedrefs'' module which provides the public API for creating and managing leased object references. 
 +</note> 
 + 
 +The ''leasedrefs'' module exports language constructs to create three different types of leased object references: 
 +  * ''lease:for:''returns a leased reference that remains valid for the indicated time interval. 
 +  * ''renewOnCallLease:for:'' returns a leased reference that is automatically renewed (with the specified time interval) each time the remote object receives a message. 
 +  * ''singleCallLease:for:'' returns a leased reference that remains valid for only a single method call on the remote object. 
 + 
 +Variations of these constructs are also provided to allow developers to specify the renewal time interval in renew-on-call leased references and the name(s) of the method(s) which trigger expiration of a single-call leased reference. 
 + 
 +The ''leasedrefs'' module also provides the following constructs to explicitly manage the lifetime of leased references: 
 + 
 +<code> 
 +renew: leasedRef for: interval; // renews a lease 
 +revoke: leasedRef; // revokes a lease 
 +leaseTimeLeft: leasedRef; // return time left until lease expires 
 +when: lease expired: {...}; // trigger a closure when the lease expires 
 +</code> 
 + 
 +The ''when:expired:'' construct is provided to schedule clean-up actions with a leased reference upon its expiration. 
 + 
 +Finally, the ''leasedrefs'' module exports support primitives to manipulate time intervals (i.e. ''minutes'', ''seconds'', ''millisecs'') so that developers do not need to explicitly import the timer module to use leased references. 
 + 
 + 
 + 
 +===== TOTAM ===== 
 + 
 +The module ''/.at.lang.totam'' provides an implementation for TOTAM, a tuple space model geared towards mobile ad hoc networks which combines a replication-based tuple space model with a dynamic scoping mechanism that limits the transportation of tuples.  
 + 
 +Please have a look to [[:uf:totam]] for further details on the model and its API. 
 + 
 +===== Dynamic Variables =====
  
 The module ''/.at.lang.dynvars'' provides support for defining and using 'Dynamic Variables'. Dynamic variables 'simulate' dynamically scoped variables and are often used to parameterize large parts of code. For example, the 'current output stream'. A dynamic variable has the advantage over a simple global variable that it can only be assigned a value for the extent of a block of code. The module ''/.at.lang.dynvars'' provides support for defining and using 'Dynamic Variables'. Dynamic variables 'simulate' dynamically scoped variables and are often used to parameterize large parts of code. For example, the 'current output stream'. A dynamic variable has the advantage over a simple global variable that it can only be assigned a value for the extent of a block of code.
Line 490: Line 559:
 You can find more usage examples of dynamic variables in the unit test included in the file ''at/lang/dynvars.at''. You can find more usage examples of dynamic variables in the unit test included in the file ''at/lang/dynvars.at''.
  
-==== Ambient References ====+===== Ambient References =====
  
 Ambient references are defined in the module ''/.at.lang.ambientrefs'' . An ambient reference is a special kind of far reference which refers to an ever-changing collection of objects of a certain type. For example: Ambient references are defined in the module ''/.at.lang.ambientrefs'' . An ambient reference is a special kind of far reference which refers to an ever-changing collection of objects of a certain type. For example:
Line 504: Line 573:
 Ambient references ship with two so-called "implementation modules": the module ''/.at.ambient.ar_extensional_impl'' and the module ''/.at.m2mi.ar_intensional_impl''. By default, the extensional implementation is used, but this can be changed by passing the desired implementation module as a parameter to the ''/.at.lang.ambientrefs'' module. Ambient references ship with two so-called "implementation modules": the module ''/.at.ambient.ar_extensional_impl'' and the module ''/.at.m2mi.ar_intensional_impl''. By default, the extensional implementation is used, but this can be changed by passing the desired implementation module as a parameter to the ''/.at.lang.ambientrefs'' module.
  
-==== Structural Types ====+===== Structural Types ====
 + 
 +The module ''/.at.lang.structuraltypes'' implements a small library to use structural typing. The library allows for the creation of 'protocols', which are first-class structural types. A structural type is simply a set of selectors. An object o conforms to a protocol P <=> for all selectors s of P, o respondsTo s where respondsTo is determined by o's mirror. 
 + 
 +A structural type can be branded with type tags. In this case, objects only conform to the type if they are structurally conformant **and** if they are tagged with the structural type's brands. 
 + 
 +Use the ''protocol:'' function to create a new protocol: 
 + 
 +<code> 
 +def PersonProtocol := protocol: { 
 +  def name; 
 +  def age; 
 +} named: `Person; 
 +</code> 
 + 
 +The ''`Person'' argument is used to give the protocol a name simply for display purposes. The ''object:implements:'' function automatically checks whether an object conforms to any declared types: 
 + 
 +<code> 
 +def tom := object: { 
 +  def name := "Tom"; 
 +  def age() { 24 }; 
 +} implements: PersonProtocol; 
 +</code> 
 + 
 +You can also create a protocol from an object: 
 +<code>def tomsProtocol := protocolOf: tom;</code> 
 + 
 +You can test protocol conformance in either of two styles: 
 +  * ''does: tom implement: PersonProtocol'' => true or false 
 +  * ''PersonProtocol <? tom'' => true or false 
 + 
 +You can also force a ''StructuralTypeMismatch'' exception to be raised if the object does not conform to the type: 
 +  *  ''ensure: tom implements: PersonProtocol'' => true or exception 
 +  *  ''PersonProtocol.checkConformance(tom)'' => true or exception 
 + 
 +More usage examples of structural types can be found in the unit test defined in the file ''at/lang/structuraltypes.at''
 + 
 +===== Traits ===== 
 + 
 +The module ''/.at.lang.traits'' exports a small library to use AmbientTalk's traits in a more structured manner. In the literature, traits are described as reusable components with two interfaces: an interface of methods that are //provided// by the trait //to// the composite and an interface of methods that are //required// by the trait //from// the composite. AmbientTalk's traits only make the provided interface explicit. The required interface remains implicit and unchecked at composition time. 
 + 
 +Using the ''traits'' module, a trait can specify that it requires its composite to adhere to a certain protocol (i.e. a structural type, cf. the previous section). Using traits in this way requires an explicit composition step where the trait's requirements are checked. 
 + 
 +To define a "structured" trait, define your  trait objects as follows: 
 +<code> 
 +trait: { 
 +  ... 
 +} requiring: Protocol; 
 +</code> 
 + 
 +The above code creates a trait that can only be composed into an object adhering to the specified protocol. To compose traits, use the following language construct: 
 + 
 +<code> 
 +object: { 
 +  use: { 
 +    import T1 exclude ...; 
 +    import T2 alias ...;  
 +  } 
 +
 +</code> 
 + 
 +The ''use:'' block can **only** include ''import'' statements. It simply executes the ''import'' statements, but in addition checks whether the composite, //after// having imported all of its traits, provides all of the methods specified in the required protocol of its imported traits. 
 + 
 +Note that the place where ''use:'' is used inside an object matters: if one of the traits requires a method ''m()'' that is defined only later in the composite, the check will fail. To avoid this, place the ''use:'' block at the bottom of the object declaration. 
 + 
 +Usage examples can be found in the unit tests in the file ''at/lang/traits.at''
 + 
 +===== Utilities ===== 
 + 
 +The files in the ''at/support'' subdirectory of the standard library implement various utilities of use to the AmbientTalk programmer. We discuss the most useful modules below. 
 + 
 + 
 +==== Timing Utilities ==== 
 + 
 +The module ''/.at.support.timer'' provides utility functions to schedule code for execution at a later point in time. Its most useful control construct is the following: 
 + 
 +<code> 
 +def subscription := when: timeoutPeriod elapsed: { 
 +  ... 
 +
 +</code> 
 + 
 +The ''when:elapsed:'' function takes as its arguments a timeout period (in milliseconds) and a block closure and schedules the closure for execution after the given timeout period. The function returns a subscription object whose single ''cancel'' method can be used to abort the execution of the scheduled code. Once ''cancel'' has been invoked, it is guaranteed that the closure will no longer be executed by the timer module. 
 + 
 +The milliseconds used to define the timeout period must be provided as a Java ''long'' value. To construct such a value from an AmbientTalk number, the timer module defines the following auxiliary functions: 
 + 
 +  * ''millisec(ms)'' => convert AmbientTalk number to a Java long value representing a timeout period in milliseconds. 
 +  * ''seconds(s)'' => convert AmbientTalk number to a Java long value representing a timeout period in seconds. 
 +  * ''minutes(m)'' => convert AmbientTalk number to a Java long value representing a timeout period in minutes. 
 + 
 +Additionally, the timer module defines a function ''now()'' which returns the current system time as a Java long value. 
 + 
 +The timer module also defines a function ''whenever:elapsed:'' which repetitively invokes the given block closure every time the timeout period has elapsed. The returned subscription object can be used to eventually stop the repetitive invocation of the closure. 
 + 
 +Finally, there is a variant of ''when:elapsed:'' called ''when:elapsedWithFuture:'' which returns a future that will be resolved or ruined by executing the given closure after the given timeout. This variant is very useful in unit tests, e.g: 
 + 
 +<code> 
 +def testAsyncNearbyPlayerReply(){ 
 +  def nearbyPlayers := // search 2 nearby player orjbects; 
 +  // wait a bit so that there are the 2 members. 
 +  when: 2.seconds elapsedWithFuture:
 + self.assertEquals(2, nearbyPlayers.getReceivedAnswers); 
 +  } 
 +}; 
 +</code> 
 + 
 + 
 +==== Logging Framework ==== 
 + 
 +The module ''/.at.support.logger'' defines a tiny logging framework akin to the well-known [[http://logging.apache.org/log4j|Log4J]] logging framework for Java. 
 + 
 +Here's a typical example of how to use a logger: 
 +<code> 
 +import /.at.support.logger; 
 +def log := makeLogger("my prefix", INFO); // do not log DEBUG 
 +log("a message", ERROR); // message level is optional and defaults to INFO 
 +</code> 
 + 
 +The ''makeLogger'' function returns a function which can be used to log messages to an output object. It takes three arguments, all of which are optional: a string to be prefixed to every logged message (default ''""''), a logging level (default ''DEBUG'') and an output object (default ''system''). 
 + 
 +The logging level determines which messages are shown on the output log. The available error levels are: ''NONE'', ''DEBUG'', ''WARNING'', ''INFO'', ''ERROR'' and ''FATAL'' in order of exceeding importance. Hence, a log whose default is ''WARNING'' will not show ''DEBUG''-level messages. 
 + 
 +The output object is an object that understands ''println(string)''. It is used by the logging framework to write its log to the screen, a file, etc. 
 + 
 +==== Object Inspector ==== 
 + 
 +The module ''/.demo.inspector'' implements a graphical object inspector. The module requires ''java.awt'' and ''javax.swing'' support from the underlying JVM running AmbientTalk. To inspect an object ''o'', execute: 
 + 
 +<code> 
 +import /.demo.inspector; 
 +inspect(o); 
 +</code> 
 + 
 +This will pop up a graphical inspector on the object, listing the object's fields and methods. The object's fields and methods can recursively be inspected through the graphical user interface of the object inspector. 
 + 
 +==== Symbiosis Utilities ==== 
 + 
 +The module ''/.at.support.symbiosis'' defines a number of utility functions with respect to the symbiosis with the JVM. It defines the following functions which can be used to quickly create a wrapped Java value of the given primitive type: 
 + 
 +<code> 
 +long(anAmbientTalkNumber) -> aJavaLong 
 +short(anAmbientTalkNumber) -> aJavaShort 
 +float(anAmbientTalkFraction) -> aJavaFloat 
 +byte(anAmbientTalkNumber) -> aJavaByte 
 +</code> 
 + 
 +The module also defines the following function: 
 +<code> 
 +cast: obj into: Interface 
 +</code> 
 + 
 +The ''Interface'' argument should be a Java class wrapper for an interface type. The function returns a Java proxy object implementing the given interface, wrapping the given AmbientTalk object. If this proxy is subsequently passed to Java code, it will hold that ''proxy instanceof Interface''
 + 
 +==== Miscellaneous ==== 
 + 
 +The module ''/.at.support.util'' is a utility module grouping several miscellaneous tasks. 
 + 
 +=== Random Numbers === 
 + 
 +The utility module defines functions for easily generating random numbers. Its implementation uses the random number generators from the underlying JVM. The following functions are the most useful: 
 + 
 +<code> 
 +// generate a random integer in the interval [min, max[ 
 +def randomNumberBetween(min, max) 
 +// generate a random fraction in the interval [min, max[ 
 +def randomFractionBetween(min, max) 
 +</code> 
 + 
 +=== Custom Object Serialization === 
 + 
 +The method ''uponArrivalBecome:'' exported by the utility module creates a transporter object which can be used in ''pass'' meta-level methods to execute code upon deserialization. The closure passed to this function should return the object with which the transported object should be replaced. For example: 
 + 
 +<code> 
 +//inside a mirror 
 +def instancevar := ...; 
 +def pass() { 
 +  uponArrivalBecome: { |instancevar| 
 +    // return object to become here 
 +  } 
 +
 +</code>
  
-==== Traits ====+The function plays a role similar to ''readResolve'' in the Java object serialization framework.
at/tutorial/appendix.1215699861.txt.gz · Last modified: 2008/07/10 16:31 (external edit)