<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 
 <title>Bluish Coder: pony</title>
 <link href="http://bluishcoder.co.nz/tag/pony/atom.xml" rel="self"/>
 <link href="http://bluishcoder.co.nz/"/>
 <updated>2020-07-10T16:25:05+12:00</updated>
 <id>http://bluishcoder.co.nz/</id>
 <author>
   <name>Bluishcoder</name>
   <email>admin@bluishcoder.co.nz</email>
 </author>

 
 <entry>
   <title>Reference Capabilities, Consume and Recover in Pony</title>
   <link href="http://bluishcoder.co.nz/2017/07/31/reference_capabilities_consume_recover_in_pony.html"/>
   <updated>2017-07-31T18:00:00+12:00</updated>
   <id>http://bluishcoder.co.nz/2017/07/31/reference_capabilities_consume_recover_in_pony</id>
   <content type="html">&lt;p&gt;I&#39;ve written about reference capabilities in the &lt;a href=&quot;http://ponylang.org&quot;&gt;Pony programming language&lt;/a&gt;  spread across &lt;a href=&quot;http://bluishcoder.co.nz/tags/pony/index.html&quot;&gt;some of my other posts&lt;/a&gt; but haven&#39;t written about them directly. This post is my attempt to provide an intuitive understanding of reference capabilities and when to use &lt;code&gt;consume&lt;/code&gt; and &lt;code&gt;recover&lt;/code&gt;. Hopefully this reduces the confusion when faced with reference capability compilation errors and the need to memorize capability tables.&lt;/p&gt;

&lt;p&gt;Reference capabilities are used to control aliasing. Controlling aliasing is important when sharing data to avoid data races in the presence of multiple threads. An example of aliasing is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object = create_an_object()
let b: Object = a
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In that snippet, &#39;b&#39; is an alias to the object referenced by &#39;a&#39;. If I pass &#39;b&#39; to a parallel thread then the same object can be mutated and viewed by two different threads at the same time resulting in data races.&lt;/p&gt;

&lt;p&gt;Reference capabilities allow annotating types to say how they can be aliased. Only objects with a particular set of reference capabilities can be shared across actors.&lt;/p&gt;

&lt;h2&gt;tag - opaque reference&lt;/h2&gt;

&lt;p&gt;A &lt;code&gt;tag&lt;/code&gt; reference capability is an opaque reference to an object. You cannot read or write fields of the object referenced through a &lt;code&gt;tag&lt;/code&gt; alias. You can store &lt;code&gt;tag&lt;/code&gt; objects, compare object identity and share them with other actors. The sharing is safe since no reading or writing of state is allowed other than object identity.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object tag = create_a_tag()
let b: Object tag = a
if a is b then ...we&#39;re the same object... end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There is also the &lt;code&gt;digestof&lt;/code&gt; operator that returns a unique unsigned 64 bit integer value of an object. This is safe to use on &lt;code&gt;tag&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object tag = create_a_tag()
env.out.print(&quot;Id is: &quot; + (digestof a).string())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;tag&lt;/code&gt; reference capability is most often used for actors and passing references to actors around. Actor behaviours (asynchronous method calls) can be made via &lt;code&gt;tag&lt;/code&gt; references.&lt;/p&gt;

&lt;h2&gt;val - immutable and sharable&lt;/h2&gt;

&lt;p&gt;A &lt;code&gt;val&lt;/code&gt; reference capability on a variable means that the object is immutable. It cannot be written via that variable. Only read-only fields and methods can be used. Aliases can be shared with other actors because it cannot be changed - there is no issue of data races when accessed from multiple threads. There can be any number of aliases to the object but they all must be &lt;code&gt;val&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object val = create_an_object()
let b: Object val = a
let c: Object val = a
call_some_function(b)
send_to_an_actor(c)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All the above are valid uses of &lt;code&gt;val&lt;/code&gt;. Multiple aliases can exist within the same actor or shared with other actors.&lt;/p&gt;

&lt;h2&gt;ref - readable, writable but not sharable&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;ref&lt;/code&gt; reference capability means the object is readable and writable but only within a single actor. There can exist multiple aliases to it within an actor but it cannot be shared with other actors. If it were sharable with other actors then this would allow data races as multiple threads of control read or write to it in a non-deterministic manner.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object ref = create_a_ref_object()
let b: Object ref = a
call_some_function(b)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The above are valid uses of &lt;code&gt;ref&lt;/code&gt; if they are occuring within a single actor. The following are invalid uses - they will result in a compile error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object ref = create_a_ref_object()
send_to_an_actor(a)
let b: Object val = a
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;send_to_an_actor&lt;/code&gt; call would result in an alias of &lt;code&gt;a&lt;/code&gt; being accessible from another thread. This would cause data races so is disallowed and results in a compilation error. The assignment to an &lt;code&gt;Object val&lt;/code&gt; is also a compilation error. The reasoning for this is access via &lt;code&gt;b&lt;/code&gt; would assume that the object is immutable but it could be changed through the underlying alias &lt;code&gt;a&lt;/code&gt;. If &lt;code&gt;b&lt;/code&gt; were passed to another actor then changes made via &lt;code&gt;a&lt;/code&gt; will cause data races.&lt;/p&gt;

&lt;h2&gt;iso - readable, writable uniquely&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;iso&lt;/code&gt; reference capability means the object is readable and writable but only within a single actor - much like &lt;code&gt;ref&lt;/code&gt;. But unlike &lt;code&gt;ref&lt;/code&gt; it cannot be aliased. There can only be one variable holding a reference to an &lt;code&gt;iso&lt;/code&gt; object at a time. It is said to be &#39;unique&#39; because it can only be written or read via that single unique reference.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object iso = create_an_iso_object()
let b: Object iso = a
call_some_function(a)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The first line above creates an &lt;code&gt;iso&lt;/code&gt; object. The other two lines are compilation errors. The assignment to &lt;code&gt;b&lt;/code&gt; attempts to alias &lt;code&gt;a&lt;/code&gt;. This would enable reading and writing via &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; which breaks the uniqueness rule.&lt;/p&gt;

&lt;p&gt;The second line calls a function passing &lt;code&gt;a&lt;/code&gt;. This is an implicit alias of &lt;code&gt;a&lt;/code&gt; in that the parameter to &lt;code&gt;call_some_function&lt;/code&gt; has aliased. It is readable and writable via &lt;code&gt;a&lt;/code&gt; and the parameter in &lt;code&gt;call_some_function&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When it comes to fields of objects things get a bit more complicated. Reference capabilities are &#39;deep&#39;. This means that the capability of an enclosing object affects the capability of the fields as seen by an external user of the object. Here&#39;s an example that won&#39;t work:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo
  var bar: Object ref = ...

let f: Foo iso = create_a_foo()
let b: Object ref = create_an_object()
f.bar = b
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If this were to compile we would have a &lt;code&gt;ref&lt;/code&gt; alias alive in &lt;code&gt;b&lt;/code&gt; and another alias to the same object alive in the &lt;code&gt;bar&lt;/code&gt; field of &lt;code&gt;f&lt;/code&gt;. We could then pass our &lt;code&gt;f&lt;/code&gt; iso object to another actor and that actor would have a data race when trying to use &lt;code&gt;bar&lt;/code&gt; since the original actor also has an alias to it via &lt;code&gt;b&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The uniqueness restriction would seem to make &lt;code&gt;iso&lt;/code&gt; not very useful. What makes it useful is the ability to mark aliases as no longer used via the &lt;code&gt;consume&lt;/code&gt; keyword.&lt;/p&gt;

&lt;h2&gt;consume - I don&#39;t want this alias&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;consume&lt;/code&gt; keyword tells Pony that an alias should be destroyed. Not the object itself but the variable holding a reference to it. By removing an alias we can pass &lt;code&gt;iso&lt;/code&gt; objects around.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object iso = create_an_iso_object()
let b: Object iso = consume a
call_some_function(consume b)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This snippet creates an &lt;code&gt;iso&lt;/code&gt; object referenced in variable &lt;code&gt;a&lt;/code&gt;. The &lt;code&gt;consume&lt;/code&gt; in the second line tells Pony that &lt;code&gt;a&lt;/code&gt; should no longer alias that object. It&#39;s floating around with nothing pointing to it now. Pony refers to this state as being &#39;ephemeral&#39;. At this point the variable &lt;code&gt;a&lt;/code&gt; doesn&#39;t exist and it is a compile error to use it further. The object has no aliases and can now be assigned to another variable, in this case &lt;code&gt;b&lt;/code&gt;. This meets the requirements of &lt;code&gt;iso&lt;/code&gt; because there is still only one reference to the object, via &lt;code&gt;b&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The function call works in the same manner. The &lt;code&gt;consume b&lt;/code&gt; makes the object ephemeral and can then be assigned to the parameter for the function and still meet the uniqueness requirements of &lt;code&gt;iso&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;iso&lt;/code&gt; objects can be sent to other actors. This is safe because there is only a single alias. Once it has been sent to another actor, the alias from the original actor cannot read or be written to because the alias it had was consumed:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object iso = create_an_iso_object()
send_to_an_actor(consume a)
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Converting capabilities&lt;/h2&gt;

&lt;p&gt;Given an &lt;code&gt;iso&lt;/code&gt; reference that is consumed, can that ephemeral object be assigned to other reference capabilities other than &lt;code&gt;iso&lt;/code&gt;? The answer to that is yes.&lt;/p&gt;

&lt;p&gt;Intuitively this makes sense. If you have no aliases to an object then when you alias that object you can make it whatever capability you want - it is like having created a new object, nothing else references it until you assign it. From that point on what you can do with it is restricted by the reference capability of the variable you assigned it to.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object iso = create_an_iso()
let b: Object val = consume a

let c: Object iso = create_an_iso()
let d: Object ref = consume c;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The above are examples of valid conversions. You can have an &lt;code&gt;iso&lt;/code&gt;, make changes to the object, then consume the alias to assign to some other reference capability. Once you&#39;ve done that you are restricted by that new alias:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let c: Object iso = create_an_iso()
let d: Object ref = consume c;
send_to_an_actor(d)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That snippet is an error as &lt;code&gt;ref&lt;/code&gt; cannot be sent to another actor as explained earlier. This is also invalid:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let c: Object iso = create_an_iso()
let d: Object ref = consume c;
send_to_an_actor(c)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we are trying to use &lt;code&gt;c&lt;/code&gt; after it is consumed. The &lt;code&gt;c&lt;/code&gt; alias no longer exists so it is a compile error.&lt;/p&gt;

&lt;p&gt;What if you want to go the other way and convert a &lt;code&gt;val&lt;/code&gt; to an &lt;code&gt;iso&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object val = create_a_val()
let b: Object iso = consume a
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is an error. Consuming the &lt;code&gt;a&lt;/code&gt; alias does not allow assigning to another reference capability. Because &lt;code&gt;val&lt;/code&gt; allows multiple aliases to exist the Pony compiler doesn&#39;t know if &lt;code&gt;a&lt;/code&gt; is the only alias to the object. There could be others aliases elsewhere in the program. &lt;code&gt;iso&lt;/code&gt; requires uniqueness and the compiler can&#39;t guarantee it because of this. The same reasoning is why the following is an error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object val = create_a_val()
let b: Object ref = consume a
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Intuitively we can reason why this fails. &lt;code&gt;ref&lt;/code&gt; allows reading and writing within an actor. &lt;code&gt;val&lt;/code&gt; requires immutability and can have multiple aliases. Even though we consume &lt;code&gt;a&lt;/code&gt; there may be other aliases around, like the &lt;code&gt;iso&lt;/code&gt; example before. Writing to the object via the &lt;code&gt;b&lt;/code&gt; alias would break the guarantee of any other aliases to &lt;code&gt;a&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Given this, how do you do this type of conversion? This is what the &lt;code&gt;recover&lt;/code&gt; expression is used for.&lt;/p&gt;

&lt;h2&gt;recover - restricted alias conversion&lt;/h2&gt;

&lt;p&gt;A &lt;code&gt;recover&lt;/code&gt; expression provides a block scope where the variables that can enter the scope are restricted based on their reference capability. The restriction is that only objects that you could send to an actor are allowed to enter the scope of the &lt;code&gt;recover&lt;/code&gt; expression. That is &lt;code&gt;iso&lt;/code&gt;, &lt;code&gt;val&lt;/code&gt; and &lt;code&gt;tag&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Within the &lt;code&gt;recover&lt;/code&gt; expression you can create objects and return them from the expression as a different reference capability than what you created them as. This is safe because the compiler knows what entered the block, knows what was created within the block, and can track the aliases such that it knows it&#39;s safe to perform a particular conversion.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object val = recover val
                      let b: Object ref = create_a_ref()
                      ...do something...
                      b
                    end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this snippet we create a &lt;code&gt;ref&lt;/code&gt; object within the &lt;code&gt;recover&lt;/code&gt; block. This can be returned as a &lt;code&gt;val&lt;/code&gt; because the compiler knows that all aliases to that &lt;code&gt;ref&lt;/code&gt; object exist within the &lt;code&gt;recover&lt;/code&gt; block. When the block scope exits those aliases don&#39;t exist - there are no more aliases to the object and can be returned as the reference type of the &lt;code&gt;recover&lt;/code&gt; block.&lt;/p&gt;

&lt;p&gt;How does the compiler know that the &lt;code&gt;b&lt;/code&gt; object wasn&#39;t stored elsewhere within the &lt;code&gt;recover&lt;/code&gt; block? There are no global variables in Pony so it can&#39;t be stored globally. It could be passed to another object but the only objects accessable inside the block are the restricted ones mentioned before (&lt;code&gt;iso&lt;/code&gt;, &lt;code&gt;val&lt;/code&gt; and &lt;code&gt;tag&lt;/code&gt;). Here&#39;s an attempt to store it that fails:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var x: Object ref = create_a_ref()
let a: Object val = recover val
                      let b: Object ref = create_a_ref()
                      x = b
                      b
                    end 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This snippet has a &lt;code&gt;ref&lt;/code&gt; object created in the enclosing lexical scope of the &lt;code&gt;recover&lt;/code&gt; expression. Inside the &lt;code&gt;recover&lt;/code&gt; an attempt is made to assign the object &lt;code&gt;b&lt;/code&gt; to that variable &lt;code&gt;x&lt;/code&gt;. Intuitively this should not work - allowing it would mean that we have a readable and writeable alias to the object held in &lt;code&gt;x&lt;/code&gt;, and an immutable alias in &lt;code&gt;a&lt;/code&gt; allowing data races. The compiler prevents this by not allowing a &lt;code&gt;ref&lt;/code&gt; object from the enclosing scope to enter a &lt;code&gt;recover&lt;/code&gt; expression.&lt;/p&gt;

&lt;p&gt;Can we go the other way and convert a &lt;code&gt;val&lt;/code&gt; to a &lt;code&gt;ref&lt;/code&gt; using &lt;code&gt;recover&lt;/code&gt;? Unfortunately the answer here is no.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object ref = recover ref
                      let b: Object val = create_a_ref()
                      ...do something...
                      b
                    end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This results in an error. The reason is a &lt;code&gt;val&lt;/code&gt; can be stored in another &lt;code&gt;val&lt;/code&gt; variable in the enclosing scope because &lt;code&gt;val&lt;/code&gt; objects are safely shareable. This would make it unsafe to return a writeable alias to the &lt;code&gt;val&lt;/code&gt; if it is stored as an immutable alias elsewhere. This code snippet shows how it could be aliased in this way:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let x: Object val = create_a_val()
let a: Object val = recover val
                      let b: Object val = create_a_ref()
                      x = b
                      b
                    end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We are able to assign &lt;code&gt;b&lt;/code&gt; to a variable in the enclosing scope as the &lt;code&gt;x&lt;/code&gt; variable is a &lt;code&gt;val&lt;/code&gt; which is one of the valid reference capabilities that can be accessed from within the &lt;code&gt;recover&lt;/code&gt; block. If we were able to recover to a &lt;code&gt;ref&lt;/code&gt; then we&#39;d have a writeable and an immutable alias alive at the same time so that particular conversion path is an error.&lt;/p&gt;

&lt;p&gt;A common use for &lt;code&gt;recover&lt;/code&gt; is to create objects with a reference capability different to that defined by the constructor of the object:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo
  new ref create() =&amp;gt; ...

let a: Foo val = recover val Foo end
let b: Foo iso = recover iso Foo end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The reference capability of the recover expression can be left out and then it is inferred by the capability of the variable being assigned to:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Foo val = recover Foo end
let b: Foo iso = recover Foo end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Two more reference capabilities to go. They are &lt;code&gt;box&lt;/code&gt; and &lt;code&gt;trn&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;box - allows use of val or ref&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;box&lt;/code&gt; reference capability provides the ability to write code that works for &lt;code&gt;val&lt;/code&gt; or &lt;code&gt;ref&lt;/code&gt; objects. A &lt;code&gt;box&lt;/code&gt; alias only allows readonly operations on the object but can be used on either &lt;code&gt;val&lt;/code&gt; or &lt;code&gt;ref&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object ref = create_a_ref()
let b: Object val = create_a_val()
let c: Object box = a
let d: Object box = b
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is particularly useful when writing methods on a class that should work for a receiver type of &lt;code&gt;val&lt;/code&gt; and &lt;code&gt;ref&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Bar
  var count: U32 = 0

  fun val display(out:OutStream) =&amp;gt;
    out.print(count.string())

actor Main
  new create(env:Env) =&amp;gt;
    let b: Bar val = recover Bar end
    b.display(env.out)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This example creates a &lt;code&gt;val&lt;/code&gt; object and calls a method &lt;code&gt;display&lt;/code&gt; that expects to be called by a &lt;code&gt;val&lt;/code&gt; object (the &quot;fun val&quot; syntax). The &lt;code&gt;this&lt;/code&gt; from within the &lt;code&gt;display&lt;/code&gt; method is of reference capability &lt;code&gt;val&lt;/code&gt;. This compiles and works. The following does not:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let b: Bar ref = recover Bar end
b.display(env.out)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here the object is a &lt;code&gt;ref&lt;/code&gt; but &lt;code&gt;display&lt;/code&gt; expects it to be &lt;code&gt;val&lt;/code&gt;. We can change &lt;code&gt;display&lt;/code&gt; to be &lt;code&gt;ref&lt;/code&gt; and it would work:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun ref display(out:OutStream) =&amp;gt;
  out.print(count.string())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But now we can&#39;t call it with a &lt;code&gt;val&lt;/code&gt; object as in our first example. This is where &lt;code&gt;box&lt;/code&gt; comes in. It allows a &lt;code&gt;ref&lt;/code&gt; or a &lt;code&gt;val&lt;/code&gt; object to be assigned to it and it only allows read only access. This is safe for &lt;code&gt;val&lt;/code&gt; as that is immutable and it is safe for &lt;code&gt;ref&lt;/code&gt; as an immutable view to the &lt;code&gt;ref&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun box display(out:OutStream) =&amp;gt;
  out.print(count.string())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Methods are &lt;code&gt;box&lt;/code&gt; by default so can be written as:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun display(out:OutStream) =&amp;gt;
  out.print(count.string())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As an aside, the default of &lt;code&gt;box&lt;/code&gt; is the cause for a common &quot;new to Pony&quot; error message where an attempt to mutate a field in an object fails with an &quot;expected box got ref&quot; error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun increment() =&amp;gt; count = count + 1
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This needs to be the following as the implicit &lt;code&gt;box&lt;/code&gt; makes the &lt;code&gt;this&lt;/code&gt; immutable within the method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun ref increment() =&amp;gt; count = count + 1
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;trn - writeable uniquely, consumable to immutable&lt;/h2&gt;

&lt;p&gt;A &lt;code&gt;trn&lt;/code&gt; reference capability is writeable but can be consumed to an immutable reference capability, &lt;code&gt;val&lt;/code&gt;. This is useful for cases where you want to create an object, perform mutable operations on it and then make it immutable to send to an actor.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Array[U32] trn = recover Array[U32] end
a.push(1)
a.push(2)
let b: Array[U32] val = consume a
send_to_actor(b)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;box&lt;/code&gt; and &lt;code&gt;ref&lt;/code&gt; methods can be called on &lt;code&gt;trn&lt;/code&gt; objects:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Bar
  var count: U32 = 0

  fun box display(out:OutStream) =&amp;gt;
    out.print(count.string())

  fun ref increment() =&amp;gt; count = count + 1

actor Main
  new create(env:Env) =&amp;gt;
    let a: Bar trn = recover Bar end
    a.increment()
    a.display(env.out)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This provides an alternative to the &quot;How do I convert a &lt;code&gt;ref&lt;/code&gt; to a &lt;code&gt;val&lt;/code&gt;?&quot; question. Instead of starting with a &lt;code&gt;ref&lt;/code&gt; inside a &lt;code&gt;recover&lt;/code&gt; expression you can use &lt;code&gt;trn&lt;/code&gt; and &lt;code&gt;consume&lt;/code&gt; to a &lt;code&gt;val&lt;/code&gt; later.&lt;/p&gt;

&lt;p&gt;You can use &lt;code&gt;iso&lt;/code&gt; in place of &lt;code&gt;trn&lt;/code&gt; in these examples. Where &lt;code&gt;trn&lt;/code&gt; is useful is passing it to &lt;code&gt;box&lt;/code&gt; methods to perform readonly operations on it. This is difficult with &lt;code&gt;iso&lt;/code&gt; as you have to consume the alias everytime you pass it around, and the methods you pass it to have to return it again if you want to perform further operations on it. With &lt;code&gt;trn&lt;/code&gt; you can pass it directly.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  let out: OutStream

  fun display(b: Bar box) =&amp;gt;
    b.display(out)

  new create(env:Env) =&amp;gt;
    out = env.out

    let a: Bar trn = recover Bar end
    display(a)
    let b : Bar val = consume a
    send_to_actor(b)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The equivalent with &lt;code&gt;iso&lt;/code&gt; is more verbose and requires knowledge of ephemeral types (the hat, &lt;code&gt;^&lt;/code&gt;, symbol):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  let out: OutStream

  fun display(b: Bar iso): Bar iso^ =&amp;gt;
    b.display(out)
    consume b

  new create(env:Env) =&amp;gt;
    out = env.out

    let a: Bar iso = recover Bar end
    let b: Bar iso = display(consume a)
    let c: Bar val = consume b
    send_to_actor(c)
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Capability Subtyping&lt;/h2&gt;

&lt;p&gt;I&#39;ve tried to use a lot of examples to help gain an intuitive understanding of the capability rules. The &lt;a href=&quot;https://tutorial.ponylang.org&quot;&gt;Pony Tutorial&lt;/a&gt; has a &lt;a href=&quot;https://tutorial.ponylang.org/capabilities/capability-subtyping.html&quot;&gt;Capability Subtyping&lt;/a&gt; page that gives the specific rules. Although technical seeming the rules there encode our implicit understanding. This section is a bit more complex and isn&#39;t necessary for basic Pony programming if you have a reasonable grasp of it intuitively. It is however useful for working out tricky capability errors and usage.&lt;/p&gt;

&lt;p&gt;The way to read those rules are that &quot;&lt;code&gt;&amp;lt;:&lt;/code&gt;&quot; means &quot;is a subtype of&quot; or &quot;can be substituted for&quot;. So &quot;&lt;code&gt;ref&lt;/code&gt; :&amp;lt; &lt;code&gt;box&lt;/code&gt;&quot; means that a &lt;code&gt;ref&lt;/code&gt; object can be assigned to a &lt;code&gt;box&lt;/code&gt; variable:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object ref = create_a_ref()
let b: Object box = a
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The effects are transitive. So if &quot;&lt;code&gt;iso^&lt;/code&gt; &amp;lt;: &lt;code&gt;iso&lt;/code&gt;&quot; and &quot;&lt;code&gt;iso&lt;/code&gt; &amp;lt;: &lt;code&gt;trn&lt;/code&gt;&quot; and &quot;&lt;code&gt;trn&lt;/code&gt; &amp;lt;: &lt;code&gt;ref&lt;/code&gt;&quot; then &quot;&lt;code&gt;iso^&lt;/code&gt; &amp;lt;: &lt;code&gt;ref&lt;/code&gt;&quot;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object iso = create_an_iso()
let b: Object ref = consume a
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice we start with &lt;code&gt;iso^&lt;/code&gt; which is an ephemeral reference capability. We get ephemeral types with &lt;code&gt;consume&lt;/code&gt;. So consuming the &lt;code&gt;iso&lt;/code&gt; gives an &lt;code&gt;iso^&lt;/code&gt; which can be assigned to a &lt;code&gt;ref&lt;/code&gt; due to the transitive subtyping path above.&lt;/p&gt;

&lt;p&gt;Why couldn&#39;t we assign the &lt;code&gt;iso&lt;/code&gt; directly without the &lt;code&gt;consume&lt;/code&gt;? This is explained previously using inutition but following the rules on the subtyping page we see that &quot;&lt;code&gt;iso!&lt;/code&gt; &amp;lt;: &lt;code&gt;tag&lt;/code&gt;&quot;. The &lt;code&gt;!&lt;/code&gt; is for an aliased reference capability. When we do &quot;something = a&quot; we are aliasing the &lt;code&gt;iso&lt;/code&gt; and the type of that &lt;code&gt;a&lt;/code&gt; in that expression is &lt;code&gt;iso!&lt;/code&gt;. This can only be assigned to a &lt;code&gt;tag&lt;/code&gt; according to that rule:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Object iso = create_an_iso()
let b: Object tag = a
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice there is no &quot;&lt;code&gt;iso!&lt;/code&gt; &amp;lt;: &lt;code&gt;iso&lt;/code&gt;&quot; which tells us that an alias to an &lt;code&gt;iso&lt;/code&gt; cannot be assigned to an &lt;code&gt;iso&lt;/code&gt; which basically states the rule that &lt;code&gt;iso&lt;/code&gt; can&#39;t be aliased.&lt;/p&gt;

&lt;p&gt;In a previous section I used an ephemeral type in a method return type:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun display(b: Bar iso): Bar iso^ =&amp;gt;
    b.display(out)
    consume b
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This was needed because the result of &lt;code&gt;display&lt;/code&gt; was assigned to an &lt;code&gt;iso&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let b: Bar iso = display(consume a)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If we used &lt;code&gt;Bar iso&lt;/code&gt; as the return type then the compiler expects us to be aliasing the object being returned. This alias is of type &lt;code&gt;iso!&lt;/code&gt;. The error message states that &lt;code&gt;iso!&lt;/code&gt; is not a subtype of &lt;code&gt;iso&lt;/code&gt; which is correct as there is no &quot;&lt;code&gt;iso!&lt;/code&gt; :&amp;lt; &lt;code&gt;iso&lt;/code&gt;&quot; rule. Thankfully the error message tells us that &quot;this would be possible if the subcap were more ephemeral&quot; which is the clue that we need the return type to be ephemeral.&lt;/p&gt;

&lt;h2&gt;Viewpoint Adaption&lt;/h2&gt;

&lt;p&gt;I briefly mentioned in a previous section that reference capabilities are &#39;deep&#39; and this is important when accessing fields of objects. It is also important when writing generic classes and methods and using collections.&lt;/p&gt;

&lt;p&gt;Viewpoint adaption is described in the &lt;a href=&quot;https://tutorial.ponylang.org/capabilities/combining-capabilities.html&quot;&gt;combining capabilities&lt;/a&gt; part of the tutorial. I also have a post, &lt;a href=&quot;http://bluishcoder.co.nz/2016/07/18/borrowing-in-pony.html&quot;&gt;Borrowing in Pony&lt;/a&gt; which works through some examples.&lt;/p&gt;

&lt;p&gt;The thing to remember is that a containing objects reference capability affects the reference capabilities of fields and methods when accessed via a user of the container.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Array[Bar ref] iso = recover Array[Bar ref] end
a.push(Bar)
try
  let b: Bar ref = a(0)?
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here is an &lt;code&gt;iso&lt;/code&gt; array of &lt;code&gt;Bar ref&lt;/code&gt; objects. The third line to retrieve an element of the array fails to compile, stating that &lt;code&gt;tag&lt;/code&gt; is not a subtype of &lt;code&gt;ref&lt;/code&gt;. Where does the &lt;code&gt;tag&lt;/code&gt; come from? Intuitively we can reason that we shouldn&#39;t be able to get a &lt;code&gt;ref&lt;/code&gt; alias of an item in an &lt;code&gt;iso&lt;/code&gt; array as that would give us two &lt;code&gt;ref&lt;/code&gt; aliases of an item in an &lt;code&gt;iso&lt;/code&gt; that could be shared across actors. This can give data races.&lt;/p&gt;

&lt;p&gt;Viewpoint adaption encodes this in the type rules. We have receiver, &lt;code&gt;a&lt;/code&gt; of type &lt;code&gt;iso&lt;/code&gt;, attempting to call the &lt;code&gt;apply&lt;/code&gt; method of the array. This method is declared as:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun apply(i: USize): this-&amp;gt;A ?
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;this-&amp;gt;A&lt;/code&gt; syntax is the viewpoint adaption. It states that the result of the call is the reference capability of &lt;code&gt;A&lt;/code&gt; as seen by &lt;code&gt;this&lt;/code&gt;. In our case, &lt;code&gt;this&lt;/code&gt; is an &lt;code&gt;iso&lt;/code&gt; and &lt;code&gt;A&lt;/code&gt; is a &lt;code&gt;ref&lt;/code&gt;. The viewpoint adaption for &lt;code&gt;iso-&amp;gt;ref&lt;/code&gt; is &lt;code&gt;tag&lt;/code&gt; and that&#39;s where the &lt;code&gt;tag&lt;/code&gt; in the error message comes from.&lt;/p&gt;

&lt;p&gt;We could get an immutable alias to an item in the array if the array was &lt;code&gt;trn&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Array[Bar ref] trn = recover Array[Bar ref] end
a.push(Bar)
try
  let b: Bar box = a(0)?
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The viewpoint adaption table shows that &lt;code&gt;trn-&amp;gt;ref&lt;/code&gt; gives &lt;code&gt;box&lt;/code&gt;. To get a &lt;code&gt;ref&lt;/code&gt; item we&#39;d need the array to be &lt;code&gt;ref&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Array[Bar ref] ref = recover Array[Bar ref] end
a.push(Bar)
try
  let b: Bar ref = a(0)?
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For more on viewpoint adaption I recommend my &lt;a href=&quot;http://bluishcoder.co.nz/2016/07/18/borrowing-in-pony.html&quot;&gt;Borrowing in Pony&lt;/a&gt; and &lt;a href=&quot;http://bluishcoder.co.nz/2016/05/04/bang-hat-and-arrow-in-pony.html&quot;&gt;Bang, Hat and Arrow&lt;/a&gt; posts.&lt;/p&gt;

&lt;h2&gt;Miscellaneous things&lt;/h2&gt;

&lt;p&gt;In my examples I&#39;ve used explicit reference capabilities in types to make it a bit clearer of what is happening. They can be left off in places to get reasonable defaults.&lt;/p&gt;

&lt;p&gt;When declaring types the default capability is the capability defined in the &lt;code&gt;class&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class ref Foo

let a: Foo = ...

class val Bar
let b: Bar = ...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The type of &lt;code&gt;a&lt;/code&gt; is &lt;code&gt;Foo ref&lt;/code&gt; and the type of &lt;code&gt;Bar&lt;/code&gt; is &lt;code&gt;Bar val&lt;/code&gt; due to the annotation in the &lt;code&gt;class&lt;/code&gt; definition. By default classes are &lt;code&gt;ref&lt;/code&gt; if they aren&#39;t annotated.&lt;/p&gt;

&lt;p&gt;The type of an object returned from a constructor is based on the type defined in the constructor:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo
  new ref create() =&amp;gt; ...
  new val create_as_val() =&amp;gt; ...
  new iso create_as_iso() =&amp;gt; ...

let a: Foo val = Foo.create_as_val()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here the &lt;code&gt;Foo&lt;/code&gt; class is the default type &lt;code&gt;ref&lt;/code&gt;, but there are constructors that explicitly return &lt;code&gt;ref&lt;/code&gt;, &lt;code&gt;val&lt;/code&gt; and &lt;code&gt;iso&lt;/code&gt; objects. As shown previously you can use &lt;code&gt;recover&lt;/code&gt; to change the capability returned by a constructor in some instances.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a: Foo val = recover Foo.create() end // Ok - ref to val
let b: Foo ref = recover Foo.create_as_val() end // Not Ok - val to ref
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As can be seen, converting &lt;code&gt;val&lt;/code&gt; to &lt;code&gt;ref&lt;/code&gt; using &lt;code&gt;recover&lt;/code&gt; is problematic as shown in previous examples.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Reference capabilities are complex for people new to Pony. An intuitive grasp can be gained without needing to memorize tables of conversions. This intuitive understanding requires thinking about how objects are being used and whether such use might cause data races or prevent sharing across actors. Based on that understanding you pick the capabilities to match what you want to use. For those times that errors don&#39;t match your understanding use the viewpoint adaption and capability subtyping tables to work out where things are going wrong. Over time your intuitive understanding improves for these additional edge cases.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Borrowing in Pony</title>
   <link href="http://bluishcoder.co.nz/2016/07/18/borrowing-in-pony.html"/>
   <updated>2016-07-18T23:00:00+12:00</updated>
   <id>http://bluishcoder.co.nz/2016/07/18/borrowing-in-pony</id>
   <content type="html">&lt;p&gt;The &#39;TL;DR&#39; of this post on how to borrow internal fields of &lt;code&gt;iso&lt;/code&gt; objects in Pony is:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;To borrow fields internal to an &lt;code&gt;iso&lt;/code&gt; object, &lt;code&gt;recover&lt;/code&gt; the object to a &lt;code&gt;ref&lt;/code&gt; (or other valid capability) perform the operations using the field, then consume the object back to an &lt;code&gt;iso&lt;/code&gt;.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;Read on to find out why.&lt;/p&gt;

&lt;p&gt;In this post I use the term borrowing to describe the process of taking a pointer or reference internal to some object, using it, then returning it. An example from C would be something like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;void* new_foo();
void* get_bar(foo* f);
void  delete_foo(foo* f);

...
void* f = new_foo();
void* b = get_bar(f);
...
delete_foo(f);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here a new &lt;code&gt;foo&lt;/code&gt; is created and a pointer to a &lt;code&gt;bar&lt;/code&gt; object returned from it. This pointer is to data internal to &lt;code&gt;foo&lt;/code&gt;. It&#39;s important not to use it after &lt;code&gt;foo&lt;/code&gt; is deleted as it will be a dangling pointer. While holding the &lt;code&gt;bar&lt;/code&gt; pointer you have an alias to something internal to &lt;code&gt;foo&lt;/code&gt;. This makes it difficult to share &lt;code&gt;foo&lt;/code&gt; with other threads or reason about data races. The &lt;code&gt;foo&lt;/code&gt; object could change the &lt;code&gt;bar&lt;/code&gt; data without the holder of the borrowed pointer to &lt;code&gt;bar&lt;/code&gt; knowing making it a dangling pointer, or invalid data, at any time. I go through a real world case of this in my article on &lt;a href=&quot;http://bluishcoder.co.nz/2010/11/23/more-on-type-safety-using-c-and-ats.html&quot;&gt;using C in the ATS programming language&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://www.ponylang.org/&quot;&gt;Pony&lt;/a&gt; has the concept of a reference to an object where only one pointer to that object exists. It can&#39;t be aliased and nothing else can read or write to that object but the current reference to it. This is the &lt;code&gt;iso&lt;/code&gt; reference capability. Capabilities are &#39;deep&#39; in pony, rather than &#39;shallow&#39;. This means that the reference capability of an alias to an object affects the reference capabilities of fields of that object as seen by that alias. The description of this is in the &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/combining-capabilities.html&quot;&gt;viewpoint adaption&lt;/a&gt; section of the Pony tutorial.&lt;/p&gt;

&lt;p&gt;The following is a Pony equivalent of the previous C example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo
  let bar: Bar ref
...
let f: Foo ref = Foo.create()
let b: Bar ref = f.bar
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The reference capability of &lt;code&gt;f&lt;/code&gt; determines the reference capability of &lt;code&gt;bar&lt;/code&gt; as seen by &lt;code&gt;f&lt;/code&gt;. In this case &lt;code&gt;f&lt;/code&gt; is a &lt;code&gt;ref&lt;/code&gt; (the default of class objects) which according to the &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/combining-capabilities.html&quot;&gt;viewpoint adaption table&lt;/a&gt; means that &lt;code&gt;bar&lt;/code&gt; as seen by &lt;code&gt;f&lt;/code&gt;  is also a &lt;code&gt;ref&lt;/code&gt;. Intuitively this makes sense - a &lt;code&gt;ref&lt;/code&gt; signifies multiple read/write aliases can exist therefore getting a read/write alias to something internal to the object is no issue. A &lt;code&gt;ref&lt;/code&gt; is not sendable so cannot be accessed from multiple threads.&lt;/p&gt;

&lt;p&gt;If &lt;code&gt;f&lt;/code&gt; is an &lt;code&gt;iso&lt;/code&gt; then things change:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo
  let bar: Bar ref
...
let f: Foo iso = recover iso Foo.create() end
let b: Bar tag = f.bar
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now &lt;code&gt;bar&lt;/code&gt; as seen by &lt;code&gt;f&lt;/code&gt; is a &lt;code&gt;tag&lt;/code&gt;. A &lt;code&gt;tag&lt;/code&gt; can be aliased but cannot be used to read/write to it. Only object identity and calling behaviours is allowed. Again this is intuitive. If we have a non-aliasable reference to an object (&lt;code&gt;f&lt;/code&gt; being &lt;code&gt;iso&lt;/code&gt; here) then we can&#39;t alias internally to the object either. Doing so would mean that the object could be changed on one thread and the internals modified on another giving a data race.&lt;/p&gt;

&lt;p&gt;The viewpoint adaption table shows that given an iso &lt;code&gt;f&lt;/code&gt; it&#39;s very difficult to get a &lt;code&gt;bar&lt;/code&gt; that you can write to. The following read only access to &lt;code&gt;bar&lt;/code&gt; is ok:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo
  let bar: Bar val
...
let f: Foo iso = recover iso Foo.create() end
let b: Bar val = f.bar
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here &lt;code&gt;bar&lt;/code&gt; is a val. This allows multiple aliases, sendable across threads, but only read access is provided. Nothing can write to it. According to viewpoint adaption, &lt;code&gt;bar&lt;/code&gt; as seen by &lt;code&gt;f&lt;/code&gt; is a &lt;code&gt;val&lt;/code&gt;. It makes sense that given a non-aliasable reference to an object, anything within that object that is immutable is safe to borrow since it cannot be changed. What if &lt;code&gt;bar&lt;/code&gt; is itself an &lt;code&gt;iso&lt;/code&gt;?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo
  let bar: Bar iso = recover iso Bar end
...
let f: Foo iso = recover iso Foo.create() end
let b: Bar iso = f.bar
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This won&#39;t compile. Viewpoint adaption shows that &lt;code&gt;bar&lt;/code&gt; as seen by &lt;code&gt;f&lt;/code&gt; is an &lt;code&gt;iso&lt;/code&gt;. The assignment to &lt;code&gt;b&lt;/code&gt; doesn&#39;t typecheck because it&#39;s aliasing an &lt;code&gt;iso&lt;/code&gt; and &lt;code&gt;iso&lt;/code&gt; reference capabilities don&#39;t allow aliasing. The usual solution when a field isn&#39;t involved is to &lt;code&gt;consume&lt;/code&gt; the original but it won&#39;t work here. The contents of an objects field can&#39;t be consumed because it would then be left in an undefined state. A &lt;code&gt;Foo&lt;/code&gt; object that doesn&#39;t have a valid &lt;code&gt;bar&lt;/code&gt; is not really a &lt;code&gt;Foo&lt;/code&gt;. To get access to &lt;code&gt;bar&lt;/code&gt; externally from &lt;code&gt;Foo&lt;/code&gt; the &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/consume-and-destructive-read.html&quot;&gt;destructive read&lt;/a&gt; syntax is required:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo
  var bar: Bar iso = recover iso Bar end
...
let f: Foo iso = recover iso Foo.create() end
let b: Bar iso = f.bar = recover iso Bar end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This results in &lt;code&gt;f.bar&lt;/code&gt; being set to a new instance of &lt;code&gt;Bar&lt;/code&gt; so it&#39;s never in an undefined state. The old value of &lt;code&gt;f.bar&lt;/code&gt; is then assigned to &lt;code&gt;b&lt;/code&gt;. This is safe as there are no aliases to it anymore due to the first part of the assignment being done first.&lt;/p&gt;

&lt;p&gt;What if the internal field is a &lt;code&gt;ref&lt;/code&gt; and we really want to access it as a &lt;code&gt;ref&lt;/code&gt;? This is possible using &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/recovering-capabilities.html&quot;&gt;recover&lt;/a&gt;. As described in the tutorial, one of the uses for recover is:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;&quot;Extract&quot; a mutable field from an iso and return it as an iso.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;This looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo
  let bar: Bar ref
... 
let f: Foo iso = recover iso Foo end
let f&#39; = recover iso
           let f&#39;&#39;: Foo ref = consume f
           let b: Bar ref = f&#39;&#39;.bar
           consume f&#39;&#39;
         end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Inside the &lt;code&gt;recover&lt;/code&gt; block &lt;code&gt;f&lt;/code&gt; is consumed and returned as a &lt;code&gt;ref&lt;/code&gt;. The &lt;code&gt;f&lt;/code&gt; alias to the object no longer exists at this point and we have the same object but as a &lt;code&gt;ref&lt;/code&gt; capability in &lt;code&gt;f&#39;&#39;&lt;/code&gt;. &lt;code&gt;bar&lt;/code&gt; as seen by &lt;code&gt;f&#39;&#39;&lt;/code&gt; is a &lt;code&gt;ref&lt;/code&gt; according to viewpoint adaption and can now be used within the recover block as a &lt;code&gt;ref&lt;/code&gt;. When the recover block ends the &lt;code&gt;f&#39;&#39;&lt;/code&gt; alias is consumed and returned out of the block as an &lt;code&gt;iso&lt;/code&gt; again in &lt;code&gt;f&#39;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This works because inside the recover block only sendable values from the enclosing scope can be accessed (ie. &lt;code&gt;val&lt;/code&gt;, &lt;code&gt;iso&lt;/code&gt;, or &lt;code&gt;tag&lt;/code&gt;). When exiting the block all aliases except for the object being returned are destroyed. There can be many aliases to &lt;code&gt;bar&lt;/code&gt; within the block but none of them can leak out. Multiple aliases to &lt;code&gt;f&#39;&lt;/code&gt; can be created also and they are not going to leaked either. At the end of the block only one can be returned and by consuming it the compiler knows that there are no more aliases to it so it is safe to make it an &lt;code&gt;iso&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To show how the &lt;code&gt;ref&lt;/code&gt; aliases created within the recover block can&#39;t escape, here&#39;s an example of an erroneous attempt to assign the &lt;code&gt;f&#39;&lt;/code&gt; alias to an object in the outer scope:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Baz
  var a: (Foo ref | None) = None
  var b: (Foo ref | None) = None

  fun ref set(x: Foo ref) =&amp;gt;
    a = x
    b = x

class Bar

class Foo
  let bar: Bar ref = Bar

var baz: Baz iso = recover iso Baz end
var f: Foo iso = recover iso Foo end
f = recover iso
      let f&#39;: Foo ref = consume f
      baz.set(f&#39;)
      let b: Bar ref = f&#39;.bar
      consume f&#39;
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If this were to compile then &lt;code&gt;baz&lt;/code&gt; would contain two references to the &lt;code&gt;f&#39;&lt;/code&gt; object which is then consumed as an &lt;code&gt;iso&lt;/code&gt;. &lt;code&gt;f&lt;/code&gt; would contain what it thinks is non-aliasable reference but &lt;code&gt;baz&lt;/code&gt; would actually hold two additional references to it. This fails to compile at this line:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;main.pony:20:18: receiver type is not a subtype of target type
          baz.set(f&#39;)
                 ^
Info:
main.pony:20:11: receiver type: Baz iso!
              baz.set(f&#39;)
              ^
main.pony:5:3: target type: Baz ref
      fun ref set(x: Foo ref) =&amp;gt;
      ^
main.pony:20:18: this would be possible if the arguments and return value were all sendable
              baz.set(f&#39;)
                     ^
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;baz&lt;/code&gt; is an &lt;code&gt;iso&lt;/code&gt; so is allowed to be accessed from within the recover block. But the &lt;code&gt;set&lt;/code&gt; method on it expects a &lt;code&gt;ref&lt;/code&gt; receiver. This doesn&#39;t work because the receiver of a method of an object is also an implicit argument to that method and therefore needs to be aliased. In this way it&#39;s not possible to store data created within the recover block in something passed into the recover block externally. No aliases can be leaked and the compiler can track things easily.&lt;/p&gt;

&lt;p&gt;There is something called &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/recovering-capabilities.html&quot;&gt;automatic receiver recovery&lt;/a&gt; that is alluded to in the error message (&quot;this would be possible...&quot;) which states that if the arguments were sendable then it is possible for the compiler to work out that it&#39;s ok to call a &lt;code&gt;ref&lt;/code&gt; method on an &lt;code&gt;iso&lt;/code&gt; object. Our &lt;code&gt;ref&lt;/code&gt; arguments are not sendable which is why this doesn&#39;t kick in.&lt;/p&gt;

&lt;p&gt;A real world example of where all this comes up is using the Pony &lt;code&gt;net/http&lt;/code&gt; package. A user on IRC posted the following code snippet:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;use &quot;net/http&quot;
class MyRequestHandler is RequestHandler

  let env: Env

  new val create(env&#39;: Env) =&amp;gt;
    env = env&#39;

  fun val apply(request: Payload iso): Any =&amp;gt;
    for (k, v) in request.headers().pairs() do
      env.out.print(k)
      env.out.print(v)
    end

    let r = Payload.response(200)
    r.add_chunk(&quot;Woot&quot;)
    (consume request).respond(consume r)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The code attempts to iterate over the HTTP request headers and print them out. It fails in the &lt;code&gt;request.headers().pairs()&lt;/code&gt; call, complaining that &lt;code&gt;tag is not a subtype of box&lt;/code&gt; in the result of &lt;code&gt;headers()&lt;/code&gt; when calling &lt;code&gt;pairs()&lt;/code&gt;. Looking at the &lt;code&gt;Payload&lt;/code&gt; class definition shows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class iso Payload
  let _headers: Map[String, String] = _headers.create()

  fun headers(): this-&amp;gt;Map[String, String] =&amp;gt;
    _headers
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the example code &lt;code&gt;request&lt;/code&gt; is an &lt;code&gt;iso&lt;/code&gt; and the &lt;code&gt;headers&lt;/code&gt; function is a &lt;code&gt;box&lt;/code&gt; (the default for &lt;code&gt;fun&lt;/code&gt;). The return value of &lt;code&gt;headers&lt;/code&gt; uses &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/arrow-types.html&quot;&gt;an arrow type&lt;/a&gt;. It reads as &quot;return a &lt;code&gt;Map[String, String]&lt;/code&gt; with the reference capability of &lt;code&gt;_headers&lt;/code&gt; as seen by &lt;code&gt;this&lt;/code&gt;&quot;. In this example &lt;code&gt;this&lt;/code&gt; is the &lt;code&gt;request&lt;/code&gt; object which is &lt;code&gt;iso&lt;/code&gt;. &lt;code&gt;_headers&lt;/code&gt; is a &lt;code&gt;ref&lt;/code&gt; according to the class definition. So it&#39;s returning a &lt;code&gt;ref&lt;/code&gt; as seen by an &lt;code&gt;iso&lt;/code&gt; which according to viewpoint adaption is a &lt;code&gt;tag&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This makes sense as we&#39;re getting a reference to the internal field of an &lt;code&gt;iso&lt;/code&gt; object. As explained previously this must be a &lt;code&gt;tag&lt;/code&gt; to prevent data races. This means that &lt;code&gt;pairs()&lt;/code&gt; can&#39;t be called on the result as &lt;code&gt;tag&lt;/code&gt; doesn&#39;t allow function calls. &lt;code&gt;pairs()&lt;/code&gt; is a &lt;code&gt;box&lt;/code&gt; method which is why the error message refers to &lt;code&gt;tag&lt;/code&gt; not being a subtype of &lt;code&gt;box&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To borrow the &lt;code&gt;headers&lt;/code&gt; correctly we can use the approach done earlier of using a recover block:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun val apply(request: Payload iso): Any =&amp;gt;
  let request&#39;&#39; = recover iso
    let request&#39;: Payload ref = consume request
    for (k, v) in request&#39;.headers().pairs() do
      env.out.print(k)
      env.out.print(v)
    end
    consume request&#39;
  end
  let r = Payload.response(200)
  r.add_chunk(&quot;Woot&quot;)
  (consume request&#39;&#39;).respond(consume r)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In short, to borrow fields internal to an &lt;code&gt;iso&lt;/code&gt; object, &lt;code&gt;recover&lt;/code&gt; the object to a &lt;code&gt;ref&lt;/code&gt; (or other valid capability) perform the operations using the field, then consume the object back to an &lt;code&gt;iso&lt;/code&gt;.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Exploring actors in Pony</title>
   <link href="http://bluishcoder.co.nz/2016/05/11/exploring-actors-in-pony.html"/>
   <updated>2016-05-11T18:00:00+12:00</updated>
   <id>http://bluishcoder.co.nz/2016/05/11/exploring-actors-in-pony</id>
   <content type="html">&lt;p&gt;&lt;a href=&quot;http://ponylang.org&quot;&gt;Pony&lt;/a&gt; is an actor oriented programming language. In Pony Actors are objects that can send and receive messages asychronously while processing their received messages sequentially and in parallel with other actors processing their messages. They are the unit of concurrency in the language. Each actor is similar to a lightweight thread of execution in languages that support those.&lt;/p&gt;

&lt;p&gt;For background on the Actor model of computation there are a lot of papers at the &lt;a href=&quot;http://erights.org/history/actors.html&quot;&gt;erights.org actor page&lt;/a&gt;. They make good background reading. In this post I&#39;m going to go through some things I&#39;ve learnt while learning Pony and using actors in some small projects.&lt;/p&gt;

&lt;p&gt;An &lt;code&gt;actor&lt;/code&gt; is defined very similar to a &lt;code&gt;class&lt;/code&gt;. The following class definition creates a counter that can be incremented and decremented:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Counter
  var count: U32

  new create(start: U32) =&amp;gt;
    count = 0

  fun ref inc() =&amp;gt;
    count = count + 1

  fun ref dec() =&amp;gt;
    count = count - 1

  fun get(): U32 =&amp;gt;
    count

actor Main
  new create(env: Env) =&amp;gt;
    let c1 = Counter(0)
    c1.inc()
    c1.inc()
    env.out.print(c1.get().string())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The first thing to note here is the actor called &lt;code&gt;Main&lt;/code&gt;. Every Pony program has an actor called &lt;code&gt;Main&lt;/code&gt; that is the entry point for the program. This actor is instantiated by the Pony runtime and the constructor is expected to perform the program operations in a similar manner to how the &lt;code&gt;main&lt;/code&gt; functions works in the &lt;code&gt;C&lt;/code&gt; programming language.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Counter&lt;/code&gt; class is created in the constructor of &lt;code&gt;Main&lt;/code&gt; and incremented a couple of times. All this happens in a single thread of control. Because it operates within a single thread there is no concurrent access to the state held by the counter. This makes it safe to call the &lt;code&gt;inc&lt;/code&gt;, &lt;code&gt;dec&lt;/code&gt; and &lt;code&gt;get&lt;/code&gt; methods. The order of operations is well defined. We can only pass the counter instance to another thread if we give up any aliases to it so we can ensure that it can be safely used elsewhere or if we make it immutable so that nothing can change it at any time.&lt;/p&gt;

&lt;h2&gt;Behaviours&lt;/h2&gt;

&lt;p&gt;If we want to use a &lt;code&gt;Counter&lt;/code&gt; from multiple threads but still allow modification then making it an actor is an option. This can be done by changing the &lt;code&gt;class&lt;/code&gt; keyword to &lt;code&gt;actor&lt;/code&gt; and the methods to behaviours:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Counter
  var count: U32

  new create(start: U32) =&amp;gt;
    count = 0

  be inc() =&amp;gt;
    count = count + 1

  be dec() =&amp;gt;
    count = count - 1

  be display(out:OutStream) =&amp;gt;
    out.print(count.string())

actor Main
  new create(env: Env) =&amp;gt;
    let c1 = Counter(0)
    c1.inc()
    c1.inc()
    c1.display(env.out)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A behaviour is introduced with the &lt;code&gt;be&lt;/code&gt; keyword. It is like a function except that it is asynchronous. When a behaviour is called it is not executed immediately.&lt;/p&gt;

&lt;p&gt;Internally each actor has a queue for holding messages. Each behaviour call on an actor puts a message in that queue to run that behaviour at some future point in time. The actor runs a message loop that pops a message off the queue and runs the associated behaviour. When the behaviour completes executing then it will run the next one in the queue for that actor. If there are none left to run the the actor is idle until a behaviour is called. During this idle period it can perform garbage collection. The Pony runtime has a scheduler that uses operating system threads to execute actor behaviours. In this way multiple behaviours for different actors can be running on many OS threads at the same time.&lt;/p&gt;

&lt;p&gt;The behaviours that are queued for an individual actor are executed sequentially. Two behaviours for the same actor will never run concurrently. This means that within a behaviour the actor has exclusive access to its internal state. There is no need for locks or guards to control access. For this reason it helps to think of actors as a unit of sequentiality rather than of a parallelism. See the &lt;a href=&quot;http://tutorial.ponylang.org/types/actors.html&quot;&gt;actors section of the tutorial&lt;/a&gt; for more on this.&lt;/p&gt;

&lt;p&gt;The main change with the conversion of the counter class is there is no longer a &lt;code&gt;get&lt;/code&gt; method. It&#39;s replaced by a &lt;code&gt;display&lt;/code&gt; behaviour that outputs the string. &lt;code&gt;get&lt;/code&gt; was removed because behaviours are executed asynchronously so they cannot return the result of the function - they&#39;ve returned to the caller before the body of the behaviour is executed. They always return the object the behaviour was called on. This makes chaining behaviour calls possible:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    let c1 = Counter(0)
    c1.inc()
      .inc()
      .display(env.out)
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;tag reference capability&lt;/h2&gt;

&lt;p&gt;A &lt;code&gt;class&lt;/code&gt; defaults to a reference capability of &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/reference-capabilities.html&quot;&gt;ref&lt;/a&gt;. An &lt;code&gt;actor&lt;/code&gt; defaults to &lt;code&gt;tag&lt;/code&gt;. A &lt;code&gt;tag&lt;/code&gt; only allows object identification. No read or write operations are allowed but you can alias &lt;code&gt;tag&lt;/code&gt; objects and you can pass them to other actors. This is safe since the holder of a &lt;code&gt;tag&lt;/code&gt; alias can&#39;t view or modify the state. It can call behaviours on it though. This is safe because behaviours are queued for sequential processing at a future point in time - access to the state of the actor is serialized through behaviours.&lt;/p&gt;

&lt;h2&gt;Simulating return values&lt;/h2&gt;

&lt;p&gt;How do you deal with returning values from behaviours if they don&#39;t support return values? One approach is to pass an object to the behaviour that it uses as a callback with the result. For the counter example this could look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Counter
  ...as before...

  be get(cb: {(U32)} iso) =&amp;gt;
    cb(count)

actor Main
  new create(env: Env) =&amp;gt;
    let c1 = Counter(0)
    c1.inc()
      .inc()
      .get(recover lambda (x:U32)(env) =&amp;gt; env.out.print(x.string()) end end)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here the &lt;code&gt;get&lt;/code&gt; behaviour receives a &lt;a href=&quot;http://bluishcoder.co.nz/2016/03/15/closures-in-pony.html&quot;&gt;closure&lt;/a&gt; as an argument. This is called passing a closure that prints the value out. When &lt;code&gt;get&lt;/code&gt; is executed asynchronously it&#39;s safe for it to pass the &lt;code&gt;count&lt;/code&gt; value to the closure. The closure can&#39;t modify it. The closure itself is an &lt;code&gt;iso&lt;/code&gt; reference capability so nothing else but the behaviour is accessing it.&lt;/p&gt;

&lt;p&gt;This approach leads to a very &#39;callback&#39; style of programming. It can feel like programming in &lt;a href=&quot;https://en.wikipedia.org/wiki/Continuation-passing_style&quot;&gt;continuation passing style&lt;/a&gt; at times. It requires careful design when dealing with error handling. Pony includes a &lt;code&gt;promises&lt;/code&gt; library to help manage this.&lt;/p&gt;

&lt;h3&gt;Promises&lt;/h3&gt;

&lt;p&gt;The promises library provides the ability to pass callbacks, handle errors and chain promises together to make it easier to manage callback style programming. The counter example converted to use promises looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;use &quot;promises&quot;

actor Counter
  ...as before...

  be get(p: Promise[U32]) =&amp;gt;
    p(count) 

actor Main
  new create(env: Env) =&amp;gt;
    let c1 = Counter(0)
    let p = Promise[U32]
    c1.inc()
      .inc()
      .get(p)
    p.next[None](recover lambda ref(x:U32)(env) =&amp;gt; env.out.print(x.string()) end end)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;get&lt;/code&gt; method has been changed to take a &lt;code&gt;Promise[U32]&lt;/code&gt;. The &lt;code&gt;Promise&lt;/code&gt; type is a generic type and here it is indexed over the &lt;code&gt;U32&lt;/code&gt; value that it will be provided with. In the &lt;code&gt;Main&lt;/code&gt; actor a promise is created and passed to &lt;code&gt;get&lt;/code&gt;. Then the &lt;code&gt;next&lt;/code&gt; method is called on the promise to tell it what to do when a value is provided to it. In this case it&#39;s the same closure as in the previous example so there&#39;s not much of a win here.&lt;/p&gt;

&lt;p&gt;What promises do provide though is a way to handle failure. A callback used in the promise can &lt;a href=&quot;http://tutorial.ponylang.org/expressions/exceptions.html&quot;&gt;raise an error&lt;/a&gt; and the promise will try the next operation in the chain. Chained promises can manipulate values as they&#39;re passed down the chain to form a pipeline of operations.&lt;/p&gt;

&lt;p&gt;The boilerplate to create the promise and pass it to the behaviour can be hidden by a method on the actor:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Counter
  ...as before...

  be myget(p: Promise[U32]) =&amp;gt;
    p(count)

  fun tag get(): Promise[U32] =&amp;gt;
    let p = Promise[U32]
    myget(p)
    p

actor Main
  new create(env: Env) =&amp;gt;
    let c1 = Counter(0)
    c1.inc()
      .inc()
      .get().next[None](recover lambda ref(x:U32)(env) =&amp;gt; env.out.print(x.string()) end end)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this example the &lt;code&gt;get&lt;/code&gt; method creates the promise and passes it to the behaviour then returns the promise. The caller can then use method chaining to call &lt;code&gt;next&lt;/code&gt; on the promise to perform the action.&lt;/p&gt;

&lt;p&gt;Notice that the &lt;code&gt;get&lt;/code&gt; method has a &lt;code&gt;tag&lt;/code&gt; reference capability. This is required to allow other actors to call it. A reference to an actor has the &lt;code&gt;tag&lt;/code&gt; capability so only behaviours and &lt;code&gt;tag&lt;/code&gt; methods can be called with it. A &lt;code&gt;tag&lt;/code&gt; method can&#39;t modify internal state - all it can do is call behaviours on the actor - so this is safe to be called externally. It would be a compile error if the method attempted to view or modify actor state.&lt;/p&gt;

&lt;p&gt;The following demonstrates promise chaining:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Counter
  ...as before...

  fun tag get_string(): Promise[String] =&amp;gt;
    get().next[String](object iso
                         fun ref apply(x:U32): String =&amp;gt; x.string()
                       end)

actor Main
  new create(env: Env) =&amp;gt;
    let c1 = Counter(0)
    c1.inc()
      .inc()
      .get_string().next[Main](recover this~print(env.out) end)

  be print(out:OutStream, s: String) =&amp;gt;
    out.print(s)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this case we want a &lt;code&gt;String&lt;/code&gt; from the behaviour call. The &lt;code&gt;get_string&lt;/code&gt; method on &lt;code&gt;Counter&lt;/code&gt; calls &lt;code&gt;get&lt;/code&gt; and chains the &lt;code&gt;next&lt;/code&gt; callback to be one that returns a result of type `String. It just does a conversion by calling  the string method. I use an object literal here instead of a closure for clarity.&lt;/p&gt;

&lt;p&gt;The caller in &lt;code&gt;Main&lt;/code&gt; calls &lt;code&gt;get_string&lt;/code&gt; and chains the returned promise with another callback. This callback uses &lt;a href=&quot;http://tutorial.ponylang.org/expressions/partial-application.htmlhttp://tutorial.ponylang.org/expressions/partial-application.html&quot;&gt;partial application&lt;/a&gt; to call the &lt;code&gt;print&lt;/code&gt; behaviour on &lt;code&gt;Main&lt;/code&gt; to print the string. The &lt;code&gt;next&lt;/code&gt; call uses &lt;code&gt;Main&lt;/code&gt; to parameterize the promise result as calling the &lt;code&gt;print&lt;/code&gt; behaviour returns the receiver - in this case &lt;code&gt;Main&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The result of this is that when the &lt;code&gt;get&lt;/code&gt; behaviour is executed it calls the first promise in the chain to return the result. That converts the &lt;code&gt;U32&lt;/code&gt; to a &lt;code&gt;String&lt;/code&gt;. The next promise in the chain is then called which calls &lt;code&gt;print&lt;/code&gt; on the &lt;code&gt;Main&lt;/code&gt; actor. That behaviour gets queued and eventually run to output the result.&lt;/p&gt;

&lt;p&gt;Which is best to use, promises or callbacks? It depends on what the objects are doing. For single return values with an error case then promises are a good approach. For objects that need to callback multiple times then a callback or notifier object may be a better choice. For an example of the latter, see the &lt;code&gt;net&lt;/code&gt; packages use of various notifier classes like &lt;code&gt;TCPConnectionNotify&lt;/code&gt; to provide notification of different states in the TCP connection lifetime:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;interface TCPConnectionNotify
  fun ref accepted(conn: TCPConnection ref)
  fun ref connecting(conn: TCPConnection ref, count: U32)
  fun ref connected(conn: TCPConnection ref)
  fun ref connect_failed(conn: TCPConnection ref)
  fun ref auth_failed(conn: TCPConnection ref)
  fun ref sent(conn: TCPConnection ref, data: ByteSeq): ByteSeq ?
  fun ref sentv(conn: TCPConnection ref, data: ByteSeqIter): ByteSeqIter ?
  fun ref received(conn: TCPConnection ref, data: Array[U8] iso)
  fun ref expect(conn: TCPConnection ref, qty: USize): USize
  fun ref closed(conn: TCPConnection ref)
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Sendable objects&lt;/h2&gt;

&lt;p&gt;As behaviours are sent asycnhronously this means the arguments to those behaviours must be sharable. The &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/passing-and-sharing.html&quot;&gt;passing and sharing&lt;/a&gt; section of the tutorial makes the distinction between &#39;passing&#39; and &#39;sharing&#39; objects.&lt;/p&gt;

&lt;p&gt;In &#39;passing&#39; an object from one actor to another the originating actor is giving up ownership. It can no longer access the object after giving it to the receiving actor. This is the &lt;code&gt;iso&lt;/code&gt; reference capability. The sending actor must consume it when passing it to the receiver:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  new create(env: Env) =&amp;gt;
    let a = recover iso String end
    let b = Something
    b.doit(consume a)

actor Something
  be doit(s: String iso) =&amp;gt;
    s.append(&quot;Hello World&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In &#39;sharing&#39; an object you want both the originating actor and the receiver (and any others) to be able to read from the object. Nothing should be able to write to it. This is the &lt;code&gt;val&lt;/code&gt; reference capability:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Data
  var count: U32 = 0

  fun ref inc() =&amp;gt;
    count = count + 1

actor Main
  new create(env: Env) =&amp;gt;
    let a: Data trn = recover trn Data end
    a.inc()

    let d: Data val = consume a
    let s1 = Something(env.out)
    let s2 = Something(env.out)
    s1.doit(d)
    s2.doit(d)

actor Something
  let _out: OutStream

  new create(out: OutStream) =&amp;gt;
    _out = out

  be doit(d: Data val) =&amp;gt;
    _out.print(&quot;Got &quot; + d.count.string())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This example has a &lt;code&gt;Data&lt;/code&gt; class with an integer &lt;code&gt;count&lt;/code&gt; field. In the &lt;code&gt;Main&lt;/code&gt; actor we create an instance as a &lt;code&gt;trn&lt;/code&gt; reference capability. This is used for objects that you want to write to initially but give out immutable access to later. While we hold the mutable &lt;code&gt;trn&lt;/code&gt; reference we increment it and then consume it to get an immutable &lt;code&gt;val&lt;/code&gt; reference capability for it. The old &lt;code&gt;a&lt;/code&gt; alias is no longer usable at this point - no writeable aliases to the object exist. Because it is immutable we can now pass it to as many actors as we want and they get read only access to the objects fields and methods.&lt;/p&gt;

&lt;p&gt;Another sharable type is the &lt;code&gt;tag&lt;/code&gt; reference capability. This provides only identity access to an object. A receiver of a &lt;code&gt;tag&lt;/code&gt; object can&#39;t read or write fields but it can call behaviours. It is the reference capability used for actors and is what you use to pass actors around. The previous sharing example uses this to pass the &lt;code&gt;env.out&lt;/code&gt; object around. The &lt;code&gt;OutStream&lt;/code&gt; is an actor.&lt;/p&gt;

&lt;p&gt;It&#39;s important to keep in mind that creating aliases of objects doesn&#39;t copy the object. It&#39;s a new variable pointing to the same object. There is no copy operation involved in passing the &lt;code&gt;Data val&lt;/code&gt; objects around. Although the capability is called &#39;val&#39; it is not a &#39;&lt;a href=&quot;https://en.wikipedia.org/wiki/Value_object&quot;&gt;value object&lt;/a&gt;&#39;. The two &lt;code&gt;Something&lt;/code&gt; actors have the same &lt;code&gt;Data&lt;/code&gt; object in terms of object identity. The &lt;code&gt;val&lt;/code&gt; only means &#39;immutable&#39;.&lt;/p&gt;

&lt;p&gt;The reference capabilities and the checking by the type system is what allows avoiding copies to be safe in the presence of multiple actors. This does mean that if you have a &lt;code&gt;ref&lt;/code&gt; object you can&#39;t pass it to an actor. This is a compile error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Something
  be doit(s: String ref) =&amp;gt;
  None
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Only &lt;code&gt;val&lt;/code&gt;, &lt;code&gt;iso&lt;/code&gt; and &lt;code&gt;tag&lt;/code&gt; can be used as an argument to a behaviour. This will also fail to compile:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  new create(env: Env) =&amp;gt;
    let a = recover ref String end
    a.append(&quot;Hello World&quot;)
    let b = Something
    b.doit(a)

actor Something
  be doit(s: String val) =&amp;gt;
    None
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we have a &lt;code&gt;String ref&lt;/code&gt; and are trying to pass it to a behaviour expecting a &lt;code&gt;String val&lt;/code&gt;. It is not possible to convert a &lt;code&gt;ref&lt;/code&gt; to a &lt;code&gt;val&lt;/code&gt;. A &lt;code&gt;ref&lt;/code&gt; provides read and write access to the object. Multiple aliases to the same &lt;code&gt;ref&lt;/code&gt; object can exist within a single actor. This is safe because behaviour execution within an actor is sequential. All of these aliases would need to be consumed to safely get a &lt;code&gt;val&lt;/code&gt; alias. The type system doesn&#39;t (and probably couldn&#39;t) prove that all aliases are consumed at the time of converting to a &lt;code&gt;val&lt;/code&gt; so it is not possible to do the conversion.&lt;/p&gt;

&lt;p&gt;This is a case where a copy is needed:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  new create(env: Env) =&amp;gt;
    let a = recover ref String end
    a.append(&quot;Hello World&quot;)
    let b = Something
    b.doit(a.clone())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;clone&lt;/code&gt; method on &lt;code&gt;String&lt;/code&gt; returns a &lt;code&gt;String iso^&lt;/code&gt; which is convertable automatically to a &lt;code&gt;String val&lt;/code&gt; by virtue of the fact that it has no aliases (The &lt;code&gt;^&lt;/code&gt; part of the type). See &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/capability-subtyping.html&quot;&gt;capability subtyping&lt;/a&gt; for details&lt;/p&gt;

&lt;p&gt;Cloning creates a copy distinct from the original. They have different identities and is a less efficient operation so it&#39;s worthwhile examining the data being passed around and seeing if it&#39;s possible to avoid holding multiple references to data and use the strictest reference capability to avoid aliasing.&lt;/p&gt;

&lt;h2&gt;Blocking operations&lt;/h2&gt;

&lt;p&gt;Pony has no blocking operations (outside of using the C FFI). In languages like &lt;a href=&quot;http://www.erlang.org/&quot;&gt;Erlang&lt;/a&gt; it&#39;s common to do a blocking receive within a function to wait for a message and operate on it. In Pony this is implicitly done by actors in their event loop, hidden from the programmer. A behaviour call queues the message and it is executed when it&#39;s popped off the queue. You can&#39;t block for a message within the body of a behaviour itself.&lt;/p&gt;

&lt;p&gt;This results in having to change the programming mode from &quot;wait for data and do something&quot; to &quot;notify me of data when it&#39;s available&quot;. Instead of blocking for N seconds within a behaviour you &lt;a href=&quot;http://patterns.ponylang.org/async/waiting.html&quot;&gt;create a timer to notify the actor&lt;/a&gt; of something &#39;N&#39; seconds later.&lt;/p&gt;

&lt;p&gt;The Pony standard library is structured in this way to use notifier objects, callbacks and promises to make programming in this style easier.&lt;/p&gt;

&lt;h2&gt;Causal Messaging&lt;/h2&gt;

&lt;p&gt;Data races can be difficult to avoid in the presence of asynchronous executation of threads. Pony has a message ordering guarantee to make the following type of code safe:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Counter
  let _out: OutStream
  var count: U32 = 0

  new create(out: OutStream) =&amp;gt;
    _out = out

  be inc() =&amp;gt;
    count = count + 1

  be dec() =&amp;gt;
    count = count - 1
    if count == 0 then _out.print(&quot;counter is destoyed&quot;) end

actor Something
  be doit(counter: Counter) =&amp;gt;
    counter.dec()

actor Main
  new create(env: Env) =&amp;gt;
    let c1 = Counter(env.out)
    let c2 = Something
    c1.inc()
    c2.doit(c1)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this example the &lt;code&gt;Counter&lt;/code&gt; object does something when the count is decremented to zero. In the &lt;code&gt;Main&lt;/code&gt; actor a counter is created, incremented and passed to another actor where it is decremented. The &lt;code&gt;inc&lt;/code&gt; and &lt;code&gt;doit&lt;/code&gt; calls are on different actors and therefore are executed asynchronously. It&#39;s important that the &lt;code&gt;inc&lt;/code&gt; call executes before the &lt;code&gt;dec&lt;/code&gt; call in the &lt;code&gt;doit&lt;/code&gt; behaviour of the other actor.&lt;/p&gt;

&lt;p&gt;Pony has a message ordering guarantee, called &#39;causal messaging&#39;, to ensure this ordering happens. This is described in a &lt;a href=&quot;https://news.ycombinator.com/item?id=9483333&quot;&gt;forum thread discussion&lt;/a&gt; as:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;[...] Pony makes a messaging order guarantee that&#39;s much stronger than is typical for the actor model. It guarantees causal messaging. That is, any message that is a &quot;cause&quot; of another message (i.e. was sent or received by an actor prior to the message in question) is guaranteed to arrive before the &quot;effect&quot; if they have the same destination.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;For more information the paper &lt;a href=&quot;https://github.com/ponylang/ponylang.github.io/blob/master/papers/opsla237-clebsch.pdf&quot;&gt;Fully Concurrent Garbage Collection of Actors on Many-Core Machines&lt;/a&gt; goes into detail about how it works.&lt;/p&gt;

&lt;h2&gt;Garbage Collection&lt;/h2&gt;

&lt;p&gt;Actor&#39;s have their own garbage collection heap. Garbage collection occurs between behaviour calls on the actor. This allows GC to occur for an actor without interrupting execution of other actors. The runtime detects when it is no longer possible for an actor to receive messages and will garbage collect the actor itself. This can avoid the need to implement a &#39;poison pill&#39; protocol whereby the actor receives a message to say it can terminate.&lt;/p&gt;

&lt;p&gt;Even with this automatic actor garbage detection in place there are times when it is necessary to implement a shutdown protocol. An actor may be receiving notification callbacks - the actor sending the callbacks needs to be told to stop sending the messages so the system can detect that the receiver can be garbage collected. In my &lt;a href=&quot;https://github.com/doublec/imap-idler/blob/master/idle/main.pony&quot;&gt;IMAP Idle monitor&lt;/a&gt; I use &lt;a href=&quot;https://github.com/doublec/imap-idler/blob/9dc7b1e2fce8e6d3551952f141d4d5e71593e9c8/idle/main.pony#L165&quot;&gt;dispose methods&lt;/a&gt; to cancel timers or &lt;a href=&quot;https://github.com/doublec/imap-idler/blob/9dc7b1e2fce8e6d3551952f141d4d5e71593e9c8/idle/main.pony#L319&quot;&gt;close TCP connections&lt;/a&gt;. A Pony library class called a &lt;a href=&quot;https://github.com/doublec/imap-idler/blob/9dc7b1e2fce8e6d3551952f141d4d5e71593e9c8/idle/main.pony#L78&quot;&gt;Custodian&lt;/a&gt; holds a collection of actors to be disposed and calls &lt;code&gt;dispose&lt;/code&gt; on each one when its own &lt;code&gt;dispose&lt;/code&gt; behaviour is called. This results in the runtime detecting that none of the actors in the application can receive messages anymore and the entire application terminates.&lt;/p&gt;

&lt;p&gt;One thing to be careful of with garbage collection only happening between behaviour calls is that a long running behaviour will not GC during its execution. Simple benchmark applications that do everything in the &lt;code&gt;Main&lt;/code&gt; actors constructor exhibit this. They use large amounts of memory due to no GC happening if the benchmark doesn&#39;t call a behaviour on the actor.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Bang, Hat and Arrow in Pony</title>
   <link href="http://bluishcoder.co.nz/2016/05/04/bang-hat-and-arrow-in-pony.html"/>
   <updated>2016-05-04T18:00:00+12:00</updated>
   <id>http://bluishcoder.co.nz/2016/05/04/bang-hat-and-arrow-in-pony</id>
   <content type="html">&lt;p&gt;If you&#39;ve looked at &lt;a href=&quot;http://www.ponylang.org/&quot;&gt;Pony programming language&lt;/a&gt; code you&#39;ve probably seen use of punctuation symbols in places and wondered what they meant. This post is an attempt to explain three of those - the bang, hat and arrow (&lt;code&gt;!&lt;/code&gt;, &lt;code&gt;^&lt;/code&gt; and &lt;code&gt;-&amp;gt;&lt;/code&gt; respectively). Note that this is my understanding based on usage, reading the tutorials and watching videos so there may be errors. I welcome corrections!&lt;/p&gt;

&lt;h2&gt;Bang&lt;/h2&gt;

&lt;p&gt;The bang symbol (otherwise known as an exclamation mark) combined with a type name can be thought of as the type of an &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/aliasing.html&quot;&gt;alias&lt;/a&gt; of the given type. Having an alias of an object means having another reference to that object. So an alias to a &lt;code&gt;String iso&lt;/code&gt; is of type &lt;code&gt;String iso!&lt;/code&gt;. This matters mostly in generic code which will be explained later but it does come up in error messages.&lt;/p&gt;

&lt;p&gt;If you see &lt;code&gt;!&lt;/code&gt; in an error message like &quot;iso! is not a subtype of iso&quot; this means you are probably trying to assign an object that cannot be aliased without first consuming it.&lt;/p&gt;

&lt;p&gt;If you see &lt;code&gt;!&lt;/code&gt; in a type declaration in code like &quot;let foo: A!&quot; then you can read this as &quot;replace A! with a type that can safely hold an alias to A&quot;. If &lt;code&gt;A&lt;/code&gt; is a &lt;code&gt;String iso&lt;/code&gt; then &lt;code&gt;A!&lt;/code&gt; would be a &lt;code&gt;String tag&lt;/code&gt; for example (following the rules for &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/capability-subtyping.html&quot;&gt;aliased substitution&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;Bang in errors&lt;/h3&gt;

&lt;p&gt;The following code demonstrates something that is often encountered by first time Pony users:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Something

actor Main
  new create(env: Env) =&amp;gt;
    let a = recover iso Something end
    Foo(a)

actor Foo
  new create(s: Something iso) =&amp;gt;
    None
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we have a class called &lt;code&gt;Something&lt;/code&gt;. A new instance of it is created in the Main actor with reference capability &lt;code&gt;iso&lt;/code&gt;. A new &lt;code&gt;Foo&lt;/code&gt; actor is created passing this instance to it. This will fail to compile as we are aliasing the &lt;code&gt;Something&lt;/code&gt; object held in &lt;code&gt;a&lt;/code&gt;. &lt;code&gt;a&lt;/code&gt; holds a reference to it and the variable &lt;code&gt;s&lt;/code&gt; holding the argument to the &lt;code&gt;Foo&lt;/code&gt; constructor is holding a reference to it at the same time. Objects with a reference capability of &lt;code&gt;iso&lt;/code&gt; cannot have more than one reference to it. The error from the compiler will look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Error:
e1/main.pony:6:9: argument not a subtype of parameter
    Foo(a)
        ^
    Info:
    e1/main.pony:9:14: parameter type: Something iso
      new create(s: Something iso) =&amp;gt;
                 ^
    e1/main.pony:6:9: argument type: Something iso!
        Foo(a)
            ^
    e1/main.pony:1:1: Something iso! is not a subtype of Something iso: iso! is not a subtype of iso
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This error states that the expected type of the parameter for the &lt;code&gt;Foo&lt;/code&gt; constructor is of type &lt;code&gt;Something iso&lt;/code&gt; but the type that we passed is a &lt;code&gt;Something iso!&lt;/code&gt;. It further explains things by noting that &lt;code&gt;Something iso!&lt;/code&gt; is not a subtype of &lt;code&gt;Something iso&lt;/code&gt; because &lt;code&gt;iso!&lt;/code&gt; is not a subtype of &lt;code&gt;iso&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Armed with the knowledge that the bang symbol means the type for an alias this can be read as the argument passed was an alias to a &lt;code&gt;Something iso&lt;/code&gt;. This is an error as &lt;code&gt;iso&lt;/code&gt; cannot be aliased - this is what &lt;code&gt;iso! is not a subtype of iso&lt;/code&gt; means. The subtyping relationship for aliases is outlined in the &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/capability-subtyping.html&quot;&gt;Capability Subtyping&lt;/a&gt; section of the tutorial.&lt;/p&gt;

&lt;p&gt;The code can be fixed by consuming the &lt;code&gt;a&lt;/code&gt; so it is no longer aliased:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let a = recover iso Something end
Foo(consume a)
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Bang in generics&lt;/h3&gt;

&lt;p&gt;The other place where you&#39;ll see the alias type is in generic code. The following non-generic code compiles fine:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Something
  let a: U8

  new create(x: U8) =&amp;gt;
    a = x

actor Main
  new create(env: Env) =&amp;gt;
    let aint = Something(42)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;U8&lt;/code&gt; defaults to &lt;code&gt;val&lt;/code&gt; reference capability which can be aliased. This allows the assignment to the field &lt;code&gt;a&lt;/code&gt; in &lt;code&gt;Something&lt;/code&gt; which is aliasing the &lt;code&gt;x&lt;/code&gt; object. If we make this a generic so that any type can be used then it fails to compile:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Something[A]
  let a: A

  new create(x: A) =&amp;gt;
    a = x

actor Main
  new create(env: Env) =&amp;gt;
    let aint = Something[U8](42)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The error is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Error:
e3/main.pony:5:7: right side must be a subtype of left side
    a = x
      ^
    Info:
    e3/main.pony:4:17: right side type: A #any !
      new create(x: A) =&amp;gt;
                    ^
    e3/main.pony:5:5: left side type: A #any
        a = x
        ^
    e3/main.pony:4:17: A #any ! is not a subtype of A #any: the subtype has no constraint
      new create(x: A) =&amp;gt;
                ^
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For now, ignore the &lt;code&gt;#any&lt;/code&gt;  in the error message. I&#39;ll expand on this later but it&#39;s informing us that the type &lt;code&gt;A&lt;/code&gt; is unconstrained and can have any reference capability.&lt;/p&gt;

&lt;p&gt;The error states that &lt;code&gt;x&lt;/code&gt; is an &lt;code&gt;A!&lt;/code&gt; but &lt;code&gt;a&lt;/code&gt; is an &lt;code&gt;A&lt;/code&gt; and &lt;code&gt;A!&lt;/code&gt; is not a subtype of &lt;code&gt;A&lt;/code&gt; so the assignment cannot happen.&lt;/p&gt;

&lt;p&gt;This occurs Because &lt;code&gt;A&lt;/code&gt; is unconstrained. It can be any reference capability. Therefore the code must be able to be compiled under the assumption that the most restrictive reference capability can be used. It works fine with &lt;code&gt;val&lt;/code&gt;, which can be aliased, but not with &lt;code&gt;iso&lt;/code&gt; which cannot. Therefore the generic code cannot be compiled. You can see how &lt;code&gt;iso&lt;/code&gt; would fail by expanding a version using &lt;code&gt;String iso&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Something
  let a: String  iso

  new create(x: String iso) =&amp;gt;
    a = x

actor Main
  new create(env: Env) =&amp;gt;
    let aint = Something(recover iso String end)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The error is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Error:
e5/main.pony:5:7: right side must be a subtype of left side
    a = x
      ^
    Info:
    e5/main.pony:4:17: right side type: String iso!
      new create(x: String iso) =&amp;gt;
                    ^
    e5/main.pony:2:10: left side type: String iso
      let a: String  iso
             ^
    e5/main.pony:4:17: String iso! is not a subtype of String iso: iso! is not a subtype of iso
      new create(x: String iso) =&amp;gt;
                    ^
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is the same error that the generic code is giving us. The generic code can be fixed in a few ways. The first is to constrain the type so that it is a specific reference capability that works. Here it is changed to &lt;code&gt;val&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Something[A: Any val]
  let a: A

  new create(x: A) =&amp;gt;
    a = x

actor Main
  new create(env: Env) =&amp;gt;
    let aint = Something[U8](42)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;A: Any val&lt;/code&gt; syntax constrains the type parameter to be a subtype of the type after the &lt;code&gt;:&lt;/code&gt;. In this case, any type with a reference capability of val. This won&#39;t work if you want to be able to use any aliasable type (eg &lt;code&gt;ref&lt;/code&gt; as well as &lt;code&gt;val&lt;/code&gt;):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Something[A: Any val]
  let a: A

  new create(x: A) =&amp;gt;
    a = x

actor Main
  new create(env: Env) =&amp;gt;
    let aint = Something[U8](42)
    let bint = Something[String ref](recover ref String end)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The error here is obvious in that we are trying to pass a &lt;code&gt;ref&lt;/code&gt; parameter to a function expecting a &lt;code&gt;val&lt;/code&gt;. Pony generics solves this by allowing code to be polymorphic over the reference capability. There are specific annotations for classes of reference capabilities. They are:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#read  = { ref, val, box }                = Anything you can read from
#send  = { iso, val, tag }                = Anything you can send to an actor
#share = { val, tag }                     = Anything you can send to more than one actor
#any   = { iso, trn, ref, val, box, tag } = Default of a constraint
#alias = {ref,val, box, tag}              = Set of capabilities that alias as themselves (used by compiler)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A version that will work for &lt;code&gt;ref&lt;/code&gt;, &lt;code&gt;val&lt;/code&gt; and &lt;code&gt;box&lt;/code&gt; becomes:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Something[A: Any #read]
  let a: A

  new create(x: A) =&amp;gt;
    a = x

actor Main
  new create(env: Env) =&amp;gt;
    let aint = Something[U8](42)
    let bint = Something[String ref](recover ref String end)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But what if you want it to work with non-aliasable types like &lt;code&gt;iso&lt;/code&gt;? A solution is to &lt;code&gt;consume&lt;/code&gt; the parameter:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Something[A]
  let a: A

  new create(x: A) =&amp;gt;
    a = consume x

actor Main
  new create(env: Env) =&amp;gt;
    let aint = Something[U8](42)
    let bint = Something[String ref](recover ref String end)
    let cint = Something[String iso](recover iso String end)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Another solution is to declare the field type to be &lt;code&gt;A!&lt;/code&gt; instead of &lt;code&gt;A&lt;/code&gt;. In the &lt;code&gt;String iso&lt;/code&gt; case using &lt;code&gt;A&lt;/code&gt; means &lt;code&gt;String iso&lt;/code&gt; which cannot hold an alias. Using &lt;code&gt;A!&lt;/code&gt; means &lt;code&gt;String iso!&lt;/code&gt; which should be read as &quot;a type that can safely alias a &lt;code&gt;String iso&lt;/code&gt;&quot;. Looking at the &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/capability-subtyping.html&quot;&gt;Aliased substitution&lt;/a&gt; table this is a &lt;code&gt;tag&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Something[A]
  let a: A!

  new create(x: A) =&amp;gt;
    a = x

actor Main
  new create(env: Env) =&amp;gt;
    let aint = Something[U8](42)
    let bint = Something[String ref](recover ref String end)
    let cint = Something[String iso](recover iso String end)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this case we are using &lt;code&gt;!&lt;/code&gt; to tell the compiler to use a reference capability that works for whatever the type of &lt;code&gt;A&lt;/code&gt; is. An &lt;code&gt;iso&lt;/code&gt; becomes a &lt;code&gt;tag&lt;/code&gt;, a &lt;code&gt;trn&lt;/code&gt; becomes a &lt;code&gt;box&lt;/code&gt;, a &lt;code&gt;ref&lt;/code&gt; stays a &lt;code&gt;ref&lt;/code&gt;, etc.&lt;/p&gt;

&lt;h2&gt;Hat&lt;/h2&gt;

&lt;p&gt;The hat symbol (or &lt;code&gt;^&lt;/code&gt;) is an &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/aliasing.html&quot;&gt;ephemeral type&lt;/a&gt;. It&#39;s the type of an object that is not assigned to a variable. &lt;code&gt;consume x&lt;/code&gt; is used to prevent aliasing of &lt;code&gt;x&lt;/code&gt; but at the point of being consumed and before it is assigned to anything else, what type is it? If &lt;code&gt;x&lt;/code&gt; is type &lt;code&gt;A&lt;/code&gt; then the type of &lt;code&gt;consume x&lt;/code&gt; is &lt;code&gt;A^&lt;/code&gt;. Constructors always return an ephemeral type as they create objects and return them but they aren&#39;t yet assigned to anything.&lt;/p&gt;

&lt;p&gt;The following example creates a &lt;code&gt;Box&lt;/code&gt; type that acts like single instance array of &lt;code&gt;String iso&lt;/code&gt; objects. A value can be stored and updated. A utility function &lt;code&gt;Foo.doit&lt;/code&gt; takes a &lt;code&gt;String iso&lt;/code&gt; as an argument. It&#39;s stubbed out since it doesn&#39;t need to do anything for the example. The main code creates a &lt;code&gt;Box&lt;/code&gt;, updates it, and calls the utility function on it.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Box
  var a: String iso

  new create(x: String iso) =&amp;gt;
    a = consume x

  fun ref update(x: String iso): String iso =&amp;gt;
    let b = a = consume x
    consume b

primitive Foo
  fun doit(s: String iso) =&amp;gt;
    None

actor Main
  new create(env: Env) =&amp;gt;
    let a = Box(recover iso String end)
    let b = a.update(recover iso String end)
    Foo.doit(consume b)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Some things to note based on prior discussion. The &lt;code&gt;create&lt;/code&gt; method consumes the argument to prevent aliasing. The &lt;code&gt;update&lt;/code&gt; function also consumes the argument to prevent aliasing. It uses the &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/consume-and-destructive-read.html&quot;&gt;destructive read&lt;/a&gt; syntax to assign the argument &lt;code&gt;x&lt;/code&gt; to the field &lt;code&gt;a&lt;/code&gt; and assign the old value of &lt;code&gt;a&lt;/code&gt; to &lt;code&gt;b&lt;/code&gt; to avoid aliasing. Unfortunately this example fails to compile:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Error:
f3/main.pony:19:14: argument not a subtype of parameter
    Foo.doit(consume b)
             ^
    Info:
    f3/main.pony:12:12: parameter type: String iso
      fun doit(s: String iso) =&amp;gt;
               ^
    f3/main.pony:19:14: argument type: String iso!
        Foo.doit(consume b)
                 ^
    f3/main.pony:7:34: String iso! is not a subtype of String iso: iso! is not a subtype of iso
      fun ref update(x: String iso): String iso =&amp;gt;
                                     ^
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;From the discussion previously on &lt;code&gt;!&lt;/code&gt; this error tells us that we are aliasing &lt;code&gt;b&lt;/code&gt;. We can narrow it down by explicitly declaring the type of &lt;code&gt;b&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let b: String iso = a.update(recover iso String end)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The error is due to &lt;code&gt;update&lt;/code&gt; returning a &lt;code&gt;String iso&lt;/code&gt;. We are consuming &lt;code&gt;b&lt;/code&gt; and returning it as a &lt;code&gt;String iso&lt;/code&gt; which then gets aliased when assigned to &lt;code&gt;b&lt;/code&gt; in the main routine. Changing the return type to use hat resolves the issue. &lt;code&gt;consume b&lt;/code&gt; returns the ephmeral type which is an object with no variable referencing it. It is safe to assign to a &lt;code&gt;String iso&lt;/code&gt; so the change compiles:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Box
  var a: String iso

  new create(x: String iso) =&amp;gt;
    a = consume x

  fun ref update(x: String iso): String iso^ =&amp;gt;
    let b = a = consume x
    consume b

primitive Foo
  fun doit(s: String iso) =&amp;gt;
    None

actor Main
  new create(env: Env) =&amp;gt;
    let a = Box(recover iso String end)
    let b = a.update(recover iso String end)
    Foo.doit(consume b)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Another approach would be to return a &lt;code&gt;String iso&lt;/code&gt; but change &lt;code&gt;doit&lt;/code&gt; to be a &lt;code&gt;String tag&lt;/code&gt; (the type that can alias a &lt;code&gt;String iso&lt;/code&gt;). This compiles but because &lt;code&gt;doit&lt;/code&gt; now takes &lt;code&gt;String tag&lt;/code&gt; it is limited in what it can do with the string. The approach of using an ephemeral type allows obtaining the mutable object from the &lt;code&gt;Box&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;Hat in parameters&lt;/h3&gt;

&lt;p&gt;Sometimes you&#39;ll see hat in parameter lists. The &lt;code&gt;Array&lt;/code&gt; builtin has an &lt;code&gt;init&lt;/code&gt; constructor that looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;new init(from: A^, len: USize)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This initializes an array so that all elements are the &lt;code&gt;from&lt;/code&gt; value. To explore how this works, here&#39;s a smaller example that does something similar:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Box[A]
  var a: A
  var b: A

  new create(x: A^) =&amp;gt;
    a = x
    b = x
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Without the hat in &lt;code&gt;A^&lt;/code&gt; there is an error due to aliasing. We can&#39;t assign &lt;code&gt;x&lt;/code&gt; to both &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; in case &lt;code&gt;A&lt;/code&gt; is an &lt;code&gt;iso&lt;/code&gt;. With the hat it compiles. The is because an epehemeral reference capability is a way of saying &quot;a reference capability that, when aliased, results in the base reference capability&quot;. So a &lt;code&gt;String iso^&lt;/code&gt; can be assigned to a &lt;code&gt;String iso&lt;/code&gt;, a &lt;code&gt;String ref^&lt;/code&gt; can be assigned to a &lt;code&gt;String ref&lt;/code&gt;, etc. This means the generic class itself compiles but using it for a &lt;code&gt;String iso&lt;/code&gt; will fail due to aliasing but it can be used for other reference capability types. Compare this to a plain &lt;code&gt;x: A&lt;/code&gt; where the generic class itself won&#39;t compile since a &lt;code&gt;String iso&lt;/code&gt; can&#39;t be assigned to another &lt;code&gt;String iso&lt;/code&gt; due to aliasing.&lt;/p&gt;

&lt;p&gt;Code demonstrating this is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  new create(env: Env) =&amp;gt;
    let a = Box[String iso](recover iso String end)
    let c = Box[String ref](recover ref String end)
    let e = Box[String val](recover val String end)
&lt;/code&gt;&lt;/pre&gt;

&lt;h1&gt;Arrow&lt;/h1&gt;

&lt;p&gt;The arrow syntax (or &lt;code&gt;-&amp;gt;&lt;/code&gt;) is known as &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/arrow-types.html&quot;&gt;viewpoint adapter types&lt;/a&gt; and is related to &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/combining-capabilities.html&quot;&gt;viewpoint adaption&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;Arrow in error messages&lt;/h3&gt;

&lt;p&gt;Viewpoint adaption defines what the reference capability of a field looks like to some caller based on the reference capability of the object the field is being read from. This is important to maintain the reference capability guarantees. A &lt;code&gt;val&lt;/code&gt; object should not be able to access an &lt;code&gt;iso&lt;/code&gt; field as &lt;code&gt;iso&lt;/code&gt; or it breaks the constraints of &lt;code&gt;val&lt;/code&gt; - it should be immutable but obtaining it as &lt;code&gt;iso&lt;/code&gt; allows mutation of the field. There is a table in &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/combining-capabilities.html&quot;&gt;viewpoint adaption&lt;/a&gt; that shows what the mapping is.&lt;/p&gt;

&lt;p&gt;An example of an error that can occur by ignoring viewpoint adaption is in the following code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Something
  var a: String iso

  new create() =&amp;gt;
    a = recover iso String end

  fun doit(s: String) =&amp;gt;
    a.append(s) 

actor Main
  new create(env: Env) =&amp;gt;
    let a = Something
    a.doit(&quot;hello&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The error here is calling &lt;code&gt;append&lt;/code&gt; on a the &lt;code&gt;a&lt;/code&gt; field in the &lt;code&gt;doit&lt;/code&gt; method. By default methods have a receiver reference capability of &lt;code&gt;box&lt;/code&gt;. Anything that happens inside the method cannot affect the state of the object. This is why you see methods that modify object fields start with &lt;code&gt;fun ref&lt;/code&gt; - it&#39;s to change the receiver reference capability to something mutable. Even though the field &lt;code&gt;a&lt;/code&gt; is &lt;code&gt;iso&lt;/code&gt; and therefore mutable because we are inside a &lt;code&gt;box&lt;/code&gt; method it appears as a non-mutable reference capability. The viewpoint adaption table shows that a &lt;code&gt;box&lt;/code&gt; origin with an &lt;code&gt;iso&lt;/code&gt; field gives a &lt;code&gt;tag&lt;/code&gt; type. So &lt;code&gt;a&lt;/code&gt; looks like a &lt;code&gt;String tag&lt;/code&gt; within the method. The compiler gives:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Error:
v/main.pony:8:13: receiver type is not a subtype of target type
    a.append(s) 
            ^
    Info:
    v/main.pony:8:5: receiver type: this-&amp;gt;String iso!
        a.append(s) 
        ^
    ny/ponyc/packages/builtin/string.pony:622:3: target type: String ref
      fun ref append(seq: ReadSeq[U8], offset: USize = 0, len: USize = -1)
      ^
    v/main.pony:2:10: String tag is not a subtype of String ref: tag is not a subtype of ref
      var a: String iso
             ^
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &#39;receiver type&#39; of &lt;code&gt;this-&amp;gt;String iso!&lt;/code&gt; is an example of arrow usage. It&#39;s saying that an object of type &lt;code&gt;String iso!&lt;/code&gt; (an alias to a &lt;code&gt;String iso&lt;/code&gt;) as seen by an origin of &lt;code&gt;this&lt;/code&gt;. The reference capability of &lt;code&gt;this&lt;/code&gt; in a method is that of the receiver reference capability on the function - in this case &lt;code&gt;box&lt;/code&gt;. So &lt;code&gt;this-&amp;gt;String iso!&lt;/code&gt; is &lt;code&gt;String tag&lt;/code&gt;. That&#39;s why the last error description line refers to &lt;code&gt;String tag&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The solution here is to change the reference capability for the method to something that allows mutation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun ref doit(s: String) =&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Arrow in type declarations&lt;/h3&gt;

&lt;p&gt;When writing generic code it&#39;s sometimes required to be explicit in what viewpoint adaption to use for generic types. Returning to the &lt;code&gt;Box&lt;/code&gt; example used previously we&#39;ll make it generic and make it usable for any reference capability:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Box[A]
  var a: A

  new create(x: A) =&amp;gt;
    a = consume x

  fun apply(): this-&amp;gt;A! =&amp;gt;
    a

  fun ref update(x: A): A^ =&amp;gt;
    let b = a = consume x
    consume b

  fun clone(): Box[this-&amp;gt;A!] =&amp;gt;
    Box[this-&amp;gt;A!](a)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice the use of &lt;code&gt;this-&amp;gt;A!&lt;/code&gt; in the return type of &lt;code&gt;apply&lt;/code&gt;. We want to return what is held in the &lt;code&gt;Box&lt;/code&gt;. If it is a &lt;code&gt;Box[String val] val&lt;/code&gt; then we can return a &lt;code&gt;String val&lt;/code&gt; since it is immutable and the box is immutable. If it is a &lt;code&gt;Box[String ref] val&lt;/code&gt; we still want to return a &lt;code&gt;String val&lt;/code&gt;, not a &lt;code&gt;String ref&lt;/code&gt;. The latter would allow modifying an immutable box. If it&#39;s a &lt;code&gt;Box[String ref] ref&lt;/code&gt; then it&#39;s safe to return a &lt;code&gt;String ref&lt;/code&gt;. This is what the arrow type handles for us. The &lt;code&gt;this&lt;/code&gt; refers to the reference capability of the object. The &lt;code&gt;A!&lt;/code&gt; refers to the field type - note that it is being aliased here so we want a type that can hold an alias to an &lt;code&gt;A&lt;/code&gt;. The viewpoint adaption gives the resulting reference capability of the type.&lt;/p&gt;

&lt;p&gt;Looking up the table of &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/combining-capabilities.html&quot;&gt;viewpoint adaption&lt;/a&gt; gives:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Box[String val] val =&amp;gt; val-&amp;gt;val =&amp;gt; val =&amp;gt; String val
Box[String ref] val =&amp;gt; val-&amp;gt;ref =&amp;gt; val =&amp;gt; String val
Box[String ref] ref =&amp;gt; ref-&amp;gt;ref =&amp;gt; ref =&amp;gt; String ref
Box[String iso] ref =&amp;gt; ref-&amp;gt;iso =&amp;gt; iso =&amp;gt; String iso
Box[String ref] iso =&amp;gt; iso-&amp;gt;ref =&amp;gt; tag =&amp;gt; String tag
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That last one is interesting in that the &lt;code&gt;Box[String ref] iso&lt;/code&gt; says that only one reference of the &lt;code&gt;Box&lt;/code&gt; can exist. If we allow a &lt;code&gt;String ref&lt;/code&gt; to be obtained from it then it breaks this condition since both the original reference to the box can modify the string and so can the returned reference. This is why the viewpoint adaption gives a &lt;code&gt;String tag&lt;/code&gt;. A &lt;code&gt;tag&lt;/code&gt; only allows identity operations so it&#39;s safe to have this type of alias of an &lt;code&gt;iso&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Note that the table above gives the mapping for &lt;code&gt;this-&amp;gt;A&lt;/code&gt;. Because it&#39;s a &lt;code&gt;this-&amp;gt;A!&lt;/code&gt; it has to be a type that can hold an alias to the type of the table. So we have another mapping:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;String val! =&amp;gt; String val
String ref! =&amp;gt; String ref
String iso! =&amp;gt; String tag
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this way a &lt;code&gt;Box[String iso] ref&lt;/code&gt; will give out a &lt;code&gt;String tag&lt;/code&gt; - the only safe way of aliasing the original string in the box.&lt;/p&gt;

&lt;p&gt;The other use of an arrow type in this example is in the &lt;code&gt;clone&lt;/code&gt; function. This must do a shallow copy of the object. It returns a new &lt;code&gt;Box&lt;/code&gt; holding a reference to the same value. Because we need to alias the value the same constraints as described for the &lt;code&gt;apply&lt;/code&gt; method exist. We want to return a &lt;code&gt;Box[this-&amp;gt;A!]&lt;/code&gt; to ensure the value object for that box instance is a safe alias to the original. For a &lt;code&gt;Box[String iso] ref&lt;/code&gt; this returns a &lt;code&gt;Box[String tag]&lt;/code&gt; for example.&lt;/p&gt;

&lt;p&gt;The following code can be used with the &lt;code&gt;Box&lt;/code&gt; class above to test it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;primitive Foo
  fun doit(s: String tag) =&amp;gt;
    None

actor Main
  new create(env: Env) =&amp;gt;
    let a = Box[String iso](recover iso String end)
    let b = a.clone()
    Foo.doit(b())

    let c = Box[String ref](recover ref String end)
    let d = c.clone()
    Foo.doit(d())

    let e = Box[String val](recover val String end)
    let f = e.clone()
    Foo.doit(f())
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;A-&gt;B arrows&lt;/h3&gt;

&lt;p&gt;Arrow types don&#39;t need to always use &lt;code&gt;this&lt;/code&gt; on the receiver side. They can use an explicit reference capability like &lt;code&gt;box-&amp;gt;A&lt;/code&gt; or they can use another parameterized type. Examples of this are in some of the library code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class ArrayValues[A, B: Array[A] #read] is Iterator[B-&amp;gt;A]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;An &lt;code&gt;ArrayValues&lt;/code&gt; is returned by the &lt;code&gt;values&lt;/code&gt; method on &lt;code&gt;Array&lt;/code&gt;. It&#39;s an iterator over the objects in the array. The &lt;code&gt;B-&amp;gt;A&lt;/code&gt; syntax means that the type of the generic argument to &lt;code&gt;Iterator&lt;/code&gt; is of type &quot;&lt;code&gt;A&lt;/code&gt; as seen by &lt;code&gt;B&lt;/code&gt;&quot; using viewpoint adaption. It&#39;s not an iterator over &lt;code&gt;A&lt;/code&gt;, it&#39;s an iterator over &quot;A as seen by B&quot;. This allows iteration over arrays whether they are &lt;code&gt;val&lt;/code&gt; or &lt;code&gt;ref&lt;/code&gt; and produces a compatible type for the &lt;code&gt;Iterator&lt;/code&gt; that works with both.&lt;/p&gt;

&lt;h1&gt;Conclusion&lt;/h1&gt;

&lt;p&gt;Most of the functionality described here is some of the more esotoric Pony functionality. It is mainly hit when using generics. The best current reference for generics is a video by Sylvan Clebsch for the virtual Pony users group - &lt;a href=&quot;https://www.youtube.com/watch?v=Vq1vRfv-A6g&quot;&gt;Writing Generic Code&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;A good way to learn is to try some of the examples in this post and play around with them. Try aliasing, using different types, different reference capabilities and see what happens. The Pony library code, &lt;a href=&quot;https://github.com/ponylang/ponyc/blob/master/packages/builtin/array.pony&quot;&gt;Array.pony for example&lt;/a&gt;, is a useful reference.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Closures in Pony</title>
   <link href="http://bluishcoder.co.nz/2016/03/15/closures-in-pony.html"/>
   <updated>2016-03-15T11:00:00+13:00</updated>
   <id>http://bluishcoder.co.nz/2016/03/15/closures-in-pony</id>
   <content type="html">&lt;p&gt;Note 2017-08-01: Recent releases of Pony have changed syntax for lambda calls and partial function calls. This post has been updated to work with these changes as of Pony 0.16.1.&lt;/p&gt;

&lt;p&gt;The &lt;a href=&quot;http://www.ponylang.org/&quot;&gt;Pony programming language&lt;/a&gt; has support for closures but the documentation hasn&#39;t caught up with changes to the implementation. This post describes some of the features of Pony closures with examples. These examples require the latest version of Pony from the &lt;a href=&quot;https://github.com/ponylang/ponyc&quot;&gt;github repository&lt;/a&gt;. I used commit &lt;a href=&quot;https://github.com/ponylang/ponyc/commit/e4f6f91dfb91b9f7a6ec1028c3d0448001713e8b&quot;&gt;e4f6f91d&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Lambda&lt;/h2&gt;

&lt;p&gt;Closures are functions combined with an environment mapping names to values. Pony has a &lt;code&gt;{...}&lt;/code&gt; syntax that can be used to create them. It&#39;s possible to create a function that captures from the lexical scope and to create a function with no capturing at all.&lt;/p&gt;

&lt;p&gt;The following example shows using a lambda that does not capture anything (note that this is an artificial example - the &lt;code&gt;List&lt;/code&gt; type already has various mapping and fold functions on it):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;use &quot;collections&quot;

actor Main
  new create(env:Env) =&amp;gt;
    let l = List[U32]
    l.push(10)
    l.push(20)
    l.push(30)
    l.push(40)
    let r = reduce(l, 0, {(a:U32,b:U32): U32 =&amp;gt; a + b})
    env.out.print(&quot;Result: &quot; + r.string())

  fun reduce(l: List[U32], acc: U32, f: {(U32, U32): U32} val): U32 =&amp;gt;
    try
      let acc&#39; = f(acc, l.shift()?)
      reduce(l, acc&#39;, f)
    else
      acc
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;reduce&lt;/code&gt; function takes an anonymous function as a parameter, named &lt;code&gt;f&lt;/code&gt;. This is is defined as &lt;code&gt;{(U32, U32): U32}&lt;/code&gt;. This syntax means that it must take two &lt;code&gt;U32&lt;/code&gt; arguments and returns a &lt;code&gt;U32&lt;/code&gt;. A &lt;code&gt;U32&lt;/code&gt; is a 32-bit unsigned integer.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;val&lt;/code&gt; is a &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/reference-capabilities/&quot;&gt;reference capability&lt;/a&gt; annotation. It states that &lt;code&gt;f&lt;/code&gt; is an immutable value. Since nothing inside &lt;code&gt;f&lt;/code&gt; can be mutated it is safe for &lt;code&gt;f&lt;/code&gt; to be shared with other actors. Lambda functions that do not close over other variables default to &lt;code&gt;val&lt;/code&gt; as they cannot change anything outside of the function. We need to explicitly annotate the &lt;code&gt;val&lt;/code&gt; as &lt;code&gt;{...}&lt;/code&gt; declarations default to &lt;code&gt;ref&lt;/code&gt;. A compile error would result without it due to passing a &lt;code&gt;val&lt;/code&gt; object to a &lt;code&gt;ref&lt;/code&gt; parameter.&lt;/p&gt;

&lt;p&gt;Compiling and running produces the result &lt;code&gt;100&lt;/code&gt; as expected:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ ponyc example
$ ...
$ ./example1
  Result: 100
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Lambda with environment&lt;/h2&gt;

&lt;p&gt;The following example closes over the &lt;code&gt;env&lt;/code&gt; variable so that it can be accessed within the lambda to print the &lt;code&gt;String&lt;/code&gt; contained in the &lt;code&gt;List&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;use &quot;collections&quot;

actor Main
  new create(env:Env) =&amp;gt;
    let l = List[String]
    l.push(&quot;hello&quot;)
    l.push(&quot;world&quot;)
    for_each(l, {(s:String)(env) =&amp;gt; env.out.print(s)})

  fun for_each(l: List[String], f: {(String)}) =&amp;gt;
    try
      f(l.shift()?)
      for_each(l, f)
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice that the lambda has an additional set of parameters, the &lt;code&gt;(env)&lt;/code&gt;. This is an argument list of the variables that are being closed over. Variables listed there can be accessed from the body of the &lt;code&gt;lambda&lt;/code&gt;. Pony requires you to be explicit about what gets captured vs many other languages that implicitly capture variables in scope. Variables can be renamed in this parameter list using the following syntax:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;for_each(l, {(s:String)(myenv=env) =&amp;gt; myenv.out.print(s)})
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The lambda here returns &lt;code&gt;None&lt;/code&gt; which is the default so it is left off the declaration &lt;code&gt;{(String)}&lt;/code&gt;. This declaration requires a function that takes a single &lt;code&gt;String&lt;/code&gt; argument and returns &lt;code&gt;None&lt;/code&gt;. The return value is also left off the actual lambda expression. No reference capability annotations are required here as &lt;code&gt;{...}&lt;/code&gt; defaults to &lt;code&gt;ref&lt;/code&gt; and a &lt;code&gt;lambda&lt;/code&gt; that closes over variables also defaults to &lt;code&gt;ref&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;Lambda modifying closed variables&lt;/h2&gt;

&lt;p&gt;A modification of the above example might be to keep a count of each time the lambda is called and display the count:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  new create(env:Env) =&amp;gt;
    let l = List[String]
    l.push(&quot;hello&quot;)
    l.push(&quot;world&quot;)
    var count = U32(0)
    for_each(l, {ref(s:String)(env,count) =&amp;gt;
                    env.out.print(s)
                    count = count + 1})
    // Displays &#39;0&#39; as the count
    env.out.print(&quot;Count: &quot; + count.string())

fun for_each(l: List[String], f: {ref(String)}) =&amp;gt;
  try
    f(l.shift()?)
    for_each(l, f)
  end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The main thing to note here is that both the lambda definition and the declaration have a &lt;code&gt;ref&lt;/code&gt; prefixed to the argument list. This signifies a lambda that might mutate itself when called. The effect of this is that within the body of the lambda the receiver of method calls and field access (ie. the &lt;code&gt;this&lt;/code&gt; of the lambda object) is a &lt;code&gt;ref&lt;/code&gt; vs the default of &lt;code&gt;box&lt;/code&gt;. A &lt;code&gt;box&lt;/code&gt; receiver won&#39;t allow &lt;code&gt;ref&lt;/code&gt; functions to be called and mutating requires a &lt;code&gt;ref&lt;/code&gt; receiver.&lt;/p&gt;

&lt;p&gt;There is an issue with this example as noted by the comment. The final count is displayed as zero. The assignment of &lt;code&gt;count&lt;/code&gt; within the lambda changes the &lt;code&gt;count&lt;/code&gt; field within the lambda object. The count within the lambda increments and could be displayed showing the increasing values. The &lt;code&gt;count&lt;/code&gt; outside of this does not. There is no reference or pointer to the closed over variable. Indirection can be used to do this by using a one element array:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var count : Array[U32] = Array[U32].init(0, 1)
for_each(l, {ref(s:String)(env,count) =&amp;gt;
              try
                env.out.print(s)
                count(0)? = count(0)? + 1
              end})
try
  env.out.print(&quot;Count: &quot; + count(0)?.string())
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The array access is wrapped with &lt;code&gt;try&lt;/code&gt; as it is a partial function and can fail. Another approach could be to move the act of counting into an Actor:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;use &quot;collections&quot;

actor Counter
  var n: U32 = 0

  be increment() =&amp;gt;
    n = n + 1

  be print(env:Env) =&amp;gt;
    env.out.print(&quot;Count: &quot; + n.string())

actor Main
  new create(env:Env) =&amp;gt;
    let l = List[String]
    l.push(&quot;hello&quot;)
    l.push(&quot;world&quot;)
    let counter = Counter
    for_each(l, {(s:String)(env,counter) =&amp;gt;
                  env.out.print(s)
                  counter.increment()})
    counter.print(env)

  fun for_each(l: List[String], f: {(String)}) =&amp;gt;
    try
      f(l.shift()?)
      for_each(l, f)
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Actors have the &lt;code&gt;tag&lt;/code&gt; reference capability and are easier to pass around to other objects, including lambda.&lt;/p&gt;

&lt;p&gt;The example here is contrived in that it can be done without modifying a captured variable. Sylvan produced the following approach, using the methods in the collections package:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;use &quot;collections&quot;

actor Main
  new create(env:Env) =&amp;gt;
    let l = List[String]
    l.push(&quot;hello&quot;)
    l.push(&quot;world&quot;)

    let count = l.fold[U32](
      {(x: U32, s: String)(env): U32 =&amp;gt;
        env.out.print(s)
        x + 1}, 0)

    env.out.print(&quot;Count: &quot; + count.string())
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Object Literals&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;http://tutorial.ponylang.org/expressions/object-literals/&quot;&gt;Object literals&lt;/a&gt; are a way to create objects inline without having to name a class or actor. They look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;object
  let x = 10
  fun foo() =&amp;gt;
    ...do something...
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Lambda&#39;s are actually syntactic sugar on top of object literals. A lambda expansion looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Lambda
{(s:String)(env) =&amp;gt; env.out.print(s)}

// Expands to:
object
  var env:Env = env
  fun apply(s:String) =&amp;gt;
    env.out.print(s)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;apply&lt;/code&gt; method of an object is called when the &lt;code&gt;()&lt;/code&gt; function call syntax is used. Keeping this syntactic transformation in mind can help solve errors that occur when using lambda. The example earlier where the &lt;code&gt;count&lt;/code&gt; total didn&#39;t account for the increments in the lambda becomes obvious here. The transformation would be:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var count = U32(0)
for_each(l, object
              var env:Env = env
              var count:U32 = count
              fun ref apply(s:String) =&amp;gt;
                env.out.print(s)
                count = count + 1
            end)
env.out.print(&quot;Count: &quot; + count.string())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the &lt;code&gt;ref&lt;/code&gt; annotation in the &lt;code&gt;apply&lt;/code&gt; method. This is what the &lt;code&gt;{ref(...)}&lt;/code&gt; syntax results in. Without the &lt;code&gt;ref&lt;/code&gt; in the &lt;code&gt;{}&lt;/code&gt; syntax the syntactic expansion is &lt;code&gt;fun apply(...)&lt;/code&gt;. The default reference capability for &lt;code&gt;fun&lt;/code&gt; in objects is &lt;code&gt;box&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The object literal expansion helps show the difference between &lt;code&gt;{(string)} ref&lt;/code&gt; and &lt;code&gt;{ref(String))}&lt;/code&gt;. The first requires an object with the given reference capability to match the type. Although the object is a &lt;code&gt;ref&lt;/code&gt;, the &lt;code&gt;apply&lt;/code&gt; method is the default, a &lt;code&gt;box&lt;/code&gt;. This means it cannot modify any fields in the object. In the case of a lambda it won&#39;t be able to modify the captured variables:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;object ref
  fun apply(...)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To match the second type definition it requires an object where the &lt;code&gt;apply&lt;/code&gt; method itself has the &lt;code&gt;ref&lt;/code&gt; capability. This allows &lt;code&gt;apply&lt;/code&gt; to modify fields of the object:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;object
  fun ref apply(...)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Partial Application&lt;/h2&gt;

&lt;p&gt;Related to lambda is &lt;a href=&quot;http://tutorial.ponylang.org/expressions/partial-application/&quot;&gt;partial application&lt;/a&gt;. It allows supplying some arguments to a function (or constructor or behaviour) and returns something that allows supplying the other arguments later.&lt;/p&gt;

&lt;p&gt;In cases where you would use a lambda to return a function that sets the value of some arguments you can use partial application instead. The following example creates a lambda that adds five to another number:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  new create(env:Env) =&amp;gt;
    let add5 = {(a:U32): U32 =&amp;gt; 5 + a}
    env.out.print(add5(10).string())
    env.out.print(add5(20).string())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With partial application this becomes:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  new create(env:Env) =&amp;gt;
    let add5 = U32(5)~add()
    env.out.print(add5(10).string())
    env.out.print(add5(20).string())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The use of &lt;code&gt;+&lt;/code&gt; is an &lt;a href=&quot;http://tutorial.ponylang.org/expressions/infix-ops/&quot;&gt;alias&lt;/a&gt; for the &lt;code&gt;add&lt;/code&gt; method on an object. In the example above the &lt;code&gt;~&lt;/code&gt; operator represents partial application. We are binding the receiver of the &lt;code&gt;add&lt;/code&gt; method to be the 32-bit unsigned value &lt;code&gt;5&lt;/code&gt;. The resulting object can be called with the remaining arguments.&lt;/p&gt;

&lt;p&gt;Partial application allows binding any arguments, by position or by name. The &lt;a href=&quot;http://tutorial.ponylang.org/expressions/partial-application/&quot;&gt;tutorial&lt;/a&gt; goes into a lot of detail.&lt;/p&gt;

&lt;h2&gt;Accumulator Generator&lt;/h2&gt;

&lt;p&gt;Paul Graham has an &lt;a href=&quot;http://www.paulgraham.com/accgen.html&quot;&gt;accumulator generator&lt;/a&gt; problem with &lt;a href=&quot;http://www.paulgraham.com/icad.html&quot;&gt;examples in various languages&lt;/a&gt;. The problem is defined as:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;Write a function foo that takes a number n and returns a function that takes a number i, and returns n incremented by i.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;A Pony implementation, using closures, could be:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  fun foo(n:U32): {ref(U32): U32} =&amp;gt;
    var s: Array[U32] = Array[U32].init(n, 1)
    {ref(i:U32)(s): U32 =&amp;gt;
      try
        s(0)? = s(0)? + i
        s(0)?
      else
        0
      end}

  new create(env:Env) =&amp;gt;
    var f = foo(5)
    env.out.print(f(10).string())
    env.out.print(f(20).string())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This uses the one element array trick to enable modifying the captured variable due to the requirement that the number &lt;code&gt;n&lt;/code&gt; is incremented. It works only for &lt;code&gt;U32&lt;/code&gt; rather than any number which is also part of the problem definition. Pony has generics which would allow solving this but I&#39;ll leave that as an exercise or a future post.&lt;/p&gt;

&lt;h2&gt;Further reading&lt;/h2&gt;

&lt;p&gt;Some links to documentation and posts about lambda and reference capabilities to dive into more detail:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://tutorial.ponylang.org/capabilities/reference-capabilities/&quot;&gt;Tutorial on reference capabilities&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://tutorial.ponylang.org/expressions/object-literals/&quot;&gt;Tutorial on object literals&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://tutorial.ponylang.org/expressions/partial-application/&quot;&gt;Tutorial on partial application&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://tutorial.ponylang.org/capabilities/reference-capabilities/&quot;&gt;Tutorial on reference capabilities&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://jtfmumm.com/blog/2016/03/06/safely-sharing-data-pony-reference-capabilities/&quot;&gt;Safely sharing data: Reference capabilities in Pony&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</content>
 </entry>
 
 <entry>
   <title>Cross compile Pony programs for Android</title>
   <link href="http://bluishcoder.co.nz/2015/12/17/cross-compile-pony-programs-for-android.html"/>
   <updated>2015-12-17T19:00:00+13:00</updated>
   <id>http://bluishcoder.co.nz/2015/12/17/cross-compile-pony-programs-for-android</id>
   <content type="html">&lt;p&gt;Support for compiling &lt;a href=&quot;http://ponylang.org/&quot;&gt;Pony&lt;/a&gt; programs on ARM and 32-bit x86 &lt;a href=&quot;https://github.com/CausalityLtd/ponyc/commit/f59b7c9d593df246b388816ca68617b998f8371b&quot;&gt;landed recently&lt;/a&gt;. This allows compiling and running Pony on Raspberry Pi and other ARM devices. I was curious if it would be possible to compile Pony programs to run on Android and this post outlines how I got a &quot;Hello World&quot; example working.&lt;/p&gt;

&lt;p&gt;The Pony compiler, &lt;a href=&quot;https://github.com/CausalityLtd/ponyc&quot;&gt;ponyc&lt;/a&gt;, does not currently support cross compilation. It uses the C pre-processor to generate code for the platform it is running on. This has hardcoded assumptions for byte size (32 vs 64 bit) and processor support (ARM vs x86). Note that this is a proof of concept and hacks the compiler and runtime source to get things working. From this I hope to learn more elegant ways of supporting cross compiling.&lt;/p&gt;

&lt;h2&gt;Ponyc Android Cross Compiler&lt;/h2&gt;

&lt;p&gt;The first step was to build a version of &lt;code&gt;ponyc&lt;/code&gt; that would generate Android compatible ARM code without any host platform specific code being included. I built &lt;code&gt;ponyc&lt;/code&gt; for 32-bit x86, modified to not include any x86 specific code generation and to allow selecting the non-native LLVM backends. This ensures that the hard coded assumptions for the 32-bit size matches my target, 32-bit Android.&lt;/p&gt;

&lt;p&gt;The changes for this are in the &lt;a href=&quot;https://github.com/doublec/ponyc/tree/android_ponyc_cross&quot;&gt;android_ponyc_cross&lt;/a&gt; branch of my github repository. The changes were:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Modify the &lt;code&gt;Makefile&lt;/code&gt; to use 32-bit flags to the compiler.&lt;/li&gt;
&lt;li&gt;Add some LLVM initialization to allow selection of non-native backends so ARM can be generated on x86 hosts.&lt;/li&gt;
&lt;li&gt;Comment out some &lt;code&gt;PLATFORM_IS_X86&lt;/code&gt; preprocessor statements to prevent x86 specific code being generated.&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;For a real cross compiler these would be changed to be runtime selectable in some way. For the proof of concept it suffices to create a hardcoded compiler specific for this example.&lt;/p&gt;

&lt;p&gt;For me it was necessary to build a version of LLVM for 32-bit as I&#39;m on a 64-bit host. This was done by doing the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ sudo apt-get install libicu-dev:i386 libncurses5-dev:i386 libxml2-dev:i386
$ tar xvf /tmp/llvm-3.6.2.src.tar.xz
$ cd llvm-3.6.2.src/tools
$ tar xvf /tmp/cfe-3.6.2.src.tar.xz
$ mv cfe-3.6.2.src clang
$ cd ..
$ mkdir build
$ cd build
$ cmake -DLLVM_BUILD_32_BITS=ON -DCMAKE_INSTALL_PREFIX=/tmp/llvm ..      
$ make
$ make install
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Building the modified &lt;code&gt;ponyc&lt;/code&gt; used these steps:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ git clone -b android_ponyc_cross https://github.com/doublec/ponyc android_ponyc_cross
$ cd android_ponyc_cross
$ LLVM_CONFIG=/tmp/llvm/bin/llvm-config CXX=&quot;g++ -m32&quot; make config=release ponyc
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This generates a &lt;code&gt;ponyc&lt;/code&gt; executable in the &lt;code&gt;build/release&lt;/code&gt; directory.&lt;/p&gt;

&lt;h2&gt;Android compatible Pony runtime&lt;/h2&gt;

&lt;p&gt;An Android compatible &lt;code&gt;libponyrt&lt;/code&gt; library is needed to link. The changes to build this are on the &lt;a href=&quot;https://github.com/doublec/ponyc/tree/android_libponyrt&quot;&gt;android_libponyrt&lt;/a&gt; branch. This must be built using an Android NDK standalone toolkit. A compatible standalone toolkit can be created with the following run from the NDK root directory:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ ./build/tools/make-standalone-toolchain.sh --arch=arm \
     --platform=android-21 --install-dir=/tmp/stk21
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Add the resulting installation directory to the &lt;code&gt;PATH&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ export PATH=/tmp/stk21/bin:$PATH
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Make sure a recent &lt;code&gt;ponyc&lt;/code&gt; compiler is on the &lt;code&gt;PATH&lt;/code&gt;. This should not be the cross compiler built previously but a &lt;code&gt;ponyc&lt;/code&gt; compiler for the host platform. Build the runtime library with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ git clone -b android_libponyrt https://github.com/doublec/ponyc android_libponyrt
$ cd android_libponyrt
$ CC=arm-linux-androideabi-gcc make config=release libponyrt
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The resulting library is in the directory &lt;code&gt;build/release/libponyrt.a&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;Compiling to Android&lt;/h2&gt;

&lt;p&gt;With the above tasks complete it&#39;s now possible to build an Android compatible binary. I tested with a &quot;Hello World&quot; example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  new create(env:Env) =&amp;gt;
    env.out.print(&quot;Hello Android&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With that in a &lt;code&gt;main.pony&lt;/code&gt; file in a &lt;code&gt;hello&lt;/code&gt; directory, build with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ /tmp/android_ponyc_cross/build/release/ponyc --triple arm-linux-androideabi -rir hello
...ignore warnings about core-avx2 feature here...
$ llvm-as hello.ll
$ llc -mtriple=arm-linux-androideabi hello.bc -o hello.o -filetype=obj
$ arm-linux-androideabi-gcc -fPIE -pie hello.o -o hello1 -L/tmp/android_libponyrt/build/release/ -lponyrt 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The first command instructs our cross compiler to generate code for Android and to only produce the LLVM assembly listing. This is compiled to bytecode with &lt;code&gt;llvm-as&lt;/code&gt; and then to an object file with &lt;code&gt;llc&lt;/code&gt;. The Android version of &lt;code&gt;gcc&lt;/code&gt; is used to link with the Android version of &lt;code&gt;libponyrt&lt;/code&gt; that was created earlier. The &lt;code&gt;hello&lt;/code&gt; binary that is produced can be copied to an Android device (I used a Note 3 running Lollipop) and run:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ adb push hello1 /data/local/tmp/
$ adb shell
$ cd /data/local/tmp
$ ./hello1
Hello Android
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;I haven&#39;t tested any other features running on Android yet but this is a promising start. Using the Pony FFI and JNI it is hopefluly possible to write native Android applications.&lt;/p&gt;

&lt;p&gt;The steps I used for getting &lt;code&gt;ponyc&lt;/code&gt; to generate LLVM instructions and using the LLVM tools to compile it were obtained from &lt;a href=&quot;https://gist.github.com/darach/1b8bfade3f3b2488f6db&quot;&gt;a gist by Darach Ennis&lt;/a&gt;. Similar steps would probably work on other LLVM compatible platforms.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>C linkable libraries with Pony</title>
   <link href="http://bluishcoder.co.nz/2015/12/16/c-linkable-libraries-with-pony.html"/>
   <updated>2015-12-16T19:00:00+13:00</updated>
   <id>http://bluishcoder.co.nz/2015/12/16/c-linkable-libraries-with-pony</id>
   <content type="html">&lt;p&gt;Note 2017-08-01: Recent releases of Pony have changed some of the details of interacting with C. This post has been updated to work with these changes as of Pony 0.16.1.&lt;/p&gt;

&lt;p&gt;My &lt;a href=&quot;http://bluishcoder.co.nz/2015/11/04/a-quick-look-at-pony.html&quot;&gt;quick look at Pony&lt;/a&gt; post covered how to use the FFI to call C code from a Pony program. It&#39;s also possible to compile Pony code to a C library that can be linked into a C program. This allows integrating Pony into existing C projects without having to convert the C project into a library to be called by Pony.&lt;/p&gt;

&lt;p&gt;I&#39;ve put a small example of how to do this on github at &lt;a href=&quot;https://github.com/doublec/pony-clib-example&quot;&gt;https://github.com/doublec/pony-clib-example&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Pony has a special type of actor that will result in a C compatible interface being generated. The syntax for this is &lt;code&gt;actor@&lt;/code&gt;. The example in the project is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor@ Foo
  new create() =&amp;gt;
    None

  be hi() =&amp;gt;
    @printf[I32](&quot;Hi\n&quot;.cstring())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This creates a C compatible actor called &lt;code&gt;Foo&lt;/code&gt;. It has a constructor &lt;code&gt;create&lt;/code&gt; and a behaviour &lt;code&gt;hi&lt;/code&gt;. The constructor does nothing and only exists in the example to show how to call it from C. The &lt;code&gt;hi&lt;/code&gt; behaviour calls the C function &lt;code&gt;printf&lt;/code&gt; using the Pony FFI. With a file &lt;code&gt;main.pony&lt;/code&gt; containing this code in a &lt;code&gt;clib&lt;/code&gt; directory it can be built with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ ponyc -l clib
Building builtin -&amp;gt; packages/builtin
Building clib -&amp;gt; clib
Generating
Optimising
Writing ./clib.o
Archiving ./libclib.a
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;-l&lt;/code&gt; switch to &lt;code&gt;ponyc&lt;/code&gt; results in a static library being built instead of an executable. A &lt;code&gt;libclib.a&lt;/code&gt; is generated containing the compiled Pony code. A &lt;code&gt;clib.h&lt;/code&gt; is also generated containing the C function declarations for creating and interacting with any &lt;code&gt;actor@&lt;/code&gt; instances. For the &lt;code&gt;Foo&lt;/code&gt; actor this looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;typedef struct Foo Foo;
Foo* Foo_Alloc();
None* Foo_tag_hi_o__send(Foo* self);
Foo* Foo_tag_create_o__send(Foo* self);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Pony has a runtime that needs to be initialized from C and a scheduler that needs to be started. The definitions for these runtime functions can be found in the &lt;code&gt;ponyc&lt;/code&gt; source in &lt;a href=&quot;https://github.com/CausalityLtd/ponyc/blob/master/src/libponyrt/pony.h&quot;&gt;libponyrt/pony.h&lt;/a&gt;. This needs to be included by the C program. A basic C driver for the example project is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;
#include &quot;clib.h&quot;
#include &quot;pony.h&quot;

int main(int argc, char** argv) {
  pony_init(argc, argv);

  Foo* x = Foo_Alloc();
  Foo_tag_hi_o__send(x);
  Foo_tag_create_o__send(x);

  pony_start(true, true);
  return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This sould be compiled and linked against &lt;code&gt;libclib.a&lt;/code&gt; and &lt;code&gt;libponyrt.a&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;export PONYRT_INCLUDE=/path/to/ponyc/src/libponyrt/
export PONYRT_COMMON=/path/to/ponyc/src/common
export PONYRT_LIB=/path/to/ponyc/build/release/libponyrt.a

gcc -o test -I. -I $(PONYRT_INCLUDE) -I $(PONYRT_COMMON) \
    -g -rdynamic -mcx16 test.c libclib.a $(PONYRT_LIB) -lpthread -ldl
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The C code needs to call &lt;code&gt;pony_init&lt;/code&gt; to initialize the Pony runtime. It gets passed the standard C &lt;code&gt;argc&lt;/code&gt; and &lt;code&gt;argv&lt;/code&gt; arguments that &lt;code&gt;main&lt;/code&gt; receives so it can handle any Pony runtime specific switches. After this any Pony actors can be allocated and methods or behaviours called on them. The order for actor creation is to call the &lt;code&gt;_Alloc&lt;/code&gt; function to allocate the memory for the actor and then the constructor method. Pony names the constructor method based on the name in the Pony code with &lt;code&gt;__send&lt;/code&gt; appended.&lt;/p&gt;

&lt;p&gt;Actors are asynchronous so just like in Pony code behaviours aren&#39;t run immediately. They are queued for execution and will run when the scheduler is started. This is what &lt;code&gt;pony_start&lt;/code&gt; does. The arguments passed to &lt;code&gt;pony_start&lt;/code&gt; are a boolean indicating whether to block until all Pony actors have completed (by passing a false value) or to return immediately (by passing a true value). If the latter is done then the scheduler runs asynchronously. It can be stopped with a later call to &lt;code&gt;pony_stop&lt;/code&gt;. The second parameter indicates whether to initialize Pony specific parts of the runtime (sockets and serialization). It&#39;s possible to continue calling Pony functions after the &lt;code&gt;pony_start&lt;/code&gt; and before &lt;code&gt;pony_stop&lt;/code&gt;. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;pony_init(argc, argv);

Foo* x = Foo_Alloc();
Foo_tag_hi_o__send(x);
Foo_tag_create_o__send(x);

pony_start(true, true);

Foo* y = Foo_Alloc();
Foo_tag_hi_o__send(y);
Foo_tag_create_o__send(y);

pony_stop();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this snippet another actor is created after &lt;code&gt;pony_start&lt;/code&gt; and behaviours are called on it. These are queued and run as expected. &lt;code&gt;pony_stop&lt;/code&gt; blocks until all Pony actors have completed.&lt;/p&gt;

&lt;p&gt;There are other Pony runtime functions in &lt;code&gt;pony.h&lt;/code&gt; that allow allocating memory on the current actor heap, unscheduling an actor so that no behaviours will be run until rescheduled, making a C thread &#39;become&#39; an actor so it can call Pony runtime functions, poll for messages on an unscheduled actor, etc. It&#39;s possible to allocate an actor, unschedule it, and then use a C thread to handle its message queue using &lt;code&gt;pony_become&lt;/code&gt;. When you aren&#39;t handling messages to the unscheduled actor you can call functions to it from C with no race conditions.&lt;/p&gt;

&lt;p&gt;None of this is currently documented and it will probably change as usage develops. In the meantime it&#39;s a useful feature for using Pony functionality in existing applications.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>A quick look at the Pony Programming Language</title>
   <link href="http://bluishcoder.co.nz/2015/11/04/a-quick-look-at-pony.html"/>
   <updated>2015-11-04T19:00:00+13:00</updated>
   <id>http://bluishcoder.co.nz/2015/11/04/a-quick-look-at-pony</id>
   <content type="html">&lt;p&gt;&lt;a href=&quot;http://ponylang.org/&quot;&gt;Pony&lt;/a&gt; is a new programming language described on their site as &quot;an open-source, object-oriented, actor-model, capabilities-secure, high performance programming language.&quot;&lt;/p&gt;

&lt;p&gt;It has some interesting features and is different enough to existing popular programming languages to make it a nice diversion to experiment with. Some features include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;lightweight actor based concurrency with M:N threading, mapping multiple language level threads to operating system threads.&lt;/li&gt;
&lt;li&gt;strong static typing with generics&lt;/li&gt;
&lt;li&gt;data-race free. The type system ensures at compile time that a concurrent program can never have data races.&lt;/li&gt;
&lt;li&gt;deadlock free. There are no locking mechanisms exposed to the user so there are no deadlocks.&lt;/li&gt;
&lt;li&gt;capabilities exposed to the type system to allow compile time enforcing of such things as objects that have no other references to it, immutable values, reference values, etc.&lt;/li&gt;
&lt;li&gt;lightweight C FFI&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;This post is an outline of my initial experiments with the languages including pitfalls to be aware of.&lt;/p&gt;

&lt;h2&gt;Installing&lt;/h2&gt;

&lt;p&gt;Pony can be installed from &lt;code&gt;git&lt;/code&gt; and run from the build directory:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ git clone https://github.com/CausalityLtd/ponyc
$ cd ponyc
$ make config=release
$ export PATH=`pwd`/build/release:$PATH
$ ponyc --help
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Run tests with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ make config=release test
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Some of the Pony standard packages dynamically load shared libraries. If they&#39;re not installed this will be reflected in build failures during the tests. The required libraries on a Linux based machine are &lt;code&gt;openssl&lt;/code&gt; and &lt;code&gt;pcre2-8&lt;/code&gt;. To build Pony itself &lt;code&gt;llvm&lt;/code&gt; version &lt;code&gt;3.6&lt;/code&gt; needs to be installed. There is an &lt;code&gt;llvm37&lt;/code&gt; &lt;a href=&quot;https://github.com/CausalityLtd/ponyc/tree/llvm37&quot;&gt;branch on github&lt;/a&gt; that works on Linux but is awaiting some &lt;code&gt;llvm37&lt;/code&gt; fixes before it is merged into &lt;code&gt;master&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Pony can be installed in a default location, or using &lt;code&gt;prefix&lt;/code&gt; to install it somewhere else:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ make config=release prefix=/home/user/pony install
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;One catch is that running &lt;code&gt;ponyc&lt;/code&gt; requires it to find the Pony runtime library &lt;code&gt;libponyrt.a&lt;/code&gt; for linking purposes. This might not be found if installed somewhere that it doesn&#39;t expect. This can be resolved by setting the environment variable &lt;code&gt;LIBRARY_PATH&lt;/code&gt; to the directory where &lt;code&gt;libponyrt.a&lt;/code&gt; resides. I had to do this for the &lt;a href=&quot;https://github.com/nixos/nixpkgs/commit/e261492bb03398a137ea4ea6644c7865df191651&quot;&gt;Nix Pony package&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Compiling Pony programs&lt;/h2&gt;

&lt;p&gt;A basic &quot;Hello World&quot; application looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  new create(env: Env) =&amp;gt;
    env.out.print(&quot;hello world&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Place this in a &lt;code&gt;main.pony&lt;/code&gt; file in a directory and compile:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ mkdir hello
$ cat &amp;gt;hello/main.pony
  actor Main
   new create(env: Env) =&amp;gt;
     env.out.print(&quot;hello world&quot;)
$ ponyc hello
$ ./hello1
hello world
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;ponyc&lt;/code&gt; requires a directory as an argument and it compiles the &lt;code&gt;*.pony&lt;/code&gt; files in that directory. It generates an executable based on the directory name, with a number appended if needed to prevent a name clash with the directory. The program starts executing by creating a &lt;code&gt;Main&lt;/code&gt; actor and passing it an &lt;code&gt;Env&lt;/code&gt; object allowing access to command line arguments, standard input/output, etc. The &lt;code&gt;Main&lt;/code&gt; actor can then create other actors or do whatever required for program execution.&lt;/p&gt;

&lt;h2&gt;Actors&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Actor_model&quot;&gt;Actors&lt;/a&gt; are the method of concurrency in Pony. An actor is like a normal object in that it can have state and methods. It can also have &lt;code&gt;behaviours&lt;/code&gt;. A &lt;code&gt;behaviour&lt;/code&gt; is a method that when called is executed asynchronously. It returns immediately and is queued to be run on an actor local queue. When the actor has nothing to do (not running an existing method or behaviour) it will pop the oldest queued behaviour and run that. An actor can only run one behaviour at a time - this means there needs to be no locking within the behaviour since access to actor local state is serialized. For this reason it&#39;s useful to think of an actor as a unit of sequential execution. Parallelism is achieved by utilising multiple actors.&lt;/p&gt;

&lt;p&gt;To compare the difference between a standard object and an actor I&#39;ll use the following program:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Logger
  let _env: Env
  let _prefix: String

  new create(env: Env, prefix: String) =&amp;gt;
    _env = env
    _prefix = prefix

  fun log(msg: String, delay: U32) =&amp;gt;
    @sleep[I32](delay)
    _env.out.print(_prefix + &quot;: &quot; + msg)

actor Main
  new create(env: Env) =&amp;gt;
    let l1 = Logger.create(env, &quot;logger 1&quot;)
    let l2 = Logger.create(env, &quot;logger 2&quot;)

    l1.log(&quot;one&quot;, 3)
    l2.log(&quot;two&quot;, 1)
    l1.log(&quot;three&quot;, 3)
    l2.log(&quot;four&quot;, 1)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This creates a class called &lt;code&gt;Logger&lt;/code&gt; that on construction takes an &lt;code&gt;Env&lt;/code&gt; to use to output log messages and a string &lt;code&gt;prefix&lt;/code&gt; to prepend to a message. It has a &lt;code&gt;log&lt;/code&gt; method that will log a message to standard output after sleeping for a number of seconds given by &lt;code&gt;delay&lt;/code&gt;. The unusual syntax for the &lt;code&gt;sleep&lt;/code&gt; call is the syntax for calling the &lt;a href=&quot;http://linux.die.net/man/3/sleep&quot;&gt;sleep&lt;/a&gt; C function using the Pony FFI. I&#39;ll cover this later.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Main&lt;/code&gt; actor creates two loggers and logs twice to each one with a different delay. As a standard object using &lt;code&gt;class&lt;/code&gt; is not asynchronous running this will result in a delay of three seconds, outputting the first log line, a delay of one second, outputting the second line, a delay of three seconds, outputting the third line and finally a delay of one second, outputting the final line. Everything happens on the single Pony thread that runs the &lt;code&gt;Main&lt;/code&gt; actor&#39;s create constructor. Pony runs this on a single operating system thread. Total elapsed time is the sum of the delays.&lt;/p&gt;

&lt;p&gt;Compile and build with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ mkdir clogger
$ cat &amp;gt;clogger/main.pony
  ..contents of program above...
$ ponyc clogger
$ time ./clogger1
  logger 1: one
  logger 2: two
  logger 1: three
  logger 2: four

  real  0m8.093s
  user  0m0.116s
  sys   0m0.132s
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Changing the &lt;code&gt;Logger&lt;/code&gt; class to an actor and making the &lt;code&gt;log&lt;/code&gt; method a behaviour will result in the logging happen asynchronously. The changes are:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Logger
  let _env: Env
  let _prefix: String

  new create(env: Env, prefix: String) =&amp;gt;
    _env = env
    _prefix = prefix

  be log(msg: String, delay: U32) =&amp;gt;
    @sleep[I32](delay)
    _env.out.print(_prefix + &quot;: &quot; + msg)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Nothing else in the program changes. I&#39;ve just changed &lt;code&gt;class&lt;/code&gt; to &lt;code&gt;actor&lt;/code&gt; and &lt;code&gt;fun&lt;/code&gt; to &lt;code&gt;be&lt;/code&gt;. Now when the &lt;code&gt;Main&lt;/code&gt; actor calls &lt;code&gt;log&lt;/code&gt; it will add the behaviour call to the actor&#39;s queue and immediately return. Each &lt;code&gt;Logger&lt;/code&gt; instance is running in its own Pony thread and will be mapped to an operating system thread if possible. On a multiple core machine this should mean each actor&#39;s behaviour is running on a different core.&lt;/p&gt;

&lt;p&gt;Compiling and running gives:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ mkdir alogger
$ cat &amp;gt;alogger/main.pony
  ..contents of program above...
$ ponyc alogger
$ time ./alogger1
  logger 2: two
  logger 2: four
  logger 1: one
  logger 1: three

  real  0m6.113s
  user  0m0.164s
  sys   0m0.084s
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice that the total elapsed time is now six seconds. This is the sum of the delays in the calls to &lt;code&gt;log&lt;/code&gt; in the first &lt;code&gt;Logger&lt;/code&gt; instance. The second instance is running on another OS thread so executes in parallel. Each &lt;code&gt;log&lt;/code&gt; call immediately returns and is queued to run. The delays on the second &lt;code&gt;Logger&lt;/code&gt; instance are shorter so they appear first. They two &lt;code&gt;log&lt;/code&gt; calls on the second &lt;code&gt;Logger&lt;/code&gt; run sequentially as behaviours on a single actor instance are executed in order. The &lt;code&gt;log&lt;/code&gt; calls for the first &lt;code&gt;Logger&lt;/code&gt; instance run after their delay, again sequentially for the calls within that actor.&lt;/p&gt;

&lt;h2&gt;Capabilities&lt;/h2&gt;

&lt;p&gt;Pony uses reference capabilities to allow safe concurrent access to objects. In practice this means annotating types with a tag to indicate how &#39;sharable&#39; an object is. For data to be passed to another actor it must be safe for that actor to use without data races. Reference capabilities allow enforcing this at compile time. There are defaults for most types so you don&#39;t need to annotate everything. Notice that none of the examples I&#39;ve done so far use any capability annotations. I&#39;ll go through a few examples here but won&#39;t be exhaustive. The &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/reference-capabilities/&quot;&gt;Pony tutorial&lt;/a&gt; has coverage of the combinations and defaults.&lt;/p&gt;

&lt;h3&gt;val and ref&lt;/h3&gt;

&lt;p&gt;A &lt;code&gt;val&lt;/code&gt; capability is for value types. They are immutable and therefore anyone can read from them at any time. &lt;code&gt;val&lt;/code&gt; objects can be passed to actors and used concurrently. Primitives like &lt;code&gt;U32&lt;/code&gt; are &lt;code&gt;val&lt;/code&gt; by default. This is why none of the primitive arguments to behaviours in the previous examples needed annotation.&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;ref&lt;/code&gt; capability is for references to mutable data structures. They can be read from and written to and have multiple aliases to it. You can&#39;t share these with other actors as that would potentially cause data races. Classes are &lt;code&gt;ref&lt;/code&gt; by default.&lt;/p&gt;

&lt;p&gt;This is an example of passing a &lt;code&gt;val&lt;/code&gt; to another actor:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Doer
  be do1(n: U32) =&amp;gt;
    None

actor Main
  new create(env: Env) =&amp;gt;
    let a = Doer.create()
    let n: U32 = 5
    a.do1(n)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As &lt;code&gt;U32&lt;/code&gt; is a primitive it defaults to a &lt;code&gt;val&lt;/code&gt; reference capability. It is immutable and can be read by anyone at any time so this compiles without problem. This example fails to compile however:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo
  let n: U32 = 5

actor Doer
  be do1(n: Foo) =&amp;gt;
    None

actor Main
  new create(env: Env) =&amp;gt;
    let a = Doer.create()
    let b = Foo.create()
    a.do1(b)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The error is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;main.pony:5:13: this parameter must be sendable (iso, val or tag)
  be do1(n: Foo) =&amp;gt;
            ^
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;class&lt;/code&gt; defaults to the &lt;code&gt;ref&lt;/code&gt; capability which can be read, written and aliased. It can&#39;t be used to send to another actor as there&#39;s no guarantee that it won&#39;t be modifed by any other object holding a reference to it. The &lt;code&gt;iso&lt;/code&gt; and &lt;code&gt;tag&lt;/code&gt; capabilities mentioned in the error message are other capability types.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;iso&lt;/code&gt; is for single references to data structures that can be read and written too. The type system guarantees that only one reference exists to the object. It is short for &#39;isolated&#39;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;tag&lt;/code&gt; is for identification only. Objects of capability &lt;code&gt;tag&lt;/code&gt; cannot be read from or written too. They can only be used for object identity or, if they are an Actor, calling behaviours on them. Actors default to &lt;code&gt;tag&lt;/code&gt; capabilities. Calling behaviours is safe as behaviour running is serialized for the actor instance and they don&#39;t return data.&lt;/p&gt;

&lt;p&gt;To get the previous example to work we can force the &lt;code&gt;Foo&lt;/code&gt; object to be of type &lt;code&gt;val&lt;/code&gt; if it can be immutable:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo 
  let n: U32 = 5

actor Doer
  be do1(n: Foo val) =&amp;gt;
    None

actor Main
  new create(env: Env) =&amp;gt;
    let a = Doer.create()
    let b: Foo val = Foo.create()
    a.do1(b)
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;ref and iso&lt;/h3&gt;

&lt;p&gt;Let&#39;s modify the example so we can change the value of the &lt;code&gt;Foo&lt;/code&gt; object to demonstrate moving a mutable reference from one actor to another:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo
  var n: U32 = 5

  fun ref set(m: U32) =&amp;gt;
    n = m

  fun print(env: Env) =&amp;gt;
    env.out.print(n.string())

actor Doer
  be do1(env:Env, n: Foo iso) =&amp;gt;
    n.print(env)

actor Main
  new create(env: Env) =&amp;gt;
    let a = Doer.create()
    let b = Foo.create()
    a.do1(env, b)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this example the &lt;code&gt;do1&lt;/code&gt; behaviour now requires an &lt;code&gt;iso&lt;/code&gt; reference capability. As mentioned previously, &lt;code&gt;iso&lt;/code&gt; means only one reference to the object exists therefore it is safe to read and write. But where we create the instance of &lt;code&gt;Foo&lt;/code&gt; we have a reference to it in the variable &lt;code&gt;b&lt;/code&gt;. Passing it as an argument to &lt;code&gt;do1&lt;/code&gt; effectively aliases it. The compile time error is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;main.pony:18:16: argument not a subtype of parameter
    a.do1(env, b)
               ^
main.pony:11:19: parameter type: Foo iso
  be do1(env:Env, n: Foo iso) =&amp;gt;

main.pony:18:16: argument type: Foo iso!
a.do1(env, b)
           ^
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This error states that &lt;code&gt;do1&lt;/code&gt; requires a &lt;code&gt;Foo iso&lt;/code&gt; parameter whereas it is being passed a &lt;code&gt;Foo iso!&lt;/code&gt;. The &lt;code&gt;!&lt;/code&gt; at the end means that it is an alias to another variable. Even though &lt;code&gt;class&lt;/code&gt; objects are &lt;code&gt;ref&lt;/code&gt; by default, Pony has inferred the capability for &lt;code&gt;b&lt;/code&gt; as &lt;code&gt;iso&lt;/code&gt; as we didn&#39;t declare a type for &lt;code&gt;b&lt;/code&gt; and we are passing it to a function that wants an &lt;code&gt;iso&lt;/code&gt;. However as it has an alias it can&#39;t be used as an iso therefore it&#39;s an error.&lt;/p&gt;

&lt;p&gt;One way of avoiding the aliasing is to pass the result of the &lt;code&gt;create&lt;/code&gt; call directly:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  new create(env: Env) =&amp;gt;
    let a = Doer.create()
    a.do1(env, Foo.create())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There is no alias here so it compiles fine.&lt;/p&gt;

&lt;p&gt;If we do want to have an initial reference to it, say to set a value first, we can tell the type system that we are consuming the existing reference and will no longer use it. This is what the &lt;code&gt;consume&lt;/code&gt; keyword is for:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  new create(env: Env) =&amp;gt;
    let a = Doer.create()
    let b = Foo.create()
    b.set(42)
    a.do1(env, consume b)
    // b.set(0)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This now compiles. Uncommenting out the use of &lt;code&gt;b&lt;/code&gt; after the &lt;code&gt;do1&lt;/code&gt; call will be a compile error as we&#39;ve consumed &lt;code&gt;b&lt;/code&gt; and it no longer exists. In this case the error owuld be:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;main.pony:20:5: can&#39;t use a consumed local in an expression
    b.set(0)
    ^
main.pony:20:6: invalid left hand side
    b.set(0)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;consume&lt;/code&gt; is more often used for passing &lt;code&gt;iso&lt;/code&gt; objects around. To pass it to another object you need to consume the existing reference to it. This becomes problematic if you are consuming a field of an object. Modifying the example so that the &lt;code&gt;Foo&lt;/code&gt; is stored as a field of &lt;code&gt;Main&lt;/code&gt; shows the problem:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;actor Main
  var b: Foo iso = Foo.create()

  new create(env: Env) =&amp;gt;
    let a = Doer.create()
    b.set(42)
    a.do1(env, consume b)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The error is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;main.pony:20:16: consume must take &#39;this&#39;, a local, or a parameter
    a.do1(env, consume b)
               ^
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;b&lt;/code&gt; can&#39;t be consumed as it&#39;s a field of &lt;code&gt;Main&lt;/code&gt;. It can&#39;t be left consumed - it must have a valid &lt;code&gt;Foo iso&lt;/code&gt; object stored in it. In Pony assignment returns the old value of the variable being assigned too. This allows assigning a new value to the field and returning the old value in one operation and avoiding leaving the field in an invalid state:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;new create(env: Env) =&amp;gt;
  let a = Doer.create()
  b.set(42)
  a.do1(env, b = Foo.create())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;b&lt;/code&gt; gets a new value of a new instance of &lt;code&gt;Foo&lt;/code&gt; and &lt;code&gt;do1&lt;/code&gt; gets passed the old value.&lt;/p&gt;

&lt;p&gt;There&#39;s a lot more to capabilities and the &lt;a href=&quot;http://tutorial.ponylang.org/capabilities/reference-capabilities/&quot;&gt;capabilities section of the tutorial&lt;/a&gt; covers a lot. Although there are sane defaults it feels like that &#39;capability tutorials&#39; will be the Pony equivalent of &#39;Monad tutorials&#39; in other languages for a while. When I first was learning &lt;a href=&quot;http://bluishcoder.co.nz/tags/ats/&quot;&gt;ATS&lt;/a&gt; I spent a lot of time floundering with function annotations to get things to compile, trying random changes, until I learnt how it worked. I&#39;m probably at that stage with capabilities at the moment and I hope it becomes clearer as I write more Pony programs.&lt;/p&gt;

&lt;h2&gt;Pattern Matching&lt;/h2&gt;

&lt;p&gt;Pony has many of the concepts of most modern functional programming languages. Matching on values is allowed:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let x: U32 = 2
match x
  | 1 =&amp;gt; &quot;one&quot;
  | 2 =&amp;gt; &quot;two&quot;
else
  &quot;3&quot;
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Union types with capturing:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;type Data is (U32 | String | None)
....
match x
| None =&amp;gt; &quot;None&quot;
| 1 =&amp;gt; &quot;one&quot;
| let u: U32 =&amp;gt; &quot;A number that is not one: &quot; + u.string()
| let s: String =&amp;gt; &quot;A string: &quot; + s
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Enumerations are a bit verbose in that you have to use &lt;code&gt;primitive&lt;/code&gt; to define each variant of the enumeration first:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;primitive Red
primitive Blue
primitive Green

type Colour is (Red | Blue | Green)
...
let x: Colour = Red
match x
| Red =&amp;gt; &quot;Red&quot;
| Blue =&amp;gt; &quot;Blue&quot;
| Green =&amp;gt; &quot;Green&quot;
end
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;C FFI&lt;/h2&gt;

&lt;p&gt;Pony has an easy to use C FFI. I showed an example of this previously:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@sleep[I32](delay)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;@&lt;/code&gt; signifies that this is a C FFI function call. The type in the backets is the return type of the C function call. The types of the arguments must match what the actual C function expects. Errors here will crash the program. Pony allows specifying the type of an FFI function in advance so argument types are checked. For &lt;code&gt;sleep&lt;/code&gt; it would be:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;use @sleep[I32](n: U32)
...
@sleep(10)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that it&#39;s no longer necessary to specify the return type at the call point as it&#39;s already been defined in the declaration.&lt;/p&gt;

&lt;p&gt;If the C function is part of a library already linked into the Pony executable then there is no need use a statement to define the library file to link against. &lt;code&gt;sleep&lt;/code&gt; is part of &lt;code&gt;libc&lt;/code&gt; so it isn&#39;t needed. In the cases where you need to link against a specific library then the &lt;code&gt;use&lt;/code&gt; statement is used in this manner:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;use &quot;lib:foo&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;addressof&lt;/code&gt; keyword is used to pass pointers to C code. It can be used for passing out parameters of primitives types:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var n: U32 = 0
@dosomething[None](addressof n)
env.out.print(&quot;Result: &quot; + n.string())
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Callbacks&lt;/h3&gt;

&lt;p&gt;The FFI allows passing Pony functions to C for the C code to later call back. The syntax for this looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let foo = Foo.create()
@callmeback[None](addressof foo.method, foo)
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Calling C code example&lt;/h3&gt;

&lt;p&gt;A working example for the following C function in a &lt;code&gt;cbffi.c&lt;/code&gt; file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;void do_callback(void (*func)(void* this, char* s), void* this) {
    func(this, &quot;hello world&quot;);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The Pony code to use this is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;use &quot;lib:cbffi&quot;

class Foo
  let prefix: String
  let env: Env

  new create(e: Env, p: String) =&amp;gt;
    prefix = p
    env = e

  fun display(msg: Pointer[U8]) =&amp;gt;
    env.out.print(prefix + &quot;:&quot; + String.copy_cstring(msg))

actor Main
  new create(env: Env) =&amp;gt;
    let foo = Foo.create(env, &quot;From Pony&quot;)
    @do_callback[None](addressof foo.display, foo)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that the &lt;code&gt;display&lt;/code&gt; function takes a &lt;code&gt;Pointer[U8]&lt;/code&gt; as an argument. &lt;code&gt;Pointer[U8]&lt;/code&gt; is a generic type with &lt;code&gt;U8&lt;/code&gt; being the parameter. In this case it is the C string that the C function passes. Pony &lt;code&gt;String&lt;/code&gt; types are an object with fields so C doesn&#39;t pass it directly. The &lt;code&gt;String&lt;/code&gt; type has a couple of constructor functions that take &lt;code&gt;Pointer[U8]&lt;/code&gt; as input and return a Pony &lt;code&gt;String&lt;/code&gt; - the one used here, &lt;code&gt;copy_cstring&lt;/code&gt;, makes a copy of the C string passed in.&lt;/p&gt;

&lt;p&gt;Compile with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ mkdir cb
$ cat &amp;gt;cb/main.pony
  ...Pony code...
$ cat &amp;gt;cb/cbffi.c
  ...C code...
$ gcc -fPIC -shared -o libcbffi.so cb/cbffi.c
$ LIBRARY_PATH=. ponyc cb
$ LD_LIBRARY_PATH=. ./cb1
  From Pony:hello world
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here &lt;code&gt;LIBRARY_PATH&lt;/code&gt; is set to find the shared library during compiling and linking. To run the generated executable &lt;code&gt;LD_LIBRARY_PATH&lt;/code&gt; is used to find the shared library at runtime.&lt;/p&gt;

&lt;p&gt;It&#39;s also possible to link against static C libraries:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ rm libcbffi.so
$ gcc -c -o libcbffi.o cb/cbffi.c
$ ar -q libcbffi.a libcbffi.o
$ LIBRARY_PATH=. ponyc cb
$ ./cb1
  From Pony:hello world
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Things to look out for&lt;/h2&gt;

&lt;p&gt;While writing Pony code I came across a couple of things to be aware of. Each actor has their own garbage collector but it runs only between behaviour calls. If a behaviour runs for a long time, never calling another actor behaviour, then it can be a while before garbage is collected. An example of where this can happen is a simple &lt;code&gt;Main&lt;/code&gt; actor where everything is done in the default constructor and never calls another actor. Benchmarks can be an example here. No GC will occur and you can get an OOM (Out of Memory) situation.&lt;/p&gt;

&lt;p&gt;Another is that there is no backpressure handling for behaviour calls on an actor. The message queues are unbounded so if a producer sends messages to an actor at a faster rate than it processes them then it will eventually OOM. This can occur if you have the message sender tied to an external process. For example a TCP listener that uses sockets and translates the data to a message to an actor. If the external users of the TCP interface (a webserver for example) are sending data faster than the actor handling the messages then OOM will occur. Slides from the Pony developers indicates that backpressure is on their radar to look at.&lt;/p&gt;

&lt;p&gt;As usual with a new programming language there is a lack of libraries and library documentation. Expect to look through the Pony source code to find examples of how to do things. The &lt;a href=&quot;http://tutorial.ponylang.org/&quot;&gt;tutorial&lt;/a&gt; is great though - even though parts are incomplete - and is &lt;a href=&quot;https://github.com/CausalityLtd/pony-tutorial&quot;&gt;on github&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;There is a &lt;code&gt;--docs&lt;/code&gt; command line argument that can be used to parse docstrings in Pony libraries and produce documentation in markdown format. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ cd packages
$ ponyc --docs collections
$ ls collections-docs/
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;This has only been a quick overview of some features of Pony. There&#39;s more too it. Some places to get more Pony information:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://ponylang.org/&quot;&gt;Pony website&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://tutorial.ponylang.org/&quot;&gt;Tutorial&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.reddit.com/r/ponylang&quot;&gt;/r/ponylang&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;#ponylang&lt;/code&gt; on irc.freenode.net&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://lists.ponylang.org/listinfo/ponydev&quot;&gt;Mailing List&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://sandbox.ponylang.org/&quot;&gt;Online Sandbox&lt;/a&gt; to try Pony in a browser&lt;/li&gt;
&lt;/ul&gt;

</content>
 </entry>
 
 
</feed>
