<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Haskell Exists</title>
    <link href="http://blog.haskell-exists.com/yuras/atom.xml" rel="self" />
    <link href="http://blog.haskell-exists.com/yuras" />
    <id>http://blog.haskell-exists.com/yuras/atom.xml</id>
    <author>
        <name>Yuras Shumovich</name>
        <email>shumovishy@gmail.com</email>
    </author>
    <updated>2016-03-15T00:00:00Z</updated>
    <entry>
    <title>Turn GHC into a frontend for miniSTG</title>
    <link href="http://blog.haskell-exists.com/yuras/posts/turn-ghc-into-frontend-for-ministg.html" />
    <id>http://blog.haskell-exists.com/yuras/posts/turn-ghc-into-frontend-for-ministg.html</id>
    <published>2016-03-15T00:00:00Z</published>
    <updated>2016-03-15T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="info">
    March 15, 2016
    
    	
	<br/><a href='mailto:shumovichy@gmail.com'>Yuras Shumovich</a>
	
    
</div>

<p>TLDR: <a href="https://github.com/Yuras/ghc/commits/miniSTG">Here is a patch</a> for GHC to dump STG in a form compatible with miniSTG.</p>
<h1 id="ministg">MiniSTG</h1>
<p>The Spineless Tagless G-machine (STG) is an <a href="http://research.microsoft.com/apps/pubs/default.aspx?id=67083">abstract machine</a> designed to run lazy functional languages. An abstract code for it, an STG language, is a minimal lazy functional language, GHC <a href="https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/StgSynType">uses</a> it as an intermediate representation for haskell code.</p>
<p><a href="https://wiki.haskell.org/Ministg">MiniSTG</a> is an interpreter for STG language. It is a bit limited, <a href="https://github.com/bjpop/ministg/blob/1908a9ad7653a95518473ba5f220e04f571989bc/src/Ministg/AST.hs#L31">only integral literals</a> are supported, and <a href="https://github.com/bjpop/ministg/blob/1908a9ad7653a95518473ba5f220e04f571989bc/src/Ministg/AST.hs#L201">very few primops</a> are provided. But it is very useful if you want to study how haskell code is executed by GHC. The most interesting its feature is <a href="https://wiki.haskell.org/Ministg#Execution_tracing">execution tracing</a>.</p>
<p>To show few examples, lets define boxed integers:</p>
<div class="sourceCode"><pre class="sourceCode c"><code class="sourceCode c">zero = CON(Int <span class="dv">0</span>);

one = CON(Int <span class="dv">1</span>);

plus = FUN(x y -&gt; <span class="kw">case</span> x of {
	Int i -&gt; <span class="kw">case</span> y of {
		Int j -&gt; <span class="kw">case</span> plus# i j of {
			k -&gt; let {
				r = CON(Int k);
				} in r;
		}
	}
});

main = THUNK(plus one one);</code></pre></div>
<p>Here <code>Int</code> is a constructor for boxed integers (you don’t have to define constructors upfront), <code>zero</code> and <code>one</code> define boxed literals. The next declaration is more interesting, <code>plus</code> is a function that takes two arguments. They are expected to be boxed integers, and <code>case</code> is used to unboxed them. Then built-in primop <code>plus#</code> performs the real work to add two unboxed integers. Finally the result is reboxed and returned. The last line defines an entry point for the program. The output:</p>
<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="kw">ministg</span> --noprelude -s EA main.stg
<span class="kw">(Int</span> 2<span class="kw">)</span></code></pre></div>
<p>Now lets define a list:</p>
<div class="sourceCode"><pre class="sourceCode c"><code class="sourceCode c">nil = CON(Nil);

con = FUN(x xs -&gt; let {
	r = CON(List x xs)
	} in r
);

length = FUN(l -&gt; <span class="kw">case</span> l of {
	Nil -&gt; zero;
	List x xs -&gt; let {
		n = THUNK(length xs);
		} in plus one n;
});</code></pre></div>
<p>Here <code>nil</code> is an empty list, <code>con</code> prepends a value to a list, and <code>length</code> calculates length of a list using the <code>plus</code> function we already defined. Lets test it:</p>
<div class="sourceCode"><pre class="sourceCode c"><code class="sourceCode c">list1 = THUNK(con zero nil);
list2 = THUNK(con zero list1);
list3 = THUNK(con zero list2);
list4 = THUNK(con zero list3);

main = THUNK(length list4);</code></pre></div>
<p>Output:</p>
<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="kw">ministg</span> --noprelude -s EA main.stg
<span class="kw">(Int</span> 4<span class="kw">)</span></code></pre></div>
<p>I hope you got the idea. There are few restrictions: the only way to allocate anything on heap is to use <code>CON</code>, <code>FUN</code> or <code>THUNK</code> inside <code>let</code> or on top level, so the next code is invalid because it tries to allocate a list cell outside of <code>let</code> (compare with the definition above):</p>
<div class="sourceCode"><pre class="sourceCode c"><code class="sourceCode c">con = FUN(x xs -&gt;
	CON(List x xs)
);</code></pre></div>
<p>Also all function arguments should be allocated on heap, you can’t pass a complex expression to a function. So the next code is invalid:</p>
<div class="sourceCode"><pre class="sourceCode c"><code class="sourceCode c">length = FUN(l -&gt; <span class="kw">case</span> l of {
	Nil -&gt; zero;
	List x xs -&gt; plus one (length xs);
});</code></pre></div>
<p>MiniSTG doesn’t support pattern matching on literals, so you have to use <code>eq#</code> and <code>intToBool#</code> primops to compare boxed integers:</p>
<div class="sourceCode"><pre class="sourceCode c"><code class="sourceCode c">eq = FUN(x y -&gt; <span class="kw">case</span> x of {
	Int i -&gt; <span class="kw">case</span> y of {
		Int j -&gt; <span class="kw">case</span> eq# i j of {
			k -&gt; intToBool# k
		};
	};
});

main = THUNK(eq one one);</code></pre></div>
<p>Output:</p>
<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="kw">ministg</span> --noprelude -s EA main.stg
<span class="kw">True</span></code></pre></div>
<h1 id="ghc">GHC</h1>
<p>Writing in STG is fun, but how real haskell code looks when translated into STG? GHC has a <code>-ddump-stg</code> flag to dump it, but unfortunately it looks far from what miniSTG accepts:</p>
<div class="sourceCode"><pre class="sourceCode c"><code class="sourceCode c">f_rn0 :: GHC.Types.Int -&gt; GHC.Types.Int
[GblId, Arity=<span class="dv">1</span>, Str=DmdType, Unf=OtherCon []] =
    sat-only \r [ds_s1Mn]
        <span class="kw">case</span> ds_s1Mn of wild_s1Mo {
          GHC.Types.I# ds1_s1Mp [Occ=Once!] -&gt;
              <span class="kw">case</span> ds1_s1Mp of _ [Occ=Dead] {
                __DEFAULT -&gt;
                    let {
                      sat_s1Ms [Occ=Once] :: GHC.Types.Int
                      [LclId, Str=DmdType] =
                          \u []
                              let {
                                sat_s1Mr [Occ=Once] :: GHC.Types.Int
                                [LclId, Str=DmdType] =
                                    \u [] GHC.Enum.pred GHC.Enum.$fEnumInt wild_s1Mo;
                              } in  f_rn0 sat_s1Mr;
                    } in  GHC.Num.* GHC.Num.$fNumInt wild_s1Mo sat_s1Ms;
                <span class="dv">0</span># -&gt; GHC.Types.I# [<span class="dv">1</span>#];
              };
        };</code></pre></div>
<p>Even if I remove all irrelevant information, you will probably not recognize factorial function, but at least now it looks similar to miniSTG syntax:</p>
<div class="sourceCode"><pre class="sourceCode c"><code class="sourceCode c">f_rn0 = [ds_s1Mn]
        <span class="kw">case</span> ds_s1Mn of wild_s1Mo {
          GHC.Types.I# ds1_s1Mp -&gt;
              <span class="kw">case</span> ds1_s1Mp of _ {
                __DEFAULT -&gt;
                    let {
                      sat_s1Ms = []
                              let {
                                sat_s1Mr = []
                                    GHC.Enum.pred GHC.Enum.$fEnumInt wild_s1Mo;
                              } in  f_rn0 sat_s1Mr;
                    } in  GHC.Num.* GHC.Num.$fNumInt wild_s1Mo sat_s1Ms;
                <span class="dv">0</span># -&gt; GHC.Types.I# [<span class="dv">1</span>#];
              };
        };</code></pre></div>
<p>The biggest difference, except pattern matching on unboxed literals, is <code>case</code> expression:</p>
<div class="sourceCode"><pre class="sourceCode c"><code class="sourceCode c"><span class="kw">case</span> a of b {
	__DEFAULT -&gt; ...
	...
}</code></pre></div>
<p>Here <code>b</code> is an alias for the result of <code>a</code> (note that <code>a</code> could be an expression), it corresponds to “as patter” in haskell. In miniSTG it can be represented as two nested cases:</p>
<div class="sourceCode"><pre class="sourceCode c"><code class="sourceCode c"><span class="kw">case</span> a of {
	b -&gt; <span class="kw">case</span> b of {
		...
	}
}</code></pre></div>
<p>Otherwise the conversion is trivial. The patch mentioned at the beginning tries to automatically convert GHC syntax to miniSTG one.</p>
<h1 id="using-ghc-and-ministg-together">Using GHC and miniSTG together</h1>
<p>First we need custom prelude that defines all basic declarations (<code>Prelude.hs</code>):</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">{-# LANGUAGE PackageImports #-}</span>

<span class="kw">module</span> <span class="dt">Prelude</span>
( <span class="dt">Int</span>
, zero
, one
, plus
, sub
, mul
, eqInt
, <span class="dt">Bool</span> (<span class="fu">..</span>)
)
<span class="kw">where</span>

<span class="kw">import </span>&quot;base&quot; <span class="dt">Prelude</span> (<span class="dt">Bool</span> (..))

<span class="kw">data</span> <span class="dt">Int</span> <span class="fu">=</span> <span class="dt">Int</span>

<span class="ot">{-# NOINLINE zero #-}</span>
<span class="ot">zero ::</span> <span class="dt">Int</span>
zero <span class="fu">=</span> <span class="dt">Int</span>

<span class="ot">{-# NOINLINE one #-}</span>
<span class="ot">one ::</span> <span class="dt">Int</span>
one <span class="fu">=</span> <span class="dt">Int</span>

<span class="ot">{-# NOINLINE plus #-}</span>
<span class="ot">plus ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>
plus _ _ <span class="fu">=</span> <span class="dt">Int</span>

<span class="ot">{-# NOINLINE sub #-}</span>
<span class="ot">sub ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>
sub _ _ <span class="fu">=</span> <span class="dt">Int</span>

<span class="ot">{-# NOINLINE mul #-}</span>
<span class="ot">mul ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>
mul _ _ <span class="fu">=</span> <span class="dt">Int</span>

<span class="ot">{-# NOINLINE eqInt #-}</span>
<span class="ot">eqInt ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Bool</span>
eqInt _ _ <span class="fu">=</span> <span class="dt">False</span></code></pre></div>
<p>Note that implementation for the declarations is not important, we are going to implement them directly in miniSTG anyway. Now a test module (<code>Test.hs</code>):</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">module</span> <span class="dt">Test</span>
(test
)
<span class="kw">where</span>

pred<span class="ot"> ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>
pred n <span class="fu">=</span> n <span class="ot">`sub`</span> one

<span class="ot">f ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>
f n <span class="fu">|</span> n <span class="ot">`eqInt`</span> zero
    <span class="fu">=</span> one
    <span class="fu">|</span> <span class="dt">True</span>
    <span class="fu">=</span> n <span class="ot">`mul`</span> f (pred n)

two <span class="fu">=</span> plus one one
five <span class="fu">=</span> two <span class="ot">`plus`</span> two <span class="ot">`plus`</span> one

<span class="ot">test ::</span> <span class="dt">Int</span>
test <span class="fu">=</span> f five</code></pre></div>
<p>If you compile this module with <code>-ddump-ministg</code>, you get the next:</p>
<div class="sourceCode"><pre class="sourceCode c"><code class="sourceCode c">f = FUN(n_sJm -&gt; <span class="kw">case</span> eqIntz1Prelude n_sJm z0eroz1Prelude of {
	 wild_sJn -&gt; <span class="kw">case</span> wild_sJn of {
	     Falsez1GHCz1Types -&gt; let {
		  sat_sJp = THUNK(let {
			  sat_sJo = THUNK(subz1Prelude n_sJm onez1Prelude)
			  } in
			  f sat_sJo)
		  } in
		  mulz1Prelude n_sJm sat_sJp;
	     Truez1GHCz1Types -&gt; let {
		 res_var_ = THUNK(onez1Prelude)
		 } in
		 res_var_;
	     };
	 });

two = THUNK(plusz1Prelude onez1Prelude onez1Prelude);

sat_sJr = THUNK(let {
                sat_sJq = THUNK(plusz1Prelude two two)
                } in
                plusz1Prelude sat_sJq onez1Prelude);

testz1Test = THUNK(f sat_sJr);</code></pre></div>
<p>Names are encoded, e.g. <code>Falsez1GHCz1Types</code> is a <code>False</code> constructor from <code>GHC.Types</code> module. Lets add an entry point:</p>
<div class="sourceCode"><pre class="sourceCode c"><code class="sourceCode c">main = THUNK(testz1Test);</code></pre></div>
<p>and run it:</p>
<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="kw">ministg</span> --noprelude -s EA test.stg
<span class="kw">ministg</span>: undefined variable: <span class="st">&quot;eqIntz1Prelude&quot;</span></code></pre></div>
<p>Oops, we need to define prelude. Create <code>Prelude.stg</code> with the next content:</p>
<div class="sourceCode"><pre class="sourceCode c"><code class="sourceCode c">z0eroz1Prelude = CON(Int <span class="dv">0</span>);
onez1Prelude = CON(Int <span class="dv">1</span>);

plusz1Prelude = FUN(x y -&gt; <span class="kw">case</span> x of {
	Int i -&gt; <span class="kw">case</span> y of {
		Int j -&gt; <span class="kw">case</span> plus# i j of {
			k -&gt; let {
				r = CON(Int k)
				} in r;
		};
	};
});

subz1Prelude = FUN(x y -&gt; <span class="kw">case</span> x of {
	Int i -&gt; <span class="kw">case</span> y of {
		Int j -&gt; <span class="kw">case</span> sub# i j of {
			k -&gt; let {
				r = CON(Int k)
				} in r;
		};
	};
});

mulz1Prelude = FUN(x y -&gt; <span class="kw">case</span> x of {
	Int i -&gt; <span class="kw">case</span> y of {
		Int j -&gt; <span class="kw">case</span> mult# i j of {
			k -&gt; let {
				r = CON(Int k)
				} in r;
		};
	};
});

eqIntz1Prelude = FUN(x y -&gt; <span class="kw">case</span> x of {
	Int i -&gt; <span class="kw">case</span> y of {
		Int j -&gt; <span class="kw">case</span> eq# i j of {
			k -&gt; <span class="kw">case</span> intToBool# k of {
				True -&gt; true;
				False -&gt; false;
			};
		};
	};
});

true = CON(Truez1GHCz1Types);
false = CON(Falsez1GHCz1Types);</code></pre></div>
<p>Note that here we converted built-in <code>True</code> and <code>False</code> to the corresponding constructors from <code>GHC.Types</code>. Now we can run the program (note that we removed <code>--no-prelude</code> flag):</p>
<div class="sourceCode"><pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="kw">ministg</span> -s EA test.stg
<span class="kw">(Int</span> 120<span class="kw">)</span></code></pre></div>
<p>Yay! We have working frontend for miniSTG! Note that nothing stops us from using advanced haskell features like type classes because they are compiled out to simple constructs. For example, lets write the same factorial function using <code>Eq</code> type class:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="dt">Eq</span> a <span class="kw">where</span>
<span class="ot">  eq ::</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Bool</span>

<span class="kw">instance</span> <span class="dt">Eq</span> <span class="dt">Int</span> <span class="kw">where</span>
  eq <span class="fu">=</span> eqInt

<span class="ot">f ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>
f n <span class="fu">|</span> n <span class="ot">`eq`</span> zero
    <span class="fu">=</span> one
    <span class="fu">|</span> <span class="dt">True</span>
    <span class="fu">=</span> n <span class="ot">`mul`</span> f (pred n)</code></pre></div>
<p>If you don’t yet know how type classes work in haskell, then you have a good chance to figure it out from STG dump!</p>

<p><a href="/archive.html">More posts</a></p>
<p><a href='/atom.xml'>Atom feed</a></p>
]]></summary>
</entry>
<entry>
    <title>A beginners guide to API over-engineering</title>
    <link href="http://blog.haskell-exists.com/yuras/posts/a-begginers-guide-to-over-engineering.html" />
    <id>http://blog.haskell-exists.com/yuras/posts/a-begginers-guide-to-over-engineering.html</id>
    <published>2016-03-09T00:00:00Z</published>
    <updated>2016-03-09T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="info">
    March  9, 2016
    
    	
	<br/><a href='mailto:shumovichy@gmail.com'>Yuras Shumovich</a>
	
    
</div>

<p>It is hard to <a href="https://www.reddit.com/r/haskell/comments/49i0ax/3_approaches_to_monadic_api_design_in_haskell/d0sbben">quantify over-engineering</a>. But it is crucial for library API designer to identify over-engineering as early as possible, and keep API simple and easy to use.</p>
<p>Over-engineering is about unnecessary complexity. In theory it is easy to avoid: each time you see multiple alternatives and you are not sure which one is better, you should select the simplest one. It practice we don’t always can say what alternative is simpler. Often we even don’t see other alternative, so the decision is made without any complexity analyze.</p>
<p>It this post I’ll try to do a bit unusual thing. I’ll take a problem, and make the simples API design I can imaging. Then I’ll make a series of redesigns, successively increasing complexity, and we’ll discuss whether the complexity was necessary. You can decide yourself at which point the API becomes “over-engineered”.</p>
<p>The problem is question is a key/val database. The API we’ll start looks like the next:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">DB</span>
<span class="ot">open ::</span> FilePath <span class="ot">-&gt;</span> <span class="dt">IO</span> <span class="dt">DB</span>
<span class="ot">close ::</span> <span class="dt">DB</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> ()
<span class="ot">set ::</span> <span class="dt">DB</span> <span class="ot">-&gt;</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> ()
<span class="ot">get ::</span> <span class="dt">DB</span> <span class="ot">-&gt;</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> (<span class="dt">Maybe</span> <span class="dt">ByteString</span>)</code></pre></div>
<p>It is so simple, that I’m even not going to describe what it is doing. One even don’t need to know anything about monads to use it (I assume that do-notation doesn’t count). Now lets start iterating on the API.</p>
<h1 id="boilerplate">Boilerplate</h1>
<p>The first thing we notice is that three functions accept <code>DB</code> as an argument. What is user uses this functions in a row, like this:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">withDB ::</span> FilePath <span class="ot">-&gt;</span> (<span class="dt">DB</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> a) <span class="ot">-&gt;</span> <span class="dt">IO</span> a
withDB path use <span class="fu">=</span> bracket (new path) close use

withDB <span class="st">&quot;some.db&quot;</span> <span class="fu">$</span> \db <span class="ot">-&gt;</span> <span class="kw">do</span>
  set db <span class="st">&quot;key1&quot;</span> <span class="st">&quot;val1&quot;</span>
  set db <span class="st">&quot;key2&quot;</span> <span class="st">&quot;val2&quot;</span>
  <span class="fu">...</span>
  set db <span class="st">&quot;keyN&quot;</span> <span class="st">&quot;valN&quot;</span></code></pre></div>
<p>It is a boilerplate! We can avoid it using <code>Reader</code> monad transformer:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">set ::</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> <span class="dt">Reader</span> <span class="dt">DB</span> <span class="dt">IO</span> ()
<span class="ot">get ::</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> <span class="dt">Reader</span> <span class="dt">DB</span> <span class="dt">IO</span> (<span class="dt">Maybe</span> <span class="dt">ByteString</span>)</code></pre></div>
<p>Now user doesn’t have to pass <code>DB</code> explicitly:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">withDB ::</span> FilePath <span class="ot">-&gt;</span> <span class="dt">Reader</span> <span class="dt">DB</span> <span class="dt">IO</span> a <span class="ot">-&gt;</span> <span class="dt">IO</span> a
withDB path use <span class="fu">=</span> bracket (new path) close (runReader use)

withDB <span class="st">&quot;some.db&quot;</span> <span class="fu">$</span> <span class="kw">do</span>
  set <span class="st">&quot;key1&quot;</span> <span class="st">&quot;val1&quot;</span>
  set <span class="st">&quot;key2&quot;</span> <span class="st">&quot;val2&quot;</span>
  <span class="fu">...</span>
  set <span class="st">&quot;keyN&quot;</span> <span class="st">&quot;valN&quot;</span></code></pre></div>
<p>Kind of cool. But also we increased complexity of the API. Now user has to know about monads, transformers, lifting, etc. Even worse, we introduce new abstraction, implicit environment, which is inadequate to out problem. Imaging that you want two databases at the same time. With the initial version of API it is trivial:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">withDB <span class="st">&quot;some1.db&quot;</span> <span class="fu">$</span> \db1 <span class="ot">-&gt;</span> <span class="kw">do</span>
  withDB <span class="st">&quot;some2.db&quot;</span> <span class="fu">$</span> \db2 <span class="ot">-&gt;</span> <span class="kw">do</span>
    maybe_v1 <span class="ot">&lt;-</span> get db1 <span class="st">&quot;key1&quot;</span>
    set db2 <span class="st">&quot;key1&quot;</span> (fromMaybe <span class="st">&quot;&quot;</span> maybe_v1)

    maybe_v2 <span class="ot">&lt;-</span> get db1 <span class="st">&quot;key2&quot;</span>
    set db2 <span class="st">&quot;key2&quot;</span> (fromMaybe <span class="st">&quot;&quot;</span> maybe_v2)
    <span class="fu">...</span></code></pre></div>
<p>With the new API we’ll need a bit of code golfing to do something like that. Does a bit of boilerplate worse the complexity? How will users use the API more often? As a library writers, we can’t know, so it is better to stick with simpler version, the initial one. A bit of boilerplate is <a href="http://www.sandimetz.com/blog/2016/1/20/the-wrong-abstraction">far cheaper then wrong abstraction</a>. But lets accept this additional complexity, and make the next step.</p>
<h1 id="mtl">MTL</h1>
<p>At the previous step we introduced another issue. What if user uses his own transformer stack? We can’t compose different transformer stacks, we can only nest them. Lets introduce <code>mtl</code>!</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">set ::</span> (<span class="dt">MonadReader</span> <span class="dt">DB</span> m, <span class="dt">MonadIO</span> m) <span class="ot">=&gt;</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> m ()
<span class="ot">get ::</span> (<span class="dt">MonadReader</span> <span class="dt">DB</span> m, <span class="dt">MonadIO</span> m) <span class="ot">=&gt;</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> m (<span class="dt">Maybe</span> <span class="dt">ByteString</span>)</code></pre></div>
<p>Now API user has to understand type classes and <code>mtl</code>. Type signature becomes longer. Seasoned haskellers will certainly not find it problematic, but they are able to solve the issue with transformer stacks! By contrast newcomers will probably not be able to use the API at all. Note that the original design we started with doesn’t suffer from the issue with transformer stacks composition, simply because it doesn’t use transformers. Is the complexity necessary here? I think it is not, but you can decide for yourself.</p>
<h1 id="structured-data">Structured data</h1>
<p>It is rare to store plain strings in database. Usually we store some structured data, so we need a way to serialize and deserialize it. The standard way to handle serialization is to use type classes:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">set ::</span> (<span class="dt">MonadReader</span> <span class="dt">DB</span> m, <span class="dt">MonadIO</span> m, <span class="dt">Serialize</span> v) <span class="ot">=&gt;</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> v <span class="ot">-&gt;</span> m ()
<span class="ot">get ::</span> (<span class="dt">MonadReader</span> <span class="dt">DB</span> m, <span class="dt">MonadIO</span> m, <span class="dt">Serialize</span> v) <span class="ot">=&gt;</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> m (<span class="dt">Maybe</span> v)</code></pre></div>
<p>Looks good. Here I used <code>Serialize</code> type class from <code>cereal</code> package. Wait, but what if user uses <code>binary</code> package? What about the next:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">set ::</span> (<span class="dt">MonadReader</span> <span class="dt">DB</span> m, <span class="dt">MonadIO</span> m, <span class="dt">Binary</span> a) <span class="ot">=&gt;</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> m ()
<span class="ot">get ::</span> (<span class="dt">MonadReader</span> <span class="dt">DB</span> m, <span class="dt">MonadIO</span> m, <span class="dt">Binary</span> a) <span class="ot">=&gt;</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> m (<span class="dt">Maybe</span> a)</code></pre></div>
<p>Which one to use? Should we provide both variants? It will be really bad idea, because it will introduce incidental dependencies on <code>cereal</code> and/or <code>binary</code>. Should we introduce our own type class? Does it worse the complexity? No, it doesn’t. Serialization is not the core functionality for our library, so our users should not be forced to learn one more serialization API just to get a value from the database.</p>
<p>(A hint: key name sometimes is a structured data too, what about encoding and decoding it too just like we do for values?)</p>
<h1 id="effects">Effects</h1>
<p>Suppose we want to count all operations we do on the database. It could be useful for example for performance monitoring. We can just count everything inside <code>MVar</code> and provide an API to access it:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">getPerformanceCounters ::</span> <span class="dt">DB</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> <span class="dt">Counters</span></code></pre></div>
<p>But we should keep <a href="http://blog.haskell-exists.com/yuras/posts/effects-encoded-in-types-break-encapsulation.html">effects under control</a>! Lets use free monad to solve the issue:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Op</span> next
  <span class="fu">=</span> <span class="dt">Set</span> <span class="dt">ByteString</span> <span class="dt">ByteString</span> next
  <span class="fu">|</span> <span class="dt">Get</span> <span class="dt">ByteString</span> (<span class="dt">Maybe</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> next)
  <span class="kw">deriving</span> (<span class="dt">Functor</span>)

<span class="ot">interpret ::</span> <span class="dt">Free</span> <span class="dt">Op</span> a <span class="ot">-&gt;</span> <span class="dt">IO</span> a</code></pre></div>
<p>Ops, we just moved the core functionality of our library out to interpreter. Now the library does everything except writing to and reading from database. I hope it is obviously over-engineering, so I’ll stop right here.</p>
<h1 id="conclusion">Conclusion</h1>
<p>So monad transformers, free monads, etc. are bad and should be avoided? No, they are cool and useful. But as any other tool, they have their own application areas. There is nothing wrong in tranformer stack, <code>mtl</code> or free monad used in implementation, but please think twice before exposing them to external API. And certainly there are legitimate use cases where you really need them in API. Design API thoughtfully and keep it simple.</p>

<p><a href="/archive.html">More posts</a></p>
<p><a href='/atom.xml'>Atom feed</a></p>
]]></summary>
</entry>
<entry>
    <title>Realtime collaborative editor. Algebraic properties of the problem.</title>
    <link href="http://blog.haskell-exists.com/yuras/posts/realtime-collaborative-editor.html" />
    <id>http://blog.haskell-exists.com/yuras/posts/realtime-collaborative-editor.html</id>
    <published>2016-03-05T00:00:00Z</published>
    <updated>2016-03-05T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="info">
    March  5, 2016
    
    	
	<br/><a href='mailto:shumovichy@gmail.com'>Yuras Shumovich</a>
	
    
</div>

<p>Collaborative editors (or <a href="https://en.wikipedia.org/wiki/Collaborative_real-time_editor">RTCE</a>) are very popular this days. There are lots of open source and proprietary solutions. So I was not surprised when I got a request to build one.</p>
<p>But I was surprised that I can’t find exhaustive description of technologies used to implement RTCE. Probably the best source I found <a href="http://www.codecommit.com/blog/java/understanding-and-applying-operational-transformation">here</a>, it describes the general idea and pitfalls of RCTE implementations based on operational transformation (<a href="https://en.wikipedia.org/wiki/Operational_transformation">OT</a>). Unfortunately it can’t be used to implement custom RTCE immediately – the algorithm is not explicitly stated, and correctness of the solution is not clear. And the <a href="http://dl.acm.org/citation.cfm?id=66926.66963&amp;coll=portal&amp;dl=ACM">original paper</a> contains substantially more complex algorithm.</p>
<p>While reading different materials about the topic, I noticed that the problem has pretty reach set of algebraic properties. Exploring them allowed me to formulate the algorithm and proof its correctness. I’ll try to document the results below. Probably the most important result is a set of properties which we should prove by equation reasoning or check automatically to ensure correctness.</p>
<h1 id="document-operations">Document operations</h1>
<p>Suppose we have a document <span class="math inline">\(A\)</span>, and some operation <span class="math inline">\(a\)</span> transforms it to other document <span class="math inline">\(B\)</span>:</p>
<p><span class="math display">\[ B = a(A) \]</span></p>
<p>For example, document could be a text, and operation can insert or delete few characters in it. There is an identity operation <span class="math inline">\(e\)</span>, it doesn’t change the document.</p>
<p>The operation <span class="math inline">\(a\)</span> is tightly coupled with <span class="math inline">\(A\)</span>. We can’t apply it to <span class="math inline">\(B\)</span> or any other document. E.g. if <span class="math inline">\(a\)</span> deletes <code>&quot;world&quot;</code> from <code>&quot;hello world!&quot;</code>, then it makes no sense to delete it from <code>&quot;hello !&quot;</code>. But there can exist other operation <span class="math inline">\(b\)</span>, which operates on <span class="math inline">\(B\)</span>:</p>
<p><span class="math display">\[ C = b(B) \]</span></p>
<p>And we can apply them in a row:</p>
<p><span class="math display">\[ C = b(a(A)) \label{composition}\tag{1} \]</span></p>
<p>That forms a new operation <span class="math inline">\(c\)</span>, which is a composition of <span class="math inline">\(a\)</span> and <span class="math inline">\(b\)</span> (note the order in composition, compare with <span class="math inline">\((\ref{composition})\)</span>):</p>
<p><span class="math display">\[
c = a b \\
C = c(A)
\]</span></p>
<p>Two operations are equivalent if they transform equal documents into equal. Identity operation <span class="math inline">\(e\)</span> has usual properties with respect to composition:</p>
<p><span class="math display">\[
e a = a \\
a e = a
\]</span></p>
<p>To make sense composition should be associative:</p>
<p><span class="math display">\[ (ab)c = a(bc) = abc \label{associativity}\tag{2}\]</span></p>
<p>But it is not commutative in general case, so <span class="math inline">\(ab\)</span> is not necessary equivalent to <span class="math inline">\(ba\)</span>. Also each operation has an inverse because we always can undo any change.</p>
<h1 id="example-text-document">Example: text document</h1>
<p>As an example, lets see how operations can be implemented for simple plain text document. There are two atomic edits, one to insert at given position some string, and other to delete starting from given position a number of characters:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Edit</span>
  <span class="fu">=</span> <span class="dt">Insert</span> <span class="dt">Int</span> <span class="dt">Text</span>
  <span class="fu">|</span> <span class="dt">Delete</span> <span class="dt">Int</span> <span class="dt">Int</span>
  <span class="kw">deriving</span> (<span class="dt">Show</span>)</code></pre></div>
<p>Composite operation can be just an array or atomic edits</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">newtype</span> <span class="dt">Patch</span> <span class="fu">=</span> <span class="dt">Patch</span>
  {<span class="ot"> edits ::</span> <span class="dt">Vector</span> <span class="dt">Edit</span>
  }
  <span class="kw">deriving</span> (<span class="dt">Show</span>)

<span class="kw">instance</span> <span class="dt">Monoid</span> <span class="dt">Patch</span> <span class="kw">where</span>
  mempty <span class="fu">=</span> empty
  mappend <span class="fu">=</span> append

<span class="ot">empty ::</span> <span class="dt">Patch</span>
empty <span class="fu">=</span> <span class="dt">Patch</span> Vector.empty

<span class="ot">singleton ::</span> <span class="dt">Edit</span> <span class="ot">-&gt;</span> <span class="dt">Patch</span>
singleton edit <span class="fu">=</span> <span class="dt">Patch</span> (Vector.singleton edit)

<span class="ot">append ::</span> <span class="dt">Patch</span> <span class="ot">-&gt;</span> <span class="dt">Patch</span> <span class="ot">-&gt;</span> <span class="dt">Patch</span>
append p1 p2 <span class="fu">=</span> <span class="dt">Patch</span> (edits p1 <span class="fu">Vector.++</span> edits p2)</code></pre></div>
<p>Associativity <span class="math inline">\((\ref{associativity})\)</span> is obviously satisfied. Applying <code>Edit</code> and <code>Patch</code> to a document is trivial, so lets omit that.</p>
<h1 id="operational-transformation">Operational transformation</h1>
<p>Suppose we have a document <span class="math inline">\(S\)</span>, and two clients at the same time apply some arbitrary operations:</p>
<p><span class="math display">\[
A = a(S) \\
B = b(S)
\]</span></p>
<p>Now the documents diverged, and we need some other operations <span class="math inline">\(a^\prime\)</span> and <span class="math inline">\(b^\prime\)</span> to transform them into a consistent state <span class="math inline">\(S^\prime\)</span>:</p>
<p><span class="math display">\[
b^\prime(A) = a b^\prime(S) = S^\prime = b a^\prime(S) = b a^\prime(S)
\]</span></p>
<p>They should satisfy the obvious property:</p>
<p><span class="math display">\[ a b^\prime = b a^\prime \label{commute}\tag{3}\]</span></p>
<p>It can be represented using the following diagram:</p>
<div class="figure">
<img src="../images/ot_ot.png" alt="" />

</div>
<p>Lets assume that there is an operational transformation <span class="math inline">\(T\)</span> that it produces <span class="math inline">\(a^\prime\)</span> and <span class="math inline">\(b^\prime\)</span> for each <span class="math inline">\(a\)</span> and <span class="math inline">\(b\)</span> such that <span class="math inline">\((\ref{commute})\)</span> is satisfied:</p>
<p><span class="math display">\[ (a^\prime, b^\prime) = T(a, b) \label{OT}\tag{4}\]</span></p>
<p>It is important to keep in mind that <span class="math inline">\(T\)</span> is not necessary symmetric, so <span class="math inline">\(T(a, b)\)</span> is not necessary equivalent to <span class="math inline">\(T(b, a)\)</span>. We should be careful not to mess with arguments, and we will draw diagrams preserving the order – the first argument always on left.</p>
<p>Now we should check that operation composition doesn’t break <span class="math inline">\((\ref{commute})\)</span> under operational transformation <span class="math inline">\(T\)</span>. Lets try a composite operation as the second argument of <span class="math inline">\(T\)</span>, see the following diagram.</p>
<div class="figure">
<img src="../images/ot_compose.png" alt="" />

</div>
<p>(<em>UPDATE</em> I messed things up a bit in the following proof, see <a href="https://www.reddit.com/r/haskell/comments/491ou1/realtime_collaborative_editor_algebraic/d0oflug">here</a>. Basically, the proof make sense for the <code>Edit</code> and <code>Patch</code> in the example, but in general case <span class="math inline">\((\ref{5c})\)</span> can’t be proven, we should require it instead.)</p>
<p>Here by definition</p>
<p><span class="math display">\[ (a^\prime, b^\prime) = T(a, b) \label{5a}\tag{5a} \]</span> <span class="math display">\[ (a^{\prime\prime}, c^\prime) = T(a^\prime, c) \label{5b}\tag{5b} \]</span> <span class="math display">\[ (a^{\prime\prime}, b^\prime c^\prime) = T(a, b c) \label{5c}\tag{5c} \]</span></p>
<p>From <span class="math inline">\((\ref{5a})\)</span> follows <span class="math inline">\(a b^\prime = b a^\prime\)</span>. From <span class="math inline">\((\ref{5b})\)</span> follows <span class="math inline">\(a^\prime c^\prime = c a^{\prime\prime}\)</span>. Then</p>
<p><span class="math display">\[ a b^\prime c^\prime = b a^\prime c^\prime = b c a^{\prime\prime} \]</span></p>
<p>That is exactly what <span class="math inline">\((\ref{commute})\)</span> states for <span class="math inline">\((\ref{5c})\)</span>. The same way we can prove that for a composed operation as the first argument of <span class="math inline">\(T\)</span>.</p>
<p>By induction we can prof that <span class="math inline">\((\ref{commute})\)</span> is satisfied for arbitrary complex operations. It is more important then it sounds – it allows us to define operations in terms of a small number of basic operations. We define operational transformation only for them, and get it for complex operations automatically.</p>
<h1 id="back-to-the-example">Back to the example</h1>
<p>Lets defined <span class="math inline">\(T\)</span> for the plain text document example. For insert operations, we simply adjust insert position for one of them:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">transform ::</span> <span class="dt">Edit</span> <span class="ot">-&gt;</span> <span class="dt">Edit</span> <span class="ot">-&gt;</span> (<span class="dt">Edit</span>, <span class="dt">Edit</span>)
transform (<span class="dt">Insert</span> at1 t1) (<span class="dt">Insert</span> at2 t2) <span class="fu">=</span>
  <span class="kw">if</span> at1 <span class="fu">&gt;</span> at2
    <span class="kw">then</span> (<span class="dt">Insert</span> (at1 <span class="fu">+</span> Text.length t2) t1, <span class="dt">Insert</span> at2 t2)
    <span class="kw">else</span> (<span class="dt">Insert</span> at1 t1, <span class="dt">Insert</span> (at2 <span class="fu">+</span> Text.length t1) t2)</code></pre></div>
<p>The case with two delete operations is a bit more involved. If ranges doesn’t overlap, we adjust starting position, the same way as for insert operations. But if they overlap, we should be careful not to delete more then necessary.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">transform (<span class="dt">Delete</span> from1 count1) (<span class="dt">Delete</span> from2 count2)
  <span class="fu">|</span> from2 <span class="fu">&gt;=</span> from1 <span class="fu">+</span> count1
  <span class="fu">=</span> (<span class="dt">Delete</span> from1 count1, <span class="dt">Delete</span> (from2 <span class="fu">-</span> count1) count2)

  <span class="fu">|</span> from1 <span class="fu">&gt;=</span> from2 <span class="fu">+</span> count2
  <span class="fu">=</span> (<span class="dt">Delete</span> (from1 <span class="fu">-</span> count2) count1, <span class="dt">Delete</span> from2 count2)

  <span class="fu">|</span> from1 <span class="fu">&gt;=</span> from2 <span class="fu">&amp;&amp;</span> from1 <span class="fu">+</span> count1 <span class="fu">&lt;=</span> from2 <span class="fu">+</span> count2
  <span class="fu">=</span> (<span class="dt">Delete</span> from2 <span class="dv">0</span>, <span class="dt">Delete</span> from2 (count2 <span class="fu">-</span> count1))

  <span class="fu">|</span> from2 <span class="fu">&gt;=</span> from1 <span class="fu">&amp;&amp;</span> from2 <span class="fu">+</span> count2 <span class="fu">&lt;=</span> from1 <span class="fu">+</span> count1
  <span class="fu">=</span> (<span class="dt">Delete</span> from1 (count1 <span class="fu">-</span> count2), <span class="dt">Delete</span> from1 <span class="dv">0</span>)

  <span class="fu">|</span> from1 <span class="fu">&gt;=</span> from2
  <span class="fu">=</span> <span class="kw">let</span> d <span class="fu">=</span> from2 <span class="fu">+</span> count2 <span class="fu">-</span> from1
    <span class="kw">in</span> (<span class="dt">Delete</span> from2 (count1 <span class="fu">-</span> d), <span class="dt">Delete</span> from2 (count2 <span class="fu">-</span> d))

  <span class="fu">|</span> otherwise
  <span class="fu">=</span> <span class="kw">let</span> d <span class="fu">=</span> from1 <span class="fu">+</span> count1 <span class="fu">-</span> from2
    <span class="kw">in</span> (<span class="dt">Delete</span> from1 (count1 <span class="fu">-</span> d), <span class="dt">Delete</span> from1 (count2 <span class="fu">-</span> d))</code></pre></div>
<p>The first two guards handle the case of not overlapping edits. The second two – when one covers another. The last two – partially overlapping edits. The mixed case, when we transform insert and delete operations, is analogous:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">transform (<span class="dt">Insert</span> at t) (<span class="dt">Delete</span> from count)
  <span class="fu">|</span> at <span class="fu">&gt;=</span> from <span class="fu">&amp;&amp;</span> at <span class="fu">&lt;</span> from <span class="fu">+</span> count
  <span class="fu">=</span> (<span class="dt">Insert</span> from Text.empty, <span class="dt">Delete</span> from (count <span class="fu">+</span> Text.length t))
  <span class="fu">|</span> at <span class="fu">&lt;</span> from
  <span class="fu">=</span> (<span class="dt">Insert</span> at t, <span class="dt">Delete</span> (from <span class="fu">+</span> Text.length t) count)
  <span class="fu">|</span> otherwise
  <span class="fu">=</span> (<span class="dt">Insert</span> (at <span class="fu">-</span> count) t, <span class="dt">Delete</span> from count)

transform d<span class="fu">@</span><span class="dt">Delete</span>{} i<span class="fu">@</span><span class="dt">Insert</span>{} <span class="fu">=</span>
  Tuple.swap <span class="fu">$</span> transform i d</code></pre></div>
<p>Note that the implementation above is not the only possible one. For example I decided to preserve both edits in case of two inserts into the same position. Other implementations can e.g. prefer the first insert, or ignore both conflicting inserts.</p>
<p>Transforming composed operations follows the inductive logic of proving <span class="math inline">\((\ref{commute})\)</span> for them:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">transform ::</span> <span class="dt">Patch</span> <span class="ot">-&gt;</span> <span class="dt">Patch</span> <span class="ot">-&gt;</span> (<span class="dt">Patch</span>, <span class="dt">Patch</span>)
transform (<span class="dt">Patch</span> a) b <span class="fu">=</span>
  <span class="kw">let</span> step (a&#39;, b&#39;) a1 <span class="fu">=</span>
        <span class="kw">let</span> (a1&#39;, b&#39;&#39;) <span class="fu">=</span> transformEdit a1 b&#39;
        <span class="kw">in</span> (append a&#39; (singleton a1&#39;), b&#39;&#39;)
  <span class="kw">in</span> Vector.foldl&#39; step (empty, b) a

<span class="ot">transformEdit ::</span> <span class="dt">Edit</span> <span class="ot">-&gt;</span> <span class="dt">Patch</span> <span class="ot">-&gt;</span> (<span class="dt">Edit</span>, <span class="dt">Patch</span>)
transformEdit a (<span class="dt">Patch</span> b) <span class="fu">=</span>
  <span class="kw">let</span> step (a&#39;, b&#39;) b1 <span class="fu">=</span>
        <span class="kw">let</span> (a&#39;&#39;, b1&#39;) <span class="fu">=</span> Edit.transform a&#39; b1
        <span class="kw">in</span> (a&#39;&#39;, append b&#39; (singleton b1&#39;))
  <span class="kw">in</span> Vector.foldl&#39; step (a, empty) b</code></pre></div>
<p>Equation reasoning and QuickCheck can be used to prove properties we developed in previous section, but we omit that.</p>
<h1 id="algorithm">Algorithm</h1>
<p>Now we are ready to describe the algorithm.</p>
<p>Server maintains a state, which is a tuple of 3 elements <span class="math inline">\((S, n, s)\)</span>: the current document state <span class="math inline">\(S\)</span>; an integral number to identify current revision; a sequence of operations <span class="math inline">\(s = [..., a, b, c]\)</span> applied to the initial revision to get <span class="math inline">\(S\)</span>. Server receives from clients tuples of 2 elements, an operations <span class="math inline">\(p\)</span> to apply and a number identifying a revision to apply the operation to.</p>
<div class="figure">
<img src="../images/ot_server.png" alt="" />

</div>
<p>Each time new tuple received from a client, server finds the corresponding revision <span class="math inline">\(R\)</span> and transforms <span class="math inline">\(p\)</span> over all the operations from <span class="math inline">\(R\)</span> to <span class="math inline">\(S\)</span>:</p>
<p><span class="math display">\[ (b^\prime c^\prime, p^\prime) = T(b c, p) \]</span></p>
<p>Server broadcasts <span class="math inline">\(p^\prime\)</span> to all clients (we assume order-preserving channel), applies it to <span class="math inline">\(S\)</span>, increments revision <span class="math inline">\(n\)</span> and appends <span class="math inline">\(p^\prime\)</span> to <span class="math inline">\(s\)</span>:</p>
<p><span class="math display">\[ (S, n, s) \Rightarrow (p^\prime(S), n + 1, (s, p^\prime)) \label{server}\tag{SERVER}\]</span></p>
<p>Client side is a bit more involved. Each client maintains a state, a tuple of 5 elements: the last known server document state <span class="math inline">\(S\)</span>, the last known server revision <span class="math inline">\(n\)</span>, the operation it is trying to push to server <span class="math inline">\(a\)</span> (in-flight operations), a buffered operation <span class="math inline">\(b\)</span>, and current local document state <span class="math inline">\(C\)</span>. Both <span class="math inline">\(a\)</span> and <span class="math inline">\(b\)</span> could be (and initially are) identity operations <span class="math inline">\(e\)</span>. In-flight operation is operations we sent to server, but not got an acknowledgment. All the local operations before the acknowledgment are buffered in <span class="math inline">\(b\)</span>, then client tries to push <span class="math inline">\(b\)</span>.</p>
<p>More formally, when local change is received, it is applied to the local document <span class="math inline">\(C\)</span> and combined with buffered operation <span class="math inline">\(b\)</span>:</p>
<p><span class="math display">\[ (S, n, a, b, C) \Rightarrow (S, n, a, b p, p(C)) \label{local}\tag{LOCAL}\]</span></p>
<p>When remote change <span class="math inline">\(p\)</span> is received form server (it is the operation <span class="math inline">\(p^\prime\)</span> broadcasted by <span class="math inline">\((\ref{server})\)</span> rule), and <span class="math inline">\(p\)</span> is not equivalent to <span class="math inline">\(a\)</span>, client applies it to <span class="math inline">\(S\)</span> to get new server document state and increments <span class="math inline">\(n\)</span>. Then client transforms <span class="math inline">\(a\)</span> and <span class="math inline">\(b\)</span> and updates <span class="math inline">\(C\)</span> according the following rule:</p>
<p><span class="math display">\[ (S, n, a, b, C) \Rightarrow (p(S), n + 1, a^\prime, b^\prime, p&#39;&#39;(C)) \label{remote}\tag{REMOTE} \]</span> where <span class="math display">\[ (p^\prime, a^\prime) = T(p, a) \]</span> <span class="math display">\[ (p^{\prime\prime}, b^\prime) = T(p^\prime, b) \]</span></p>
<p>It will be more clear from the following diagram. Here <span class="math inline">\(S^\prime\)</span> represents new server document state, and <span class="math inline">\(C^\prime\)</span> represents new local document state.</p>
<div class="figure">
<img src="../images/ot_client.png" alt="" />

</div>
<p>We need two more state transition rules. When client receives remote change <span class="math inline">\(p\)</span> which is equivalent to <span class="math inline">\(a\)</span>, then it means that server accepted our in-flight operation. We should simply discard <span class="math inline">\(a\)</span> (replace it with identity operation <span class="math inline">\(e\)</span>), apply <span class="math inline">\(p\)</span> to server document state and increment revision:</p>
<p><span class="math display">\[ (S, n, a, b, C) \Rightarrow (p(S), n + 1, e, b, C) \label{ack}\tag{ACK}\]</span> where <span class="math display">\[ a = p \]</span></p>
<p>And finally client should push buffered operations to server. Whenever <span class="math inline">\(a\)</span> is equivalent to identity but <span class="math inline">\(b\)</span> is not, client sends a tuple of 2 elements, buffered operations <span class="math inline">\(b\)</span> and last know server revision <span class="math inline">\(n\)</span>, to server, see <span class="math inline">\((\ref{server})\)</span> rule. Client state transition rule:</p>
<p><span class="math display">\[ (S, n, a, b, C) \Rightarrow  (S, n, b, e, C) \label{send}\tag{SEND} \]</span> where <span class="math display">\[ a = e \land b \ne e \]</span></p>
<h1 id="convergence">Convergence</h1>
<p>Lets now prove that server and client versions of the document will converge eventually. First of all we notice that the client’s algorithm is built to preserve the following property for each state:</p>
<p><span class="math display">\[  (S, n, a, b, C) \Rrightarrow C = ab(S) = b(a(S)) \label{invariant}\tag{6}\]</span></p>
<p>I.e. local document state is <span class="math inline">\(ab\)</span> far from the last known server document state. Lets prove it for each client’s transition rule. After applying <span class="math inline">\((\ref{local})\)</span> we obviously have</p>
<p><span class="math display">\[ abp(S) = p(ab(S)) = p(C) \]</span></p>
<p>Proved. After <span class="math inline">\((\ref{remote})\)</span></p>
<p><span class="math display">\[ p a^\prime b^\prime (S) = ap^\prime b^\prime (S) = a b p^{\prime\prime}(S)
	= p^{\prime\prime} (ab(S)) = p^{\prime\prime}C \]</span></p>
<p>(We used <span class="math inline">\((\ref{commute})\)</span> here.) Proved. I’ll omit profs for <span class="math inline">\((\ref{ack})\)</span> and <span class="math inline">\((\ref{send})\)</span> – they are analogous.</p>
<p>If client receives operations from server in the same order it sends them, then his last known server document state obviously converges to server’s document state. Now it is enough to prove that <span class="math inline">\(a\)</span> and <span class="math inline">\(b\)</span> (in-flight and buffered operations) will become identity operations <span class="math inline">\(e\)</span> eventually, and we prove convergence:</p>
<p><span class="math display">\[ C = ab(S) = ee(S) = S \]</span></p>
<p>From <span class="math inline">\((\ref{send})\)</span> follows that <span class="math inline">\(b\)</span> vanishes whenever <span class="math inline">\(a\)</span> vanishes. And from <span class="math inline">\((\ref{ack})\)</span> follows that <span class="math inline">\(a\)</span> vanishes when <span class="math inline">\(a = p\)</span> condition is met. It means that server should acknowledge client’s in-flight operations by equivalent one. Lets prove it is the case.</p>
<p>Lets client state after the last acknowledge is <span class="math inline">\((S, n, e, a, C)\)</span>. Server state at the same revision is <span class="math inline">\((S, n, s)\)</span>. Now client applies <span class="math inline">\((\ref{send})\)</span> rule, sends a tuple <span class="math inline">\((a, n)\)</span> to the server and jumps to <span class="math inline">\((S, n, a, e, C)\)</span> state.</p>
<p>At the same time server receives operation from some other client. Server applies <span class="math inline">\((\ref{server})\)</span> rule. Lets denote transformed operation as <span class="math inline">\(b\)</span>, then server broadcasts <span class="math inline">\(b\)</span> and jumps to the next state:</p>
<p><span class="math display">\[ (b(S), n + 1, (s, b)) \]</span></p>
<p>Midtime the client applies (a number of) local operation <span class="math inline">\(c\)</span>, according to <span class="math inline">\((\ref{local})\)</span>, it performs the next transition:</p>
<p><span class="math display">\[ (S, n, a, e, C) \Rightarrow (S, n, a, c, c(C))\]</span></p>
<p>Then client receives <span class="math inline">\(b\)</span> from server and applies <span class="math inline">\((\ref{remote})\)</span>:</p>
<p><span class="math display">\[ (S, n, a, c, c(C)) \Rightarrow (b(S), n + 1, a^\prime, c^\prime, b^{\prime\prime}(C)) \]</span> where <span class="math display">\[ (b^\prime, a^\prime) = T(b, a) \]</span> <span class="math display">\[ (b^{\prime\prime}, a^\prime) = T(b^\prime, c) \]</span></p>
<p>At the same time server receives (<span class="math inline">\(a\)</span>, n) from client, applies <span class="math inline">\((\ref{server})\)</span> and broadcasts <span class="math inline">\(a^\prime\)</span>:</p>
<p><span class="math display">\[ (b(S), n + 1, (s, b)) \Rightarrow (ba^\prime(S), n + 2, (s, b, a^\prime)) \]</span> where <span class="math display">\[ (b^\prime, a^\prime) = T(b, a) \]</span> <span class="math display">\[ (b^{\prime\prime}, a^\prime) = T(b^\prime, c) \]</span></p>
<p>Note that “where” clause in the last step on server exactly identical to the last step performed on client. It means that the operation broadcasted by server is equivalent to the in-flight operational on client. Client receives it and applies <span class="math inline">\((\ref{ack})\)</span>:</p>
<p><span class="math display">\[ (b(S), n + 1, a^\prime, c^\prime, b^{\prime\prime}(C)) \Rightarrow (ba^\prime(S), n + 2, e, c^\prime, b^{\prime\prime}a^\prime(C)) \]</span></p>
<p>Now client is ready to push the next operation. When all local operations are pushed and all remote operations are received, client state is <span class="math inline">\((S^\prime, n^\prime, e, e, C^\prime)\)</span>, where <span class="math inline">\(S^\prime = C^\prime\)</span>. We just proved convergence.</p>
<h1 id="demo-implementation">Demo implementation</h1>
<p>You can find demo <a href="https://github.com/Yuras/colab/blob/8f6955dbf93c648897d73be4825313b9a7a24fa3/Client.hs">client</a> and <a href="https://github.com/Yuras/colab/blob/8f6955dbf93c648897d73be4825313b9a7a24fa3/Server.hs">server</a> on github. If you are interested in ready-to-use demo, then checkout <a href="https://github.com/Yuras/colab/blob/8f6955dbf93c648897d73be4825313b9a7a24fa3/CliServer.hs">cli to server</a> and <a href="https://github.com/Yuras/colab/blob/8f6955dbf93c648897d73be4825313b9a7a24fa3/UIClient.hs">gtk ui for client</a> Just start server and a number of clients and start typing. (Client requires theaded runtime)</p>
<p>The operation representation as an array of basic edits is simple. But it is hard to compare operations – two equivalent ones could be represented differently. That is why the demo compare operations by applying them to a document and comparing results. More sophisticated representation usually comes with a some kind of normalized form. See for example how it is implemented in <a href="http://hackage.haskell.org/package/ot-0.2.0.0/docs/Control-OperationalTransformation-Text.html">ot</a> package.</p>

<p><a href="/archive.html">More posts</a></p>
<p><a href='/atom.xml'>Atom feed</a></p>
]]></summary>
</entry>
<entry>
    <title>Incremental lexer for IDE</title>
    <link href="http://blog.haskell-exists.com/yuras/posts/incremental-lexer.html" />
    <id>http://blog.haskell-exists.com/yuras/posts/incremental-lexer.html</id>
    <published>2015-11-05T00:00:00Z</published>
    <updated>2015-11-05T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="info">
    November  5, 2015
    
    	
	<br/><a href='mailto:shumovichy@gmail.com'>Yuras Shumovich</a>
	
    
</div>

<p>I’m not an active IDE user. This days I use XCode sometimes, because writing Objective-C without an IDE is a pain. Otherwise I use vim without any plugins.</p>
<p>But I always was interested in IDE internals. Many years ago I was working on Visual Studio debugger plugin for some proprietary RTOS, and I was impressed how huge and complex Visual Studio was. One person can’t create anything comparable. But that doesn’t mean we should not try :)</p>
<p>So I finally found time to experiment with some IDE features. In this post I’ll describe the roadmap and present the first phase – incremental lexer.</p>
<h1 id="what-i-would-like-to-achieve">What I would like to achieve</h1>
<p>The most basic IDE features are syntax highlighting, navigation, autocompletion and refactoring. To be usefull IDE should be interactive – we expect instant response to our actions. That is the most interesting aspect for me. So the feature list I’d like to experiment with:</p>
<ul>
<li>incremental lexing</li>
<li>source highlighting</li>
<li>incremental parsing</li>
<li>navigation</li>
<li>incremental typechecking</li>
<li>type directed autocompletion</li>
</ul>
<p>The goal is to make these work in soft real time, without blocking UI. For example, if we can’t hightlight code after an edit quickly enough, then lets show raw text and highlight it in backgroud. If we can’t show all possible autocompletions, then lets show only available ones and add more later. Basically all foreground operations should have complexity not worse then <span class="math inline">\(O(\log n)\)</span> whatever <span class="math inline">\(n\)</span> is.</p>
<p>Raw performance and memory usage are not the direct goals. Building full featured IDE is not the goal too.</p>
<h1 id="incremental-lexing">Incremental lexing</h1>
<p>Incremental lexer should maintain a list of tokens while user is editing the code. Ideally it should reuse already processed tokens.</p>
<p>It is not so hard, for example <code>yi</code> <a href="https://yi-editor.github.io/posts/2014-09-04-incremental-parsing/">caches</a> intermediate lexer states. On modification we just find the last valid point and restart from it.</p>
<p>But that way on each modification we have to process all the code from the modification to the end of the file. It is OK for highlighting though, because we can analyze the code only as far as it is necessary to hightlight visible part of the file. But we want to use results of lexing to build syntax tree incrementally, and nodes of the tree can be annotated with results of incremental type checking. We don’t want to lose all the work on each keystroke.</p>
<p>The solution is obvious – lets analyze code only until the next valid point. Basically, we stop when:</p>
<ul>
<li>we are outsize the affected area, and</li>
<li>the current token parsed is equal to the cached one at this point, and</li>
<li>the lexer state is equal to the cached one at this point</li>
</ul>
<h1 id="conventions">Conventions</h1>
<p>(You can <a href="#implementation">skip</a> the details.)</p>
<p>More formally, we have a tokinizer</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">tokenize ::</span> <span class="dt">State</span> <span class="ot">-&gt;</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Result</span>

<span class="kw">data</span> <span class="dt">Result</span>
  <span class="fu">=</span> <span class="dt">Partial</span> (<span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Result</span> <span class="dt">Token</span>)  <span class="co">-- continuation</span>
  <span class="fu">|</span> <span class="dt">Done</span> <span class="dt">Token</span> <span class="dt">State</span> <span class="dt">Int</span> <span class="dt">Int</span>          <span class="co">-- token, lexer state,</span>
                                      <span class="co">-- length of input consumed</span>
                                      <span class="co">-- and lookahead</span></code></pre></div>
<p>It never fails, instead it returns some special token representing lexical error.</p>
<p>Lexer maintains the current source code as a list of characters</p>
<p><span class="math display">\[C = [c_0, c_1, ..., c_n]\]</span></p>
<p>and list of lexemes</p>
<p><span class="math display">\[L = [L_0, L_1, ..., L_n]\]</span></p>
<p>where</p>
<ul>
<li><span class="math inline">\(L_i = (t_i, s_i, l_i, a_i)\)</span></li>
<li><span class="math inline">\(t_i\)</span> is a token,</li>
<li><span class="math inline">\(s_i\)</span> – lexer state after reading the token,</li>
<li><span class="math inline">\(l_i\)</span> – number of characters consumed by lexer to produce the token, and</li>
<li><span class="math inline">\(a_i\)</span> – lookahead, number of characters lexer examined without consuming.</li>
</ul>
<p>The following invariant should be reserved:</p>
<p><span class="math display">\[\sum_{k=0}^{n}l_i = length(C) \label{invariant}\tag{1}\]</span></p>
<p>Single edit of the source code can be represented as a tuple</p>
<p><span class="math display">\[(p_s, p_e, C&#39;)\]</span></p>
<p>where</p>
<ul>
<li><span class="math inline">\([p_s, p_e)\)</span> – interval in <span class="math inline">\(C\)</span> to delete</li>
<li><span class="math inline">\(C&#39;\)</span> – list of characters to insert.</li>
</ul>
<p>For example, deleting 5 characters starting from position 3 will look like</p>
<p><span class="math display">\[(3, 8, \emptyset)\]</span></p>
<p>where <span class="math inline">\(\emptyset\)</span> – empty list.</p>
<p>Inserting string “hello” at position 3 will look like</p>
<p><span class="math display">\[(3, 3, hello)\]</span></p>
<h1 id="dirty-region">Dirty region</h1>
<p>After each edit, lexer should invalidate part of the lexeme list <span class="math inline">\(L\)</span> by replacing lexemes from <span class="math inline">\(L_i\)</span> to <span class="math inline">\(L_j\)</span> with special <span class="math inline">\(D\)</span> token representing dirty region:</p>
<p><span class="math display">\[ [L_0, ...,L_{i-1}, (D, \_, l, 0), L_{j+1},..., L_n] \]</span></p>
<p>where</p>
<p><span class="math display">\[l = \sum_{k=i}^{j}l_k - (p_e-p_s) + length(C&#39;)\]</span></p>
<p>is a length of the dirty area, lookahead is zero and lexer state is irrelevant. Note that the invariant <span class="math inline">\((\ref{invariant})\)</span> is satisfied.</p>
<p>Finding <span class="math inline">\(L_j\)</span> is straightforward, it should be the first lexeme, such that</p>
<p><span class="math display">\[\sum_{k=0}^{j-1}l_k &gt; p_e\]</span></p>
<p>Finding <span class="math inline">\(L_i\)</span> is a bit harder. Obviously it should satisfy</p>
<p><span class="math display">\[\sum_{k=0}^{i-1}l_k &lt; p_s\]</span></p>
<p>but it doesn’t take lookahead into account. Lexema <span class="math inline">\(L_k\)</span> should be invalidated whenever the edit affects any of <span class="math inline">\(a_k\)</span> characters after it.</p>
<p>Lets introduce a function to calculate lookahead of two subsequent lexemes</p>
<p><span class="math display">\[lookahead(L_k,L_{k+1}) = max (a_{k+1}, a_k-l_{k+1}) \label{lookahead}\tag{2}\]</span></p>
<p>It can be easily generalized to any number of lexemes. Now the beginning of the dirty region should satisfy</p>
<p><span class="math display">\[\sum_{k=0}^{i-1}l_k + lookahead(L_0,...,L_{i-1}) &lt; p_s\]</span></p>
<h1 id="lexing">Lexing</h1>
<p>Now it is time to do actuall lexing of dirty region. Lets length of <span class="math inline">\(C\)</span> before the dirty region is <span class="math inline">\(p\)</span></p>
<p><span class="math display">\[p = length (L_0, L_1, ..., L_{i-1}) = \sum_{k=0}^{i-1}l_k\]</span></p>
<p>Lets feed tokinizer with the last valid state and the input</p>
<p><span class="math display">\[ Done(t&#39;, s&#39;, l&#39;, a&#39;) = tokenize(s_{i-1}, [c_{p+1},c_{p+2},...])\]</span></p>
<p>(If the tokenizer returns <code>Partial</code>, we should feed more input. Lets assume it always returns <code>Done</code>.)</p>
<p>Now we can insert new lexeme into <span class="math inline">\(L\)</span>. If <span class="math inline">\(l&#39; &lt; l\)</span>, then</p>
<p><span class="math display">\[ [L_0, ...,L_{i-1}, (t&#39;, s&#39;, l&#39;, a&#39;), (D, \_, l-l&#39;, 0), L_{j+1},..., L_n] \]</span></p>
<p>If <span class="math inline">\(l&#39; &gt; l\)</span>, then <span class="math inline">\(L_{j+1}\)</span> (and probably few more lexemes) is invalid too</p>
<p><span class="math display">\[ [L_0, ...,L_{i-1}, (t&#39;, s&#39;, l&#39;, a&#39;), (D, \_, l+l_{j+1}-l&#39;, 0), L_{j+2},..., L_n] \]</span></p>
<p>The <span class="math inline">\(l&#39;=l\)</span> case is more interesting. We should chech whether we are done, so lets run tokenizer one time more</p>
<p><span class="math display">\[ Done(t&#39;&#39;, s&#39;&#39;, l&#39;&#39;, a&#39;&#39;) = tokenize(s&#39;, [c_{p+l&#39;+1},c_{p+l&#39;+2},...])\]</span></p>
<p>If <span class="math inline">\((t&#39;&#39; = t_{j+1}) \land (s&#39;&#39; = s_{j+1})\)</span>, then we are done</p>
<p><span class="math display">\[ [L_0, ...,L_{i-1}, (t&#39;, s&#39;, l&#39;, a&#39;), L_{j+1},..., L_n] \]</span></p>
<p>otherwise the next lexeme is still invalid</p>
<p><span class="math display">\[ [L_0, ...,L_{i-1}, (t&#39;, s&#39;, l&#39;, a&#39;), (t&#39;&#39;, s&#39;&#39;, l&#39;&#39;, a&#39;&#39;), (D, \_, l+l_{j+1}-l&#39;-l&#39;&#39;, 0), L_{j+2},..., L_n] \]</span></p>
<p>In reallity we stop after a limited number of steps to ensure user gets instant feedback. E.g. when large chunk of code pasted into editor, only the initial part of it is visible, and we can hightlight it before the whole chunk is processed, and then continue processing the rest.</p>
<h1 id="complexity-of-operations">Complexity of operations</h1>
<p>In theory everything is good. But it practice, we have a number of operations with <span class="math inline">\(O(n)\)</span> complexity:</p>
<ul>
<li>to find <span class="math inline">\(L_i\)</span> and <span class="math inline">\(L_j\)</span> we have to traverse the entire <span class="math inline">\(L\)</span> list</li>
<li>to find the first dirty region, we have to traverse <span class="math inline">\(L\)</span> too</li>
<li>to update <span class="math inline">\(C\)</span> and to build an input <span class="math inline">\([c_{p+1},...]\)</span> for tokenizer, we have to traverse <span class="math inline">\(C\)</span> list</li>
</ul>
<p>That it not acceptable for real time UI.</p>
<p>The solution for the last issue is when know – it is a <a href="https://en.wikipedia.org/wiki/Rope_%28data_structure%29">Rope</a>. Basically it is a tree with small substrings of the whole string as a leafs. Each intermedite note is annotated with a length of a substring, represented by the subtrees, so insert, delete and split operations can be implemented with <span class="math inline">\(O(\log n)\)</span> complexity.</p>
<p>Rope can be <a href="http://hackage.haskell.org/package/fingertree">generalized</a> to arbitrary list with some monoid as an annotation. In our case, we can represent <span class="math inline">\(L\)</span> as a fingertree with the next monoid:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">
<span class="kw">data</span> <span class="dt">Size</span> <span class="fu">=</span> <span class="dt">Size</span>
  {<span class="ot"> chars ::</span> <span class="fu">!</span><span class="dt">Int</span>
  ,<span class="ot"> lookAhead ::</span> <span class="fu">!</span><span class="dt">Int</span>
  ,<span class="ot"> dirty ::</span> <span class="fu">!</span><span class="dt">Bool</span>
  }
  <span class="kw">deriving</span> (<span class="dt">Eq</span>, <span class="dt">Show</span>)

<span class="kw">instance</span> <span class="dt">Monoid</span> <span class="dt">Size</span> <span class="kw">where</span>
  mempty <span class="fu">=</span> <span class="dt">Size</span> <span class="dv">0</span> <span class="dv">0</span> <span class="dt">False</span>
  mappend (<span class="dt">Size</span> chars1 lookAhead1 dirty1)
          (<span class="dt">Size</span> chars2 lookAhead2 dirty2)
    <span class="fu">=</span> <span class="dt">Size</span> chars lookAhead dirty
    <span class="kw">where</span>
    chars <span class="fu">=</span> chars1 <span class="fu">+</span> chars2
    lookAhead <span class="fu">=</span> max lookAhead2 (lookAhead1 <span class="fu">-</span> chars2)
    dirty <span class="fu">=</span> dirty1 <span class="fu">||</span> dirty2</code></pre></div>
<p>Here <code>chars</code> represents <span class="math inline">\(l_k\)</span>, <code>lookahead</code> – <span class="math inline">\(a_k\)</span> (compare with <span class="math inline">\((\ref{lookahead})\)</span>), and <code>dirty</code> is <code>True</code> for <span class="math inline">\(D\)</span> and <code>False</code> otherwise.</p>
<p>That way we can implement all mentioned operations with <span class="math inline">\(O(\log n)\)</span> complexity.</p>
<h1 id="implementation">Implementation</h1>
<p>You can find the implementation on <a href="https://github.com/Yuras/tide">github</a>.</p>
<ul>
<li><a href="https://github.com/Yuras/tide/blob/master/src/TextBuffer.hs">TextBuffer.hs</a> contains implementation of <span class="math inline">\(C\)</span>,</li>
<li><a href="https://github.com/Yuras/tide/blob/master/src/TokenBuffer.hs">TokenBuffer.hs</a> contains implementation of <span class="math inline">\(L\)</span>,</li>
<li><a href="https://github.com/Yuras/tide/blob/master/src/Lex.hs">Lex.hs</a> implements the main lexer logic, and</li>
<li><a href="https://github.com/Yuras/tide/blob/master/src/HaskellLex.hs">HaskellLex.hs</a> is a simplified tokinizer for haskell.</li>
</ul>
<p>The is also a <a href="https://github.com/Yuras/tide/blob/master/ui.hs">UI</a> based on gtk3 with syntax highlighting implemented using the incremental lexer. It is fully asynchronous, so you can edit file while it is processed in background. It also logs to the console the region processed on each step.</p>
<p>A short <a href="../images/tide.ogv">video</a>.</p>
<p>Screenshot:</p>
<div class="figure">
<img src="../images/tide.png" alt="" />

</div>
<h1 id="final-notes">Final notes</h1>
<p>It is important to make sure tokenizer consumes limited number of characters on each run. For example, multiline comments can be pretty long, but we want to provide user with instant feedback. To achieve that, we can split comment token into <a href="https://github.com/Yuras/tide/blob/25c848afda25fe0b1a60536f04a27a5be39da683/src/HaskellLex.hs#L103">parts</a>. That is the reason we have <a href="https://github.com/Yuras/tide/blob/25c848afda25fe0b1a60536f04a27a5be39da683/src/HaskellLex.hs#L112">tokenizer state</a> in the first place.</p>
<p>Other issue is not solved yet. Each time user enters <code>{-</code> into the buffer, all the rest of the file becomes a comment until user enters the closing <code>-}</code>. It probably requires special handling to prevent unnecessary reprocessing.</p>

<p><a href="/archive.html">More posts</a></p>
<p><a href='/atom.xml'>Atom feed</a></p>
]]></summary>
</entry>
<entry>
    <title>Effects encoded in types break encapsulation</title>
    <link href="http://blog.haskell-exists.com/yuras/posts/effects-encoded-in-types-break-encapsulation.html" />
    <id>http://blog.haskell-exists.com/yuras/posts/effects-encoded-in-types-break-encapsulation.html</id>
    <published>2015-05-17T00:00:00Z</published>
    <updated>2015-05-17T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="info">
    May 17, 2015
    
    	
	<br/><a href='mailto:shumovichy@gmail.com'>Yuras Shumovich</a>
	
    
</div>

<p>One of the most important Haskell features for me is a clear separation of pure and impure code. I can say whether a function can have side effects only by looking to its type. For example, <code>print</code> can perform arbitrary side effect, while <code>(++)</code> can’t perform any:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">print<span class="ot"> ::</span> <span class="dt">Show</span> a <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">IO</span> ()
<span class="ot">(++) ::</span> [a] <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> [a]</code></pre></div>
<h1 id="restricted-side-effects">Restricted side effects</h1>
<p>But sometimes such the binary separation (pure vs impure) is not enough, we may need fine grained control on what side effects a function may perform. Lets quote <a href="http://book.realworldhaskell.org/read/programming-with-monads.html#id648782">RWH</a></p>
<blockquote>
<p>The blessing and curse of the IO monad is that it is extremely powerful. If we believe that careful use of types helps us to avoid programming mistakes, then the IO monad should be a great source of unease. Because the IO monad imposes no restrictions on what we can do, it leaves us vulnerable to all kinds of accidents.</p>
<p>How can we tame its power? Let’s say that we would like to guarantee to ourselves that a piece of code can read and write files on the local filesystem, but that it will not access the network. We can’t use the plain IO monad, because it won’t restrict us.</p>
</blockquote>
<p>And Haskell provides us with tools to restrict side effects to a known set. For example, we can define custom type class, that restricts effects to HTTP operations (we are ignoring some details, like error handling etc.):</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="dt">Monad</span> m <span class="ot">=&gt;</span> <span class="dt">MonadHttp</span> m <span class="kw">where</span>
<span class="ot">  get ::</span> <span class="dt">Url</span> <span class="ot">-&gt;</span> m <span class="dt">ByteString</span>
<span class="ot">  post ::</span> <span class="dt">Url</span> <span class="ot">-&gt;</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> m <span class="dt">ByteString</span></code></pre></div>
<p>Lets suppose we want to fetch weather information. It can look like the next:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">fetchWeather ::</span> <span class="dt">MonadHttp</span> m <span class="ot">=&gt;</span> m <span class="dt">Weather</span>
fetchWeather <span class="fu">=</span>
  parseWeather <span class="fu">&lt;$&gt;</span> get <span class="st">&quot;http://example.com/weather.json&quot;</span></code></pre></div>
<p>Note that <code>MonadHttp</code> doesn’t have <code>MonadIO</code> instance, so <code>fetchWeather</code> can’t perform any side effects except HTTP request. So far so good.</p>
<p>But later we decide to cache weather information in file. How can we do that? Lets define another type class for filesystem operations:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="dt">Monad</span> m <span class="ot">=&gt;</span> <span class="dt">MonadFS</span> m <span class="kw">where</span>
<span class="ot">  readFile ::</span> FilePath <span class="ot">-&gt;</span> m (<span class="dt">Maybe</span> <span class="dt">ByteString</span>)
<span class="ot">  writeFile ::</span> FilePath <span class="ot">-&gt;</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> m ()</code></pre></div>
<p>Then <code>fetchWeather</code> function will try to read weather information from a file, and perform HTTP request only if the file doesn’t exists:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">fetchWeather ::</span> (<span class="dt">MonadHttp</span> m, <span class="dt">MonadFS</span> m) <span class="ot">=&gt;</span> m <span class="dt">Weather</span>
fetchWeather <span class="fu">=</span> <span class="kw">do</span>
  json <span class="ot">&lt;-</span> <span class="kw">do</span>
    cached <span class="ot">&lt;-</span> readFile <span class="st">&quot;cache.json&quot;</span>
    <span class="kw">case</span> cached <span class="kw">of</span>
      <span class="dt">Just</span> json <span class="ot">-&gt;</span> return json
      <span class="dt">Nothing</span> <span class="ot">-&gt;</span> <span class="kw">do</span>
        json <span class="ot">&lt;-</span> get <span class="st">&quot;http://example.com/weather.json&quot;</span>
        writeFile <span class="st">&quot;cache.json&quot;</span> json
        return json
  return (parseWeather json)</code></pre></div>
<p>Note that the function can perform two types of side effects: make HTTP requests and access filesystem, and it is clearly reflected by its type. Excellent!</p>
<h1 id="encapsulation">Encapsulation</h1>
<p>But lets look from point of view of function’s users. After introducing the cache, they have to update their code to introduce new type constraint, <code>MonadFS</code>. That is not a big deal when we control all the client code, but what if we have a lot of downstream dependencies? People will be angry because we broke their code.</p>
<p>The main question is why our users even noticed the change? Introducing cache should be transparent for them because it is actually an implementation detail. People just want to get weather forecast, they don’t want to care where we get weather information from. Implementation details should be encapsulated, but <code>fetchWeather</code> leaks them via type classes for restricted effects.</p>
<p>The best way to encapsulate effects is not to restrict them. We should provide users with <code>fetchWeather</code> function that works in unrestricted <code>IO</code> monad:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">fetchWeatherIO ::</span> <span class="dt">IO</span> <span class="dt">Weather</span></code></pre></div>
<p>That way we are free to change its implementation and introduce other side effects without affecting users, e.g. we may cache weather information in database or global mutable variable.</p>
<h1 id="interface-vs-implementation">Interface vs implementation</h1>
<p>But that doesn’t mean that restricting side effects always is bad. It is just a tool, that can be useful sometimes, but it is not a silver bullet. Most of the time it should not be used in public interface, but it is good to have in implementation. The point of the article is that we should be careful when exposing side effects to users unless it is desired.</p>
<h1 id="on-exceptions">On exceptions</h1>
<p>It is interesting that the same arguments could be applied to exceptions vs <code>ExceptT</code> discussion (see <a href="http://www.reddit.com/r/haskell/comments/35sk6w/best_practices_for_using_exceptions_an_fp/">here</a>). A list of all exceptions function may throw (or a list of failures in error sum type) is actually an implementation detail. That sound counterintuitive, but we don’t actually need to handle all exceptional cases, so we don’t need a gigant sum type for them.</p>

<p><a href="/archive.html">More posts</a></p>
<p><a href='/atom.xml'>Atom feed</a></p>
]]></summary>
</entry>
<entry>
    <title>Haskell pdf-toolbox: new release, future API changes and design mistakes</title>
    <link href="http://blog.haskell-exists.com/yuras/posts/pdf-toolbox-release-future-api-changes-and-design-mistakes.html" />
    <id>http://blog.haskell-exists.com/yuras/posts/pdf-toolbox-release-future-api-changes-and-design-mistakes.html</id>
    <published>2015-03-06T00:00:00Z</published>
    <updated>2015-03-06T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="info">
    March  6, 2015
    
    	
	<br/><a href='mailto:shumovichy@gmail.com'>Yuras Shumovich</a>
	
    
</div>

<p>As you probably don’t know, I’m working on a PDF processing library in Haskell, <a href="https://github.com/Yuras/pdf-toolbox">pdf-toolbox</a>. It can parse PDF files, generate them, it supports encrypted files, it can do incremental updates, extract text, blah-blah-blah. If you are interested, let me outline the current state and my future plans.</p>
<h1 id="new-release">New release</h1>
<p>I just released new versions for all packages that belong to the library: <a href="https://hackage.haskell.org/package/pdf-toolbox-core">core</a> , <a href="https://hackage.haskell.org/package/pdf-toolbox-document">document</a> , <a href="https://hackage.haskell.org/package/pdf-toolbox-content">content</a> and <a href="https://hackage.haskell.org/package/pdf-toolbox-viewer">viewer</a>.</p>
<p>The main change: <code>pdf-toolbox-document</code> now supports encryption handler version 4, so it can handle files encrypted with <code>AES</code> algorithm. Also few bugs were fixed in <code>core</code> and <code>content</code>. As you can see, nothing terribly exciting, and the blog post is not about the release actually.</p>
<h1 id="current-state-of-the-head">Current state of the HEAD</h1>
<p>At the end of 2014 I started API rewrite. I mostly finished with the initial goals, though more work is necessary to fix viewer and examples to compile again. But when doing the rewrite I fount that the API is still far from ideal. Well, it is <em>bad</em>. That is why I decided to port the latest changes to stable branch and release it, and then continue working on API redesign.</p>
<h1 id="broken-api">Broken API</h1>
<p>I’m still not 100% sure what to do, and I’d like to know your opinion. Here the current plan.</p>
<h2 id="pdf-types">PDF types</h2>
<p>The design of <a href="https://hackage.haskell.org/package/pdf-toolbox-core-0.0.3.0/docs/Pdf-Toolbox-Core-Object-Types.html#t:Object">PDF types</a> is terrible. <a href="https://hackage.haskell.org/package/pdf-toolbox-core-0.0.3.0/docs/Pdf-Toolbox-Core-Object-Types.html#t:Boolean">Newtype over bool</a>?!! Yes, it was me who wrote that, but I did it more then 3 years ago, and I have no idea why I did that:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Object</span> a <span class="fu">=</span>
  <span class="dt">ONumber</span> <span class="dt">Number</span> <span class="fu">|</span>
  <span class="dt">OBoolean</span> <span class="dt">Boolean</span> <span class="fu">|</span>
  <span class="dt">OName</span> <span class="dt">Name</span> <span class="fu">|</span>
  <span class="dt">ODict</span> <span class="dt">Dict</span> <span class="fu">|</span>
  <span class="dt">OArray</span> <span class="dt">Array</span> <span class="fu">|</span>
  <span class="dt">OStr</span> <span class="dt">Str</span> <span class="fu">|</span>
  <span class="dt">OStream</span> (<span class="dt">Stream</span> a) <span class="fu">|</span>
  <span class="dt">ORef</span> <span class="dt">Ref</span> <span class="fu">|</span>
  <span class="dt">ONull</span>
  <span class="kw">deriving</span> (<span class="dt">Eq</span>, <span class="dt">Show</span>)

<span class="kw">newtype</span> <span class="dt">Boolean</span> <span class="fu">=</span> <span class="dt">Boolean</span> <span class="dt">Bool</span>
  <span class="kw">deriving</span> (<span class="dt">Eq</span>, <span class="dt">Show</span>)

<span class="kw">newtype</span> <span class="dt">Dict</span> <span class="fu">=</span> <span class="dt">Dict</span> [(<span class="dt">Name</span>, <span class="dt">Object</span> ())]
  <span class="kw">deriving</span> (<span class="dt">Eq</span>, <span class="dt">Show</span>)

<span class="co">-- and so on...</span></code></pre></div>
<p>I’m going to remove most (all?) of the newtypes and introduce <code>HashMap</code> and <code>Vector</code> instead of lists.</p>
<p>Also, right now <code>Stream</code> type has a payload. It could be an actual stream content, or just an offset of the content, or anything else. Sometimes it is convenient, but now I think that it was bad idea. I’m going to remove the payload completely and pass it separately when necessary.</p>
<p>Probably something like that:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Object</span> <span class="fu">=</span>
  <span class="dt">Number</span> <span class="dt">Scientific</span> <span class="fu">|</span>
  <span class="dt">Bool</span> <span class="dt">Bool</span> <span class="fu">|</span>
  <span class="dt">Name</span> <span class="dt">Text</span> <span class="fu">|</span>
  <span class="dt">Dict</span> (<span class="dt">HashMap</span> <span class="dt">Text</span> <span class="dt">Object</span>) <span class="fu">|</span>
  <span class="dt">Array</span> (<span class="dt">Vector</span> <span class="dt">Object</span>) <span class="fu">|</span>
  <span class="dt">String</span> <span class="dt">Text</span> <span class="fu">|</span>
  <span class="dt">Stream</span> (<span class="dt">HashMap</span> <span class="dt">Text</span> <span class="dt">Object</span>) <span class="fu">|</span>
  <span class="dt">Ref</span> (<span class="dt">Int</span>, <span class="dt">Int</span>) <span class="fu">|</span>
  <span class="dt">Null</span>
  <span class="kw">deriving</span> (<span class="dt">Eq</span>, <span class="dt">Show</span>)</code></pre></div>
<p>Also a better way to convert PDF values to domain types is necessary. Probably something like a <a href="http://hackage.haskell.org/package/aeson-0.8.0.2/docs/Data-Aeson-Types.html#t:Parser">Parser</a>, that is used in <code>FromJSON</code> type class in <code>aeson</code>?</p>
<h2 id="error-handling">Error handling</h2>
<p>The stable version uses <a href="https://hackage.haskell.org/package/pdf-toolbox-core-0.0.3.0/docs/Pdf-Toolbox-Core-Error.html">EitherT</a> to handle errors. I believe that it was wrong design decision. I switched to extensible exceptions in HEAD already. It still requires cleanup, e.g. I want to introduce more specific exceptions, but it is already much better in my opinion.</p>
<h2 id="custom-monad-transformer">Custom monad transformer</h2>
<p>I have <code>Pdf</code> monad transformer in <a href="https://hackage.haskell.org/package/pdf-toolbox-document-0.0.4.0/docs/Pdf-Toolbox-Document-Pdf.html">stable version</a>. I even have a <a href="https://hackage.haskell.org/package/pdf-toolbox-document-0.0.4.0/docs/Pdf-Toolbox-Document-Monad.html">type class</a> for PDF operations. That is probably the worst thing one may do for PDF library. Just imaging that you want to operate on two PDF files at the same time. With custom monad it becomes a pain, and the easiest solution is probably to fork a separate thread for each PDF file.</p>
<p>In HEAD I already switched to <code>IO</code>, now all objects are passed explicitly as values. I like it :)</p>
<p>Side note: I like that a lot of libraries on Hackage switched to extensible exceptions and replaced custom monads with <code>IO</code> in API. E.g. websockets and mongoDB packages.</p>
<h2 id="reading-encrypted-documents">Reading encrypted documents</h2>
<p>The current design is an example of unsafe API. You should check that the document is encrypted and then set user password , see <a href="https://hackage.haskell.org/package/pdf-toolbox-document-0.0.4.0/docs/Pdf-Toolbox-Document-Pdf.html#v:isEncrypted">here</a>. The problem occurs when you forgot to do that – you get strange errors somewhere else, e.g. when extracting text.</p>
<p>I can add a special check to each operation and throw <code>DocumentEncrypted</code> exception when user forgot to set a password. But that will slowdown everything. And I can’t require password before opening the document because user should be able to examine parts of the document (encryption dictionary) to decide what password to use. I’m still looking for better solution.</p>
<h2 id="abstractions-and-tests">Abstractions and tests</h2>
<p>PDF is very big and complex. It is hard to come with solid abstractions because you can’t keep everything in your mind. A month ago I was sure I have excellent separation between PDF as a file format; as a collection of values; and as a document with title, pages etc. But one day my naive mental picture was ruined because of interconnections I was not aware about.</p>
<p>What can I do with that? Rearrange abstractions? Drop them? I don’t want to decide upfront, I’m going to be more agile instead. And refactoring will become the most important tool, but I need more tests for that. So test coverage becomes an important goal for me.</p>
<h1 id="conclusion">Conclusion</h1>
<p>I wrote the first version of PDF parser more then 3 years ago. It was a dirty prototype, but it did the work – it was a tool to examine PDF file internal structure. Now it is a library with a lot of features and long history. It is not a prototype anymore, but it is dirty still :)</p>
<p>I don’t know how many users the library has. I get bug reports and feature requests periodically, but the only direct user is <code>hoodle-publish</code> package. As I described above, I’m going to completely change the API, and I’d like to know your opinion if you are using, going to use or even not going to use it.</p>

<p><a href="/archive.html">More posts</a></p>
<p><a href='/atom.xml'>Atom feed</a></p>
]]></summary>
</entry>
<entry>
    <title>Namespaces, modules, qualified imports and a constant pain</title>
    <link href="http://blog.haskell-exists.com/yuras/posts/namespaces-modules-qualified-imports-and-a-constant-pain.html" />
    <id>http://blog.haskell-exists.com/yuras/posts/namespaces-modules-qualified-imports-and-a-constant-pain.html</id>
    <published>2015-02-27T00:00:00Z</published>
    <updated>2015-02-27T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="info">
    February 27, 2015
    
    	
	<br/><a href='mailto:shumovichy@gmail.com'>Yuras Shumovich</a>
	
    
</div>

<p>This post is highly opinionated. It is about Haskell not having good namespace story. I’ll try to describe my point of view to this issue.</p>
<h2 id="t-m-bs">T? M? BS?</h2>
<p>What do this letters mean for you? Most likely they are <code>Data.Text</code>, <code>Data.Map</code> and <code>Data.ByteString</code>. It is common to import this modules qualified and introduce short aliases:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">import qualified</span> <span class="dt">Data.ByteString</span> <span class="kw">as</span> <span class="dt">BS</span>
<span class="kw">import qualified</span> <span class="dt">Data.ByteString.Lazy</span> <span class="kw">as</span> <span class="dt">BSL</span>
<span class="kw">import qualified</span> <span class="dt">Data.Text</span> <span class="kw">as</span> <span class="dt">T</span>

foo <span class="fu">=</span> BS.length <span class="fu">.</span> BSL.toStrict <span class="fu">.</span> BSL.fromChunks <span class="fu">.</span> map T.encodeUtf8</code></pre></div>
<p>It probably works for well known modules, but too often you can see <code>LM</code>, <code>I</code>, <code>LT</code>, <code>ST</code> and so on. That becomes a tradition to use short names. But is it a good tradition?</p>
<p>Short names make perfect sense in polymorphic code:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">catMaybes ::</span> [<span class="dt">Maybe</span> a] <span class="ot">-&gt;</span> [a]
catMaybes ls <span class="fu">=</span> [x <span class="fu">|</span> <span class="dt">Just</span> x <span class="ot">&lt;-</span> ls]</code></pre></div>
<p>Here <code>a</code> and <code>x</code> can mean anything, so descriptive names will be misleading.</p>
<p>But it is not the case for module names. Short names here are confusing because there is no common scheme, <code>T</code> can be used for <code>Data.Text</code> of <code>Data.Traversable</code>. Is it so hard to type few letters?</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">import qualified</span> <span class="dt">Data.ByteString</span> <span class="kw">as</span> <span class="dt">ByteString</span>
<span class="co">-- Yes, you can have a dot in module name alias:</span>
<span class="kw">import qualified</span> <span class="dt">Data.ByteString.Lazy</span> <span class="kw">as</span> <span class="dt">Lazy.ByteString</span>
<span class="kw">import qualified</span> <span class="dt">Data.Text</span> <span class="kw">as</span> <span class="dt">Text</span>

foo <span class="fu">=</span> <span class="dt">ByteString</span><span class="fu">.</span>length
    <span class="fu">.</span> Lazy.ByteString.toStrict
    <span class="fu">.</span> Lazy.ByteString.fromChunks
    <span class="fu">.</span> map Text.encodeUtf8</code></pre></div>
<p>It is definitely longer and a bit noisy, but at least it is unambiguous.</p>
<p>But it becomes a real pain, regardless of short vs long alias, when we have long declaration (or a set of declarations) that use a lot of functions from the same qualified module:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">import qualified</span> <span class="dt">Data.ByteString</span> <span class="kw">as</span> <span class="dt">ByteString</span>

foo <span class="fu">=</span> <span class="dt">ByteString</span><span class="fu">.</span>length
    <span class="fu">.</span> <span class="dt">ByteString</span><span class="fu">.</span>append <span class="st">&quot;!&quot;</span>
    <span class="fu">.</span> <span class="dt">ByteString</span><span class="fu">.</span>drop <span class="dv">5</span>
    <span class="fu">.</span> <span class="dt">ByteString</span><span class="fu">.</span>take <span class="dv">10</span>
    <span class="fu">.</span> <span class="dt">ByteString</span><span class="fu">.</span>pack</code></pre></div>
<p>Probably the best thing to do here is to refactor the declaration out to a separate module and import <code>Data.ByteString</code> unqualified. But it would be cool to be able to open particular module locally:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">import qualified</span> <span class="dt">Data.ByteString</span> <span class="kw">as</span> <span class="dt">ByteString</span>

foo <span class="fu">=</span> length
    <span class="fu">.</span> append <span class="st">&quot;!&quot;</span>
    <span class="fu">.</span> drop <span class="dv">5</span>
    <span class="fu">.</span> take <span class="dv">10</span>
    <span class="fu">.</span> pack
  <span class="kw">where</span>
  <span class="dt">ByteString</span>{<span class="fu">..</span>} <span class="fu">=</span> <span class="kw">import </span><span class="dt">ByteString</span></code></pre></div>
<h2 id="somethingname-somethingemail-somethingage">somethingName, somethingEmail, somethingAge</h2>
<p>Another common tradition is to prefix each record name or function with a prefix to be able to use them unqualified:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Something</span> <span class="fu">=</span> <span class="dt">Something</span>
  {<span class="ot"> somethingName ::</span> <span class="dt">Text</span>
  ,<span class="ot"> somethingEmail ::</span> <span class="dt">Email</span>
  ,<span class="ot"> somethingAge ::</span> <span class="dt">Int</span>
  }

<span class="ot">foo ::</span> <span class="dt">Something</span> <span class="ot">-&gt;</span> <span class="dt">Text</span>
foo something <span class="fu">=</span> <span class="st">&quot;name:&quot;</span> <span class="fu">&lt;&gt;</span> somethingName something</code></pre></div>
<p>Such a prefix is a poor mans namespace. Unfortunately in Haskell to create named namespace, we have to create a module:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">module</span> <span class="dt">Something</span> <span class="kw">where</span>

<span class="kw">data</span> <span class="dt">Something</span> <span class="fu">=</span> <span class="dt">Something</span>
  {<span class="ot"> name ::</span> <span class="dt">Text</span>
  ,<span class="ot"> email ::</span> <span class="dt">Email</span>
  ,<span class="ot"> age ::</span> <span class="dt">Int</span>
  }

<span class="kw">module</span> <span class="dt">Foo</span> <span class="kw">where</span>

<span class="kw">import </span><span class="dt">Something</span> (<span class="dt">Something</span>)
<span class="kw">import qualified</span> <span class="dt">Something</span>

<span class="ot">foo ::</span> <span class="dt">Something</span> <span class="ot">-&gt;</span> <span class="dt">Text</span>
foo something <span class="fu">=</span> <span class="st">&quot;name:&quot;</span> <span class="fu">&lt;&gt;</span> Something.name something</code></pre></div>
<p>It is definitely better IMO. But it would be cool if datatype declaration will introduce a namespace, so that we don’t have to create a module:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Something</span> <span class="fu">=</span> <span class="dt">Something</span>
  { qualified<span class="ot"> name ::</span> <span class="dt">Text</span>
  , qualified<span class="ot"> email ::</span> <span class="dt">Email</span>
  , qualified<span class="ot"> age ::</span> <span class="dt">Int</span>
  }

<span class="ot">foo ::</span> <span class="dt">Something</span> <span class="ot">-&gt;</span> <span class="dt">Text</span>
foo something <span class="fu">=</span> <span class="st">&quot;name:&quot;</span> <span class="fu">&lt;&gt;</span> Something.name something</code></pre></div>
<p>The syntax is terrible, I know. Probably there should be better syntax, ideally we should be able to declare free functions withing the data type namespace:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Person</span> <span class="fu">=</span> <span class="dt">Person</span>
  {<span class="ot"> firstName ::</span> <span class="dt">Text</span>
  ,<span class="ot"> lastName ::</span> <span class="dt">Text</span>
  }

  <span class="co">-- Note identation</span>
<span class="ot">  fullName ::</span> <span class="dt">Person</span> <span class="ot">-&gt;</span> <span class="dt">Text</span>
  fullName person <span class="fu">=</span> firstName person <span class="fu">&lt;&gt;</span> <span class="st">&quot; &quot;</span> <span class="fu">&lt;&gt;</span> lastName person

foo person <span class="fu">=</span> <span class="st">&quot;full name:&quot;</span> <span class="fu">&lt;&gt;</span> Person.fullName person</code></pre></div>
<p>See also <a href="https://ghc.haskell.org/trac/ghc/wiki/Records/NestedModules">nested modules</a></p>
<h2 id="type-directed-name-resolution-overloaded-record-fields-etc">Type-directed name resolution, overloaded record fields, etc</h2>
<p>I believe that code should be as unambiguous as it is possible. Adhoc polymorphism makes code ambiguous – you can’t anymore say what function is called only looking to it’s usage side. Some recently proposed extensions has their own value (e.g. I like anonymous records), but I believe that namespaces support in Haskell should be improved, because namespaces is the right solution for the described issues.</p>

<p><a href="/archive.html">More posts</a></p>
<p><a href='/atom.xml'>Atom feed</a></p>
]]></summary>
</entry>
<entry>
    <title>Malloc, free and FFI</title>
    <link href="http://blog.haskell-exists.com/yuras/posts/malloc-free-and-ffi.html" />
    <id>http://blog.haskell-exists.com/yuras/posts/malloc-free-and-ffi.html</id>
    <published>2015-02-08T00:00:00Z</published>
    <updated>2015-02-08T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="info">
    February  8, 2015
    
    	
	<br/><a href='mailto:shumovichy@gmail.com'>Yuras Shumovich</a>
	
    
</div>

<p>TL;DR You should always free memory with the same allocator that allocated it for you.</p>
<p>We’ll discuss two different sets of <code>malloc</code> and <code>free</code> functions. The first one is defined in <code>Foreign.Marshal.Alloc</code>, and the second one is part of C runtime. To distinguish them, I’ll use <code>H-malloc</code> and <code>H-free</code> names for Haskell functions, and <code>C-malloc</code> and <code>C-free</code> for C functions.</p>
<p>Actually <code>H-malloc</code> and <code>H-free</code> just call their C counterparts, so usually the same allocator is used in all this 4 functions. But that doesn’t mean that we can mix them. The documentation is clear:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- |Free a block of memory that was allocated with &#39;malloc&#39;,</span>
<span class="co">-- &#39;mallocBytes&#39;, &#39;realloc&#39;, &#39;reallocBytes&#39;, &#39;Foreign.Marshal.Utils.new&#39;</span>
<span class="co">-- or any of the @new@/X/ functions in &quot;Foreign.Marshal.Array&quot; or</span>
<span class="co">-- &quot;Foreign.C.String&quot;.</span>
<span class="fu">--</span>
<span class="ot">free ::</span> <span class="dt">Ptr</span> a <span class="ot">-&gt;</span> <span class="dt">IO</span> ()
free  <span class="fu">=</span> _free</code></pre></div>
<p>Note that it enumerates all the cases when <code>H-free</code> can be used, and <code>C-malloc</code> is not listed here. There are two reasons for that. First of all, the implementation may be changed to use some other allocator.</p>
<p>(You can skip this paragraph, it contains some low level details.) The second reason is that sometimes your program happens to be linked with multiple versions of C runtime. That sounds strange, but it is a very real situation. For example, your program may load external plugin statically linked with C runtime other then yours. As a result you have three sets of malloc/free functions: one from Haskell, another from your C runtime, and one more from the plugin’s C runtime. The last two are probably incompatible, and you’ll get random failures if you are not careful enough.</p>
<p>The usual rule to avoid any issue with allocator is: you should deallocate memory in the same module where you allocated it. E.g. if you allocated memory in Haskell, then please free it in Haskell. If you allocated memory in C library, then please deallocate it in the same C library. (The same goes for dynamically loaded plugins.)</p>
<p>The reason I wrote about it? There is an <a href="https://ghc.haskell.org/trac/ghc/ticket/9806">issue</a> on <code>ghc</code> bug tracker about replacing the allocator used in <code>H-malloc</code>. And I decided to check how often code on github relies on the current behavior (e.g. uses <code>H-free</code> to deallocate memory, that was allocated by <code>C-malloc</code>). I was surprised how common it is. Even RWH recommends wrong approach:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- file: ch17/PCRE-compile.hs</span>
<span class="ot">compile ::</span> <span class="dt">ByteString</span> <span class="ot">-&gt;</span> [<span class="dt">PCREOption</span>] <span class="ot">-&gt;</span> <span class="dt">Either</span> <span class="dt">String</span> <span class="dt">Regex</span>
compile str flags <span class="fu">=</span> unsafePerformIO <span class="fu">$</span>
  useAsCString str <span class="fu">$</span> \pattern <span class="ot">-&gt;</span> <span class="kw">do</span>
    alloca <span class="fu">$</span> \errptr       <span class="ot">-&gt;</span> <span class="kw">do</span>
    alloca <span class="fu">$</span> \erroffset    <span class="ot">-&gt;</span> <span class="kw">do</span>
        pcre_ptr <span class="ot">&lt;-</span> c_pcre_compile pattern (combineOptions flags) errptr erroffset nullPtr
        <span class="kw">if</span> pcre_ptr <span class="fu">==</span> nullPtr
            <span class="kw">then</span> <span class="kw">do</span>
                err <span class="ot">&lt;-</span> peekCString <span class="fu">=&lt;&lt;</span> peek errptr
                return (<span class="dt">Left</span> err)
            <span class="kw">else</span> <span class="kw">do</span>
                reg <span class="ot">&lt;-</span> newForeignPtr finalizerFree pcre_ptr <span class="co">-- release with free()</span>
                return (<span class="dt">Right</span> (<span class="dt">Regex</span> reg str))</code></pre></div>
<p>Here the <code>pcre_ptr</code> is allocated somewhere in pcre C library (probably using <code>C-malloc</code>), and deallocated using <code>H-free</code> (via <code>finalizerFree</code>). This code works most of the time, but it is wrong. The correct approach would be to call C function to deallocate memory. Some C libraries provide a special function that guarantees to call the correct deallocator. In case of pcre it seems to be <code>pcre_free</code>, and it should be used here instead of <code>H-free</code>.</p>

<p><a href="/archive.html">More posts</a></p>
<p><a href='/atom.xml'>Atom feed</a></p>
]]></summary>
</entry>
<entry>
    <title>Stop (ab)using CPP in Haskell sources</title>
    <link href="http://blog.haskell-exists.com/yuras/posts/stop-abusing-cpp-in-haskell.html" />
    <id>http://blog.haskell-exists.com/yuras/posts/stop-abusing-cpp-in-haskell.html</id>
    <published>2015-02-01T00:00:00Z</published>
    <updated>2015-02-01T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="info">
    February  1, 2015
    
    	
	<br/><a href='mailto:shumovichy@gmail.com'>Yuras Shumovich</a>
	
    
</div>

<h2 id="what-is-wrong-with-cpp">What is wrong with CPP</h2>
<p>CPP is a <em>C</em> preprocessor, but it is common to use it in Haskell. That leads to a number of issues.</p>
<ul>
<li>It can mess with haskell code.</li>
</ul>
<p>CPP doesn’t understand Haskell code, instead it assumes C code. It is free to remove insignificant (for C, not for Haskell) whitespace, expand macros in Haskell comments and strings or mess with identifiers that contain <code>'</code> or <code>#</code>.</p>
<ul>
<li>It leads to <a href="http://stackoverflow.com/questions/26785036/why-the-presence-absence-of-the-hscolour-binary-forces-to-recompile-the-quickche">unnecessary recompilation</a>.</li>
</ul>
<p>Every time you change your .cabal file, e.g. add new module, or update dependencies, cabal regenerates <code>cabal-macros.h</code> file. Then the recompilation checker pessimistically decides to recompile all modules with CPP enabled.</p>
<ul>
<li>It makes automatic code analyzing and transforming harder.</li>
</ul>
<p>If you use <code>hlint</code> or <code>HaRe</code>, then you probably know what I mean.</p>
<ul>
<li>When abused, it makes code harder to read.</li>
</ul>
<p>It is not rare to see code intercalated with ifdefs that specify different behaviour for different platforms of library versions. Sometimes that is unavoidable though.</p>
<p>Most of the time CPP can be avoided or minimized. The most important tool here is abstraction.</p>
<h2 id="abstract-over-specific-details">Abstract over specific details</h2>
<p>It is not Haskell specific, abstracting is widely used to minimize CPP in C. When you need different behaviour based on the current platform or the version of some dependencies, try to abstract over the difference instead of inlining platform specific code.</p>
<p>At the first glance it may look impossible to do. In such cased I usually simply duplicate code and then refactor it to reduce duplication.</p>
<p>Some times it is convenient to start with an umbrella module that provides a unified interface for the rest of program, and a number of platform specific implementations. Note: you don’t need CPP to select a specific module, cabal lets you conditionally include modules based on the platform or other conditions.</p>
<h2 id="example-fsnotify">Example: fsnotify</h2>
<p>An excellent example of such an approach is the <a href="https://github.com/haskell-fswatch/hfsnotify">fsnotify</a> package. It defines specific implementations for <a href="https://github.com/haskell-fswatch/hfsnotify/blob/master/src/System/FSNotify/Linux.hs">linux</a>, <a href="https://github.com/haskell-fswatch/hfsnotify/blob/master/src/System/FSNotify/OSX.hs">osx</a> and <a href="https://github.com/haskell-fswatch/hfsnotify/blob/master/src/System/FSNotify/Win32.hs">win32</a>, and one <a href="https://github.com/haskell-fswatch/hfsnotify/blob/master/src/System/FSNotify.hs">umbrella module</a>. A number of <a href="https://github.com/haskell-fswatch/hfsnotify/tree/master/src/System/FSNotify">other modules</a> contain common code, so duplication is really minimal.</p>
<p>Note that CPP is enabled only in the umbrella module for two reasons. First off all, it is used to import the specific implementation:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="st">#ifdef OS_Linux</span>
<span class="kw">import </span><span class="dt">System.FSNotify.Linux</span>
<span class="st">#else</span>
<span class="st"># ifdef OS_Win32</span>
<span class="kw">import </span><span class="dt">System.FSNotify.Win32</span>
<span class="st"># else</span>
<span class="st"># ifdef OS_Mac</span>
<span class="kw">import </span><span class="dt">System.FSNotify.OSX</span>
<span class="st"># else</span>
<span class="kw">type</span> <span class="dt">NativeManager</span> <span class="fu">=</span> <span class="dt">PollManager</span>
<span class="st"># endif</span>
<span class="st"># endif</span>
<span class="st">#endif</span></code></pre></div>
<p>That can be avoided too. To do that we can give the same name to platform specific modules but move them into separate directories, <code>linux</code>, <code>osx</code> and <code>win32</code>. Then manipulate the <code>hs-source-dirs</code> field in cabal file to select the correct implementation. (Make sure to add other implementations to <code>extra-source-files</code> to make sure <code>cabal sdist</code> will copy them into the tarball.)</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- in System.FSNotify:</span>
<span class="kw">import </span><span class="dt">System.FSNotify.Platform</span>

<span class="co">-- in fsnotify.cabal:</span>
extra<span class="fu">-</span>source<span class="fu">-</span>files<span class="fu">:</span> linux<span class="fu">/</span><span class="dt">System</span><span class="fu">/</span><span class="dt">FSNotify</span><span class="fu">/</span>Platform.hs
                    osx<span class="fu">/</span><span class="dt">System</span><span class="fu">/</span><span class="dt">FSNotify</span><span class="fu">/</span>Platform.hs
                    win32<span class="fu">/</span><span class="dt">System</span><span class="fu">/</span><span class="dt">FSNotify</span><span class="fu">/</span>Platform.hs
hs<span class="fu">-</span>source<span class="fu">-</span>dirs<span class="fu">:</span> src
<span class="kw">if</span> os(linux)
  hs<span class="fu">-</span>source<span class="fu">-</span>dirs<span class="fu">:</span> linux
<span class="kw">if</span> os(darwin)
  hs<span class="fu">-</span>source<span class="fu">-</span>dirs<span class="fu">:</span> osx
<span class="kw">if</span> os(windows)
  hs<span class="fu">-</span>source<span class="fu">-</span>dirs<span class="fu">:</span> win32</code></pre></div>
<p>The other use of CPP is to define <code>forkFinally</code> that is missing in older <code>base</code>:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="st">#if !MIN_VERSION_base(4,6,0)</span>
<span class="ot">forkFinally ::</span> <span class="dt">IO</span> a <span class="ot">-&gt;</span> (<span class="dt">Either</span> <span class="dt">SomeException</span> a <span class="ot">-&gt;</span> <span class="dt">IO</span> ()) <span class="ot">-&gt;</span> <span class="dt">IO</span> <span class="dt">ThreadId</span>
forkFinally action and_then <span class="fu">=</span>
  mask <span class="fu">$</span> \restore <span class="ot">-&gt;</span>
    forkIO <span class="fu">$</span> try (restore action) <span class="fu">&gt;&gt;=</span> and_then
<span class="st">#endif</span></code></pre></div>
<p>The same technique can be used to avoid CPP here. I personally prefer to hide such snippets into a <a href="https://github.com/Yuras/pdf-toolbox/blob/0732f15e8f73a724372d46670fa2d0d71d301650/core/lib/Prelude.hs">custom prelude</a> and don’t bother with <code>hs-source-path</code>.</p>
<p>(I don’t think CPP should be avoided at all costs, I think that the amount of CPP used in fsnotify is a good compromise. I just used it as a real world example of how to avoid CPP.)</p>

<p><a href="/archive.html">More posts</a></p>
<p><a href='/atom.xml'>Atom feed</a></p>
]]></summary>
</entry>
<entry>
    <title>Handling (async) exceptions in haskell: snap-server (case study)</title>
    <link href="http://blog.haskell-exists.com/yuras/posts/handling-async-exceptions-in-haskell-snap-server-case-study.html" />
    <id>http://blog.haskell-exists.com/yuras/posts/handling-async-exceptions-in-haskell-snap-server-case-study.html</id>
    <published>2014-11-22T00:00:00Z</published>
    <updated>2014-11-22T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="info">
    November 22, 2014
    
    	
	<br/><a href='mailto:shumovichy@gmail.com'>Yuras Shumovich</a>
	
    
</div>

<p>(Originally posted <a href="https://github.com/Yuras/io-region/wiki/Handling-%28async%29-exceptions-in-haskell:-snap-server-%28case-study%29">here</a>)</p>
<p>Exception handling is hard, and asynchronous exceptions make it even harder. But there are common patterns, that simplifies exception handling and make our life much easier. Here we will explore a widely used open source library, <code>snap-server</code>, and identify common issues, difficulties and mistakes. Also we’ll see how to avoid most of the mistakes and describe useful patterns. Thanks to Gregory Collins for letting me use snap-server here.</p>
<p>(I probably should note, that I’m snapframework user, and I like it. So the criticism here is friendly in it’s nature.)</p>
<p>The post is organized into a series of examples of real code. I’ll use <a href="https://github.com/snapframework/snap-server/tree/a539ac3dc7eafdff5e61b29591bc81fd9976b529">this</a> specific source code tree. We’ll mostly discuss simple, obvious cases.</p>
<h2 id="example-1">example #1</h2>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">sendFileFunc ::</span> <span class="dt">Socket</span> <span class="ot">-&gt;</span> <span class="dt">SendFileHandler</span>
sendFileFunc sock <span class="fu">!</span>_ builder fPath offset nbytes <span class="fu">=</span> bracket acquire closeFd go
  <span class="kw">where</span>
    sockFd    <span class="fu">=</span> <span class="dt">Fd</span> (fdSocket sock)
    acquire   <span class="fu">=</span> openFd fPath <span class="dt">ReadOnly</span> <span class="dt">Nothing</span> defaultFileFlags
    go fileFd <span class="fu">=</span> <span class="kw">do</span> sendHeaders builder sockFd
                   sendFile sockFd fileFd offset nbytes</code></pre></div>
<p><a href="https://github.com/snapframework/snap-server/blob/a539ac3dc7eafdff5e61b29591bc81fd9976b529/src/Snap/Internal/Http/Server/Socket.hs#L113">Source</a></p>
<p>That is an example how your exception handling code should look like. Here <code>bracket</code> does most of heavy lifting to prepare safe environment. Acquire and cleanup actions effectively are library functions (from <code>unix</code> package).</p>
<h3 id="contract">Contract</h3>
<p>So the function on itself is perfect. But it relies on library functions to be correct. Lets formulate explicitly the contract we are expecting:</p>
<ul>
<li><code>openFd</code> should not leak file descriptor if it fails.</li>
</ul>
<p>That is pretty natural requirement, because we will not get the file descriptor at all if <code>openFd</code> fails, so there is nothing we can do on our side.</p>
<ul>
<li><code>closeFd</code> should not leak file descriptor if it fails.</li>
</ul>
<p>That doesn’t look so natural, but the reason is the same – there is nothing we can do in case of failure.</p>
<p>Note: the contract should be preserved even in case of async exception, because there is no good way to distinguish async and sync exception.</p>
<p>In the ideal world we should not simply assume the contract is preserved, we should read documentation instead. Unfortunately the is no explicit contract in the documentation. Probably we should pester the maintainer. Anyway, we can either look for other library or use the existing.</p>
<h3 id="inspecting-source-code-of-dependencies">Inspecting source code of dependencies</h3>
<p>One may think that we should inspect source code of <code>openFd</code> and <code>closeFd</code>. It may be useful, but it doesn’t solve the issue. Unless the contract is explicitly states, the author is free to change it. But you can inspect the particular version of the <code>unix</code> package and commit yourself to it.</p>
<h2 id="example-2">example #2</h2>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">withLoggers afp efp act <span class="fu">=</span>
    bracket (<span class="kw">do</span> mvar <span class="ot">&lt;-</span> newMVar ()
                <span class="kw">let</span> f s <span class="fu">=</span> withMVar mvar
                            (const <span class="fu">$</span> S.hPutStr stderr s <span class="fu">&gt;&gt;</span> hFlush stderr)
                alog <span class="ot">&lt;-</span> maybeSpawnLogger f afp
                elog <span class="ot">&lt;-</span> maybeSpawnLogger f efp
                return (alog, elog))
            (\(alog, elog) <span class="ot">-&gt;</span> <span class="kw">do</span>
                maybe (return ()) stopLogger alog
                maybe (return ()) stopLogger elog)
            (\(alog, elog) <span class="ot">-&gt;</span> act ( liftM logMsg alog <span class="fu">&lt;|&gt;</span> maybeIoLog afp
                                  , liftM logMsg elog <span class="fu">&lt;|&gt;</span> maybeIoLog efp))</code></pre></div>
<p><a href="https://github.com/snapframework/snap-server/blob/a539ac3dc7eafdff5e61b29591bc81fd9976b529/src/Snap/Http/Server.hs#L183">Source</a></p>
<p>The function spawns two loggers (using <code>maybeSpawnLogger</code>) and stops them (using <code>stopLogger</code>) on exit. It is not important what loggers do, but you can check the source code if you are interested.</p>
<p>Do you see any issue here? Probably not. Lets say the function has no obvious issues. (Actually I found one minor issue, but I spent half an hour reading code.) But it doesn’t mean the function is correct.</p>
<h3 id="dont-assume-anything">Don’t assume anything</h3>
<p>I convinced myself that <code>maybeSpawnLogger</code> and <code>stopLogger</code> never throw exception. (Well, <code>stopLogger</code> is interruptible, so it actually can sometimes.) But is there any reason we need to assume that? What if someone change them when refactoring? Sometimes we need to rely on actions not to throw exception, but not here. Lets fix it:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">withLoggers afp efp act <span class="fu">=</span>
    bracket (<span class="kw">do</span> mvar <span class="ot">&lt;-</span> newMVar ()
                <span class="kw">let</span> f s <span class="fu">=</span> withMVar mvar
                            (const <span class="fu">$</span> S.hPutStr stderr s <span class="fu">&gt;&gt;</span> hFlush stderr)
                bracketOnError
                  (maybeSpawnLogger f afp)
                  (maybe (return ()) stopLogger)
                  (\alog <span class="ot">-&gt;</span> <span class="kw">do</span>
                    elog <span class="ot">&lt;-</span> maybeSpawnLogger f efp
                    return (alog, elog))

            (\(alog, elog) <span class="ot">-&gt;</span> <span class="kw">do</span>
                maybe (return ()) stopLogger alog
                <span class="ot">`finally`</span>
                maybe (return ()) stopLogger elog)
            (\(alog, elog) <span class="ot">-&gt;</span> act ( liftM logMsg alog <span class="fu">&lt;|&gt;</span> maybeIoLog afp
                                  , liftM logMsg elog <span class="fu">&lt;|&gt;</span> maybeIoLog efp))</code></pre></div>
<p>Here we did two fixes. First, we use <code>bracketOnError</code> to ensure the first logger will be stopped if we fail to spawn the second. Also <code>finally</code> is used to ensure the second logger will be stopped if the first one fails to stop. Pretty complicated, but now it is at least correct.</p>
<p>Note that the code is correct w.r.t. both sync and async exception. Here we did nothing special to handle async exceptions.</p>
<p>However the function still relies on <code>maybeSpawnLogger</code> and <code>stopLogger</code> to preserve the contract (see example #1).</p>
<h3 id="keep-it-simple">Keep it simple</h3>
<p>The function is still far from ideal. In the acquire action it does unnecessary work – allocates <code>MVar</code>. Is there any reason to do that inside <code>bracket</code>? Probably not. Lets simplify the code to make reasoning easer:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">withLoggers afp efp act <span class="fu">=</span> <span class="kw">do</span>
    mvar <span class="ot">&lt;-</span> newMVar ()
    <span class="kw">let</span> f s <span class="fu">=</span> withMVar mvar
                (const <span class="fu">$</span> S.hPutStr stderr s <span class="fu">&gt;&gt;</span> hFlush stderr)

    bracket (<span class="kw">do</span> bracketOnError
                  (maybeSpawnLogger f afp)
                  (maybe (return ()) stopLogger)
                  (\alog <span class="ot">-&gt;</span> <span class="kw">do</span>
                    elog <span class="ot">&lt;-</span> maybeSpawnLogger f efp
                    return (alog, elog))

            (\(alog, elog) <span class="ot">-&gt;</span> <span class="kw">do</span>
                maybe (return ()) stopLogger alog
                <span class="ot">`finally`</span>
                maybe (return ()) stopLogger elog)
            (\(alog, elog) <span class="ot">-&gt;</span> act ( liftM logMsg alog <span class="fu">&lt;|&gt;</span> maybeIoLog afp
                                  , liftM logMsg elog <span class="fu">&lt;|&gt;</span> maybeIoLog efp))</code></pre></div>
<h3 id="divide-and-conquer">Divide and conquer</h3>
<p>The function is very complex and hard to reason still. But notice that there is no dependency between loggers here, so we can handle them separately. Lets use two brackets, one per logger:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">withLoggers afp efp act <span class="fu">=</span> <span class="kw">do</span>
    mvar <span class="ot">&lt;-</span> newMVar ()
    <span class="kw">let</span> f s <span class="fu">=</span> withMVar mvar
                (const <span class="fu">$</span> S.hPutStr stderr s <span class="fu">&gt;&gt;</span> hFlush stderr)

    bracket (maybeSpawnLogger f afp)
            (maybe (return ()) stopLogger) <span class="fu">$</span> \alog <span class="ot">-&gt;</span> <span class="kw">do</span>

      bracket (maybeSpawnLogger f efp)
              (maybe (return ()) stopLogger) <span class="fu">$</span> \elog <span class="ot">-&gt;</span> <span class="kw">do</span>

        act ( liftM logMsg alog <span class="fu">&lt;|&gt;</span> maybeIoLog afp
            , liftM logMsg elog <span class="fu">&lt;|&gt;</span> maybeIoLog efp))</code></pre></div>
<p>Now the function consists of two nested handlers, that are very similar to example #1. It is obviously correct.</p>
<h3 id="local-reasoning">Local reasoning</h3>
<p>I’d like to draw your attention to the next. We reason about exception handling locally. Obviously all functions we use here affect exception safety of our code, but we use the contract (see example #1) to build a wall between our code and it’s dependencies. That is the only way to handle exceptions. Sometimes the contract is more complex, and we have to provide safe environment for our dependencies, but that should be explicitly stated in documentation.</p>
<p>We’ll discuss <code>maybeSpawnLogger</code> and <code>stopLogger</code> later, and you’ll see that the contract protects us from caller site too, allowing local reasoning.</p>
<h2 id="example-3">example #3</h2>
<p>Lets inspect <code>maybeSpawnLogger</code>. It is a simple wrapper over other function:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">maybeSpawnLogger f (<span class="dt">ConfigFileLog</span> fp) <span class="fu">=</span>
    liftM <span class="dt">Just</span> <span class="fu">$</span> newLoggerWithCustomErrorFunction f fp
maybeSpawnLogger _ _                  <span class="fu">=</span> return <span class="dt">Nothing</span></code></pre></div>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">newLoggerWithCustomErrorFunction ::</span> (<span class="dt">ByteString</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> ())
                                 <span class="ot">-&gt;</span> FilePath   <span class="co">-- ^ log file to use</span>
                                 <span class="ot">-&gt;</span> <span class="dt">IO</span> <span class="dt">Logger</span>
newLoggerWithCustomErrorFunction errAction fp <span class="fu">=</span> <span class="kw">do</span>
    q  <span class="ot">&lt;-</span> newIORef mempty
    dw <span class="ot">&lt;-</span> newEmptyMVar
    th <span class="ot">&lt;-</span> newEmptyMVar

    <span class="kw">let</span> lg <span class="fu">=</span> <span class="dt">Logger</span> q dw fp th errAction

    mask_ <span class="fu">$</span> <span class="kw">do</span>
      tid <span class="ot">&lt;-</span> forkIOLabeledWithUnmaskBs <span class="st">&quot;snap-server: logging&quot;</span> <span class="fu">$</span>
               loggingThread lg
      putMVar th tid

    return lg</code></pre></div>
<p><a href="https://github.com/snapframework/snap-server/blob/a539ac3dc7eafdff5e61b29591bc81fd9976b529/src/System/FastLogger.hs#L74">Source</a></p>
<h3 id="dont-use-mask_">Don’t use <code>mask_</code></h3>
<p>In most cases it is wrong, so don’t use it unless you exactly know what you are doing. If <code>newLoggerWithCustomErrorFunction</code> action is called without async exceptions masked, then it will leak resource. It is too late to mask async exceptions here. Probably it should be stated in documentation to the function, but actually it is clear enough – it should be used only inside <code>bracket</code> or similar context. There is nothing wrong with <code>mask_</code> here, it is just unnecessary. But it gives you false feeling of safety, and can be a sign of other issues.</p>
<p>One can think that <code>mask_</code> here is useful because protects at least part of the code from async exceptions. But that is not true, async exceptions will be postponed till end of <code>mask_</code>, but then will be delivered anyway (unless masked on caller site). The result is the same – orphan thread.</p>
<h3 id="other-issues">Other issues</h3>
<p>Lets identify all points where something can go wrong. First of all, the resource here is a thread, so we should make sure it doesn’t become orphan on failure. Everything above <code>forkIOLabeledWithUnmaskBs</code> is irrelevant, because the thread is not yet created here. The only point if failure is <code>putMVar</code>. To be carefull we should protect <code>forkIOLabeledWithUnmaskBs</code> against failure in <code>putMVar</code>, but it is not necessary.</p>
<p>From documentation it is clear, that it will not throw async exception unless the <code>MVar</code> is full. Here it is empty for sure. (Note: it is documented not in <code>Control.Concurrent.MVar</code>, but in <code>Control.Exception</code>.)</p>
<p>Unfortunately the documentation for <code>putMVar</code> doesn’t say anything about sync exceptions. (And it can throw at least <code>BlockedIndefinitelyOnMVar</code>, but not in our case.) But it is very common to rely on it not to throw sync exception, so nobody will break that assumption ever. We can think about it as a documentation bug.</p>
<p>Conclusion: the function is safe.</p>
<h2 id="example-4">example #4</h2>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- | Kills a logger thread, causing any unwritten contents to be</span>
<span class="co">-- flushed out to disk</span>
<span class="ot">stopLogger ::</span> <span class="dt">Logger</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> ()
stopLogger lg <span class="fu">=</span> withMVar (_loggingThread lg) killThread</code></pre></div>
<p>Lets remember the contract: function should release resource even in case of failure. Well, it is not always possible, but it should do it’s best.</p>
<p>There is two <code>IO</code> actions here, <code>withMVar</code> and <code>killThread</code>. Both are potential points of failure.</p>
<p>Documentation for <code>withMVar</code> states:</p>
<blockquote>
<p>it is only atomic if there are no other producers for this MVar.</p>
</blockquote>
<p>The wording probably can be better. But it will not throw if the <code>MVar</code> is full initially and nobody tries to put anything into it until exit from <code>withMVar</code>. In out case it is true – the mvar is not used anywhere after spawning the thread. But we need to inspect the code around to find that out, so it would be better to document the design.</p>
<p><code>killThread</code> is problematic though. AFAIK it can’t throw sync exceptions, but it can throw async exception even when wrapped into <code>uninterruptibleMask</code> (!!!). Also it is interruptible even when doesn’t block. You should read it’s documentation carefully before using it.</p>
<p>In this particular case it is enough to wrap <code>killThread</code> into <code>uninterruptibleMask</code>. Other option is to provide eventual guarantees, e.g. spawn other thread to do <code>killThread</code> asynchronously:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">stopLogger lg <span class="fu">=</span> withMVar (_loggingThread lg) <span class="fu">$</span> \threadId <span class="ot">-&gt;</span>
  killThread threadId <span class="ot">`onException`</span> void (forkIO <span class="fu">$</span> killThread threadId)</code></pre></div>
<p>Here the <code>ThreadId</code> of the helper thread is unknown to anybody else, so we can be sure nobody will send async exception to it.</p>
<h2 id="example-5">example #5</h2>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">runLoops <span class="fu">=</span> E.bracket (mapM newLoop [<span class="dv">0</span> <span class="fu">..</span> (nLoops <span class="fu">-</span> <span class="dv">1</span>)])
                     (mapM_ killLoop)
                     (mapM_ waitLoop)</code></pre></div>
<p><a href="https://github.com/snapframework/snap-server/blob/a539ac3dc7eafdff5e61b29591bc81fd9976b529/src/Snap/Internal/Http/Server/Session.hs#L132">Source</a></p>
<p>Do you see the issue here?</p>
<p>Never assume anything. What if one of <code>newLoop</code> fails? Then all already created loops will leak. What if one of <code>killLoop</code> fails? Then all subsequent loops will not be killed.</p>
<p>Note: It is possible that <code>newLoop</code> and <code>killLoop</code> never throw (not in our case though), but the principle of local reasoning forces us to handle exceptions here or at least write a comment. We probably should fold the <code>killLoop</code>s with <code>finally</code>. Something like <code>ResourceT</code> can simplify this case a lot.</p>
<h2 id="final-notes">Final notes</h2>
<p>Internally <code>snap-server</code> does a lot of non-local manipulations with mask state. It is hard to extract any meaningful example because of non-locality. I’ll simply provide a <a href="https://github.com/snapframework/snap-server/blob/a539ac3dc7eafdff5e61b29591bc81fd9976b529/src/Snap/Internal/Http/Server/TimeoutManager.hs#L169">link</a> The <code>restore</code> seems to be changing masking state, but it is not clear how it affects the code. Probably there are good reasons for such design though. Also <code>eatException</code> is used a lot, and that is a bad sign.</p>
<p><code>bracket</code> is not the only source of errors, but the same approach can be applied to most cases.</p>
<p>I didn’t have a goal to uncover all issues with exception handling here. And I’m sure there are cases much harder to find and fix. But in most cases you’ll avoid a lot of mistakes if you follow the basic principles:</p>
<ul>
<li><p>Don’t assume anything</p></li>
<li><p>Keep it simple</p></li>
<li><p>Divide and conquer</p></li>
<li><p>Reason locally</p></li>
</ul>
<p>Thanks to all authors of <code>snap-server</code> for excellent library, I really appreciate your work.</p>

<p><a href="/archive.html">More posts</a></p>
<p><a href='/atom.xml'>Atom feed</a></p>
]]></summary>
</entry>

</feed>
