<?xml version="1.0"?>
<rss version="2.0">
  <channel>
    <title>Bluishcoder</title>
    <link>http://bluishcoder.co.nz/"</link>
    <description>Bluishcoder</description>
    <pubDate>2018-01-10T15:35:12+13:00</pubDate>
    <webMaster>admin@bluishcoder.co.nz</webMaster>
 
 <item>
   <title>Capturing program invariants in ATS</title>
   <link>http://bluishcoder.co.nz/2018/01/10/capturing-program-invariants-in-ats.html</link>
   <pubDate>2018-01-10T17:00:00+13:00</pubDate>
   <guid>http://bluishcoder.co.nz/2018/01/10/capturing-program-invariants-in-ats</guid>
   <description>&lt;p&gt;I&#39;ve been reading the book &lt;a href=&quot;https://www.cambridge.org/core/books/building-high-integrity-applications-with-spark/F213D9867D2E271F5FF3EDA765D48E95&quot;&gt;Building High Integrity Applications with Spark&lt;/a&gt; to learn more about the &lt;a href=&quot;https://en.wikipedia.org/wiki/SPARK_(programming_language)&quot;&gt;SPARK/Ada&lt;/a&gt; language for formal verification. It&#39;s a great book that goes through lots of examples of how to do proofs in Spark. I wrote a &lt;a href=&quot;http://bluishcoder.co.nz/2017/04/27/installing-gnat-and-spark-gpl-editions.html&quot;&gt;post on Spark/Ada&lt;/a&gt; earlier this year and tried some of the examples in the GNAT edition.&lt;/p&gt;

&lt;p&gt;While working through the book I oftened compared how I&#39;d implement similar examples in &lt;a href=&quot;http://www.ats-lang.org/&quot;&gt;ATS&lt;/a&gt;. I&#39;ll go through one small example in this post and show how the dependent types of ATS allow capturing the invariants of a function and check them at type checking time to prove the absence of a particular class of runtime errors.&lt;/p&gt;

&lt;p&gt;The example I&#39;m looking at from the book is from the &lt;code&gt;Loop Invariants&lt;/code&gt; section, which aims to prove things about iterative loops in Ada. The procedure &lt;code&gt;Copy_Into&lt;/code&gt; copies characters from a &lt;code&gt;String&lt;/code&gt; into a &lt;code&gt;Buffer&lt;/code&gt; object that has a maximum capacity. If the source string is too short then the buffer is padded with spaces. The Spark/Ada code from the book is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;procedure Copy_Into(Buffer: out Buffer_Type; Source: in String) is
  Characters_To_Copy : Buffer_Count_type := Maximum_Buffer_Size;
begin
  Buffer := (others =&amp;gt; &#39; &#39;);
  if Source&#39;Length &amp;lt; Characters_To_Copy then
    Characters_To_Copy := Source`Length;
  end if;
  for Index in Buffer_Count_Type range 1 .. Characters_To_Copy loop
    pragma Loop_Invariant (Characters_To_Copy &amp;lt;= Source&#39;Length and
                           Characters_To_Copy = Characters_To_Copy&#39;Loop_Entry);
    Buffer(Index) := Source(Source&#39;First + (Index - 1));
  end loop;
end Copy_Into;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is quite readable for anyone familiar with imperative languages. The number of characters to copy is initially set to the maximum buffer size, then changed to the length of the string if it is less than that. The buffer is set to contain the initial characters &#39; &#39;. The buffer is 1-indexed and during the loop the characters from the string are copied to it.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Loop_Invariant&lt;/code&gt; pragma is a Spark statement that tells the checker that certain invariants should be true. The invariant used here is that the number of characters to copy is always less than or equal to the length of the string and does not change within the loop. Given this loop invariant Spark can assert that the indexing into the &lt;code&gt;Source&lt;/code&gt; string cannot exceed the bounds of the string. Spark is able to reason itself that &lt;code&gt;Buffer&lt;/code&gt; does not get indexed out of bounds as the loop ranges up to &lt;code&gt;Characters_To_Copy&lt;/code&gt; which is capped at &lt;code&gt;Maximum_Buffer_Size&lt;/code&gt;. I&#39;m not sure why this doesn&#39;t need a loop invariant but the book notes that the Spark tools improve over time at what invariants they can compute automatically. As an example, the second invariant check above for &lt;code&gt;Characters_To_Copy&#39;Loop_Entry&lt;/code&gt; isn&#39;t needed for newer versions of Spark but is kept to enable checking on older toolchains.&lt;/p&gt;

&lt;p&gt;For ATS I modeled the &lt;code&gt;Buffer&lt;/code&gt; type as an array of characters:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;stadef s_max_buffer_size: int = 128
typedef Buffer0 = @[char?][s_max_buffer_size]
typedef Buffer1 = @[char][s_max_buffer_size]
val max_buffer_size: size_t s_max_buffer_size = i2sz(128)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In ATS, &lt;code&gt;@[char][128]&lt;/code&gt; represents an array of contiguous &#39;char&#39; types in memory, where those char&#39;s are initialized to value. The &lt;code&gt;@[char?][128]&lt;/code&gt; represents an array of unitialized char&#39;s. It would be a type error to use an element of that array before initializing it. The &#39;0&#39; and &#39;1&#39; suffixes to the &#39;Buffer&#39; name is an ATS idiom for uninitialized and initialized data respectively.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;stadef&lt;/code&gt; keyword creates a constant in the &#39;statics&#39; system of ATS. That is a constant in the language of types, vs a constant in the language of values where runtime level programming is done. For this post I have prefixed variables in the &#39;statics&#39; system with &lt;code&gt;s_&lt;/code&gt; to make it clearer where they can be used.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;max_buffer_size&lt;/code&gt; creates a constant in the &#39;dynamics&#39; part of ATS, in the language of values, of type &quot;&lt;code&gt;size_t max_buffer_size&lt;/code&gt;&quot;. &lt;code&gt;size_t&lt;/code&gt; is the type for indexes into arrays and &lt;code&gt;size_t 128&lt;/code&gt; is a dependent type representing a type where only a single value matches the type - &lt;code&gt;128&lt;/code&gt; in this instance. The &lt;code&gt;i2sz&lt;/code&gt; function converts an integer to a &lt;code&gt;size_t&lt;/code&gt;. So in this case we&#39;ve created a &lt;code&gt;max_buffer_size&lt;/code&gt; constant that can only ever be the same value as the &lt;code&gt;s_max_buffer_size&lt;/code&gt; type level constant.&lt;/p&gt;

&lt;p&gt;The ATS equivalent of &lt;code&gt;copy_into&lt;/code&gt; looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun copy_into {n:nat}
       (buffer: &amp;amp;Buffer0 &amp;gt;&amp;gt; Buffer1, source: string n): void = let
  val () = array_initize_elt(buffer, max_buffer_size, &#39; &#39;)
  val len = string1_length(source)
  stadef s_tocopy = min(s_max_buffer_size, n)
  val tocopy: size_t s_tocopy = min(max_buffer_size, len)
  fun loop {m:nat | m &amp;lt; s_tocopy } .&amp;lt;s_tocopy - m&amp;gt;.
        (buffer: &amp;amp;Buffer1, m: size_t m): void = let
    val () = buffer[m] := source[m]
  in
    if m &amp;lt; tocopy - 1 then loop(buffer, m+1)
  end
in
  if len &amp;gt; 0 then
    loop(buffer, i2sz(0))
end 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Starting with the function declaration:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun copy_into {n:nat}
       (buffer: &amp;amp;Buffer0 &amp;gt;&amp;gt; Buffer1, source: string n): void
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The items between the curly brackets, &lt;code&gt;{...}&lt;/code&gt;, are universal variables used for setting constraints on the function arguments. Between the round brackets, &lt;code&gt;(...)&lt;/code&gt;, are the function arguments. The return type is &lt;code&gt;void&lt;/code&gt;. The function takes two arguments, &lt;code&gt;buffer&lt;/code&gt; and &lt;code&gt;source&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;buffer&lt;/code&gt; is a reference type, represented by the &lt;code&gt;&amp;amp;&lt;/code&gt; in the type. This is similar to a reference argument in C++ or a pointer argument in C. It allows modification of the argument by the function. The &lt;code&gt;Buffer0 &amp;gt;&amp;gt; Buffer1&lt;/code&gt; means on entry to the function the type is &lt;code&gt;Buffer0&lt;/code&gt;, the uninitialized &lt;code&gt;char&lt;/code&gt; array described earlier, and on exit it will be a &lt;code&gt;Buffer1&lt;/code&gt;, an initialized char array. if the body of the function fails to initialize the elements of the array it will be a type error.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;source&lt;/code&gt; argument is a &lt;code&gt;string n&lt;/code&gt;, where &lt;code&gt;n&lt;/code&gt; is a type index for the length of the string. By using a dependently typed string here we can use it later in the function body to set some invariants.&lt;/p&gt;

&lt;p&gt;In the body of the function the call to &lt;code&gt;array_initize_elt&lt;/code&gt; sets each element of the array to the space character. This also has the effect of changing the type stored in the array from &lt;code&gt;char?&lt;/code&gt; to &lt;code&gt;char&lt;/code&gt;, and the array is now a valid &lt;code&gt;Buffer1&lt;/code&gt;. This matches the type change specified in the function declaration for the &lt;code&gt;buffer&lt;/code&gt; argument.&lt;/p&gt;

&lt;p&gt;The next three lines compute the number of characters to copy:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;val len = string1_length(source)
stadef s_tocopy = min(s_max_buffer_size, n)
val tocopy: size_t s_tocopy = min(max_buffer_size, len)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The length of the string is obtained. The &lt;code&gt;string1_&lt;/code&gt; prefix to function names is an idiom to show that they operate on dependently typed strings. &lt;code&gt;string1_length&lt;/code&gt; will return the string length. It returns a dependently typed &lt;code&gt;size_t x&lt;/code&gt;, where &lt;code&gt;x&lt;/code&gt; is the length of the string. This means that calling &lt;code&gt;string_length&lt;/code&gt; not only returns the length of the string but it sets a constraint such that the type index of the result is equal to the type index of the string passed in. Here is the declaration of &lt;code&gt;string1_length&lt;/code&gt; from the prelude (with some additional annotations removed):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun string1_length {n:int} (x: string n): size_t n
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The reuse of the &lt;code&gt;n&lt;/code&gt; in the argument and result type is what tells the compiler to set the constraint when it is called. This is important for the next two lines. These perform the same operation, once in the statics and once in the dynamics. That is, once at the type level and once at the runtime level. The &lt;code&gt;stadef&lt;/code&gt; sets a type level constant called &lt;code&gt;s_tocopy&lt;/code&gt; to be constrained to be the same as the minimum of the max buffer size and the type level string length, &lt;code&gt;n&lt;/code&gt;. The &lt;code&gt;val&lt;/code&gt; line sets the runtime variable to the same calculation but using the runtime length. These two lengths must much as a result of the call to &lt;code&gt;string1_length&lt;/code&gt; described earlier. The type of &lt;code&gt;tocopy&lt;/code&gt; ensures this by saying that it is the singleton type that can only be fulfilled by the value represented by &lt;code&gt;s_tocopy&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;ATS has looping constructs but it&#39;s idiomatic to use tail recursion instead of loops. It is also easier to create types for tail recursive functions than to type iterative loops in ATS. For this reason I&#39;ve converted the loop to a tail recursive function. When ATS compiles to C it converts tail recursive functions to a C loop so there is no danger of stack overflow. The looping function without dependent type annotations would be:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun loop (buffer: &amp;amp;Buffer1, m: size_t): void = let
  val () = buffer[m] := source[m]
in
  if m &amp;lt; tocopy - 1 then loop(buffer, m+1)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It takes a &lt;code&gt;buffer&lt;/code&gt; and an index, &lt;code&gt;m&lt;/code&gt;, as arguments and assigns to &lt;code&gt;buffer&lt;/code&gt; at that index the equivalent entry from the &lt;code&gt;source&lt;/code&gt; string. If it hasn&#39;t yet copied the number of characters needed to copy it tail recursively calls itself, increasing the index. The initial call is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;loop(buffer, i2sz(0))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;i2sz&lt;/code&gt; is needed to convert the integer number zero from an &lt;code&gt;int&lt;/code&gt; type to a &lt;code&gt;size_t&lt;/code&gt; type.&lt;/p&gt;

&lt;p&gt;The declaration for the &lt;code&gt;loop&lt;/code&gt; function contains the dependent type definitions that give invariants similar to the Spark example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun loop {m:nat | m &amp;lt; s_tocopy } .&amp;lt;s_tocopy - m&amp;gt;.
      (buffer: &amp;amp;Buffer1, m: size_t m): void = let
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Starting with the arguments, the &lt;code&gt;buffer&lt;/code&gt; is a &lt;code&gt;Buffer&lt;/code&gt; meaning it must be an initialized array. The index, &lt;code&gt;m&lt;/code&gt; is a dependently typed &lt;code&gt;size_t m&lt;/code&gt; where &lt;code&gt;m&lt;/code&gt; at the type level is constrained to be less than the number of characters to copy. This ensures that the indexing into the buffer and source string is never out of bounds due to the previous statements that set &lt;code&gt;s_tocopy&lt;/code&gt; to be the lesser of the maximum buffer size and the string size. &lt;code&gt;s_tocopy&lt;/code&gt; is needed here instead of &lt;code&gt;tocopy&lt;/code&gt; due to universal arguments being written in the language of the typesystem, not the runtime system.&lt;/p&gt;

&lt;p&gt;The body of the loop does the copying of the indexed character from the source string to the buffer and recursively calls itself with an incremented index if it hasn&#39;t copied the required number of characters.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  val () = buffer[m] := source[m]
in
  if m &amp;lt; tocopy - 1 then loop(buffer, m+1)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Due to the constraints set in the function declaration the buffer and source string indexes are checked at compile time to ensure they aren&#39;t out of bounds, and the recursive call to loop will fail typechecking if an out of bounds index is passed as an argument.&lt;/p&gt;

&lt;p&gt;One issue with recursive functions is that they could loop forever if the termination condition check is incorrect, or the variables being used in that check don&#39;t explicitly increase or decrease. In this case the index must increase to eventually reach the value for the termination check.&lt;/p&gt;

&lt;p&gt;ATS resolves this by allowing &lt;a href=&quot;http://ats-lang.sourceforge.net/DOCUMENT/INT2PROGINATS/HTML/x2500.html&quot;&gt;termination metrics&lt;/a&gt; to be added to the function. This is the part of the function declaration that is bracketed by &lt;code&gt;.&amp;lt; ... &amp;gt;.&lt;/code&gt; markers. The expression inside these markers is expected to be in the &#39;statics&#39; constraint language and evaluate to a tuple of natural numbers that the compiler needs to prove are lexicographically decreasing in value. The &lt;code&gt;loop&lt;/code&gt; index counts up so this needs to be converted to a decreasing value:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;.&amp;lt;s_tocopy - m&amp;gt;.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is done by taking the static constant of the number of characters to copy and subtracting the index value. The compiler proves that each recursive call in the body of the function results in something strictly less than the previous call. With the termination metric added it statically proves that the recursive function terminates.&lt;/p&gt;

&lt;p&gt;The program can be run and tested with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

stadef s_max_buffer_size: int = 128
typedef Buffer0 = @[char?][s_max_buffer_size]
typedef Buffer1 = @[char][s_max_buffer_size]
val max_buffer_size: size_t s_max_buffer_size = i2sz(128)

fun copy_into {n:nat}
    (buffer: &amp;amp;Buffer0 &amp;gt;&amp;gt; Buffer1, source: string n): void = let
  val () = array_initize_elt(buffer, max_buffer_size, &#39; &#39;)
  val len = string1_length(source)
  stadef s_tocopy = min(s_max_buffer_size, n)
  val tocopy: size_t s_tocopy = min(max_buffer_size, len)
  fun loop {m:nat | m &amp;lt; s_tocopy } .&amp;lt;s_tocopy - m&amp;gt;.
        (buffer: &amp;amp;Buffer1, m: size_t m): void = let
    val () = buffer[m] := source[m]
  in
    if m &amp;lt; tocopy - 1  then loop(buffer, m+1)
  end
in
  if len &amp;gt; 0 then
    loop(buffer, i2sz(0))
end 

implement main0() = let
  var  b = @[char?][max_buffer_size]()
  val () = copy_into(b, &quot;hello world&quot;)
  fun print_buffer {n:nat | n &amp;lt; s_max_buffer_size}
                   .&amp;lt;s_max_buffer_size - n&amp;gt;.
       (buffer: &amp;amp;Buffer1, n: size_t n):void = let
    val () = if n = 0 then print!(&quot;[&quot;)
    val () = print!(buffer[n])
    val () = if n = max_buffer_size - 1 then print!(&quot;]&quot;)
  in
    if n &amp;lt; 127 then print_buffer(buffer, n + 1)
  end
  val () = print_buffer(b, i2sz(0))
in
  ()
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This example creates the array as a stack allocated object in the line:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var  b = @[char?][max_buffer_size]()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Being stack allocated the memory will be deallocated on exit of the scope it was defined in. It&#39;s also possible to create a heap allocated buffer and pass that to &lt;code&gt;copy_into&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;implement main0() = let
  val (pf_b , pf_gc| b) = array_ptr_alloc&amp;lt;char&amp;gt;(max_buffer_size)
  val () = copy_into(!b, &quot;hello world&quot;)
  fun print_buffer {n:nat | n &amp;lt; 128} .&amp;lt;128 - n&amp;gt;. (buffer: &amp;amp;(@[char][128]), n: int n):void = let
    val () = if n = 0 then print!(&quot;[&quot;)
    val () = print!(buffer[n])
    val () = if n = 127 then print!(&quot;]&quot;)
  in
    if n &amp;lt; 127 then print_buffer(buffer, n + 1)
  end
  val () = print_buffer(!b, 0)
  val () = array_ptr_free(pf_b, pf_gc | b)
in
  ()
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This explicitly allocates the memory for the array using &lt;code&gt;array_ptr_alloc&lt;/code&gt; and dereferences it in the &lt;code&gt;copy_into&lt;/code&gt; call using the &#39;&lt;code&gt;!b&lt;/code&gt;&#39; syntax. Note that this array is later free&#39;d using &lt;code&gt;array_ptr_free&lt;/code&gt;. Not calling that to free the memory would be a compile error.&lt;/p&gt;

&lt;p&gt;Although this is a simple function it demonstrates a number of safety features:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The destination buffer cannot indexed beyond its bounds.&lt;/li&gt;
&lt;li&gt;The source string cannot be indexed beyond its bounds.&lt;/li&gt;
&lt;li&gt;There can be no buffer overflow on writing to the destination buffer.&lt;/li&gt;
&lt;li&gt;There can be no uninitialized data in the buffer on function exit.&lt;/li&gt;
&lt;li&gt;The internal recursive call must terminate.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The book &lt;a href=&quot;https://www.cambridge.org/core/books/building-high-integrity-applications-with-spark/F213D9867D2E271F5FF3EDA765D48E95&quot;&gt;Building High Integrity Applications with Spark&lt;/a&gt; is a great book for learning Spark and also for learning about the sorts of proofs used in production applications using Spark/Ada. Apart from learning a bit about Spark it&#39;s also a good exercise to think about how similar safety checks can be implemented in your language of choice.&lt;/p&gt;
</description>
 </item>
 
 <item>
   <title>Writing basic proofs in ATS</title>
   <link>http://bluishcoder.co.nz/2018/01/03/writing-basic-proofs-in-ats.html</link>
   <pubDate>2018-01-03T17:00:00+13:00</pubDate>
   <guid>http://bluishcoder.co.nz/2018/01/03/writing-basic-proofs-in-ats</guid>
   <description>&lt;p&gt;This post covers using the latest version of ATS, &lt;a href=&quot;http://www.ats-lang.org/&quot;&gt;ATS 2&lt;/a&gt;, and goes through proving some basic algorithms. I&#39;ve written a couple of posts before on using proofs in ATS 1:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://bluishcoder.co.nz/2013/07/01/constructing-proofs-with-dataprop-in-ats.html&quot;&gt;Constructing Proofs with dataprop in ATS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://bluishcoder.co.nz/2012/10/04/implementing-a-stack-with-proofs-in-ats.html&quot;&gt;Implementing a stack with proofs in ATS&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;Writing proofs in ATS is complicated by the fact that the dependent types and proof component of the language does not use the full ATS language. It uses a restricted subset of the language. When implementing a proof for something like the factorial function you can&#39;t write factorial in the type system in the same way as you write it in the runtime system. Factorial in the latter is written using a function but in the former it needs to be encoded as relations in dataprop or dataview definitions.&lt;/p&gt;

&lt;p&gt;Recent additions to ATS 2 have simplified the task of writing some proofs by enabling the constraint checking of ATS to be done by an external SMT solver rather than the built in solver. External solvers like &lt;a href=&quot;https://github.com/Z3Prover/z3&quot;&gt;Z3&lt;/a&gt; have more features than the builtin solver and can solve constraints that the ATS solver cannot. For example, non-linear constraints are not solveable by ATS directly but are by using Z3 as the solver.&lt;/p&gt;

&lt;p&gt;In this post I&#39;ll start by describing how to write proofs using &lt;a href=&quot;https://groups.google.com/d/msg/ats-lang-users/YzU5FL2utdk/Cr583a3KuAEJ&quot;&gt;quantified constraints&lt;/a&gt;. This is the easiest proof writing method in ATS but requires Z3 as the solver. Next I&#39;ll continue with Z3 as the solver but describe how to write proofs using Z3 without quantified constraints. Finally I&#39;ll go through writing the proofs by encoding the algorithm as relations in dataprop. This approach progressively goes from an easy, less intrusive to the code method, to more the more difficult system requiring threading proofs throughout the code.&lt;/p&gt;

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

&lt;p&gt;&lt;a href=&quot;https://github.com/Z3Prover/z3&quot;&gt;Z3&lt;/a&gt; is the external solver used in the examples in this post. To install from the Z3 github on Linux:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ git clone https://github.com/Z3Prover/z3
$ cd z3
$ mkdir build
$ cd build
$ cmake -G &quot;Unix Makefiles&quot; -DCMAKE_BUILD_TYPE=Release ../
$ make &amp;amp;&amp;amp; sudo make install
&lt;/code&gt;&lt;/pre&gt;

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

&lt;p&gt;I used &lt;a href=&quot;http://www.ats-lang.org/Downloads.html&quot;&gt;ATS2-0.3.8&lt;/a&gt; for the examples in this post. There are various &lt;a href=&quot;https://github.com/ats-lang/ats-lang.github.io/tree/master/SCRIPT&quot;&gt;scripts for installing&lt;/a&gt; but to do install manually from the &lt;a href=&quot;https://github.com/githwxi/ATS-Postiats/&quot;&gt;git repository&lt;/a&gt; on an Ubuntu based system:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ sudo apt-get install build-essential libgmp-dev libgc-dev libjson-c-dev
$ git clone git://git.code.sf.net/p/ats2-lang/code ATS2
$ git clone https://github.com/githwxi/ATS-Postiats-contrib.git ATS2-contrib
$ export PATSHOME=`pwd`/ATS2
$ export PATSCONTRIB=`pwd`/ATS2-contrib
$ export PATH=$PATSHOME/bin:$PATH
$ (cd ATS2 &amp;amp;&amp;amp; ./configure &amp;amp;&amp;amp; make all)
$ (cd ATS2/contrib/ATS-extsolve &amp;amp;&amp;amp; make DATS_C)
$ (cd ATS2/contrib/ATS-extsolve-z3 &amp;amp;&amp;amp; make all &amp;amp;&amp;amp; mv -f patsolve_z3 $PATSHOME/bin)
$ (cd ATS2/contrib/ATS-extsolve-smt2 &amp;amp;&amp;amp; make all &amp;amp;&amp;amp; mv -f patsolve_smt2 $PATSHOME/bin)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Optionally you can install the various ATS backends for generating code in other languages:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ (cd ATS2/contrib/CATS-parsemit &amp;amp;&amp;amp; make all)
$ (cd ATS2/contrib/CATS-atscc2js &amp;amp;&amp;amp; make all &amp;amp;&amp;amp; mv -f bin/atscc2js $PATSHOME/bin)
$ (cd ATS2/contrib/CATS-atscc2php &amp;amp;&amp;amp; make all &amp;amp;&amp;amp; mv -f bin/atscc2php $PATSHOME/bin)
$ (cd ATS2/contrib/CATS-atscc2py3 &amp;amp;&amp;amp; make all &amp;amp;&amp;amp; mv -f bin/atscc2py3 $PATSHOME/bin)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Add &lt;code&gt;PATSHOME&lt;/code&gt;, &lt;code&gt;PATSCONTRIB&lt;/code&gt; and the change to &lt;code&gt;PATH&lt;/code&gt; to &lt;code&gt;.bash-rc&lt;/code&gt;, &lt;code&gt;.profile&lt;/code&gt;, or some other system file to have these environment variables populated when starting a new shell.&lt;/p&gt;

&lt;h2&gt;Dependent Types&lt;/h2&gt;

&lt;p&gt;A function to add numbers in ATS can be proven correct using dependent types by specifying the expected result using dependently typed integers:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun add_int {m,n:int} (a: int m, b: int n): int (m + n) = a + b
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This won&#39;t compile if the implementation does anything but result in the addition of the two integers. The constraint language used in dependent types is a restricted subset of the ATS language. I wrote a bit about this in my post on &lt;a href=&quot;http://bluishcoder.co.nz/2010/09/01/dependent-types-in-ats.html&quot;&gt;dependent types in ATS&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The following is an implementation of the factorial function without proofs:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

fun fact (n: int): int =
  if n &amp;gt; 0 then n * fact(n- 1) else 1

implement main0() = let
  val r = fact(5)
in
  println!(&quot;5! = &quot;, r)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Compile and run with something like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc -o f0 f0.dats
$ ./f0
5! = 120
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To prove that the implementation of factorial is correct we need to specify what factorial is in the constraint language of ATS. Ideally we&#39;d like to write something like the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun fact {n: nat} (n: int n): int (fact(n)) = ...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This would check that the body of the function implements something that matches the result of &lt;code&gt;fact&lt;/code&gt;. Unfortunately the restricted constraint language of ATS doesn&#39;t allow implementing or using arbitary functions in the type definition.&lt;/p&gt;

&lt;h2&gt;Using Z3 as an external solver&lt;/h2&gt;

&lt;p&gt;By default ATS solves constraints using its built in constraint solver. It has a mechanism for using an external solver, in this case Z3. To type check the previous factorial example using Z3 use the following commands:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patsopt -tc --constraint-export -d f0.dats |patsolve_z3 -i
Hello from [patsolve_z3]!
typechecking is finished successfully!
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the change to use &lt;code&gt;patsopt&lt;/code&gt; instead of &lt;code&gt;patscc&lt;/code&gt;. The &lt;code&gt;-tc&lt;/code&gt; flag does the type checking phase only. &lt;code&gt;--constraint-export&lt;/code&gt; results in the constraints to be exported to &lt;code&gt;stdout&lt;/code&gt; which is piped to &lt;code&gt;patsolve_z3&lt;/code&gt;. That command invokes Z3 and checks the constraint results.&lt;/p&gt;

&lt;p&gt;Since the resulting program may contain code that ATS can&#39;t typecheck itself, to actually build the final executable we invoke &lt;code&gt;patscc&lt;/code&gt; with a command line option to disable type checking. It&#39;s important that the checking has succeeded through the external solver before doing this!&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc --constraint-ignore -o f0 f0.dats
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Z3 and quantified constraints&lt;/h2&gt;

&lt;p&gt;Using Z3 with quantified constraints is a new feature of ATS and quite experimental. &lt;a href=&quot;https://groups.google.com/d/msg/ats-lang-users/YzU5FL2utdk/MWQdZYRbcHwJ&quot;&gt;Hongwei notes some issues&lt;/a&gt; due to different versions of Z3 that can cause problems. It is however an interesting approach to proofs with ATS so I include the process of using it here and hope it becomes more stable as it progresses.&lt;/p&gt;

&lt;p&gt;ATS provides the &lt;code&gt;stacst&lt;/code&gt; keyword to introduce a constant into the &#39;statics&#39; part of the type system. The &#39;statics&#39; is the restricted constraint language used when specifying types. There are some examples of &lt;code&gt;stacst&lt;/code&gt; usage in the prelude file &lt;a href=&quot;https://github.com/ats-lang/ATS-Postiats-release/blob/master/prelude/basics_pre.sats&quot;&gt;basics_pre.sats&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Using &lt;code&gt;stacst&lt;/code&gt; we can introduce a function in the statics system for factorial:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;stacst fact: int -&amp;gt; int
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the following code is valid:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun fact {n:nat} (n: int n): int (fact(n)) = ...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;ATS doesn&#39;t know about &lt;code&gt;fact&lt;/code&gt; in the statics system, it only knows it&#39;s a function that takes an &lt;code&gt;int&lt;/code&gt; and returns an &lt;code&gt;int&lt;/code&gt;. With Z3 as the external solver we can extend ATS&#39; constraint knowledge by adding assertions to the Z3 solver engine using &lt;code&gt;$static_assert&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;praxi fact_base(): [fact(0) == 1] void
praxi fact_ind {n:int | n &amp;gt;= 1} (): [fact(n) == n * fact(n-1)] void
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The keyword &lt;code&gt;praxi&lt;/code&gt; is used for defining axioms, whereas &lt;code&gt;prfun&lt;/code&gt; is used for proof functions that need an implementation. This is currently not checked by the compiler but may be at some future time. From a documentation perspective using &lt;code&gt;praxi&lt;/code&gt; shows no plan to actually prove the axiom.&lt;/p&gt;

&lt;p&gt;The two axioms here will add to the proof store the facts about the factorial function. The first, &lt;code&gt;fact_base&lt;/code&gt;, asserts that the factorial of zero is one. The second asserts that for all &lt;code&gt;n&lt;/code&gt;, where &lt;code&gt;n&lt;/code&gt; is greater than or equal to &lt;code&gt;1&lt;/code&gt;, that the factorial of &lt;code&gt;n&lt;/code&gt; is equivalent to &lt;code&gt;n * fact (n - 1)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To add these facts to Z3&#39;s knowledge, use &lt;code&gt;$solver_assert&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun fact {n:int | n &amp;gt;= 0} (n: int n): int (fact(n)) = let
  prval () = $solver_assert(fact_base)
  prval () = $solver_assert(fact_ind)
in
  if n = 0 then 1 else n * fact(n - 1)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This typechecks successfully. Changing the implementation to be incorrect results in a failed typecheck. Unfortunately, as is often the case with experimental code, sometimes an incorrect implementation will hang Z3 causing it to consume large amounts of memory
as noted earlier.&lt;/p&gt;

&lt;p&gt;The implementation of &lt;code&gt;fact&lt;/code&gt; here closely mirrors the specification. The following is a tail recursive implementation of &lt;code&gt;fact&lt;/code&gt; that is also proved correct to the specification:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

stacst fact: int -&amp;gt; int

extern praxi fact_base(): [fact(0) == 1] unit_p
extern praxi fact_ind{n:pos}(): [fact(n)==n*fact(n-1)] unit_p

fun fact {n:nat} (n: int n): int (fact(n)) = let
  prval () = $solver_assert(fact_base)
  prval () = $solver_assert(fact_ind)

  fun loop {n,r:nat} (n: int n, r: int r): int (fact(n) * r) =
    if n &amp;gt; 0 then loop (n - 1, n * r) else r
in
  loop (n, 1)
end

implement main0() = let
  val r = fact(5)  
in
  println!(&quot;5! = &quot;, r)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This was tested and built with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patsopt -tc --constraint-export -d f4.dats |patsolve_z3 -i
Hello from [patsolve_z3]!
typechecking is finished successfully!
$ patscc --constraint-ignore -o f4 f4.dats
./f4
5! = 120
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Z3 with threaded proofs&lt;/h2&gt;

&lt;p&gt;Another approach to using the external solver is not to add constraints to the Z3 store via &lt;code&gt;$solver_assert&lt;/code&gt; but instead call the axioms explicitly as proof functions threaded in the body of the function. This is &lt;code&gt;fact&lt;/code&gt; implemented in such a way:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;stacst fact: int -&amp;gt; int

extern praxi fact_base(): [fact(0) == 1] void
extern praxi fact_ind {n:int | n &amp;gt;= 1} (): [fact(n) == n * fact(n-1)] void

fun fact {n:nat} (n: int n): int (fact(n)) =
  if n &amp;gt; 0 then let
      prval () = fact_ind {n} ()
    in
      n * fact(n - 1)
    end
  else let
      prval () = fact_base()
     in
       1
     end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The code  is more verbose due to needing to embed the &lt;code&gt;prval&lt;/code&gt; statements in a &lt;code&gt;let&lt;/code&gt; block but it doesn&#39;t suffer the Z3 incompatibility that the quantified constraint example did. An incorrect implementation will give an error from Z3.&lt;/p&gt;

&lt;p&gt;The equivalent tail recursive version is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun fact {n:nat} (n: int n): int (fact(n)) = let
  fun loop {n,r:nat} (n: int n, r: int r): int (fact(n) * r) =
    if n &amp;gt; 0 then let
        prval () = fact_ind {n} ()
      in
        loop (n - 1, n * r)
      end
    else let
        prval () = fact_base()
      in
        r + 1
      end
in
  loop (n, 1)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Dataprops and Datatypes&lt;/h2&gt;

&lt;p&gt;It&#39;s still possible to write a verified version of factorial without using an external solver but the syntactic overhead is higher. The specification of &lt;code&gt;fact&lt;/code&gt; needs to be implemented as a relation using &lt;code&gt;dataprop&lt;/code&gt;. A &lt;code&gt;dataprop&lt;/code&gt; introduces a type for the proof system in much the same way as declaring a datatype in the runtime system of ATS. Proof objects constructed from this type exist only at proof checking time and are erased at runtime. They can be taken as proof arguments in functions or included in return values. Proof functions can also be written to use them.  In the &lt;a href=&quot;https://groups.google.com/d/msg/ats-lang-users/2C9sRsGP430/q3DKdpmPCgAJ&quot;&gt;words of Hongwei Xi&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;A prop is like a type; a value classified by a prop is often called a proof, which is dynamic but erased by the compiler. So while proofs are dynamic, there is no proof construction at run-time.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;For a comparison of the syntax of &lt;code&gt;dataprop&lt;/code&gt; and &lt;code&gt;datatype&lt;/code&gt;, here is a type for &quot;list of integers&quot; implement as both:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;dataprop prop_list =
 | prop_nil
 | prop_cons of (int, prop_list)

datatype list =
 | list_nil
 | list_cons of (int, list)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To specifiy &lt;code&gt;fact&lt;/code&gt; as a relation it is useful to see how it is implemented in a logic based progamming language like Prolog:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fact(0, 1).
fact(N, R) :-
    N &amp;gt; 0,
    N1 is N - 1,
    fact(N1, R1),
    R is R1 * N.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The equivalent as a &lt;code&gt;dataprop&lt;/code&gt; is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;dataprop FACT (int, int) =
  | FACTzero (0, 1)
  | {n,r1:int | n &amp;gt; 0} FACTsucc (n, r1 * n) of (FACT (n-1, r1))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;FACT(n,r)&lt;/code&gt; encodes the relation that &lt;code&gt;fact(n) = r&lt;/code&gt; where fact is defined as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;fact(0) = 1, and&lt;/li&gt;
&lt;li&gt;fact(n) where n &gt; 0 = n * fact(n - 1)&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The &lt;code&gt;dataprop&lt;/code&gt; creates a &lt;code&gt;FACT(int, int)&lt;/code&gt; prop with two constructors:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;FACTzero()&lt;/code&gt; which encodes the relation that &lt;code&gt;fact(0) = 1&lt;/code&gt;, and&lt;/li&gt;
&lt;li&gt;&lt;code&gt;FACTsucc(FACT(n-1, r1))&lt;/code&gt; which encodes the relation that &lt;code&gt;fact(n) = n * fact(n-1)&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The declaration of the &lt;code&gt;fact&lt;/code&gt; function uses this prop as a proof return value to enforce that the result must match this relation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun fact {n:nat} (n: int n): [r:int] (FACT (n, r) | int r) = ...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The return value there is a tuple, where the first element is a proof value (the left of the pipe symbol) and the second element is the factorial result. The existential variable &lt;code&gt;[r:int]&lt;/code&gt; is used to associate the returned value with the result of the &lt;code&gt;FACT&lt;/code&gt; relation and the universal variable, &lt;code&gt;{n:nat}&lt;/code&gt; is used to provide the first argument of the fact prop. Through unification the compiler checks that the relationships between the variables match.&lt;/p&gt;

&lt;p&gt;The implementation of the function is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun fact {n:nat} (n: int n): [r:int] (FACT (n, r) | int r) =
  if n &amp;gt; 0 then let
    val (pf1 | r1) = fact (n - 1)
    val r = n * r1
  in
    (FACTsucc (pf1) | r)
  end else begin
    (FACTzero () | 1)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that the result of the recursive call to &lt;code&gt;fact&lt;/code&gt; deconstructs the proof result into &lt;code&gt;pf1&lt;/code&gt; and the value into &lt;code&gt;r1&lt;/code&gt; and that proof is used in the result of the &lt;code&gt;FACTsucc&lt;/code&gt; constructor. Proofs are constructed like datatypes. For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;FACTsucc(FACTzero())&lt;/code&gt; is &lt;code&gt;fact(1)&lt;/code&gt; (the successor, or next factorial, from &lt;code&gt;fact(0)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;FACTsucc(FACTsucc(FACTzero()))&lt;/code&gt; is &lt;code&gt;fact(2)&lt;/code&gt;, etc.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;In this way it can be seen that a call to &lt;code&gt;fact(1)&lt;/code&gt; will hit the first branch of the &lt;code&gt;if&lt;/code&gt; condition which recursively calls &lt;code&gt;fact(0)&lt;/code&gt;. That hits the second branch of the conditional to return the prop &lt;code&gt;FACTzero()&lt;/code&gt;. On return back to the caller this is returned as  &lt;code&gt;FACTsucc(FACTzero())&lt;/code&gt;, giving our prop return type as &lt;code&gt;FACT(1, 1)&lt;/code&gt;. Plugging these values into the &lt;code&gt;n&lt;/code&gt; and &lt;code&gt;r&lt;/code&gt; of the return type for the &lt;code&gt;int r&lt;/code&gt; value means that value the function returns must be &lt;code&gt;1&lt;/code&gt; for the function to pass type checking.&lt;/p&gt;

&lt;p&gt;Although these proofs have syntactic overhead, the runtime overhead is nil. Proofs are erased after typechecking and only the factorial computation code remains. The full compilable program is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

dataprop FACT (int, int) =
  | FACTzero (0, 1)
  | {n,r1:int | n &amp;gt; 0} FACTsucc (n, r1 * n) of (FACT (n-1, r1))

fun fact {n:nat} (n: int n): [r:int] (FACT (n, r) | int r) =
  if n &amp;gt; 0 then let
    val (pf1 | r1) = fact (n - 1)
    val r = n * r1
  in
    (FACTsucc (pf1) | r)
  end else begin
    (FACTzero () | 1)
end

implement main0() = let
  val (pf | r) = fact(5)
in
  println!(&quot;5! = &quot;, r)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To compile and run:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc -o f8 f8.dats
$ ./f8
5! = 120
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A tail recursive implementation of &lt;code&gt;fact&lt;/code&gt; using dataprop that type checks is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fun fact {n:nat} (n: int n): [r:int] (FACT (n, r) | int r) = let
  fun loop {r:int}{i:nat | i &amp;lt;= n}
           (pf: FACT(i, r) | n: int n, r: int r, i: int i):
           [r1:int] (FACT(n, r1) | int (r1)) =
    if n - i &amp;gt; 0 then
        loop (FACTsucc(pf) | n, (i + 1) * r, i + 1)
    else (pf | r)
in
  loop (FACTzero() | n, 1, 0)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Because our dataprop is defined recursively based on successors to a previous factorial, and we can&#39;t get a predecessor, the tail recursive loop is structured to count up. This means we have to pass in the previous factorial prop as a proof argument, in &lt;code&gt;pf&lt;/code&gt;, and pass an index, &lt;code&gt;i&lt;/code&gt;, to be the current factorial being computed.&lt;/p&gt;

&lt;h2&gt;Fibonacci&lt;/h2&gt;

&lt;p&gt;Fibonacci is similar to factorial in the way the proofs are constructed. The quantified constraints versions is trivial:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;stacst fib: int -&amp;gt; int

extern praxi fib0(): [fib(0) == 0] unit_p
extern praxi fib1(): [fib(1) == 1] unit_p
extern praxi fib2 {n:nat|n &amp;gt;= 2} (): [fib(n) == fib(n-1) + fib(n-2)] unit_p

fun fib {n:int | n &amp;gt;= 0} (n: int n): int (fib(n)) = let
  prval () = $solver_assert(fib0)
  prval () = $solver_assert(fib1)
  prval () = $solver_assert(fib2)
in
  if n = 0 then 0
  else if n = 1 then 1
  else fib(n-1) + fib(n -2)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The threaded version using the external solver isn&#39;t much more verbose:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;stacst fib: int -&amp;gt; int

extern praxi fib0(): [fib(0) == 0] void
extern praxi fib1(): [fib(1) == 1] void
extern praxi fib2 {n:nat|n &amp;gt;= 2} (): [fib(n) == fib(n-1) + fib(n-2)] void

fun fib {n:int | n &amp;gt;= 0} (n: int n): int (fib(n)) =
  if n = 0 then let
      prval () = fib0()
    in
      0
    end
  else if n = 1 then let
      prval () = fib1()
    in
      1
    end
  else let
      prval () = fib2 {n} ()
    in
      fib(n-1) + fib(n -2)
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The dataprop version is quite readable too and has the advantage of not needing an external solver:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;dataprop FIB (int, int) =
  | FIB0 (0, 0)
  | FIB1 (1, 1)
  | {n:nat}{r0,r1:int} FIB2(n, r1+r0) of (FIB(n-1, r0), FIB(n-2, r1))

fun fib {n:nat} (n: int n): [r:int] (FIB (n, r) | int r) =
  if n = 0 then (FIB0() | 0)
  else if n = 1 then (FIB1() | 1)
  else let
      val (pf0 | r0) = fib(n-1)
      val (pf1 | r1) = fib(n-2)
    in
      (FIB2(pf0, pf1) | r0 + r1)
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The dataprop maps nicely to the Prolog implementation of fibonacci:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fib(0,0).
fib(1,1).
fib(N,R) :- N1 is N-1, N2 is N-2, fib(N1,R1),fib(N2,R2),R is R1+R2.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I leave proving different implementations of &lt;code&gt;fib&lt;/code&gt; to the reader.&lt;/p&gt;

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

&lt;p&gt;There are more algorithms that could be demonstrated but this post is getting long. Some pointers to other interesting examples and articles on ATS and proofs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/jats-ug/practice-ats/tree/master/static_rps&quot;&gt;Rock, Paper, Scissors in the type system&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.slideshare.net/master_q/atslf-for-coq-users/6&quot;&gt;ATS/LF for Coq Users&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://ats-lang.sourceforge.net/DOCUMENT/INT2PROGINATS/HTML/HTMLTOC/c2867.html&quot;&gt;Theorem proving in ATS/LF&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://ats-lang.sourceforge.net/DOCUMENT/INT2PROGINATS/HTML/HTMLTOC/c3154.html&quot;&gt;Programming with Theorem proving&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://ats-lang.sourceforge.net/EXAMPLE/EFFECTIVATS/prop-logic/main.html&quot;&gt;Encoding Propositional Logic&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://ats-lang.sourceforge.net/EXAMPLE/EFFECTIVATS/PwTP-bool-vs-prop/main.html&quot;&gt;Two styles of theorem proving in ATS&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;In general proof code adds a syntactic overhead to the code. With more work on using external solvers it looks like things will become easier with automated solving. ATS allows the programmer to write normal code and add proofs as needed so the barrier to entry to applying proofs is quite low, given suitable documentation and examples.&lt;/p&gt;
</description>
 </item>
 
 <item>
   <title>Casting in ATS</title>
   <link>http://bluishcoder.co.nz/2018/01/02/casting-in-ats.html</link>
   <pubDate>2018-01-02T17:00:00+13:00</pubDate>
   <guid>http://bluishcoder.co.nz/2018/01/02/casting-in-ats</guid>
   <description>&lt;p&gt;The &lt;a href=&quot;http://www.ats-lang.org/&quot;&gt;ATS programming language&lt;/a&gt; has a powerful type and proof system to enable safe construction of programs. Sometimes there is a need to cast a value from one type to another. ATS provides a feature that enables the programming to write their own rules specifying what can be cast. This becomes important when converting types from non-dependent typed values to dependantly typed values and dealing with conversion of proofs. This post goes through some common examples.&lt;/p&gt;

&lt;p&gt;A casting function is introduced using the keyword &lt;code&gt;castfn&lt;/code&gt;. It only has a declaration - there is no implementation or body of the casting function. From a value perspective there is no change to the actual value being cast, only to the type. It is effectively the identity function except for the type change. This means the cast is only allowed for types that are the same size, typically a machine word. There is no runtime overhead for using a casting function.&lt;/p&gt;

&lt;h2&gt;Standard Types&lt;/h2&gt;

&lt;p&gt;The following example ATS program attempts to add an integer to an unsigned integer value:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

implement main0() = let
  val x: uint = 5u
  val y: int = x + 5
in
  println!(&quot;y=&quot;, y)
end 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This results in a type error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc -o c2 c2.dats
c2.dats: 133(line=6, offs=16) -- 138(line=6, offs=21):
         error(3): the symbol [+] cannot be resolved as no match is found.
c2.dats: 124(line=6, offs=7) -- 130(line=6, offs=13):
         error(3): the pattern cannot be given the ascribed type.
c2.dats: 124(line=6, offs=7) -- 130(line=6, offs=13):
         error(3): mismatch of static terms (tyleq):
The actual term is: S2Eerrexp()
The needed term is: S2Eapp(S2Ecst(g0int_t0ype); S2Eextkind(atstype_int))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The error is saying that the operator &lt;code&gt;+&lt;/code&gt; has no matching implementation for the types provided. It is expecting an &lt;code&gt;int&lt;/code&gt; but got something else.&lt;/p&gt;

&lt;p&gt;The addition operator requires the two arguments to be of the same type. A casting function can be added to cast the unsigned integer to an integer:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

extern castfn int_of_uint(x: uint): int

implement main0() = let
  val x: uint = 5u
  val y: int = int_of_uint(x) + 5
in
  println!(&quot;y=&quot;, y)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This compiles and runs:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc -o c3 c3.dats
$ ./c3
y=10
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A &lt;code&gt;castfn&lt;/code&gt; looks very much like a &lt;code&gt;fun&lt;/code&gt; declaration. It requires the name of the casting function, the argument it expects and a return type. There is no implementation as mentioned earlier. The compiler will convert the type of the argument to that of the return type. Another example follows showing conversion to a floating point value:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

extern castfn double_of_uint(x: uint): double

implement main0() = let
  val x: uint = 5u
  val y: double = double_of_uint(x) + 5.0
in
  println!(&quot;y=&quot;, y)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;castfn&lt;/code&gt; can have any name but most of the ATS prelude follows a format of including the &#39;from&#39; and &#39;to&#39; types in the name.&lt;/p&gt;

&lt;h2&gt;Dependent Types&lt;/h2&gt;

&lt;p&gt;Conversion between dependently typed values and non-dependently typed values are a common use of casting functions. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;val x: [n:int] size_t n = string1_length(&quot;hello&quot;)
val y: int = x + 1 // Error here, mismatch between dependent and non-dependent int
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The type of &lt;code&gt;x&lt;/code&gt; is dependently typed in that it has a type index of sort &lt;code&gt;int&lt;/code&gt; for the length of the string. It is also of type &lt;code&gt;size_t&lt;/code&gt; but the snippet expects an &lt;code&gt;int&lt;/code&gt;. A &lt;code&gt;castfn&lt;/code&gt; allows casing away the dependent type index and converting the type at the same time:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; #include &quot;share/atspre_define.hats&quot;
 #include &quot;share/atspre_staload.hats&quot;

 extern castfn int0_of_size1 {n:int} (x: size_t n): int

 implement main0() = let
   val x: [n:int] size_t n = string1_length(&quot;hello&quot;)
   val y: int = int0_of_size1(x) + 1
 in
   println!(&quot;y=&quot;, y)
 end 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the use of the &#39;0&#39; and &#39;1&#39; suffixes used for the type names in the &lt;code&gt;castfn&lt;/code&gt;. This is an idiom in ATS naming where a &#39;0&#39; means not dependently typed and &#39;1&#39; means it has a dependent type.&lt;/p&gt;

&lt;p&gt;It&#39;s possible to go in the other direction, casting from a non-dependent typed value to a dependently type value. This is an example of code that won&#39;t compile and needs a cast:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;val x: int = 5
val y: [n:int] size_t n = x
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This fails due to &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt; being different types. Adding a cast function to convert the &lt;code&gt;int&lt;/code&gt; to a &lt;code&gt;size_t&lt;/code&gt; and including a type index will allow it to compile:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

extern castfn size1_of_int0 (x: int): [n:int] size_t n

implement main0() = let
  val x: int = 5
  val y: [n:int] size_t n = size1_of_int0(x)
in
  println!(&quot;y=&quot;, y)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here the &lt;code&gt;castfn&lt;/code&gt; adds an existential variable to the return type (the &#39;&lt;code&gt;[n:int]&lt;/code&gt;&#39; part) to attach a type index of &quot;unspecified integer value&#39; to the type.&lt;/p&gt;

&lt;p&gt;Another common use of casting functions is to convert different string types. A &lt;code&gt;string&lt;/code&gt; is a non dependently typed string and a &lt;code&gt;string1&lt;/code&gt; is a dependently typed string with the length of the string as a type index. For example, arguments on a command line are &lt;code&gt;string&lt;/code&gt;, but if a &lt;code&gt;string&lt;/code&gt; function is called on it then there is a type error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;implement main0(argc, argv) =
  if argc &amp;gt; 1 then let
      val s: string = argv[1]
      val n = string1_length(s)
    in
      ()
    end
  else
    ()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Using a &lt;code&gt;castfn&lt;/code&gt; can convert the &lt;code&gt;string&lt;/code&gt; to a &lt;code&gt;string1&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

extern castfn string1_of_string (s: string): [n:int] string n

implement main0(argc, argv) =
  if argc &amp;gt; 1 then let
      val s: string = argv[1]
      val n = string1_length(string1_of_string(s)) 
    in
      ()
    end
  else
    ()
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Casting linear types&lt;/h2&gt;

&lt;p&gt;Types can be cast to and from linear types. When programming with strings in ATS you often deal with &lt;code&gt;string&lt;/code&gt; which does not need to be manually free&#39;d and &lt;code&gt;strptr&lt;/code&gt; which is a linear type and needs to be manually free&#39;d. Sometimes you want to treat a &lt;code&gt;strptr&lt;/code&gt; as a &lt;code&gt;string&lt;/code&gt; to call a &lt;code&gt;string&lt;/code&gt; based function. An example is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

extern fun strdup(s: string): [l:addr] strptr l = &quot;ext#&quot;
extern castfn strptr_to_string {l:addr} (s: !strptr l): string

implement main0() = let
  val s: [l:addr] strptr l = strdup(&quot;hello world&quot;)
  val n = string0_length(strptr_to_string(s))
  val _ = strptr_free(s)
in
  ()
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This example needs to be compiled passing &#39;&lt;code&gt;-DATS_MEMALLOC_LIBC&lt;/code&gt;&#39; to tell ATS to use the standard C malloc/free calls.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc -DATS_MEMALLOC_LIBC -o c8 c8.dats
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For the purposes of this example I use a FFI function to call the C &lt;code&gt;strdup&lt;/code&gt; function to copy a static string to a linear string that needs to be free&#39;d. Note that the &lt;code&gt;castfn&lt;/code&gt; does not consume this linear type (evidenced by the &#39;&lt;code&gt;!&lt;/code&gt;&#39; prefixing the type name in the argument). This is dangerous because we can store the return value of the cast and use it after the free:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;val oops = strptr_to_string(s)
val _ = strptr_free(s)
val _ = println!(oops)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The danger can be restricted by using locally scoped cast functions:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;val n = string0_length(strptr_to_string(s)) where {
          extern castfn strptr_to_string {l:addr} (s: !strptr l): string
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now &lt;code&gt;strptr_to_string&lt;/code&gt; can only be used within that local block of code. Cast functions can be dangerous so need some care. There are various prelude casting functions for performing these types of conversions already.&lt;/p&gt;

&lt;h2&gt;Prelude unsafe casts&lt;/h2&gt;

&lt;p&gt;The prelude has an &#39;unsafe&#39; module with a casting polymorphic function which can be used instead of defining casting functions for trivial things. There are also functions for converting &lt;code&gt;strptr&lt;/code&gt; to &lt;code&gt;string&lt;/code&gt;, etc. The equivalent of the previous example would be:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

staload UN = $UNSAFE

extern fun strdup(s: string): [l:agz] strptr l = &quot;ext#&quot;

implement main0() = let
  val s: [l:agz] strptr l = strdup(&quot;hello world&quot;)
  val n = string0_length($UN.strptr2string(s))
  val _ = strptr_free(s)
in
  ()
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Basic type casting can be done using the &lt;code&gt;cast&lt;/code&gt; function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &quot;share/atspre_define.hats&quot;
#include &quot;share/atspre_staload.hats&quot;

staload UN = $UNSAFE

implement main0() = let
  val x: uint = 5u
  val y: int = $UN.cast{int}(x) + 5
in
  println!(&quot;y=&quot;, y)
end 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The swiss army knife of unsafe casting functions are &lt;code&gt;castvwtp0&lt;/code&gt; and &lt;code&gt;castvwtp1&lt;/code&gt;. They can be used for casting linear types. The string example previously can use this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;val s: [l:agz] strptr l = strdup(&quot;hello world&quot;)
val n = string0_length($UN.castvwtp1{string}(s))
val _ = strptr_free(s)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;castvwtp1&lt;/code&gt; will not consume the input argument whereas &lt;code&gt;castvwtp0&lt;/code&gt; will. Looking through the &lt;code&gt;prelude/SATS/unsafe.sats&lt;/code&gt; file will give an idea of the range of available functions.&lt;/p&gt;

&lt;p&gt;The examples in this post are somewhat contrived in that there are standard prelude functions for doing most everything already. The need to cast &lt;code&gt;string&lt;/code&gt; to &lt;code&gt;string1&lt;/code&gt; and &lt;code&gt;strptr&lt;/code&gt; are reduced due to specific functions being available for those types. However it is useful to learn to use the &lt;code&gt;castfn&lt;/code&gt; functionality and it is handy for one-off local casts, or defining protocols using proofs to ensure safe casting to and from types.&lt;/p&gt;
</description>
 </item>
 
 <item>
   <title>Cross Compiling ATS Programs</title>
   <link>http://bluishcoder.co.nz/2017/12/02/cross-compiling-ats-programs.html</link>
   <pubDate>2017-12-02T23:00:00+13:00</pubDate>
   <guid>http://bluishcoder.co.nz/2017/12/02/cross-compiling-ats-programs</guid>
   <description>&lt;p&gt;A few years ago I wrote a mailing list post on &lt;a href=&quot;https://sourceforge.net/p/ats-lang/mailman/message/29036314/&quot;&gt;cross compiling ATS to Android&lt;/a&gt;. With &lt;a href=&quot;http://www.ats-lang.org/&quot;&gt;ATS2&lt;/a&gt; being released the ability to cross compile has been made easier. In this post I&#39;ll show how to produce static linux binaries using &lt;a href=&quot;https://www.musl-libc.org/&quot;&gt;musl libc&lt;/a&gt; and how to build Android and Windows ATS programs by cross compiling on linux.&lt;/p&gt;

&lt;p&gt;For these examples I&#39;m using &lt;a href=&quot;http://www.ats-lang.org/Downloads.html&quot;&gt;ATS2-0.3.8&lt;/a&gt;. I&#39;ll use the simplest of &#39;Hello World&#39; programs in ATS to cross compile. The following is the contents of &lt;code&gt;hello.dats&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;implement main0() = print!(&quot;Hello World\n&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To compile:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ cat hello.dats
implement main0() = print!(&quot;Hello World\n&quot;)

$ patscc -o hello hello.dats
$ ./hello
Hello World
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Static musl libc binaries&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://www.musl-libc.org/&quot;&gt;musl libc&lt;/a&gt; is a lightweight standard library for C programs. I use this instead of glibc because statically linked binaries using glibc have issues using networking functionality. There are no problems using networking routines with musl libc, it&#39;s smaller and lightweight and works well statically linked into executables. To build musl libc I used these steps:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ git clone git://git.musl-libc.org/musl
$ cd musl
$ ./configure
$ make
$ sudo make install
$ export PATH=$PATH:/usr/local/musl/bin/
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The ATS compiler, &lt;code&gt;patscc&lt;/code&gt;, compiles ATS code to C. It defaults to using  &lt;code&gt;gcc&lt;/code&gt; but takes an &lt;code&gt;atsccomp&lt;/code&gt; command line argument to define an alternative C compiler to use for compiling the generated C code. Unknown command line arguments are passed directly to that C compiler. Given musl libc installed in &lt;code&gt;/usr/local/musl&lt;/code&gt; as above, a static binary can be built with &lt;code&gt;musl-gcc&lt;/code&gt; like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ patscc -o hello -atsccomp &quot;/usr/local/musl/bin/musl-gcc&quot; -static \
         -I $PATSHOME/ccomp/runtime -I $PATSHOME \
         hello.dats
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I pass the &lt;code&gt;-static&lt;/code&gt; flag to produce a statically linked binary and two &lt;code&gt;-I&lt;/code&gt; include paths to find the ATS runtime. These appear to be required if &lt;code&gt;-atsccomp&lt;/code&gt; is used. In this case I use the environment variable &lt;code&gt;PATSHOME&lt;/code&gt; to find the installation directory of ATS. Hopefully that was set at ATS installation time. If this command succeeded then we have a static binary:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ ./hello
Hello World
$ ldd hello
not a dynamic executable
$ strip hello &amp;amp;&amp;amp; ls -l hello
-rwxr-xr-x 1 myuser myuser 18224 Dec  2 23:21 hello
$ file hello
hello: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, stripped
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Cross compiling Windows binaries&lt;/h2&gt;

&lt;p&gt;To build Windows compatible binaries on Linux I used &lt;a href=&quot;https://mingw-w64.org/doku.php&quot;&gt;mingw-w64&lt;/a&gt;. On Ubuntu this is available in the &lt;code&gt;gcc-mingw-w64&lt;/code&gt; package. With that installed a Windows &lt;code&gt;hello&lt;/code&gt; binary can be built with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; $ patscc -o hello.exe -atsccomp &quot;i686-w64-mingw-gcc&quot; \
         -I $PATSHOME/ccomp/runtime -I $PATSHOME \
         hello.dats
 $ file hello.exe
 hello.exe: PE32 executable (console) Intel 80386, for MS Windows
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Copying to a Windows machine:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;C:\Users\Myuser&amp;gt; .\hello
Hello World
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Cross compiling Android binaries&lt;/h2&gt;

&lt;p&gt;To build on Android I generated a &lt;a href=&quot;https://developer.android.com/ndk/guides/standalone_toolchain.html&quot;&gt;standalone toolchain&lt;/a&gt; using the Android NDK. This produces standard command line compilers that generate Android compatible binaries. Install the &lt;a href=&quot;https://developer.android.com/ndk/downloads/index.html&quot;&gt;Android NDK&lt;/a&gt; - I used &lt;code&gt;android-ndk-r16&lt;/code&gt; - and run:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ANDROID_NDK/build/tools/make-standalone-toolchain.sh \
  --arch=arm --install-dir=$STK_ROOT
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Replace &lt;code&gt;ANDROID_NDK&lt;/code&gt; with the path to the Android NDK and &lt;code&gt;STK_ROOT&lt;/code&gt; with the destination where you want the standalone toolchain installed. Use &lt;code&gt;arm64&lt;/code&gt; instead of &lt;code&gt;arm&lt;/code&gt; to build an ARM 64-bit binary.&lt;/p&gt;

&lt;p&gt;Now the &quot;Hello World&quot; program can be built using the C compiler from the standalone toolchain. To build on 32-bit using an &lt;code&gt;arm&lt;/code&gt; standalone toolchain, use &lt;code&gt;arm-linux-androideabi-clang&lt;/code&gt; as the C compiler:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; $ patscc -o hello -atsccomp $STK_ROOT/bin/arm-linux-androideabi-clang \
         -I $PATSHOME/ccomp/runtime -I $PATSHOME \
         hello.dats
 $ file hello
 hello: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV),
        dynamically linked, interpreter /system/bin/linker, not stripped
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To build on 64-bit ARM using an &lt;code&gt;arm64&lt;/code&gt; standalone toolchain, use &lt;code&gt;aarch64-linux-android-clang&lt;/code&gt; as the compiler:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt; $ patscc -o hello -atsccomp $STK_ROOT/bin/aarch64-linux-android-clang \
         -I $PATSHOME/ccomp/runtime -I $PATSHOME \
         hello.dats
 $ file hello
 hello64: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV),
          dynamically linked, interpreter /system/bin/linker64, not stripped
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice the use of &lt;code&gt;clang&lt;/code&gt; instead of &lt;code&gt;gcc&lt;/code&gt;. I believe &lt;code&gt;gcc&lt;/code&gt; support for building native Android executables with the NDK is deprecated - I got link errors when I tried.&lt;/p&gt;

&lt;p&gt;Copy the &lt;code&gt;hello&lt;/code&gt; executable to an Android phone. It needs to be somewhere writeable on the phone. On a recent non-rooted phone you should be able to use &lt;code&gt;/data/local/tmp&lt;/code&gt;. The following &lt;code&gt;adb&lt;/code&gt; commands work for me when the device is connected:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ adb push hello /data/local/tmp
$ adb shell
$ cd /data/local/tmp
$ chmod 0755 hello
$ ./hello
Hello World
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Producing an actual Android application would require using the ATS FFI to interface with the Android runtime - given the low level nature of ATS, if it can be done in C, it should be able to be done in ATS.&lt;/p&gt;
</description>
 </item>
 
 <item>
   <title>ZeroMe - Decentralized Microblogging on ZeroNet</title>
   <link>http://bluishcoder.co.nz/2017/10/12/zerome-decentralized-microblogging-on-zeronet.html</link>
   <pubDate>2017-10-12T21:00:00+13:00</pubDate>
   <guid>http://bluishcoder.co.nz/2017/10/12/zerome-decentralized-microblogging-on-zeronet</guid>
   <description>&lt;p&gt;I wrote about &lt;a href=&quot;https://zeronet.io/&quot;&gt;ZeroNet&lt;/a&gt; a few years ago when it was released and it mostly was about &lt;a href=&quot;http://bluishcoder.co.nz/2015/01/15/decentralized-websites-with-zeronet.html&quot;&gt;decentralized websites&lt;/a&gt;. In the time between then and now it has gained a lot of features and regular use. It still does distributed websites well but it adds features suchs as support for sharing large files, merging sites and distributed pseudo-anonymous identity. This post is about an application hosted on ZeroNet called &lt;code&gt;ZeroMe&lt;/code&gt;. It&#39;s a microblogging platform (i.e. A twitter like system) that takes advantage of ZeroNet&#39;s identity system and merging of sites.&lt;/p&gt;

&lt;h2&gt;Starting ZeroNet&lt;/h2&gt;

&lt;p&gt;To start with ZeroMe you first need to &lt;a href=&quot;https://github.com/HelloZeroNet/ZeroNet#user-content-how-to-join&quot;&gt;install ZeroNet&lt;/a&gt;. Given all the right dependancies are installed you can clone the github repository and run the Python script to get online:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ git clone https://github.com/HelloZeroNet/ZeroNet
$ cd ZeroNet
$ ./zeronet.py
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will start the ZeroNet node and run a local webserver on port &lt;code&gt;43110&lt;/code&gt; to access it. This port is available on the local machine only. It also opens a port on &lt;code&gt;15441&lt;/code&gt; to communicate with other nodes. This port is open to the internet at large and will attempt to punch a hole through firewalls using UPNP.&lt;/p&gt;

&lt;p&gt;If you have the Tor daemon running then ZeroNet will connect to it and bridge between clearnet nodes and nodes running on Tor. You can force the node to run only on Tor by providing a command line argument:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ ./zeronet.py --tor always
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this configuration ZeroNet will not expose the port &lt;code&gt;15441&lt;/code&gt; over the internet. It will spawn Tor onion services and expose the port to those for communication with other ZeroNet nodes running on onion services. Access to the local node is still done via port &lt;code&gt;43110&lt;/code&gt; but you should use a browser configured to use Tor if anonymity is a concern since sites can run arbitary JavaScript. The main ZeroNet &#39;Hello&#39; page warns you if you are not using Tor Browser in this configuration.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet1.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet1.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;Gaining an identity&lt;/h2&gt;

&lt;p&gt;ZeroMe requires an identity to be created. Identities are created through identity ZeroNet sites. The main one, operated by the creator of ZeroNet, is &lt;code&gt;ZeroId&lt;/code&gt;. When you first use a site that requires an identity you will be prompted to create one from any identity providers you have access to. For this example I&#39;ll use &lt;code&gt;ZeroId&lt;/code&gt;, accessible at &lt;code&gt;zeroid.bit&lt;/code&gt; - &lt;code&gt;http://localhost:43110/zeroid.bit&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet2.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet2.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click &lt;code&gt;Get auth cert&lt;/code&gt; and choose a username. There are two ways to make the request for the identity. The first is a request over the internet via HTTP. If you&#39;re not running the browser over Tor this will expose your IP address to the identity service. The other is using &lt;a href=&quot;https://bitmessage.org/wiki/Main_Page&quot;&gt;BitMessage&lt;/a&gt;, which is an anonymous messaging system. &lt;code&gt;ZeroId&lt;/code&gt; will request that you send a confirmation message to a &lt;code&gt;BitMessage&lt;/code&gt; address.&lt;/p&gt;

&lt;p&gt;This may seem very centralized - it requires the identity service to be running, if it goes down you can&#39;t create a new identity. There are other identity services on ZeroNet that have different requirements for creating an identity. And there&#39;s an API to create your own. Identities created using these work on any service using the ZeroNet identity API in the same was as &lt;code&gt;ZeroId&lt;/code&gt; identities.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;ZeroId&lt;/code&gt; site will show your identity name once you&#39;ve signed up:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet3.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet3.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;From &lt;code&gt;ZeroId&lt;/code&gt; you can search for existing users and choose to &lt;code&gt;Mute&lt;/code&gt; or &lt;code&gt;Unmute&lt;/code&gt;. By muting a particular identity you won&#39;t see any posts from that identity. This is useful for dealing with spam or users posting on topics you don&#39;t want to see. This will prevent you seeing their content on any ZeroNet site.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet4.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet4.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can manage muted users from the &lt;code&gt;Hello&lt;/code&gt; page left sidebar menu:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet15.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet15.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;Joining a ZeroMe Hub&lt;/h2&gt;

&lt;p&gt;Access &lt;code&gt;ZeroMe&lt;/code&gt; by activating the &lt;code&gt;ZeroMe&lt;/code&gt; icon on the main user interface or going directly to &lt;code&gt;Me.ZeroNetwork.bit&lt;/code&gt; - http://localhost:43110/Me.ZeroNetwork.bit/&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet5.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet5.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A prompt on the top right asks you to accept a merger site. Merge sites are a way to split large sites into a number of smaller ones. You should approve this request.&lt;/p&gt;

&lt;p&gt;Click on &quot;Select user to post new content&quot; to create a &lt;code&gt;ZeroMe&lt;/code&gt; user. It will prompt for an identity to choose and you can select the one already created in &lt;code&gt;ZeroId&lt;/code&gt; above.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet6.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet6.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once an identity is chosen you&#39;ll be asked to select a &#39;hub&#39;. &lt;code&gt;ZeroMe&lt;/code&gt; works by having the user interface operate from the main &lt;code&gt;ZeroMe&lt;/code&gt; site with data on users and posts stored in &#39;Hub&#39; sites. You only see posts from users that belong to hubs that you have requested. There is a hub operated by the &lt;code&gt;ZeroMe&lt;/code&gt; creator and it will be shown as &lt;code&gt;Sun hub&lt;/code&gt; on this page along with any other Hub sites you may already have requested. Click &lt;code&gt;Download&lt;/code&gt; on a hub to download existing posts and content for that hub and &lt;code&gt;Join&lt;/code&gt; to join one.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet7.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet7.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Downloading a hub can take some time. On the &lt;code&gt;Hello&lt;/code&gt; ZeroNet page you can see the progress of any sites currently being downloaded.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet8.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet8.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There&#39;s a useful site called &lt;code&gt;0hub.bit&lt;/code&gt; that lists known hubs and lets you download them all. It&#39;s at &lt;code&gt;http://localhost:43110/0hub.bit/&lt;/code&gt; and clicking the &lt;code&gt;Click me to unlock all hub post in ZeroNet&lt;/code&gt; will start downloading them. This takes some time but is worth it since you can then see all posts by everyone on &lt;code&gt;ZeroMe&lt;/code&gt;. You can delete hubs if you decide you don&#39;t want to see content from a particular hub.&lt;/p&gt;

&lt;h2&gt;Microblogging with ZeroMe&lt;/h2&gt;

&lt;p&gt;Now that you&#39;ve got an identity, signed into ZeroNet and joined a hub you can starting reading content and posting. The &lt;code&gt;Everyone&lt;/code&gt; tab in the user interface will show posts from all users, even those you haven&#39;t followed. This is useful at the beginning to find users and content.&lt;/p&gt;

&lt;p&gt;Posts are in Markdown format and can include images. There is no limit to the size of a post and posts can have comments. You can visit profile pages of users and choose to optionally seed their images, mute users, and edit parts of your own profile page to have an avatar and description:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet12.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet12.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;An example of a post with comments (selected randomly, identities blacked out):&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet13.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet13.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;Random stuff&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;ZeroNet&lt;/code&gt; node running on your machine enforces size limits for sites. This prevents sites that you have accessed from consuming all your disk space. When a site starts reaching the size limit it appears in the main &lt;code&gt;Hello&lt;/code&gt; page left sidebar in a special section:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet9.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet9.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When the site goes past the limit it will no longer download updates. Visiting the site will give a popup asking to increase the limit. Approving that popup will resume downloads for the site until it hits the next limit.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet10.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet10.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There&#39;s a sidebar on the right of pages that can be accessed by dragging the top right &lt;code&gt;0&lt;/code&gt; icon to the left:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet11.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet11.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This sidebar gives statistics on the number of nodes seeding the site, the size limit, and various other things.&lt;/p&gt;

&lt;p&gt;When you visit a ZeroNet site you starting seeding that sites content and receive automatic updates when the content changes. This can be disabled on the main &lt;code&gt;Hello&lt;/code&gt; page on a per site basis. Sites can have &quot;optional files&quot; which you don&#39;t automatically seed. They are downloaded on demand and are often used for user generated content or larger files. You can choose to seed a sites optional files in the right hand sidebar for that site. There are also &quot;Big Files&quot; which are treated specially. These are large files like videos and are also optionally seeded. The &lt;code&gt;Files&lt;/code&gt; tab of the &lt;code&gt;Hello&lt;/code&gt; page lists optional and big files that you are seeding:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://bluishcoder.co.nz/images/zeronet14.png&quot;&gt;&lt;img src=&quot;http://bluishcoder.co.nz/images/zeronet14.png&quot; width=320&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Sites can be set to allow cloning by end users. This creates a copy of the site with no content. An example of a site that does this is &lt;code&gt;ZeroBlog&lt;/code&gt; which you can clone to create your own blog. This extends to &lt;code&gt;ZeroMet&lt;/code&gt; itself. You can clone the &lt;code&gt;ZeroMe&lt;/code&gt; user interface site and modify that to get a customized look but it still uses the data from the existing hubs.&lt;/p&gt;

&lt;p&gt;There&#39;s a bunch of other interesting sites on ZeroNet. The &lt;code&gt;ZeroTalk&lt;/code&gt; forums, various blogs, &lt;code&gt;ZeroMail&lt;/code&gt; for encrypted email like service, etc. Be aware that the psuedo-anonymous use of identities can make for content you might not agree with and much spam. Use of &#39;Mute&#39; is useful here.&lt;/p&gt;

&lt;p&gt;Also be aware that it is &#39;psuedo-anonymous&#39; not &#39;anonymous&#39;. You create an identity and that identity is not tied to you in the real world but people can track what you do to that identity. Content is added to sites and distributed to other nodes. If you &lt;code&gt;like&lt;/code&gt; a post or add content to some site then anyone who decides to dig into the data of that site can see that your identity liked or posted that content. It is possible to have multiple identities if you want to keep aspects of your ZeroNet usage separate but that&#39;s a topic for another post.&lt;/p&gt;

&lt;p&gt;Overall ZeroMe is a nice microblogging system. It&#39;s user friendly, has a nice design and has tools for muting and &quot;Non Real Name&quot; identities. It, along with ZeroNet, is actively developed and supported by the ZeroNet developer.&lt;/p&gt;
</description>
 </item>
 
 <item>
   <title>Using the J Foreign Function Interface</title>
   <link>http://bluishcoder.co.nz/2017/09/21/using-the-j-foreign-function-interface.html</link>
   <pubDate>2017-09-21T22:00:00+12:00</pubDate>
   <guid>http://bluishcoder.co.nz/2017/09/21/using-the-j-foreign-function-interface</guid>
   <description>&lt;p&gt;The &lt;a href=&quot;http://jsoftware.com/&quot;&gt;J Programming Language&lt;/a&gt; is an array oriented or vector based programming language. It is in the same family of programming languages as &lt;a href=&quot;https://en.wikipedia.org/wiki/APL_(programming_language)&quot;&gt;APL&lt;/a&gt; and &lt;a href=&quot;https://en.wikipedia.org/wiki/K_(programming_language)&quot;&gt;K&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I won&#39;t be going into deep details of J syntax or a tutorial of how to use it in this post - for that I recommend something like &lt;a href=&quot;http://www.jsoftware.com/help/jforc/contents.htm&quot;&gt;J for C Programmers&lt;/a&gt; which is also available as &lt;a href=&quot;http://www.lulu.com/shop/henry-rich/j-for-c-programmers/paperback/product-4669553.html&quot;&gt;a paperback book&lt;/a&gt; - but I&#39;ll provide a quick overview of syntax used here.&lt;/p&gt;

&lt;p&gt;What I want to cover in this post is how to use the FFI to call C functions in J, and how to use callbacks from C back to J. The latter isn&#39;t well documented and I always forget how to do it.&lt;/p&gt;

&lt;h2&gt;Introduction to J&lt;/h2&gt;

&lt;p&gt;J provides a concise syntax for performing operations. Many things that would be expressed as english words in other languages use ASCII symbols in J. The &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/contents.htm&quot;&gt;J Dictionary&lt;/a&gt; and &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/vocabul.htm&quot;&gt;Vocabulary&lt;/a&gt; provides details on what these are.&lt;/p&gt;

&lt;p&gt;J has a REPL similar to Lisp environments. For a taste of J without installing it there is an &lt;a href=&quot;http://joebo.github.io/j-emscripten/full.html&quot;&gt;online J IDE&lt;/a&gt; that can be used from a browser and &lt;a href=&quot;http://code.jsoftware.com/wiki/NYCJUG/2014-12-09#Emscripten_Version_of_J&quot;&gt;details on that are here&lt;/a&gt;. Otherwise the native J system is available from &lt;a href=&quot;http://jsoftware.com/stable.htm&quot;&gt;JSoftware downloads&lt;/a&gt;. Source is &lt;a href=&quot;https://github.com/jsoftware/jsource&quot;&gt;available on github&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;J can be used as a calculator to perform operations on numbers:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  10 + 2
12
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There is no operator precedence, use brackets to define order of operations. Order of evaluation is right to left:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  3 * 4 + 10
42

  (3 * 4) + 10
22
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Sequences of numbers separated by white space are arrays of that number. Operations can be performed on arrays. To multiply each element of an array &lt;code&gt;1 2 3 4&lt;/code&gt; by &lt;code&gt;2&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  2 * 1 2 3 4
2 4 6 8
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Arrays can be multi-dimensional. One way of creating such arrays is via the &#39;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d210.htm&quot;&gt;$&lt;/a&gt;&#39;, or Shape, operation. To create a 2x3 array:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  2 3 $ 1 2 3
1 2 3
1 2 3
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Functions are called verbs in J terminology. The &lt;code&gt;*&lt;/code&gt; and &lt;code&gt;+&lt;/code&gt; operators above are verbs. Functions that operate on verbs are called adverbs. An example is the adverb &#39;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d420.htm&quot;&gt;/&lt;/a&gt;&#39; which inserts a verb between elements of an array and evaluates it. An example to sum an array:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  +/ 1 2 3 4
10
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;+/&lt;/code&gt; forms an operation that will do the equivalent of inserting &lt;code&gt;+&lt;/code&gt; between each element of the array like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  1 + 2 + 3 + 4
10
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Other verbs can have &lt;code&gt;/&lt;/code&gt; applied to it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  */ 1 2 3 4
24
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Verbs are monadic or dyadic. The term monadic is not related to the use of monads in languages like Haskell. It means the verb takes a single argument on the right hand side of the verb. A dyadic verb takes two arguments, one on the left and right. Many verbs have both dyadic and monadic forms. Dyadic &lt;code&gt;-&lt;/code&gt; is the subtraction operator. Monadic &lt;code&gt;-&lt;/code&gt; negates its parameter:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  10 - 5
5

  -5
_5
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;_&lt;/code&gt; character signifies a negative number to differentiate from monadic &lt;code&gt;-&lt;/code&gt;. &lt;code&gt;_5&lt;/code&gt; is negative &lt;code&gt;5&lt;/code&gt; whereas &lt;code&gt;-5&lt;/code&gt; is the application of monadic &lt;code&gt;-&lt;/code&gt; to the number &lt;code&gt;5&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A sequence of three verbs together is called a &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/intro05.htm&quot;&gt;fork&lt;/a&gt;. &#39;&lt;code&gt;+/ % #&lt;/code&gt;&#39; is a commonly demonstrated fork. It is three verbs together. The monadic &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d400.htm&quot;&gt;&lt;code&gt;#&lt;/code&gt;&lt;/a&gt; to count the number of items in an array. The &lt;code&gt;+/&lt;/code&gt; verb which sums an array and dyadic &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d130.htm&quot;&gt;&lt;code&gt;%&lt;/code&gt;&lt;/a&gt; which is division:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  # 1 2 3 4
4

  +/ 1 2 3 4
10

  10 % 4
2.5

  (+/ 1 2 3 4) % (# 1 2 3 4)
2.5

  (+/ % #) 1 2 3 4
2.5
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A fork of &#39;(A B C) X&#39;, where &lt;code&gt;B&lt;/code&gt; is dyadic and &lt;code&gt;A&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt; are monadic does &lt;code&gt;(A X) B (C X)&lt;/code&gt;. The combination of verbs, adverbs, nouns and the right to left evaluation of J gives it a &quot;Programming with functions&quot; feel and concise syntax.&lt;/p&gt;

&lt;p&gt;J has variable assignment which can include assignment of verb sequences to named variables. &lt;code&gt;=:&lt;/code&gt; does global variable assignment and &lt;code&gt;=.&lt;/code&gt; does local variable assignment (local to the scope of verb or namespace):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  x   =: 1 2 3 4
  avg =: +/%#
  avg x
2.5
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Vales in J can be boxed or unboxed. The examples below are unboxed. They can be boxed with the &#39;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d010.htm&quot;&gt;&lt;code&gt;&amp;lt;&lt;/code&gt;&lt;/a&gt;&#39; monadic verb. In the REPL boxed values are drawn with a box around them. To unbox a boxed value, use the monadic verb &#39;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d020.htm&quot;&gt;&lt;code&gt;&amp;gt;&lt;/code&gt;&lt;/a&gt;&#39;. The &#39;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d330.htm&quot;&gt;;&lt;/a&gt;&#39; varidic verb will form an array of boxed elements. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  a =: &amp;lt;1
  a
┌─┐
│1│
└─┘
  &amp;gt;a
1
  1;2;3;4
┌─┬─┬─┬─┐
│1│2│3│4│
└─┴─┴─┴─┘
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All elements in an unboxed array must have the same type. Elements in boxed arrays can be different types.&lt;/p&gt;

&lt;p&gt;Hopefully that gives a taste of J syntax so the rest of this post is understandable if you don&#39;t know much of the language. I recommend playing around in the J REPL to get a feel.&lt;/p&gt;

&lt;h2&gt;Foreign Conjunctions&lt;/h2&gt;

&lt;p&gt;Calling C functions from J requires using what&#39;s called a &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/xmain.htm&quot;&gt;Foreign Conjunction&lt;/a&gt;. These are special system operations defined by the J implementation and are of the form &#39;&lt;code&gt;x !: y&lt;/code&gt;&#39; where &lt;code&gt;x&lt;/code&gt; and &#39;y&#39; are numbers. They return verbs or adverbs themselves so the result of the conjuction is applied to more arguments. An example would be the &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/dx007.htm&quot;&gt;Space&lt;/a&gt; category of foreign conjuctions that returns information about J memory usage:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  (7 !: 0) &#39;&#39;
10939904
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here &lt;code&gt;7 !: 0&lt;/code&gt; returns a verb which takes a single argument (which is ignored) and returns the number of bytes currently in use by the J interpreter.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  (7!:2) &#39;+/ 1 2 3 4&#39;
1664
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;7!:2&lt;/code&gt; returns a verb that when called with an argument returns the number of bytes required to execute that argument as a J sentence.&lt;/p&gt;

&lt;p&gt;There&#39;s lots more described in the &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/xmain.htm&quot;&gt;Foreign Conjunction&lt;/a&gt; documentation which allows reflecting an introspecting on just about everything in the J system.&lt;/p&gt;

&lt;h2&gt;Foreign Function Interface&lt;/h2&gt;

&lt;p&gt;The foreign function interface is the set of foreign conjunctions where the left side of the conjunction verb is the number &lt;code&gt;15&lt;/code&gt;. There&#39;s a short list of these in the &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/dx015.htm&quot;&gt;Dynamic Link Library&lt;/a&gt; part of the dictionary, and further explanation in the &lt;a href=&quot;http://www.jsoftware.com/help/user/dlls.htm&quot;&gt;Dlls&lt;/a&gt; section of the user manual. There are more verbs than are listed in these pages and the J source file &lt;a href=&quot;https://github.com/jsoftware/jsource/blob/master/jsrc/x15.c&quot;&gt;x15.c&lt;/a&gt; gives an idea of the scope. Most of the additional ones are used in implementation of the J library but we have to delve into undocumented features to handle C callbacks.&lt;/p&gt;

&lt;p&gt;The J source file &lt;a href=&quot;https://github.com/jsoftware/jsource/blob/95c43476358f5c385560a72b7cfe395d446e8f4c/jlibrary/system/main/stdlib.ijs#L478&quot;&gt;stdlib.ijs&lt;/a&gt; contains the definitions for names that make the foreign conjunctions easier to use. The ones covered in this post are:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cd    =: 15!:0
memr  =: 15!:1
memw  =: 15!:2
mema  =: 15!:3
memf  =: 15!:4
cdf   =: 15!:5
cder  =: 15!:10
cderx =: 15!:11
cdcb  =: 15!:13
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To call a foreign function we use the &#39;&lt;code&gt;15!:0&lt;/code&gt;&#39; verb, defined as &lt;code&gt;cd&lt;/code&gt; in the standard library. This is described in the documentation as &#39;Call DLL Function&#39; and is documented in the &lt;a href=&quot;http://www.jsoftware.com/help/user/call_procedure.htm&quot;&gt;Calling DLLs&lt;/a&gt; section of the user manual. It is dyadic and has the form:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&#39;filename procedure [&amp;gt;] [+] [%] declaration&#39; cd parameters
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The descriptions below look complicated but will become clearer with a few examples.&lt;/p&gt;

&lt;p&gt;The first argument is a string that contains the function name and arguments it takes. It&#39;s the declaration of the function basically. The second parameter is an array of the arguments that the foreign function takes.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;filename&lt;/code&gt; is the name of a DLL or shared library. It can also be one of the following special filenames:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;0&lt;/code&gt; = If filename is &lt;code&gt;0&lt;/code&gt; then the &#39;procedure&#39; is a signed integer representing a memory address for where the function is located.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;1&lt;/code&gt; = If filename is &lt;code&gt;1&lt;/code&gt; then the &#39;procedure&#39; is a non-negative integer that is the index of a procedure in a vtable. The first element of the parameter array should be an address of the address of the vtable, the &#39;object&#39; address. The declaration of the first parameter should be &#39;&lt;code&gt;*&lt;/code&gt;&#39; or &#39;&lt;code&gt;x&lt;/code&gt;&#39;. This is used for calling COM objects or Java Native Interface objects.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The &lt;code&gt;procedure&lt;/code&gt; is the name of the function in the DLL or shared library to call. It can also be a number as described in the &lt;code&gt;filename&lt;/code&gt; portion above.&lt;/p&gt;

&lt;p&gt;The &#39;&lt;code&gt;&amp;gt;&lt;/code&gt;&#39;, &#39;&lt;code&gt;+&lt;/code&gt;&#39; and &#39;&lt;code&gt;%&lt;/code&gt;&#39; parts are optional and define attributes of the function:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&#39;&lt;code&gt;&amp;gt;&lt;/code&gt;&#39; = The procedure returns a scalar result. Without &#39;&lt;code&gt;&amp;gt;&lt;/code&gt;&#39; the result is the boxed scalar result appended to the possibly modified list of boxed arguments.&lt;/li&gt;
&lt;li&gt;&#39;&lt;code&gt;+&lt;/code&gt;&#39; = Chooses the calling convention of the fnuction. On Windows the standard calling convention is &lt;code&gt;__stdcall&lt;/code&gt; and using &#39;&lt;code&gt;+&lt;/code&gt;&#39; selects &lt;code&gt;__cdecl&lt;/code&gt;. On Unix using &#39;&lt;code&gt;+&lt;/code&gt;&#39; has no effect.&lt;/li&gt;
&lt;li&gt;&#39;&lt;code&gt;%&lt;/code&gt;&#39; = Does a floating point reset after the call. Some procedures leave floating point in an invalid state.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;&#39;declaration&#39; is a string of blank delimited characters defining the types of the arguments passed to the function, and the type of the result. They can be:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;c&lt;/code&gt; = J character (1 byte)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;w&lt;/code&gt; = J literal2 (2 byte)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;u&lt;/code&gt; = J literal4 (4 byte)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;s&lt;/code&gt; = short integer (2 byte)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;i&lt;/code&gt; = integer (4 byte)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;l&lt;/code&gt; = long integer (8 byte)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;x&lt;/code&gt; = J integer (4 or 8 byte depending on 32/64 bit architecture)&lt;/li&gt;
&lt;li&gt;&#39;f&#39; = short float (4 byte)&lt;/li&gt;
&lt;li&gt;&#39;d&#39; = J float (8 byte)&lt;/li&gt;
&lt;li&gt;&#39;j&#39; = J complex (16 byte - 2 d values) (pointer only, not as result or scalar)&lt;/li&gt;
&lt;li&gt;&#39;*&#39; = pointer. This can be followed by any of the above to indicate the type pointed to. A parameter passed in the place where a pointer is expected can be a J array of the right type, or a scalar boxed scalar integer that is a memory address.&lt;/li&gt;
&lt;li&gt;&#39;n&#39; = no result (result is ignored and &#39;0&#39; is returned)&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The first entry in the &#39;declaration&#39; is the result type and the remaining ones describe each parameter provided in the second argument to &#39;&lt;code&gt;cd&lt;/code&gt;&#39;.&lt;/p&gt;

&lt;p&gt;The &#39;parameters&#39; argument to &#39;&lt;code&gt;cd&lt;/code&gt;&#39; should be a boxed array. If it is not boxed then it will be boxed for you.&lt;/p&gt;

&lt;h2&gt;Examples&lt;/h2&gt;

&lt;p&gt;The following example calls the C function &lt;code&gt;puts&lt;/code&gt; from J on my Linux OS:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;/lib/x86_64-linux-gnu/libc.so.6 puts x *c&#39; cd &amp;lt;&#39;hello&#39;
┌─┬─────┐
│6│hello│
└─┴─────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The full path to the shared library is given with &lt;code&gt;puts&lt;/code&gt; as the function name. The &#39;declaration&#39; is set to return a J integer and marks the function as taking a pointer to characters as an argument. We pass the boxed array of characters with &lt;code&gt;&amp;lt;&#39;hello&#39;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The result is an boxed array where the first element is the value returned from the function. This is &lt;code&gt;6&lt;/code&gt;, the number of characters printed. The result of the result is the arguments passed to the function. The output of &lt;code&gt;puts&lt;/code&gt; can be seen on the console.&lt;/p&gt;

&lt;p&gt;If we just want the result of the function, without the appended list of parameters, then we can use the &#39;&lt;code&gt;&amp;gt;&lt;/code&gt;&#39; attribute in the first argument to &#39;&lt;code&gt;cd&lt;/code&gt;&#39;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;/lib/x86_64-linux-gnu/libc.so.6 puts &amp;gt; x *c&#39; cd &amp;lt;&#39;hello&#39;
6
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Loading shared libraries using &lt;code&gt;cd&lt;/code&gt; uses system resources. To unload shared libraries currently in use by J use the &#39;&lt;code&gt;15!:5&lt;/code&gt;&#39; foreign conjunction, or &lt;code&gt;cdf&lt;/code&gt;. It is monadic and ignores its argument:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  cdf &#39;&#39;
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Errors&lt;/h2&gt;

&lt;p&gt;If the shared library can&#39;t be found, or there is some other problem with the call, then a &#39;domain error&#39; will result:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;doesnotexist.so puts &amp;gt; x *c&#39; cd &amp;lt;&#39;hello&#39;
|domain error
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To find the reason for the domain error, use the &#39;&lt;code&gt;15!:10&lt;/code&gt;&#39; Foreign Function verb to identify the error. If is a monadic verb that ignores its argument and prints out information about a &lt;code&gt;domain error&lt;/code&gt;. In the standard library the name &lt;code&gt;cder&lt;/code&gt; is assigned to &#39;&lt;code&gt;15!:10&lt;/code&gt;&#39;. The meaning of &lt;a href=&quot;http://www.jsoftware.com/help/user/cd_domain_error.htm&quot;&gt;what it returns&lt;/a&gt; is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;0 0 = no error&lt;/li&gt;
&lt;li&gt;1 0 = file not found&lt;/li&gt;
&lt;li&gt;2 0 = procedure not found&lt;/li&gt;
&lt;li&gt;3 0 = too many DLLs loaded (max 20)&lt;/li&gt;
&lt;li&gt;4 0 = too many or too few parameters&lt;/li&gt;
&lt;li&gt;5 x = declaration x invalid&lt;/li&gt;
&lt;li&gt;6 x = parameter x type doesn&#39;t match declaration&lt;/li&gt;
&lt;li&gt;7 0 = system limit - linux64 max 8 float/double scalars&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;In the example above it indicates &#39;file not found&#39;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  cder &#39;&#39;
1 0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For a detailed description of the error use &#39;&lt;code&gt;15!:11&lt;/code&gt;&#39;, or &lt;code&gt;cderx&lt;/code&gt;. It is monadic, ignores its arguments, and returns a boxed array with the error number as the first element and a string description as the second:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;doesnotexist.so puts &amp;gt; x *c&#39; cd &amp;lt;&#39;hello&#39;
|domain error: cd
|   &#39;doesnotexist.so puts &amp;gt; x *c&#39;    cd&amp;lt;&#39;hello&#39;

   cderx &#39;&#39;
┌─┬──────────────────────────────────────────────────────────────────────────┐
│0│doesnotexist.so: cannot open shared object file: No such file or directory│
└─┴──────────────────────────────────────────────────────────────────────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Memory&lt;/h2&gt;

&lt;p&gt;To allocate, free, read and write C memory in J requires use of the &lt;a href=&quot;http://www.jsoftware.com/help/user/memory_management.htm&quot;&gt;memory management&lt;/a&gt; foreign verbs.  An example of an FFI call that returns a string is &lt;code&gt;getenv&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;/lib/x86_64-linux-gnu/libc.so.6 getenv *c *c&#39; cd &amp;lt;&#39;HOME&#39;
┌───────────────┬────┐
│140735847611736│HOME│
└───────────────┴────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note here that the returned value is a number. This represents a pointer to the string that &lt;code&gt;getenv&lt;/code&gt; returns. To see the string result from this pointer we need to use the J verb that deals with reading raw memory.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  memr 140735847611736 0 _1 2
/home/myuser
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&#39;&lt;code&gt;15!:1&lt;/code&gt;&#39;, or &lt;code&gt;memr&lt;/code&gt; as it is defined in the standard library, reads raw memory. It takes an array as an argument with the elements of the array being:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The numeric pointer to the memory&lt;/li&gt;
&lt;li&gt;The offset into that memory&lt;/li&gt;
&lt;li&gt;The number of elements to read. A &lt;code&gt;_1&lt;/code&gt; means read to the first NUL byte which is useful for C strings and is used in this &lt;code&gt;getenv&lt;/code&gt; example.&lt;/li&gt;
&lt;li&gt;An optional type argument for the data to be read. The default is &lt;code&gt;2&lt;/code&gt; which is used explicitly above. It can be 2, 4, 8 or 16 for char, integer, float or complex respectively. The count parameter is number of elements of the given type - it takes the size into account.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;&#39;&lt;code&gt;15!:3&lt;/code&gt;&#39;, or &lt;code&gt;mema&lt;/code&gt;, allocates memory. It takes a length argument for number of bytes to allocate and returns &lt;code&gt;0&lt;/code&gt; on allocation failure:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  mema 1024
23813424
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The numeric result return is a pointer address that can be passed to &#39;&lt;code&gt;*&lt;/code&gt;&#39; parameters in the FFI calls.&lt;/p&gt;

&lt;p&gt;&#39;&lt;code&gt;15!:4&lt;/code&gt;&#39;, or &lt;code&gt;memf&lt;/code&gt;, frees memory allocated with &lt;code&gt;mema&lt;/code&gt;. It takes the address as an argument and returns &#39;0&#39; on success or &#39;1&#39; on failure:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  memf 23813424
0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&#39;&lt;code&gt;15!:2&lt;/code&gt;&#39;, or &lt;code&gt;memw&lt;/code&gt;, writes to memory given a pointer. It is the inverse of &lt;code&gt;memr&lt;/code&gt; and is dyadic. The left hand argument is an array of data to write, the right hand argument similar to that defined by &lt;code&gt;memr&lt;/code&gt; above:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  mema 32
22371984

  &#39;hello&#39; memw 22371984 0 6 2
  memr 22371984 0 _1 2
hello

  &#39;/lib/x86_64-linux-gnu/libc.so.6 puts &amp;gt; x *c&#39; cd &amp;lt;&amp;lt;22371984
6

  memf 22371984
0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice the double boxing of the pointer argument to the &lt;code&gt;puts&lt;/code&gt; call. This is what enables J to recognise it as a pointer parameter rather than an integer argument. It is a boxed array containing a boxed integer.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;count&lt;/code&gt; argument passed to the &lt;code&gt;memw&lt;/code&gt; call can be one greater than the length of the string in the left argument if the type of the &lt;code&gt;memw&lt;/code&gt; call is &lt;code&gt;2&lt;/code&gt; (the char type). In that case a NUL byte is appended which is what we use in the example above.&lt;/p&gt;

&lt;p&gt;Here&#39;s another example using &lt;code&gt;sprintf&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  mema 1024
24110208

  &#39;/lib/x86_64-linux-gnu/libc.so.6 sprintf &amp;gt; x * *c *c x&#39; cd (&amp;lt;24110208);&#39;string is: %s %d\n&#39;;&#39;foo&#39;;42
17

  memr 24110208 0 _1
string is: foo 42

  memf 24110208
0
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Callbacks&lt;/h2&gt;

&lt;p&gt;The foreign function conjunction &#39;&lt;code&gt;15!:13&lt;/code&gt;&#39;, or &lt;code&gt;cdcb&lt;/code&gt;, is used for defining a callback function that can be passed to a C function and have it call back to J. It is a monadic verb that takes a number as an argument for the number of arguments that the callback function uses. It returns a pointer to a compiled function that can be used as the callback.&lt;/p&gt;

&lt;p&gt;When that function is called it will do argument conversion and call a J verb called &lt;code&gt;cdcallback&lt;/code&gt; with the arguments passed as a boxed array. The following demonstrates how this works by defining some callback functions with a definition of &lt;code&gt;cdcallback&lt;/code&gt; that prints its output to the REPL:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cdcallback =: monad define
  y (1!:2) 2
  0
)

f1 =: cdcb 1
f2 =: cdcb 2
f3 =: cdcb 3

  (&#39;0 &#39;,(&quot;: f1),&#39; &amp;gt; n x&#39;) cd &amp;lt;100
100
0

   (&#39;0 &#39;,(&quot;: f2),&#39; &amp;gt; n x x&#39;) cd 100;200
100 200
0

   (&#39;0 &#39;,(&quot;: f3),&#39; &amp;gt; n x x x&#39;) cd 100;200;300
100 200 300
0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this example &lt;code&gt;cdcallback&lt;/code&gt; is implemented as a monadic function that passes its argument, &#39;&lt;code&gt;y&lt;/code&gt;&#39;, to the foreign conjunction &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/dx001.htm&quot;&gt;for writing to the screen&lt;/a&gt;, &#39;&lt;code&gt;1!:2&lt;/code&gt;&#39;. It returns &#39;0&#39; as a result.&lt;/p&gt;

&lt;p&gt;Three callback functions are created for one, two and three arguments respectively. These return C pointers to the equivalent of:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;int f1(int);
int f2(int, int);
int f3(int, int, int);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then we call the functions using &lt;code&gt;cd&lt;/code&gt;. The declaration string is built dynamically by concatenating the function address into it. This uses the &lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d602.htm&quot;&gt;default format monadic verb&lt;/a&gt;, &#39;&lt;code&gt;&quot;:&lt;/code&gt;&#39;. Note how the first parameter in the delcaration string is &#39;&lt;code&gt;0&lt;/code&gt;&#39;, which as described above means a function pointer is expected instead of a function name. That&#39;s what we&#39;re concatenating in:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  (&#39;0 &#39;,(&quot;: f1),&#39; &amp;gt; n x&#39;)
0 140277582398804 &amp;gt; n x
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Calling the callback function prints to the screen the argument array. Knowing this we can start to test with a function that requires a callback. For that example I&#39;ll use the &lt;code&gt;qsort&lt;/code&gt; C function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;void qsort(void *base, size_t nmemb, size_t size,
           int (*compar)(const void *, const void *));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can test with our existing callback that just displays the argument output:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;/lib/x86_64-linux-gnu/libc.so.6 qsort n *l x x *&#39; cd (1 2 3 4);4;8;&amp;lt;&amp;lt;f2
30492672 30492676
30492680 30492684
30492672 30492680
30492676 30492680
0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For qsort I&#39;ve defined it as taking an array of integers, an integer for the number of members, an integer for the size of each member and a pointer. For arguments I pass an array of integers (the J array is automatically converted to a C array), &#39;4&#39; for the number of members, &#39;8&#39; for the size of each member (eight bytes each) and a boxed number for the pointer to the callback function that takes two arguments.&lt;/p&gt;

&lt;p&gt;When run it prints out the two arguments each time the callback is called. Because &lt;code&gt;qsort&lt;/code&gt; expects the callback to take pointers as arguments they appear as integers. Now we need to write a callback that dereferences those arguments and returns the result of a comparison.&lt;/p&gt;

&lt;p&gt;We can use &lt;code&gt;memr&lt;/code&gt; to read the integer value from memory and the &#39;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/d520.htm&quot;&gt;{&lt;/a&gt;&#39; dyadic verb to retrieve elements from the array (&#39;&lt;code&gt;x { y&lt;/code&gt;&#39; returns the xth element of y).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  cdcallback =: monad define
    lhs =. 0 { y
    rhs =. 1 { y
    i1 =. memr lhs,(0 1 4)
    i2 =. memr rhs,(0 1 4)
    diff =. i1 - i2
    (i1,i2,diff) (1!:2) 2
    if. diff &amp;lt; 0 do. diff =. _1
    elseif. diff &amp;gt; 0 do. diff =. 1
    end.
    diff
  )
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Running this with our &lt;code&gt;qsort&lt;/code&gt; call gives:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;/lib/x86_64-linux-gnu/libc.so.6 qsort &amp;gt; n *l x x *&#39; cd (3 7 1 4);4;8;&amp;lt;&amp;lt;f2
3 7 _4
1 4 _3
3 1 2
3 4 _1
7 4 3
0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This looks good! But how do we get the result back? &lt;code&gt;qsort&lt;/code&gt; modifies in place, and when converting array arguments J will copy the array to a C array and then copy the results back. To look at the results we need to remove the &#39;&gt;&#39; attribute in the declaration to view the modified parameters:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &#39;/lib/x86_64-linux-gnu/libc.so.6 qsort n *l x x *&#39; cd (3 7 1 4);4;8;&amp;lt;&amp;lt;f2
3 7 _4
1 4 _3
3 1 2
3 4 _1
7 4 3
┌─┬───────┬─┬─┬─────────────────┐
│0│1 3 4 7│4│8│┌───────────────┐│
│ │       │ │ ││140277582398867││
│ │       │ │ │└───────────────┘│
└─┴───────┴─┴─┴─────────────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The second element of the boxed array is the sorted array. Some points to note:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Notice the use of the &lt;code&gt;if.&lt;/code&gt;, &lt;code&gt;else.&lt;/code&gt;, &lt;code&gt;end.&lt;/code&gt; control structure in the callback. I couldn&#39;t get it to work returning the result of the subtraction of &lt;code&gt;i1 - i2&lt;/code&gt;. This resulted in the callback always returning zero. I think there may be some number conversion issue happening with &lt;code&gt;diff&lt;/code&gt; not being an integer. Assigning a specific integer resolved this.&lt;/li&gt;
&lt;li&gt;The callback could be written more concisely using other J features but I wanted to keep it readable given only what was covered in the introduction of this post.&lt;/li&gt;
&lt;li&gt;Dealing with integer sizes, pointers as integers, and all the conversions going on makes things crash if you get the types wrong.&lt;/li&gt;
&lt;li&gt;I defined &lt;code&gt;cdcallback&lt;/code&gt; as a global variable by using &lt;code&gt;=:&lt;/code&gt; as the assignment verb. Using &lt;code&gt;=.&lt;/code&gt; would make a local variable. This enables creating a local callback, within the scope of another verb or namespace, just before passing it to the function that requires it.&lt;/li&gt;
&lt;li&gt;If you need multiple callbacks that do different things active at the same time you need to write the one &lt;code&gt;cdcallback&lt;/code&gt; and differentiate inside that somehow, maybe based on the number or type of arguments, to decide what action needs to be performed.&lt;/li&gt;
&lt;/ul&gt;


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

&lt;p&gt;Using the FFI from J isn&#39;t difficult but requires care. Using callbacks is more complicated and not very well documented but it&#39;s possible. Searching the example J code for &lt;code&gt;cdcb&lt;/code&gt; or &lt;code&gt;15!:13&lt;/code&gt; will find example usage. There are other undocumented FFI routines but I haven&#39;t looked into them yet.&lt;/p&gt;

&lt;p&gt;For more information on J, including tutorials, books, mailing lists, etc there is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://jsoftware.com/&quot;&gt;JSoftware&lt;/a&gt;, the makers of the J system.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.jsoftware.com/help/primer/contents.htm&quot;&gt;J Primer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.jsoftware.com/help/phrases/contents.htm&quot;&gt;J Phrases&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/contents.htm&quot;&gt;J Dictionary&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.jsoftware.com/help/learning/contents.htm&quot;&gt;Learning J&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.jsoftware.com/help/jforc/contents.htm&quot;&gt;J for C programmers&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.jsoftware.com/help/dictionary/vocabul.htm&quot;&gt;J Vocabulary&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.reddit.com/r/apljk/&quot;&gt;/r/apljk&lt;/a&gt; on reddit.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://rosettacode.org/wiki/Category:J&quot;&gt;Rosetta Code J Language&lt;/a&gt; has lots of examples in J.&lt;/li&gt;
&lt;/ul&gt;

</description>
 </item>
 
 <item>
   <title>Reference Capabilities, Consume and Recover in Pony</title>
   <link>http://bluishcoder.co.nz/2017/07/31/reference_capabilities_consume_recover_in_pony.html</link>
   <pubDate>2017-07-31T18:00:00+12:00</pubDate>
   <guid>http://bluishcoder.co.nz/2017/07/31/reference_capabilities_consume_recover_in_pony</guid>
   <description>&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;
</description>
 </item>
 
 <item>
   <title>Runtime typing and eval in Alice ML</title>
   <link>http://bluishcoder.co.nz/2017/07/15/runtime-typing-and-eval-in-alice-ml.html</link>
   <pubDate>2017-07-15T23:00:00+12:00</pubDate>
   <guid>http://bluishcoder.co.nz/2017/07/15/runtime-typing-and-eval-in-alice-ml</guid>
   <description>&lt;p&gt;I originally wtote this post three years ago but I wasn&#39;t happy with how it read so never finished it. It&#39;s been sitting around in draft making me feel guilty for too long so I&#39;ve cleaned it up and published it.&lt;/p&gt;

&lt;p&gt;I like the style of prototyping and programming that dynamic languages like &lt;a href=&quot;http://selflanguage.org/&quot;&gt;Self&lt;/a&gt; promote. When building systems inside the language environment it feels like you are living in a soup of objects. Programming becomes creating and connecting objects to perform tasks while debugging and refactoring as you go. The animated image below shows a use of the Self environment to instantiate and run a VNC object I wrote for example. Other examples can be seen in screencasts in my &lt;a href=&quot;http://bluishcoder.co.nz/tags/self/index.html&quot;&gt;Self language posts&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href=&#39;http://bluishcoder.co.nz/self/self_vnc2.gif&#39;&gt;&lt;img src=&#39;http://bluishcoder.co.nz/self/self_vnc2.gif&#39; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Recently I&#39;ve been using more statically typed languages to explore the world of type safety and how it can improve correctness of programs. My series of &lt;a href=&quot;http://bluishcoder.co.nz/tags/ats/index.html&quot;&gt;ATS posts&lt;/a&gt; go through a lot of the features that this approach provides. Most of these languages promote an edit/compile/link/run style of development and I miss the live development and debugging in the dynamic environments.&lt;/p&gt;

&lt;p&gt;Some of the statically typed functional programming languages provide ways of doing dynamic types. &lt;a href=&quot;http://www.ps.uni-saarland.de/alice/&quot;&gt;Alice ML&lt;/a&gt;, developed in mid-2000, was an extension of &lt;a href=&quot;http://en.wikipedia.org/wiki/Standard_ML&quot;&gt;Standard ML&lt;/a&gt; which provided support for concurrent, distributed and constraint programming. It was an attempt to see what a statically typed functional version of the &lt;a href=&quot;http://mozart.github.io/&quot;&gt;Mozart/Oz&lt;/a&gt; language would be like. Development stopped in 2007 with the release of version 1.4 of Alice ML but the system remains very useable. I had been following Alice ML since the early days of its development and the concurrency and distribution features of it were the inspiration for some of my explorations with using &lt;a href=&quot;http://bluishcoder.co.nz/2006/09/27/futures-and-promises-in-javascript.html&quot;&gt;futures and promises in JavaScript&lt;/a&gt; and &lt;a href=&quot;http://bluishcoder.co.nz/radio/2005/07/29.html&quot;&gt;concurrency in Factor&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;As part of the support for distributed programming it required the ability to &lt;a href=&quot;http://www.ps.uni-saarland.de/alice/manual/pickling.html&quot;&gt;serialize and deserialize&lt;/a&gt; values along with their types. This form of dynamic behaviour would seem to be useful for developing a live coding environment. In fact Alice ML includes a GUI editor and REPL written in Alice ML that makes use of the library to evaluate, compile and produce components and executables.&lt;/p&gt;

&lt;p&gt;I&#39;ve imported the source of Alice ML into a &lt;a href=&quot;https://github.com/aliceml/aliceml&quot;&gt;github repository&lt;/a&gt; with minor bitrot changes and a couple of bug fixes so that it builds on recent Linux and Mac OS X systems. The code there is from the &lt;a href=&quot;http://www.ps.uni-saarland.de/alice/download.html&quot;&gt;original Alice ML source&lt;/a&gt; with many changes and fixes made by Gareth Smith in his &lt;a href=&quot;https://bitbucket.org/gareth0/&quot;&gt;bitbucket repository&lt;/a&gt;. The original Alice developers and Gareth have kindly allowed me to host this on github.&lt;/p&gt;

&lt;h2&gt;Packages&lt;/h2&gt;

&lt;p&gt;Alice ML does dynamic runtime typing through packages. A package encapsulates a module and its signature. The package is an opaque type and accessing the module stored within is only possible via an &lt;code&gt;unpack&lt;/code&gt; operation which requires giving the explicit signature of the module stored. If the signature doesn&#39;t match the type of the module stored then a runtime exception occurs. Packages can be passed around as first class values, stored in files, sent to other processes, etc.&lt;/p&gt;

&lt;p&gt;Packages are created using the &lt;code&gt;pack&lt;/code&gt; expression. This follows the form:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;pack structure_expression : signature_expression
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Where &lt;code&gt;structure_expression&lt;/code&gt; and &lt;code&gt;signature_expression&lt;/code&gt; are expressions that evaluate to &lt;a href=&quot;http://www.it.uu.se/edu/course/homepage/kompprojekt/vt12/slides/structures.html&quot;&gt;Standard ML structures and signatures&lt;/a&gt;. The following would create a package for the value 42 stored in a module (as typed in the Alice ML REPL):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; val p = pack struct val x:int = 42 end : sig val x:int end;
val p : package = package{|...|}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the &lt;code&gt;pack&lt;/code&gt; expression a structure is created with an &lt;code&gt;x&lt;/code&gt; member of type &lt;code&gt;int&lt;/code&gt; and the value of that is &lt;code&gt;42&lt;/code&gt;. This structure is the value that is stored in the package. The type of this is given by the signature expression and when later unpacked only this signature can be used to get at the value. For simple examples like this the &lt;code&gt;struct&lt;/code&gt; and &lt;code&gt;sig&lt;/code&gt; syntax is quite verbose but Alice ML allows shortening this to just the contents of the structure and signature. The following is the equivalent shortened code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; val p = pack (val x:int = 42) : (val x:int);
val p : package = package{|...|}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Getting the value back from a package is done using &lt;code&gt;unpack&lt;/code&gt;. The general form of the &lt;code&gt;unpack&lt;/code&gt; expression is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;unpack expression : signature_expression
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If the &lt;code&gt;signature_expression&lt;/code&gt; does not match the signature of the value stored in the package then an exception is raised. The type of the &lt;code&gt;unpack&lt;/code&gt; expression is &lt;code&gt;signature_expression&lt;/code&gt; so if it successfully unpacks then use of the resulting value is type safe. Unpacking our example above looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; structure S = unpack p : sig val x:int end;
structure S : sig val x : int end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or using the shorter syntax:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; structure S = unpack p : (val x:int);
structure S : sig val x : int end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The resulting module &lt;code&gt;S&lt;/code&gt; can be used as any other SML module to access the fields within:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; print (Int.toString S.x);
42
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Eval&lt;/h2&gt;

&lt;p&gt;To create an environment that allows evaluating code and manipulating results requires an &lt;code&gt;eval&lt;/code&gt; facility. Alice ML provides this through the &lt;a href=&quot;http://www.ps.uni-saarland.de/alice/manual/library/compiler.html&quot;&gt;Compiler&lt;/a&gt; module. This module provides, amongst other functions, the following variants of &lt;code&gt;eval&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;val eval :     string -&amp;gt; package
val evalWith : env * string -&amp;gt; env * package
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The first function, &lt;code&gt;eval&lt;/code&gt; takes a string of Alice ML code, evaluates it, and returns the result as a package. The second, &lt;code&gt;evalWith&lt;/code&gt;, takes an additional parameter which is the environment which is used to evaluate the code within. It also returns the modified envrionment after evaluating the code. This allows keeping a persistent state of changes made by the evaluated code.&lt;/p&gt;

&lt;p&gt;The result is returned as a &lt;code&gt;package&lt;/code&gt; because the type of the evaluated code is unknown. It could be anything. If the caller of &lt;code&gt;eval&lt;/code&gt; needs to manipulate or display the result in some manner it needs to &lt;code&gt;unpack&lt;/code&gt; it with a known type that it expects it to contain and handle any exception that might occur if the type is incorrect at runtime. An example of doing this is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; val x = Compiler.eval(&quot;1+2&quot;);
val x : package = package{|...|}
&amp;gt; structure X = unpack x : (val it:int);
structure X : sig val it : int end
&amp;gt; X.it;
val it : int = 3
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this case the result of our evaluation is an &lt;code&gt;int&lt;/code&gt; so this is what&#39;s used in the signature for the &lt;code&gt;unpack&lt;/code&gt; expression.&lt;/p&gt;

&lt;p&gt;An example using &lt;code&gt;evalWith&lt;/code&gt; to track the changes to the environment is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; val x = Compiler.evalWith(Compiler.initialEnv,
                            &quot;fun fac(n:int) = if n &amp;lt;= 1 then 1 else n * fac(n - 1)&quot;);
val x : Compiler.env * package = (_val, package{|...|})
&amp;gt; val y = Compiler.evalWith(#1 x, &quot;fac(10)&quot;);
val y : Compiler.env * package = (_val, package{|...|})
&amp;gt; structure Y = unpack (#2 y) : (val it:int);
structure Y : sig val it : int end
&amp;gt; Y.it;
val it : int = 3628800
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The function &lt;code&gt;evalWith&lt;/code&gt; returns a tuple where the first element is the resulting environment after the evaluation and the second element is the package containing the result. For the second call to &lt;code&gt;evalWith&lt;/code&gt; the environment resulting from the first call is passed to it so the function &lt;code&gt;fac&lt;/code&gt; can be found.&lt;/p&gt;

&lt;h2&gt;Pretty Printing&lt;/h2&gt;

&lt;p&gt;One thing to note in the previous example is that the call to &lt;code&gt;unpack&lt;/code&gt; required knowing the type of what we were unpacking. This is usually the case but when writing a REPL we need to print the result of evaluating what is entered at the top level - and this could be any type depending on what the user entered to evaluate.&lt;/p&gt;

&lt;p&gt;There are some internal Alice ML modules that make it possible to do this. An example follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; import structure Reflect     from &quot;x-alice:/lib/system/Reflect&quot;;
&amp;gt; import structure PPComponent from &quot;x-alice:/lib/system/PPComponent&quot;;
&amp;gt; import structure PrettyPrint from &quot;x-alice:/lib/utility/PrettyPrint&quot;;
&amp;gt; val a = Compiler.prepareWith (Compiler.initialEnv, &quot;1+2&quot;);
val a : Compiler.env * (unit -&amp;gt; package) * t = (_val, _fn, _val)
&amp;gt; val b = (#2 a) ();
val b : package = package{|...|}
&amp;gt; val c = Reflect.reflectPackage b;
val c : Reflect.module * t = (_val, _lazy)
&amp;gt; val d = PPComponent.ppComp(#1 c, #2 c);
val d : doc = _val
&amp;gt; PrettyPrint.toString(d,40);
val it : string = &quot;val it : int = 3&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;Compiler.prepareWith&lt;/code&gt; function does not evaluate the string passed to it but performs part of the step of evaluation. It returns a tuple containing the environment which will result from evaluation, a function that when called will perform the evaluation, and a value representing the type of the result of the evaluation.&lt;/p&gt;

&lt;p&gt;In step (b) the evaluation function is called which returns the package containing the result. &lt;code&gt;Reflect.reflectPackage&lt;/code&gt; returns a tuple describing the package. These are passed to &lt;code&gt;PPComponent.ppComp&lt;/code&gt; to return a &lt;code&gt;PrettyPrint&lt;/code&gt; document. The pretty printer is based on &lt;a href=&quot;https://homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier&quot;&gt;A prettier printer&lt;/a&gt; by Phil Wadler. &lt;code&gt;PrettyPrint.toString&lt;/code&gt; converts this to a &lt;code&gt;string&lt;/code&gt; which could then be displayed by a REPL.&lt;/p&gt;

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

&lt;p&gt;As mentioned previously the Alice ML tools are written in Alice ML. The &lt;a href=&quot;https://github.com/aliceml/aliceml-alice/blob/b7841b4ad401f82d14e71d91445098146c97f5d6/tools/toplevel/CoreToplevel.aml#L133&quot;&gt;toplevel code&lt;/a&gt; uses the modules and functions outlined previously to implement the REPL and IDE. Unfortunately it&#39;s mostly undocumented but the source is available to show how it is implemented and used.&lt;/p&gt;

&lt;p&gt;There&#39;s much more to Alice ML run time use of types, including &lt;a href=&quot;http://www.ps.uni-saarland.de/alice/manual/pickling.html&quot;&gt;pickling&lt;/a&gt;, &lt;a href=&quot;http://www.ps.uni-saarland.de/alice/manual/components.html&quot;&gt;components&lt;/a&gt;, &lt;a href=&quot;http://www.ps.uni-saarland.de/alice/manual/library/sandbox.html#example&quot;&gt;sandboxing&lt;/a&gt;, and &lt;a href=&quot;http://www.ps.uni-saarland.de/alice/manual/distribution.html&quot;&gt;distribution&lt;/a&gt; .&lt;/p&gt;

&lt;p&gt;An interesting exercise would to to write a web based client to provide a &quot;Try Alice ML&quot; in a similar manner to other languages online playgrounds to allow trying Alice ML code snippets without needing to install it. I&#39;d also like to explore how close to a Self like environment could be done in an Alice ML system.&lt;/p&gt;
</description>
 </item>
 
 <item>
   <title>Distributed Wikipedia Mirrors in Freenet</title>
   <link>http://bluishcoder.co.nz/2017/05/16/distributed-wikipedia-mirrors-in-freenet.html</link>
   <pubDate>2017-05-16T17:00:00+12:00</pubDate>
   <guid>http://bluishcoder.co.nz/2017/05/16/distributed-wikipedia-mirrors-in-freenet</guid>
   <description>&lt;p&gt;There was a recent post about &lt;a href=&quot;https://ipfs.io/blog/24-uncensorable-wikipedia/&quot;&gt;uncensorable Wikipedia mirrors on IPFS&lt;/a&gt;. The IPFS project put a snapshot of the Turkish version of Wikipedia on IPFS. This is a great idea and something I&#39;ve wanted to try on &lt;a href=&quot;http://freenetproject.org/&quot;&gt;Freenet&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://freenetproject.org/&quot;&gt;Freenet&lt;/a&gt;  is an anonymous, secure, distributed datastore that I&#39;ve written &lt;a href=&quot;http://bluishcoder.co.nz/tags/freenet/index.html&quot;&gt;a few posts about&lt;/a&gt;. It wasn&#39;t too difficult to convert the IPFS process to something that worked on Freenet. For the Freenet keys linked in this post I&#39;m using a proxy that retrieves data directly from Freenet. This uses the &lt;a href=&quot;https://github.com/saces/SCGIPublisher&quot;&gt;SCGIPublisher plugin&lt;/a&gt; on a local Freenet node. The list of whitelisted keys usable are at &lt;a href=&quot;https://freenet.cd.pn/&quot;&gt;freenet.cd.pn&lt;/a&gt;. There is also a gateway available at &lt;a href=&quot;https://d6.gnutella2.info/freenet&quot;&gt;d6.gnutella2.info&lt;/a&gt;. The keys can also be used directly from a Freenet node, which is likely to be more performant than going through my underpowered proxy. Keep in mind that the &quot;distributed, can&#39;t be taken down&quot; aspect of the sites on Freenet is only when accessed directly through Freenet. It&#39;s quite likely my clearnet proxy won&#39;t be able to handle large amounts of traffic.&lt;/p&gt;

&lt;p&gt;I started with the &lt;a href=&quot;https://freenet.cd.pn/USK@HdWqD7afIfjYuqqE74kJDwhYa2eetoPL7cX4TRHtZwc,CeRayXsCZR6qYq5tDmG6r24LrEgaZT9L2iirqa9tIgc,AQACAAE/pitkern-wikipedia/2/&quot;&gt;Pitkern/Norfuk Wikipedia Snapshot&lt;/a&gt; as that was relatively small. Once I got the scripts for that working I converted the &lt;a href=&quot;https://freenet.cd.pn/USK@jYBa5KmwybC9mQ2QJEuuQhCx9VMr9bb3ul7w1TnyVwE,OMqNMLprCO6ostkdK6oIuL1CxaI3PFNpnHxDZClGCGU,AQACAAE/maori-wikipedia/6/&quot;&gt;Māori Wikipedia Snapshot&lt;/a&gt;. The lastest test I did was the &lt;a href=&quot;https://freenet.cd.pn/USK@m79AuzYDr-PLZ9kVaRhrgza45joVCrQmU9Er7ikdeRI,1mtRcpsTNBiIHOtPRLiJKDb1Al4sJn4ulKcZC5qHrFQ,AQACAAE/simple-wikipedia/0/&quot;&gt;Simple English Wikipedia Snapshot&lt;/a&gt;. This was much bigger so I did the version without images first. Later I plan to try the version with images when I&#39;ve resolved some issues with the current process.&lt;/p&gt;

&lt;p&gt;The Freenet keys for these mirrors are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;small&gt;USK@m79AuzYDr-PLZ9kVaRhrgza45joVCrQmU9Er7ikdeRI,1mtRcpsTNBiIHOtPRLiJKDb1Al4sJn4ulKcZC5qHrFQ,AQACAAE/simple-wikipedia/0/&lt;/small&gt;&lt;/li&gt;
&lt;li&gt;&lt;small&gt;USK@jYBa5KmwybC9mQ2QJEuuQhCx9VMr9bb3ul7w1TnyVwE,OMqNMLprCO6ostkdK6oIuL1CxaI3PFNpnHxDZClGCGU,AQACAAE/maori-wikipedia/5/&lt;/small&gt;&lt;/li&gt;
&lt;li&gt;&lt;small&gt;USK@HdWqD7afIfjYuqqE74kJDwhYa2eetoPL7cX4TRHtZwc,CeRayXsCZR6qYq5tDmG6r24LrEgaZT9L2iirqa9tIgc,AQACAAE/pitkern-wikipedia/2/&lt;/small&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;The keys are &#39;USK&#39; keys. These keys can be updated and have an edition number at the end of them. This number will increase as newer versions of the mirrors are pushed out. The Freenet node will often find the latest edition it knows about, or the latest edition can be searched for using &#39;-1&#39; as the edition number.&lt;/p&gt;

&lt;p&gt;The approach I took for the mirroring follows the approach IPFS took. I used the ZIM archives provided by &lt;a href=&quot;http://wiki.kiwix.org/wiki/Content_in_all_languages&quot;&gt;Kiwix&lt;/a&gt; and a &lt;a href=&quot;https://github.com/dignifiedquire/zim&quot;&gt;ZIM extractor&lt;/a&gt; written in Rust. The archive was extracted with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ extract_zim wikipedia_en_simple_all_nopic.zim
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This places the content in an &lt;code&gt;out&lt;/code&gt; directory. All HTML files are stored in a single directory, &lt;code&gt;out/A&lt;/code&gt;. In the &#39;simple english&#39; case that&#39;s over 170,000 files. This is too many files in a directory for Freenet to insert. I wrote a script in bash to split the directory so that files are stored in &#39;000/filename.html&#39; where &#39;000&#39; is the first three digits of a SHA256 hash of the base filename, computed with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ echo &quot;filename.html&quot;|sha256sum|awk &#39;{ print $1 }&#39;|cut -c &quot;1,2,3&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The script then went through and adjusted the article and image links on each page to point to the new location. The script does some other things to remove HTML tags that the Freenet HTML filter doesn&#39;t like and to add a footer about the origin of the mirror.&lt;/p&gt;

&lt;p&gt;Another issue I faced was that filenames with non-ascii characters would get handled differently by Freenet if the file was inserted as a single file vs being inserted as part of a directory. In the later case the file could not be retrieved later. I worked around this by translating filenames into ascii. A more robust solution would be needed here if I can&#39;t track down where the issue is occurring.&lt;/p&gt;

&lt;p&gt;This script to do the conversion is in my &lt;a href=&quot;https://github.com/doublec/freenet-wikipedia&quot;&gt;freenet-wikipedia&lt;/a&gt; githib repository. To convert a ZIM archive the steps are:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ wget http://download.kiwix.org/zim/wikipedia_pih_all.zim
$ extract_zim wikipedia_pih_all.zim
$ ./convert.sh
$ ./putdir.sh result my-mirror index.html
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;At completion of the insert this will output a list of keys. the &lt;code&gt;uri&lt;/code&gt; key is the one that can be shared for others to retrieve the insert. The &lt;code&gt;uskinsert&lt;/code&gt; key can be used to insert an updated version of the site:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ ./putdir.sh result my-mirror index.html &amp;lt;uskinsert key&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;convert.sh&lt;/code&gt; script was a quick &#39;proof of concept&#39; hack and could be improved in many ways. It is also very slow. It took about 24 hours to do the simple english conversion. I welcome patches and better ways of doing things.&lt;/p&gt;

&lt;p&gt;The repository includes a bash script, &lt;code&gt;putdir.sh&lt;/code&gt;, which will insert the site using the Freenet &lt;code&gt;ClientPutDiskDir&lt;/code&gt; API message. This is a useful way to get a directory online quickly but is not an optimal way of inserting something the size of the mirror. The initial request for the site downloads a manifest containing a list of all the files in the site. This can be quite large. It&#39;s 12MB for the Simple English mirror with no images. For the Māori mirror it&#39;s almost 50MB due to the images. The layout of the files doesn&#39;t take into account likely retrieval patterns. So images and scripts that are included in a page are not downloaded as part of the initial page request, but may result in pulling in larger amounts of data depending on how that file was inserted. A good optimisation project would be to analyse the directory to be inserted and create an optimal Freenet insert for faster retrieval. &lt;a href=&quot;https://github.com/freenet/pyFreenet&quot;&gt;pyFreenet&lt;/a&gt; has a utility, &lt;code&gt;freesitemgr&lt;/code&gt;, that can do some of this and there are other insertion tools like &lt;a href=&quot;https://github.com/Bombe/jSite&quot;&gt;jSite&lt;/a&gt; that may also do a better job.&lt;/p&gt;

&lt;p&gt;My goal was to do a proof of concept to see if a Wikipedia mirror on Freenet was viable. This seems to be the case and the Simple English mirror is very usable. Discussion on the &lt;a href=&quot;http://freesocial.draketo.de/fms_en.html&quot;&gt;FMS&lt;/a&gt; forum when I announced the site has been positive. I hope to improve the process over time and welcome any suggestions or enhancements to do that.&lt;/p&gt;

&lt;p&gt;What are the differences between this and the IPFS mirror? It&#39;s mostly down to how IPFS and Freenet work.&lt;/p&gt;

&lt;p&gt;In Freenet content is distributed across all nodes in the network. The node that has inserted the data can turn their node off and the content remains in the network. No single node has all the content. There is redundancy built in so if nodes go offline the content can still be fully retrieved. Node space is limited so as data is inserted into Freenet, data that is not requested often is lost to make room. This means that content that is not popular disappears over time. I suspect this means that some of the wikipedia pages will become inaccessible. This can be fixed by periodically reinserting the content, healing the specific missing content, or using the &lt;code&gt;KeepAlive&lt;/code&gt; plugin to keep content around. Freenet is encrypted and anonymous. You can browse Wikipedia pages without an attacker knowing that you are doing so. Your node doesn&#39;t share the Wikipedia data, except possibly small encrypted chunks of parts of it in your datastore, and it&#39;s difficult for the attacker to identify you as a sharer of that data. The tradeoff of this security is retrievals are slower.&lt;/p&gt;

&lt;p&gt;In IPFS a node inserting the content cannot be turned off until that content is pinned by another node on the network and fully retrieved. Nodes that pin the content keep the entire content on their node. If all pinned nodes go offline then the content is lost. All nodes sharing the content advertise that fact. It&#39;s easy to obtain the IP address of all nodes that are sharing Wikipedia files. On the positive side IPFS is potentially quite a bit faster to retrieve data.&lt;/p&gt;

&lt;p&gt;Both IPFS and Freenet have interesting use cases and tradeoffs. The intent of this experiment is not to present one or the other as a better choice, but to highlight what Freenet can do and make the content available within the Freenet network.&lt;/p&gt;
</description>
 </item>
 
 <item>
   <title>Installing GNAT and SPARK GPL Editions</title>
   <link>http://bluishcoder.co.nz/2017/04/27/installing-gnat-and-spark-gpl-editions.html</link>
   <pubDate>2017-04-27T23:00:00+12:00</pubDate>
   <guid>http://bluishcoder.co.nz/2017/04/27/installing-gnat-and-spark-gpl-editions</guid>
   <description>&lt;p&gt;GNAT is an implementation of the &lt;a href=&quot;http://www.adacore.com/adaanswers/about/ada&quot;&gt;Ada programming language&lt;/a&gt;. &lt;a href=&quot;http://www.spark-2014.org/about&quot;&gt;SPARK&lt;/a&gt; is a restricted subset of Ada for formally verifying programs. It provide features comparable to languages like &lt;a href=&quot;http://rust-lang.org/&quot;&gt;Rust&lt;/a&gt; and &lt;a href=&quot;http://www.ats-lang.org/&quot;&gt;ATS&lt;/a&gt;. A recent &lt;a href=&quot;http://www.electronicdesign.com/industrial/rust-and-spark-software-reliability-everyone&quot;&gt;article comparing SPARK to Rust&lt;/a&gt; caught my eye and I decided to spend some time learnig Ada and SPARK. This post just outlines installing an implementation of both, a quick test to see if the installation worked, and some things to read to learn. I hope to post more later as I learn more.&lt;/p&gt;

&lt;h2&gt;Installation&lt;/h2&gt;

&lt;p&gt;Download GNAT GPL from &lt;a href=&quot;http://libre.adacore.com/download&quot;&gt;libre.adacore.com&lt;/a&gt;. Choose &quot;Free Software or Academic Development&quot; and click &quot;Build Your Download Package&quot;. Select the platform and click the checkboxes next to the required components. For my case I chose them all but &quot;GNAT Ada 2016&quot; and &quot;Spark 2016&quot; are the main ones I needed.&lt;/p&gt;

&lt;p&gt;To install Ada and SPARK from the downloaded tar file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ tar xvf AdaCore-Download-2017-04-27_0537.tar
$ cd x86_64-linux/adagpl-2016/gnatgpl
$ mkdir ~/ada
$ tar -xf gnat-gpl-2016-x86_64-linux-bin.tar.gz
$ cd gnat-gpl-2016-x86_64-linux-bin
$ ./doinstall
...answer prompts about where to install...
...for this example I used /home/username/gnat...
$ export PATH=/home/username/gnat/bin:$PATH

$ cd ../sparkgpl
$ tar -xf spark-gpl-2016-x86_64-linux-bin.tar.gz
$ cd spark-gpl-2016-x86_64-linux-bin
$ ./doinstall
...answer prompts about where to install...
...it should pick up the location used above...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Be aware that the install comes with its own &lt;code&gt;gcc&lt;/code&gt; and other utilities. By putting it first in the &lt;code&gt;PATH&lt;/code&gt; they are used over the systems versions.&lt;/p&gt;

&lt;h2&gt;Testing GNAT&lt;/h2&gt;

&lt;p&gt;The following is a &quot;Hello World&quot; application in Ada:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;with Ada.Text_IO; use Ada.Text_IO;
procedure Hello is
begin
  Put_Line (&quot;Hello World!&quot;);
end Hello;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It imports a package, &lt;code&gt;Ada.Text_IO&lt;/code&gt;, and uses it so the package contents can be used without prefixing them with the package name. A procedure called &lt;code&gt;Hello&lt;/code&gt; is created that outlines a line of text. If put in a file &lt;code&gt;hello.adb&lt;/code&gt; it can be compiled with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ gnatmake hello.adp
gnatbind -x hello.ali
gnatlink hello.ali

$ ./hello
Hello World!
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Completely static executables can also be created:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ gnatmake hello.adb -bargs -static -largs -static
$ ldd hello
not a dynamic executable
$ ./hello
Hello World!
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Testing SPARK&lt;/h2&gt;

&lt;p&gt;I used an example taken from &lt;a href=&quot;http://www.spark-2014.org/entries/detail/spark-16-generating-counterexamples-for-failed-proofs&quot;&gt;Generating Counterexamples for failed Proofs&lt;/a&gt;. The SPARK checker, &lt;code&gt;gnatproof&lt;/code&gt;, requires a project file. This is the contents of &lt;code&gt;saturate.gpr&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;project Saturate is
   for Source_Dirs use (&quot;.&quot;);

   package Compiler is
      for Default_Switches (&quot;Ada&quot;) use (&quot;-gnatwa&quot;);
   end Compiler;
end Saturate;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It gives the project name, &lt;code&gt;Saturate&lt;/code&gt;, the location to search for source files (the current directory), and any compiler switches. The function to be implemented is a saturation function. It ensures a value given to it is in a specific range. In this case, a non-negative value less than or equal to 255. In file &lt;code&gt;saturate.ads&lt;/code&gt; we put the interface definition:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;with Interfaces;
use Interfaces;

function Saturate (Val : Unsigned_16) return Unsigned_16 with
  SPARK_Mode,
  Post =&amp;gt; Saturate&#39;Result &amp;lt;= 255 and then
         (if Val &amp;lt;= 255 then Saturate&#39;Result = Val);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The code first pulls the &lt;code&gt;Interfaces&lt;/code&gt; package into the current namespace. This provides unprefixed access to &lt;code&gt;Unsigned_16&lt;/code&gt;. It declares a function, &lt;code&gt;Saturate&lt;/code&gt;, that takes an &lt;code&gt;Unsigned_16&lt;/code&gt; as an argument and returns the same type. The &lt;code&gt;SPARK_Mode&lt;/code&gt; is an annotation that identifes code to be checked by SPARK. The &lt;code&gt;Post&lt;/code&gt; portion is a postcondition that the implementation of the function must adhere to. In this case the result must be less than 255 and if the given value is less than 255 then the result will be equal to the value.&lt;/p&gt;

&lt;p&gt;The implementation of the function is in a file &lt;code&gt;saturate.adb&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Saturate (Val : Unsigned_16) return Unsigned_16 with
  SPARK_Mode
is
begin
  return Unsigned_16&#39;Max (Val, 255);
end Saturate;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This calls the &lt;code&gt;Max&lt;/code&gt; function for &lt;code&gt;Unsigned_16&lt;/code&gt; types to return the maximum between the given value and 255. The code compiles with the Ada compiler:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ gnatmake saturate.adb
gcc -c saturate.adb
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It fails however when running the SPARK checker:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ gnatprove -Psaturate 
Phase 1 of 2: generation of Global contracts ...
Phase 2 of 2: flow analysis and proof ...
saturate.ads:6:11: medium: postcondition might fail (e.g. when Saturate&#39;Result = 255 and Val = 0)
Summary logged in gnatprove/gnatprove.out
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This tells us that the postcondition might fail if the given value to the function is &lt;code&gt;0&lt;/code&gt; and the result is &lt;code&gt;255&lt;/code&gt;. This is because we are using &lt;code&gt;Max&lt;/code&gt; - given the value &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;Saturate&lt;/code&gt;, the &lt;code&gt;Max&lt;/code&gt; of &lt;code&gt;0&lt;/code&gt; and &lt;code&gt;255&lt;/code&gt; is &lt;code&gt;255&lt;/code&gt;. The function result will be &lt;code&gt;255&lt;/code&gt;. The postcondition however states that the result should be equal to val - it should be &lt;code&gt;0&lt;/code&gt;. Changing the function call to &lt;code&gt;Min&lt;/code&gt; fixes it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ gnatprove -Psaturate 
Phase 1 of 2: generation of Global contracts ...
Phase 2 of 2: flow analysis and proof ...
Summary logged in gnatprove/gnatprove.out
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Having a postcondition that states what the result should be is probably unlikely in a lot of code. If the signature was the following, would SPARK find the error still?:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Saturate (Val : Unsigned_16) return Unsigned_16 with
  SPARK_Mode,
  Post =&amp;gt; Saturate&#39;Result &amp;lt;= 255

$ gnatprove -Psaturate 
Phase 1 of 2: generation of Global contracts ...
Phase 2 of 2: flow analysis and proof ...
saturate.ads:6:11: medium: postcondition might fail,
         cannot prove Saturate&#39;Result &amp;lt;= 255 (e.g. when Saturate&#39;Result = 256)
Summary logged in gnatprove/gnatprove.out
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Apparently so. Now it identifies that the result can be 256. Other examples following different contracts on the function are &lt;a href=&quot;http://www.spark-2014.org/entries/detail/spark-16-generating-counterexamples-for-failed-proofs&quot;&gt;in the original article&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Documentation&lt;/h2&gt;

&lt;p&gt;The &lt;a href=&quot;http://docs.adacore.com/gnat_ugn-docs/html/gnat_ugn/gnat_ugn.html&quot;&gt;GNAT User&#39;s Guide for Native Platforms&lt;/a&gt; and &lt;a href=&quot;http://docs.adacore.com/spark2014-docs/html/ug/&quot;&gt;Spark 2014 User&#39;s Guide&lt;/a&gt; contains the instructions for the main tools. GNAT can &lt;a href=&quot;http://docs.adacore.com/gnat_ugn-docs/html/gnat_ugn/gnat_ugn/the_gnat_compilation_model.html#mixed-language-programming&quot;&gt;interface with C and C++&lt;/a&gt;. There is &lt;a href=&quot;http://libre.adacore.com/developers/documentation&quot;&gt;a full list of documentation here&lt;/a&gt;. Two useful books covering Ada and Spark:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://www.amazon.com/Building-High-Integrity-Applications-SPARK/dp/1107656842&quot;&gt;Building High Integrity Applications with SPARK&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.amazon.com/Programming-Ada-2012-John-Barnes-ebook/dp/B00JXIIGMO&quot;&gt;Programming in Ada 2012&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;Some technical papers that give a quick overview of Ada:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://www.adacore.com/knowledge/technical-papers/safe-and-secure-software-an-invitation-to-ada-2012/&quot;&gt;Safe and Secure Software - An Invitation to Ada 2012&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://libre.adacore.com/developers/technical-papers-single/ada-for-the-c-or-java-developer&quot;&gt;Ada for the C++ or Java Developer&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;I used the command line tools here but there is a &lt;code&gt;gps&lt;/code&gt; command which is a full graphical IDE which may be more approachable. I&#39;m looking forward to using Ada and SPARK and seeing how they compare to tools like Rust and ATS.&lt;/p&gt;
</description>
 </item>
 
  </channel> 
</rss>
