<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Strings over Σ</title>
<link>https://bitsrc.org/blog/</link>
<atom:link href="https://bitsrc.org/blog/index.xml" rel="self" type="application/rss+xml"/>
<description>A blog about computer science, logic and programming. Occasionally other topics reasonably consistent with the rest.</description>
<generator>quarto-1.8.27</generator>
<lastBuildDate>Thu, 03 Sep 2026 07:00:00 GMT</lastBuildDate>
<item>
  <title>A Paper a Decade #16: A simple, verified validator for software pipelining</title>
  <link>https://bitsrc.org/blog/posts/a-paper-a-decade-validator-for-software-pipelining.html</link>
  <description><![CDATA[ 




<p>What a decade since I’ve last posted about a paper I read. I have since gotten to work on compilers, so I’ve read this paper out of more than idle curiosity.</p>
<p>The paper starts out by explaining what software pipelining / Modulo Scheduling is. One point of definitional confusion is that it appears to actually be presenting the Modulo Variable Expansion<sup>1</sup> algorithm rather than vanilla Modulo Scheduling (which is a special case of MVE).</p>
<p>Then it defines the problem by introducing fancy variables to say “for every iteration count, the result of the pipelined and the original loop should be the same”:</p>
<blockquote class="blockquote">
<ul>
<li><img src="https://latex.codecogs.com/png.latex?%5Cmathcal%7BS%7D"> is the new loop body […]</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cmathcal%7BP%7D"> is the loop prolog […]</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cmathcal%7BE%7D"> is the loop epilog […]</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cmu"> is the minimum number of iterations that must be performed to be able to use the pipelined loop.</li>
<li><img src="https://latex.codecogs.com/png.latex?%5Cdelta"> is the amount of unrolling that has been performed […]</li>
</ul>
<p>[…]</p>
<p>Likewise, the generated code behaves either like <img src="https://latex.codecogs.com/png.latex?%5Cmathcal%7BB%7D%5EN"> if <img src="https://latex.codecogs.com/png.latex?N%20%3C%20%5Cmu">, or like</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cmathcal%7BP%7D;%5Cmathcal%7BS%7D%5E%7B%5Ckappa(N)%7D;%5Cmathcal%7BE%7D;%5Cmathcal%7BB%7D%5E%7B%5Crho(N)%7D"></p>
<p>if <img src="https://latex.codecogs.com/png.latex?N%20%5Cgeq%20%5Cmu">, where</p>
<p><img src="https://latex.codecogs.com/png.latex?%0A%5Cbegin%7Baligned%7D%0A%5Ckappa(N)%20&amp;%5Coverset%7B%5Ctext%7Bdef%7D%7D%7B=%7D%20(N%20-%20%5Cmu)/%5Cdelta%20%5C%5C%0A%5Crho(N)%20%20%20&amp;%5Coverset%7B%5Ctext%7Bdef%7D%7D%7B=%7D%20N%20-%20%5Cmu%20-%20%5Cdelta%20%5Ctimes%20%5Ckappa(N)%0A%5Cend%7Baligned%7D%0A"></p>
<p>The verification problem therefore reduces to establishing that, for all <img src="https://latex.codecogs.com/png.latex?N">, the two basic blocks</p>
<p><span id="eq-equiv"><img src="https://latex.codecogs.com/png.latex?%0AX_N%20%5Coverset%7B%5Ctext%7Bdef%7D%7D%7B=%7D%20%5Cmathcal%7BB%7D%5EN%0A%5Cqquad%5Ctext%7Band%7D%5Cqquad%0AY_N%20%5Coverset%7B%5Ctext%7Bdef%7D%7D%7B=%7D%20%5Cmathcal%7BP%7D;%5Cmathcal%7BS%7D%5E%7B%5Ckappa(N)%7D;%5Cmathcal%7BE%7D;%5Cmathcal%7BB%7D%5E%7B%5Crho(N)%7D%0A%5Ctag%7B1%7D"></span></p>
<p>are semantically equivalent.</p>
</blockquote>
<p>Here, <img src="https://latex.codecogs.com/png.latex?N"> is the trip count, <img src="https://latex.codecogs.com/png.latex?%5Calpha"> is the result of symbolic execution, and <img src="https://latex.codecogs.com/png.latex?%5Cmathcal%7BB%7D"> is the original, single basic-block loop body.</p>
<p>Nice. Now if we could just <img src="https://latex.codecogs.com/png.latex?%5Cforall%20N">. But there are countably too many of those to symbolically execute, so let’s read on.</p>
<blockquote class="blockquote">
<p>The key discovery of this paper is that this undecidable property <img src="https://latex.codecogs.com/png.latex?%5Cforall%20N,%5C%20%5Calpha(X_N)%20=%20%5Calpha(Y_N)"> is implied by (and, in practice, equivalent to) the following two decidable conditions:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Calpha(%5Cmathcal%7BE%7D;%5Cmathcal%7BB%7D%5E%7B%5Cdelta%7D)%20=%20%5Calpha(%5Cmathcal%7BS%7D;%5Cmathcal%7BE%7D)"></p>
<p><img src="https://latex.codecogs.com/png.latex?%5Calpha(%5Cmathcal%7BB%7D%5E%7B%5Cmu%7D)%20=%20%5Calpha(%5Cmathcal%7BP%7D;%5Cmathcal%7BE%7D)"></p>
</blockquote>
<p>In essence: exiting the pipelined loop and running the original loop body (<img src="https://latex.codecogs.com/png.latex?%5Cdelta"> times if it was unrolled) should be the same as continuing it and exiting. You throw in some conditions about the induction variable and the loop bound, and you have the algorithm in section 5.</p>
<p>That is the core insight of the paper. The rest of it concerns itself with their symbolic execution method, the proof, and some caveats about the approach.</p>
<p>The interesting one is that passing the validation condition is sufficient but not necessary for the transformation being correct (i.e.&nbsp;being equivalent to Equation&nbsp;1). The paper says they “strongly believe it holds in practice as long as the software pipelining algorithm used is purely syntactic”. Which is a somewhat unsatisfactory thing to say in a theoretical CS paper, but it sounds reasonable.</p>
<p>They implemented a software pipeliner and this validator for CompCert, and have not found it to reject correct transformations, which gives this claim a bit of empirical weight.</p>
<p>The rest of the caveats are pretty much classic caveats to any symbolic execution technique.</p>
<p>I hope to get a chance to implement this, and the fact that software pipelining algorithms are usually <em>purely syntactic</em> makes the job easier: from a very high level, we are comparing terms of def-use chains.</p>
<p>Read the <a href="https://jtristan.github.io/papers/popl10.pdf">paper here</a>.</p>




<div id="quarto-appendix" class="default"><section id="footnotes" class="footnotes footnotes-end-of-document"><h2 class="anchored quarto-appendix-heading">Footnotes</h2>

<ol>
<li id="fn1"><p><a href="https://www.cs.cmu.edu/afs/cs/academic/class/15745-s13/public/lectures/L19-Software-Pipelining-1up.pdf">slide 20</a>↩︎</p></li>
</ol>
</section></div> ]]></description>
  <category>apaw</category>
  <guid>https://bitsrc.org/blog/posts/a-paper-a-decade-validator-for-software-pipelining.html</guid>
  <pubDate>Thu, 03 Sep 2026 07:00:00 GMT</pubDate>
</item>
<item>
  <title>Compiler Jokes</title>
  <link>https://bitsrc.org/blog/posts/compiler-jokes.html</link>
  <description><![CDATA[ 




<p>Where do you put your unwanted objects? The objdump</p>
<p>What is Marie Kondo’s favorite tool? Clang-tidy</p>
<p>What wizard reduces binary size? The wizard of Oz</p>
<p>Why didn’t Frodo understand the ring? He doesn’t readelf</p>
<p>Why did a prison hire a compiler? To do escape analysis</p>
<p>What does an elf use to move houses? Relocations</p>
<p>What does the program say when it jumps to an invalid address? Every day we stray further from the light of GOT</p>
<p>Why does the compiler love origami? It’s constant folding</p>
<p>What is a compiler’s favorite sport? Inlining</p>



 ]]></description>
  <category>compilers</category>
  <guid>https://bitsrc.org/blog/posts/compiler-jokes.html</guid>
  <pubDate>Sun, 19 Apr 2026 07:00:00 GMT</pubDate>
</item>
<item>
  <title>Linux: The good, the bad and the ugly</title>
  <link>https://bitsrc.org/blog/posts/linux-the-good-the-bad-and-the-ugly.html</link>
  <description><![CDATA[ 




<p>I’ve been working on system-level software for Linux for some time now, which is a job that makes you much more likely to encounter the odd corner of an operating system than higher level development. For all practical purposes, Linux has succeeded as an operating system. Billions of web queries are being served from Linux servers every day, and it’s running on <a href="https://twitter.com/Android/status/1125822326183014401">billions</a> of mobile devices.</p>
<p>But of course an operating system ultimately rooted in the 70s will have accumulated its fair share of legacy. Of course, not all problems are rooted in this: we still are perfectly capable of making new and exciting mistakes.</p>
<section id="everything-ish-is-a-file-ish" class="level1">
<h1>Everything-ish is a file-ish</h1>
<p>File descriptors are one of the most poorly named concepts, as they don’t necessarily represent (or describe) a file. Think of them more as pointers to resources in the kernel (which are conveniently referenced-counted), and things will start making more sense. You can use file descriptors to refer to many things, among them</p>
<ul>
<li><a href="http://man7.org/linux/man-pages/man2/open.2.html">Files and Directories</a></li>
<li><a href="http://man7.org/linux/man-pages/man2/socket.2.html">Sockets</a></li>
<li><a href="http://man7.org/linux/man-pages/man2/pipe.2.html">Pipes</a></li>
<li><a href="http://man7.org/linux/man-pages/man2/timerfd_create.2.html">Timers</a></li>
<li><a href="http://man7.org/linux/man-pages/man2/signalfd.2.html">Incoming signals</a></li>
<li><a href="http://man7.org/linux/man-pages/man2/memfd_create.2.html">Anonymous memory</a></li>
<li><a href="http://man7.org/linux/man-pages/man2/eventfd.2.html">Events</a></li>
<li><a href="http://man7.org/linux/man-pages/man2/pidfd_open.2.html">Processes</a></li>
<li><a href="http://man7.org/linux/man-pages/man2/perf_event_open.2.html">Performance counters</a></li>
<li>Sadly, <a href="https://lwn.net/Articles/280960/">not locks</a></li>
</ul>
<p>Many of these things are not files in the either the sense that you can use them to store data, nor in the sense that they have a path on the file system. That all of these things are file descriptors is actually kind of cool: you can wait on many of these things, and asynchronous I/O APIs like <code>epoll</code> operate on file descriptors. This means that you can wait for data to become available on some socket <em>or</em> for some timer to run out <em>or</em> for a POSIX signal to arrive. No threading nonsense involved.</p>
<p>On the other hand, a file descriptor to an application developer is just an integer. From an API perspective, now you end up with all of these things just being integers, and all being called fd, and many functions operating on fds, all of them working on a different subset of them. For instance, what would it even mean to write to a timerfd? This gets even worse when talking about errors. Manpages will have a list of possible errnos, but with file descriptor functions, usually all bets are off (short of delving into the kernel source) of trying to understand which ones can happen for your particular case. If your FD is special enough (say, some <code>/sys</code> file), you might even get errors that are <em>not</em> listed on the manpage.</p>
</section>
<section id="quiz" class="level1">
<h1>“Everything is bytes\0”</h1>
<p>Linux has around 300 system calls that you can use in your programs. This is sometimes cited as an impressively small API surface for a kernel, but that’s only telling half of the truth. There are many, many files in the <code>/proc</code> and <code>/sys</code> virtual file-systems that you can read from to get information or write to to change some behaviour. You can use them to read a process’ command line, to get its CPU use, its memory use, to get or change the maximum number of file-descriptors open, set counters on breakpoints, etc. Long story short, you can do many things. If you are writing systems software, you will be using those quite a lot.</p>
<p>Most of those produce (or consume) information in ASCII, so if you want to use them programmatically, you’ll have to parse the output. If you want to do that, it helps to know the format well.</p>
<p>Pop quiz! No cheating.<sup>1</sup></p>
<ol type="1">
<li>Does <code>/proc/&lt;pid&gt;/cmdline</code> have a trailing NUL-byte?</li>
<li>Does <code>/proc/&lt;pid&gt;/status</code> use tabs or spaces?</li>
<li>Does <code>/proc/&lt;pid&gt;/status</code> have a trailing newline?</li>
<li>NUL-byte?</li>
<li>Does <code>/proc/&lt;pid&gt;/oom_score</code> (a single value) have a trailing newline?</li>
<li>Does <code>/proc/&lt;pid&gt;/wchan</code> (a single value) have a trailing newline?</li>
</ol>
<p>Go to results.</p>
<p>So that was fun! If you haven’t looked at the results yet, please do take a second, even if you haven’t tried to answer yourself. There are multiple problems highlighted: most of <code>/proc</code> files are ad-hoc text formats (at least <em>most</em> of them do use newlines, it appears). Another one is that they are extremely poorly documented. A quick look at <a href="http://man7.org/linux/man-pages/man5/proc.5.html"><code>man 5 proc</code></a> would not go far in answering the questions in this quiz. You have to look at the files and work out the format from this. Of course, if you read this from a program, the kernel rendering text only for your program to parse it back again is wasteful in both computer and human resources. This being ad-hoc formats, one has to write a parser for each and every one of them.</p>
<p>For some high-volume formats like ftrace, parsing from the text format is actually prohibitively expensive. This is why there is also a (undocumented) de-facto binary interface. With some configuration in, yes, you guessed it, a custom text format.</p>
</section>
<section id="manything-is-a-race" class="level1">
<h1>Manything is a race</h1>
<p>How would you implement <code>killall</code>? Conceptually, it’s fairly simple: you go through all processes, and kill the ones matching. Having some function <code>matches</code> to determine whether a PID matches the given specification, you’d write something along the lines of this:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb1-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">std::</span>vector<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">pid_t</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> pids <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_all_pids<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">();</span></span>
<span id="cb1-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">pid_t</span> pid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> pids<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-3">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>matches<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>pid<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">))</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-4">    kill<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>pid<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">);</span></span>
<span id="cb1-5">  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-6"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>Cool. That seems to work (given some imagination). But if you are a diligent programmer, maybe having done some multi-threaded programming, something might look a bit off. All we pass around is an integer <code>pid</code>, so how do we know it refers to the same process in <code>match(pid)</code> and in <code>kill(pid)</code>? Processes can go away, and their PIDs will be re-used. In that case, we could potentially match PID 1234 when it is <code>retriable_nonsense_job</code>, but kill <code>super_important_process</code> later.</p>
<p>So how do you write a <em>correct</em> <code>killall</code>? Turns out, on Linux it’s impossible before 5.1, on other Unices it might still be. All the major operating systems’ implementations are not fundamentally different to the pseudocode above<sup>2</sup>. On Linux 5.1, you can <code>opendir</code> <code>/proc/&lt;pid&gt;</code>, then use that as a handle to both read the command line (and other attributes), and <code>pidfd_send_signal</code>.</p>
<p>This might remind you of some code you might have written. Something like</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb2-1"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">pid_t</span> pid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fork<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">();</span></span>
<span id="cb2-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>pid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-3">  oh no<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-4">  abort<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">();</span></span>
<span id="cb2-5"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb2-6"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>pid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-7">  something in child<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-8"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-9">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span> status<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb2-10">  YOUR_EINTR_WRAPPER<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>waitpid<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>pid<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>status<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">));</span></span>
<span id="cb2-11"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>Could PID-reuse mean you could end up waiting on something else? Something that might never exit, in the worst case? Thankfully, not. The child process will actually stick around as a <em>zombie</em>, even if it is finished, until you waitpid for it. As you can only wait on your children, no race can occur like this. Of course, the other thing that can happen is that the parent dies before it has chance to waitpid. In that case, the problem is also averted through some gymnastics: the child process gets <em>orphaned</em> and reparented to <code>init</code>, which will wait on it to prevent the zombie from sticking around. <em>Phew</em>.</p>
</section>
<section id="for-forks-sake" class="level1">
<h1>For fork’s sake</h1>
<p><a href="http://man7.org/linux/man-pages/man2/fork.2.html"><code>fork</code></a> is one of the fundamental building blocks of Unix systems. It goes way back to the old days of Unix and is used to create a new process. That process is a copy of the original one. From an API perspective, to the child it will appear that <code>fork</code> returned 0, while to the parent the PID of the child. Kind of magical if you think of it.<sup>3</sup></p>
<p>Memory does not actually get copied just yet, but only when either the parent or the child attempt to change it (this is called copy-on-write). File descriptors will get duplicated (convenient that they are already referenced counted). Problems already start popping up here: you need to be sure to close the ones you don’t actually need in the child, or you might hold on to them forever. This gets even worse if you <code>exec</code> another program, which (in general) won’t know or care about your file descriptors. To solve the latter problem, <code>O_CLOEXEC</code> (close on exec) was invented. Of course that’s not the default, so people often manually iterate over all FDs (via <code>/proc</code>), and then close them all.</p>
<p>But then came threads, and we went from bad to worse. Because it’s unclear what to do with all these other threads (it’s not like they have a call to fork where they could take different branches), they just get terminated in whatever state they are when fork gets called. Remember we copied the whole memory state? That might contain a lock (say, in <code>malloc</code>) that was being held by one of those threads. The next time anything calls <code>malloc</code>, it will be stuck forever, waiting on the now terminated thread. Your child process is toast. Your program might even be single threaded, but some library you pulled might have created a thread, that might have happened to do an allocation when you called fork.</p>
<p>They came up with <code>pthread_atfork</code> hooks that get called before the fork, and then afterwards in the parent on the child. That was intended to allow library developers to make their libraries safe in the presence of forks, but even the manpage concedes that this “is generally too difficult to be practicable.”</p>
<p>But there’s more! Even though the memory isn’t actually copied, forking is still an expensive operation for the kernel. It has to copy all sorts of structures like page tables and so on. That’s a waste if all we are going to do is exec a new program, replacing the page tables once again. So they came up with <code>vfork</code>, which is like fork except that you pinkie-promise not to call anything except <code>exec</code> or <code>_exit</code> afterwards. This raises questions about the API design: if all you are allowed to call is <code>exec</code>, why not create a function that is the combination of vfork an exec? With all the different exec variations I can see how that would be slightly painful, but at least not something that makes it super easy to shoot your foot. In fact, <code>posix_spawn</code> is exactly that and was standardised in 2001.</p>
<p>But going further down the route of forking, modern Linux also has something else up its sleeve: <a href="http://man7.org/linux/man-pages/man2/clone.2.html"><code>clone</code></a>. That lets you mix-and-match what your new thread/process should share and what it shouldn’t. It lets you create something that has its own process id, but is a thread for all other intents and purposes. Good luck. glibc does not provide a syscall wrapper for this, so you’ll have to be extra dedicated to use this.<sup>4</sup></p>
<p>Ultimately, things do not compose in a way that make it possible to locally reason about a program. Yes, if you hold fork and threads exactly right (for instance by managing all the threads, and having a way to signal them to go to a safe state, and then forking) you <em>can</em> write a correct program. But that requires you to reason globally about your program, which only works if you control every bit of your program, and even then is very hard.</p>
</section>
<section id="enosys" class="level1">
<h1>ENOSYS</h1>
<p>Writing cross-platform software is hard. Most software is written for Linux, and if it happens to run on other Unices, that is a happy accident. For systems software, that is usually a lost cause, as it needs more powerful APIs than POSIX provides. So we’ll settle for Linux. Most of these APIs were introduced at some point, so you’d usually target Linux of some version or newer – this is a generally unavoidable thing to do. But even then Linux has compile-time configuration flags that will enable or disable some system calls, or some arguments to system calls. And some depend on the target architecture. It’s a bit like duck typing: you call it and hope it works.</p>
<blockquote class="blockquote">
<p>ENOSYS The membarrier() system call is not implemented by this kernel.</p>
<p>EINVAL cmd is invalid, or flags is nonzero, or the MEMBARRIER_CMD_GLOBAL command is disabled because the nohz_full CPU parameter has been set, or the MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE and MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_SYNC_CORE commands are not implemented by the architecture.</p>
<p>– <a href="http://man7.org/linux/man-pages/man2/membarrier.2.html"><code>man 2 membarrier</code></a></p>
</blockquote>
<p>Any software that uses one of those system calls is inherently unportable even between machines of the <em>same kernel version</em>. You will notice this incompatibility at runtime, whenever you attempt to call that syscall. Some more sanity could be achieved if there was a way to check for this without actually calling the syscall. Then some static analysis could figure out which syscalls you use, and then generate a stanza to check whether they exist that you can run at first startup. Everything would be like <code>./configure</code>. What’s not to love?</p>
</section>
<section id="standards" class="level1">
<h1>Standards</h1>
<blockquote class="blockquote">
<p>WE DO NOT BREAK USERSPACE!</p>
<p>– Linus (2012)</p>
</blockquote>
<p>C++ has <a href="https://timsong-cpp.github.io/cppwp/n3337/">The Standard</a>, which, even being aspirational<sup>5</sup> at times, gives people a way to abstractly reason about their programs. Unix has POSIX, but that is a very low common denominator. Linux-specific details have no standard whatsoever. In the end, the kernel behaviour is whatever is in the kernel source, and the kernel promises to not break userspace<sup>6</sup>. For libc, it’s the wild west without any proper specification once you go beyond what’s specified in C and POSIX.</p>
<p>With the proliferation on non-Glibc based Linux systems (musl on Alpine Linux, Bionic on Android) this makes interoperability more painful than it has to be. But more than that: it makes system programming <em>very hard</em>. It is often impossible to work in all situations client code could construct via creative use of the available syscalls. Ultimately, looking at kernel and userspace in isolation is not the right approach. In an ideal world, applications should not need to care about the kernel.</p>
</section>
<section id="errno" class="level1">
<h1>Errno</h1>
<p>Pop quiz again! How did I get this error?</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode sh code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">$</span> ./a.out </span>
<span id="cb3-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">bash:</span> ./a.out: No such file or directory</span></code></pre></div></div>
<p>If you guessed that <code>a.out</code> didn’t exist, that would be one way of getting this error. But in my case what does not exist is the linker library that is specified in the ELF file<sup>7</sup>. That’s one of the joys of <code>errno</code>: for more complicated operations like this, it is unclear what file the <code>ENOENT</code> error refers to. Some of the socket errnos on the other hand are very specific. Other syscalls just give you <code>EINVAL</code>, and you need to figure out what exactly is wrong. If all you get is a single integer, I don’t think there’s a way to really strike that balance, as you have to encode both what you want humans to see, but also what the calling code might deal with. For <code>EINVAL</code>, a human would probably want to know which of the arguments was wrong, while the calling code can’t do anything with that information.</p>
</section>
<section id="conclusion" class="level1">
<h1>Conclusion</h1>
<p>I could go on, but I think I’ll wrap it up here. People can only take so much. <sup>8</sup></p>
<p>Systems programming is exciting, and if you’ve read this far you’d probably be inclined to agree. I’ve shown some of the not-so-nice corners I’ve come across. Some are inevitable in an operating system of this size and age. But they also are a valuable lesson in system design. Generalising a bit</p>
<ul>
<li><em>Data should be machine-readable</em>: otherwise, people will have to build ad-hoc parsers. Those will contain bugs.</li>
<li><em>APIs should allow to locally reason about code</em>: it is impossible to reason about all your dependencies in big software systems. Apart from that, it is very hard to reason about large state spaces.</li>
<li><em>Errors matter:</em> good error reporting gives a good developer experience.</li>
<li><em>Consistency matters:</em> having too many knobs fragments your system.</li>
<li><em>Behaviour should be specified:</em> This creates a contract between application programmers and operating system programmers. People will violate that contract, but no one knows what to expect if there isn’t any.</li>
</ul>
<p>But also, we have to work with what we’ve got. Even if we come up with robust APIs for client applications, there will always be the long-tail of weird legacy software that uses the old ones. <code>fork</code> is here to stay, and so are threads. What we can do is meticulously document both the caveats that come with those, and the behaviour. For <code>/proc</code> files, some EBNF definition can help both formalize the format, and be used to auto-generate parsers. The less we can base our engineering on guesswork, the better.</p>
</section>
<section id="quiz-results" class="level1">
<h1>EBNF results</h1>
<ol type="1">
<li>Maybe.<sup>9</sup></li>
<li>Tabs.<sup>10</sup></li>
<li>Yes.</li>
<li>No.</li>
<li>Yes.</li>
<li>No.</li>
</ol>
<p>Of course, those were kind of trick questions. No one would ever have gotten the first one right (what kind of answer is that even?). And the last two don’t make any sense either, because they are both single values.</p>
<p>Go back up</p>
</section>
<section id="endnotes" class="level1">
<h1>Endnotes</h1>


</section>


<div id="quarto-appendix" class="default"><section id="footnotes" class="footnotes footnotes-end-of-document"><h2 class="anchored quarto-appendix-heading">Footnotes</h2>

<ol>
<li id="fn1"><p>Or cheat, I’m a sign, not a cop.↩︎</p></li>
<li id="fn2"><p><a href="https://github.com/acg/psmisc/blob/master/src/killall.c">GNU/Linux</a>, <a href="http://sources.freebsd.org/RELENG_7/src/usr.bin/killall/killall.c">FreeBSD</a>, or <a href="https://github.com/apple-open-source/macos/blob/master/shell_cmds/killall/killall.c">macOS</a>.↩︎</p></li>
<li id="fn3"><p><strong>Spoilers for Ted Chiang’s story “Anxiety Is the Dizziness of Freedom”</strong>. It’s like the premise of that story. (Assuming single-threaded) fork brings forth a new process that is the same, except for one int, which is used to make a choice. All other differences derive from that.↩︎</p></li>
<li id="fn4"><p>I’m not a fan of syscalls without wrappers, as that encourages people to use raw syscalls, which then constrains libc implementors. clone is actually a good example: Bionic (Android’s libc) has a cache for the TID of a thread. It needs to invalidate that cache upon calls to fork / clone / etc. It can only do this when people use the syscall wrapper. People don’t always.↩︎</p></li>
<li id="fn5"><p>Some of the more low-level details leave a lot to be desired. Many things are impossible in a standards compliant way, or are underspecified, so people end up doing what works in practice.↩︎</p></li>
<li id="fn6"><p>This, of course, leads to the question of what constitutes a feature, and what constitutes a bug. And what level of quality you expect from user-space. For instance, adding a new line to a proc file would break applications that do not properly look at key, value pairs, but rather hard-code the line they expect the value to be at. It’s generally accepted that writing code like this is asking to be broken.↩︎</p></li>
<li id="fn7"><p>This has actually happened to me before. But if you know where to look (<a href="http://man7.org/linux/man-pages/man2/execve.2.html"><code>man execve</code></a>), it’s at least documented.↩︎</p></li>
<li id="fn8"><p>I do have opinions on more things, including but not limited to: <code>perf_event_open</code>, signals, <code>sendmsg</code>, session leaders, controlling terminals, <code>SIGPIPE</code>, …↩︎</p></li>
<li id="fn9"><p>Depends on whether your kernel has <a href="https://github.com/torvalds/linux/commit/f5b65348fd77839b50e79bc0a5e536832ea52d8d">this commit</a>.↩︎</p></li>
<li id="fn10"><p>The <a href="http://man7.org/linux/man-pages/man5/proc.5.html">manpage</a> uses spaces.↩︎</p></li>
</ol>
</section></div> ]]></description>
  <guid>https://bitsrc.org/blog/posts/linux-the-good-the-bad-and-the-ugly.html</guid>
  <pubDate>Sun, 19 Apr 2020 07:00:00 GMT</pubDate>
</item>
<item>
  <title>Automatic Org-Mode</title>
  <link>https://bitsrc.org/blog/posts/organizing-notetaking.html</link>
  <description><![CDATA[ 




<p>With the unprecedented en vogue<sup>1</sup> right now, I have taken the unprecedented step of trying out Emacs after having been a loyal Vim user for years. This is not going to be another charge in the endless Editor War<sup>2</sup>. Rather more uncontroversially, this is going to focus on note-taking and how technology can (and cannot) help.</p>
<p>If how this relates to Emacs is a mystery, just trust me that this will make sense. But first to more elementary things.</p>
<section id="pen-and-paper" class="level1">
<h1>Pen and Paper</h1>
<p>On my desk at work<sup>3</sup> I have a notebook (of nice dotted paper<sup>4</sup>) and a fountain pen<sup>5</sup>. I use them to take notes in meetings, while working, draw diagrams, write TODO lists. I clearly mark items that are tasks, and tick them off once done. Once a notebook is full, I scan it for archival.</p>
<p>It works fairly well, but there are some limitations. An obvious drawback is the lack of searchability<sup>6</sup>. This is not helped by that the way I keep the notebook, it is sorted by time; this also makes it hard to amend or extend previous entries. Legibility occasionally is an issue, especially when I take notes in a hurry, for instance in a meeting.</p>
<p>Paper and fountain pens are technologies <em>invented 2000 and 200 years ago</em>. With all our fancy tools of the supposed information age, can we do better?</p>
</section>
<section id="maybe" class="level1">
<h1>Maybe?</h1>
<p>This has been my main note-taking system for about three years now. Before that, calling my note-taking at work a system would have been a euphemism<sup>7</sup>. How come I, as a computer engineer with terrible handwriting, still use a physical piece of paper?</p>
<p>Paper, it turns out, is quite good at what it does. No one, to my knowledge, has been able to reproduce the freedom and convenience of writing on paper. It is trivial to interleave drawings and text, you can split the page into as many sections or columns as you want. I regularly take some space I have free on the right to designate to some related thought that does not really fit into the main narrative.</p>
<p>Does this mean digital notetaking is a lost cause?</p>
</section>
<section id="beating-at-its-own-game" class="level1">
<h1>Beating at its own game</h1>
<p>Some programs, like <a href="https://onenote.com">OneNote</a>, have attempted to replicate the experience of taking notes on paper. I have tried using OneNote for a bit, and would say it has not succeeded. But that, I think, is also the wrong approach: you should not try to beat paper at its own game. Rather, you should focus on what digital technologies are good at.</p>
<p>When you do that, paper’s strength also becomes a weakness. From an information theory point of view, a hand-written piece of paper holds a lot more bits of information than the same text as an ASCII text file. Sometimes this lets you express more exactly what you want, but mostly it is unnecessary. When writing a word, chances are the exact ways you write the letters is not relevant and mostly determined by chance.</p>
<p>Having less noise in the data, as you have in digital notes, makes it easier to automatically process them. You can search within them, automatically find relationships, easily replicate, among other things.</p>
</section>
<section id="relationships" class="level1">
<h1>Relationships</h1>
<p>At least for me, one of the most important part of notes is linking different kinds of artifacts. As I work in software engineering, these artifacts might be a bug, a pull request, some mathematical concept or algorithm, things like that. A bug I am fixing might relate to an algorithm, and the fix is done as a pull request. In addition to all of this, I might want to add my own comments.</p>
<p>This is a use-case very poorly served by paper notes, as you’d have to physically bring these things to the same place. This is why, so far, I have mostly used notes as a <em>thinking aid</em>, rather than a <em>memory aid</em>. I would take down notes more as a form of <a href="https://en.wikipedia.org/wiki/Rubber_duck_debugging">rubber ducking</a> than anticipating I will revisit them later – it was often prohibitively hard to find them again at the right time.</p>
<p>But if I could revisit those notes that were intended as <em>thinking aid</em> later, it would help me remember why certain decisions were taken. If this was fairly close to when it was written, this has already proven useful. I might not remember why I had dismissed an alternative approach, but sometimes my notes do. They would say something like “<del>overload flux capacitor -&gt; bad idea, brings us back to dinosaur age.</del>” Then I can immediately dismiss that approach again, without wasting cognitive effort on it again.</p>
</section>
<section id="roam" class="level1">
<h1>Roam</h1>
<p>The <a href="https://roamresearch.com/">Roam</a> note taking app has a simple but really cool way of dealing with those relationships between concepts. Every time you refer to another concept in a note, you get a back reference from the page about that concept. So, if I write a note about, say, move semantics in C++, and mention C++ in that page, the C++ page will show me a back reference to “move semantics”. It also lets you see these relationships in a graph.</p>
<p>That goes some way of making notes more discoverable later, as you automatically get a sort of index built. But what I think is missing there is how this interacts with artifacts that are not notes. Take for instance this blog post. Say you have a great idea that is related to it, and you want to remember it. You could write a note that has a link to it. Wouldn’t it then be nice to have a backreference <em>from this post</em>? Without that, how likely are you to remember that you had even written that note in a year’s time?</p>
</section>
<section id="orgmode" class="level1">
<h1>OrgMode</h1>
<p><a href="https://orgmode.org">OrgMode</a> is a package for Emacs that is designed for note-taking. It is superficially similar to Markdown: you can have headings, lists, tables, etc. It is somewhat more sophisticated than that, even as a text processor: you can insert blocks of code that can be executed in line, and produce data to be used by another block of code. But this is somewhat beside the point here.</p>
<p>What’s more interesting are its cross-reference abilities. You can put TODO items with deadlines in your notes, and then have OrgMode generate an agenda (from all your files). You can tag your headings (and files) and then search according to that.</p>
</section>
<section id="org-roam" class="level1">
<h1>Org-Roam</h1>
<p><a href="https://org-roam.readthedocs.io/">Org-Roam</a> takes the ideas of Roam (mainly backreferences) and adapts them to OrgMode. The main feature it allows is to display the back-references to the current file. It also allows to to generate a graph of your references using GraphViz, but that is much less pretty and useful than the interactive graph Roam-proper offers.</p>
<p>That’s nice, but it’s still a walled garden. Back-references can only be created from other notes (specifically ones within your Org-Roam directory). But this time, the walled-garden is within an open-source software, so maybe we can do something to jump the wall.</p>
</section>
<section id="instant-org" class="level1">
<h1>Instant-Org</h1>
<p>These ideas have led me to write a <a href="https://gist.github.com/segfaulthunter/f56ec6b8fd579b5bf1a0298a0f8cc175">simple prototype</a> of how a system that can jump that wall might look. The idea is very simple: whenever we switch to a new window<sup>8</sup>, we analyze whether the currently focused window relates to any entity that we have a note about: for instance, if we switch to a browser window, I parse the title to see whether we are currently looking at a bug, a pull request, a GitHub repository (sadly, each of those is a hardcoded regex). If it’s a terminal window, I look at the current working directory to see if I have any notes about that.</p>
<p>It then checks the Org-Roam database to see whether we have a note about that entity, and if we do, automatically opens it in the background. This, being a prototype, is still an approximation on what I ultimately envision: we can link notes to entities outside of the walled garden this way, but we don’t collect back-references if other notes link to the entity, not the associated note. I recorded a <a href="https://drive.google.com/file/d/19v5u2AmO27IMI-H9mx-Q0TqKmzrgzVGT/view">short demo</a> on how that looks.</p>
<p>Once I get more comfortable with elisp, I will attempt to teach Org-Roam to handle more sorts of links. That would make the resulting graph much richer and more useful: whenever you visit a website, you can see all the time you referred to it in any note.</p>
<p>Is this better than paper notes? Maybe. But only once the knowledge graph has grown enough for the overhead in taking notes to pay dividends.</p>
</section>
<section id="endnotes" class="level1">
<h1>Endnotes</h1>


</section>


<div id="quarto-appendix" class="default"><section id="footnotes" class="footnotes footnotes-end-of-document"><h2 class="anchored quarto-appendix-heading">Footnotes</h2>

<ol>
<li id="fn1"><p>If anyone happens to read this in the future: this was written at the time of the global COVID-19 lockdowns.↩︎</p></li>
<li id="fn2"><p>Vim keybindings are better.↩︎</p></li>
<li id="fn3"><p>If you have never tried dotted paper, do it. It’s like squared paper with less visual clutter. I like the <a href="https://www.amazon.co.uk/gp/product/B00BCH03Z2">Rhodia A4 notebook</a>.↩︎</p></li>
<li id="fn4"><p>Which I, inconveniently, have no access to right now.↩︎</p></li>
<li id="fn5"><p>JinHao make <a href="https://www.amazon.co.uk/dp/B07PQ2RXF7">insanely affordable</a> ones. I promise I do not get paid for these Amazon links.↩︎</p></li>
<li id="fn6"><p>There will need to be some more breakthroughs in machine learning before I can subject my handwriting to OCR software, and until then I’ll have to continue to search manually.↩︎</p></li>
<li id="fn7"><p>University is easier. Things can be neatly arranged by subjects.↩︎</p></li>
<li id="fn8"><p>Actually, I just poll the active window every 100 ms to see if it changed.↩︎</p></li>
</ol>
</section></div> ]]></description>
  <guid>https://bitsrc.org/blog/posts/organizing-notetaking.html</guid>
  <pubDate>Thu, 16 Apr 2020 07:00:00 GMT</pubDate>
</item>
<item>
  <title>Analysing regexp with Golang</title>
  <link>https://bitsrc.org/blog/posts/golang-regexp.html</link>
  <description><![CDATA[ 




<p><strong>DISCLAIMER</strong>: Let me say this first. Google’s regular expression implementations are known for not implementing features that make them, well, not regular. Both <code>re2</code> and Golang’s <code>regexp</code> do not support backreferences. Otherwise, the things done here would be hard, or impossible.</p>
<p>I may not be Golang’s biggest fan in general (lack of generics, verbose syntax, simplistic type system, etc), but I’ve written a bunch of it in the last couple of years and found an unexpectedly useful feature. Golang provides a package called <code>regexp/syntax</code> that proves to be as useful as its documentation is sparse.</p>
<p>In essence, this package exposes the user to the finite state machines built by the regexp compiler. This can be used to do analyses on regular expressions such as “does this regexp ever match a particular character after matching <code>n</code> characters?” or “does this regexp match any strings starting with a particular prefix?”. These might sound like constructed examples, but both of them actually popped up in my dayjob.</p>
<section id="toy-example-loop-detection" class="level1">
<h1>Toy Example: Loop detection</h1>
<p>For sake of simplicity, let’s explore a constructed example first in this post: does a regexp match strings of arbitrary length? Or, in more technical terms: is there a loop in the finite state machine? Let’s get right started with the boilerplate of compiling a regular expression into something called a <code>Prog</code>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb1-1">r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> err <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:=</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Parse<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`.*`</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Perl<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb1-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> err <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">nil</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-3">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">panic</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>fmt<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Sprintf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Parse: %v"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> err<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">))</span></span>
<span id="cb1-4"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-5"></span>
<span id="cb1-6">p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> err <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:=</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Compile<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>r<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Simplify<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">())</span></span>
<span id="cb1-7"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> err <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">nil</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-8">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">panic</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>fmt<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Sprintf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Compile: %v"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> err<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">))</span></span>
<span id="cb1-9"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-10">fmt<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Println<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span></code></pre></div></div>
<p>This actually produces a nice and readable representation of the generated finite state machine. Note the * next to 2 which tells us that this is the initial state.</p>
<pre class="text"><code>  0 fail
  1 anynotnl -&gt; 2
  2*    alt -&gt; 1, 3
  3 match</code></pre>
<p>What we see here is the textual representation of the <code>Prog</code> object. It’s a struct containing</p>
<ul>
<li><code>Inst</code>: list of instructions</li>
<li><code>Start</code>: initial instruction</li>
</ul>
<p><code>Inst</code> is the type used to represent an instruction. It’s a struct containing:</p>
<ul>
<li><code>Op</code>: type of instruction</li>
<li><code>Out</code>: next instruction (except for InstMatch and InstFail, which are terminal instructions)</li>
<li><code>Arg</code>: additional argument to some instructions</li>
</ul>
<p>For the purposes of this toy example, all we care about is which instructions can follow from a given instruction. For most instructions, that is the instruction referred to in <code>Out</code>. Let’s introduce the odd ones here:</p>
<ul>
<li><code>InstMatch</code>: successfully match input string. Does not have successor instruction.</li>
<li><code>InstFail</code>: reject input string. Does not have successor instruction.</li>
<li><code>InstAlt</code> / <code>InstAltMatch</code>: either <code>Out</code> or <code>Arg</code> are the successor instruction. A string matches if either of the branches arrives at <code>InstMatch</code>.</li>
</ul>
<p>If you are curious about the difference between <code>InstAlt</code> and <code>InstAltMatch</code>: From all I could determine, <code>InstAltMatch</code> is an optimisation where it is known that one branch leads to a match while the other branch consumes characters. I do not see the compiler or any rewriting actually using this instruction, so it does not seem to be in use. Most of the implementation treats them interchangeably, while <a href="https://golang.org/src/regexp/backtrack.go?h=InstAltMatch#L181">backtrack.go</a> in the regex evaluator appears to use it to determine which branch to take.</p>
<p>This information allows us to implement a helper function to determining the successor instructions, given an instruction.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb3-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">func</span> GetSuccessors<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Inst<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[]</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb3-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Op <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstMatch <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">||</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Op <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstFail <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb3-3">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[]</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{}</span></span>
<span id="cb3-4">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb3-5">    o <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[]</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Out<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb3-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Op <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstAlt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">||</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Op <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstAltMatch <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb3-7">        o <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">append</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>o<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Arg<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb3-8">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb3-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> o</span>
<span id="cb3-10"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>Now we can implement loop-detection by a simple breadth-first search, keeping track of already visited nodes in a set (i.e.&nbsp;a <code>map[uint32]bool</code>, because Golang does not have a set type).</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">func</span> HasLoop<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Prog<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb4-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">var</span> tovisit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[]</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span></span>
<span id="cb4-3">    tovisit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">append</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>tovisit<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Start<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">))</span></span>
<span id="cb4-4">    seen <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">make</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">map</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb4-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>tovisit<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb4-6">        i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:=</span> tovisit<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb4-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> seen<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb4-8">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">true</span></span>
<span id="cb4-9">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb4-10">        seen<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">true</span></span>
<span id="cb4-11">        tovisit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tovisit<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:]</span></span>
<span id="cb4-12">        tovisit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">append</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>tovisit<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> GetSuccessors<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(&amp;</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Inst<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">])...)</span></span>
<span id="cb4-13">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb4-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">false</span></span>
<span id="cb4-15"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
</section>
<section id="a-regex-engine" class="level1">
<h1>A regex engine</h1>
<p>Now let’s try to build a very inefficient regex engine based on this. To do so, let us first introduce the various rune instructions (rune is Golang for Unicode codepoint). There is <code>InstRune</code>, <code>InstRune1</code>, <code>InstRuneAny</code> and <code>InstRuneAnyNotNL</code>. Most of them (except <code>InstRune</code> and <code>InstRune1</code>) should be self-explanatory, but here’s the whole list:</p>
<ul>
<li><code>InstRuneAny</code> matches any rune.</li>
<li><code>InstRuneAnyNotNL</code> matches any rune except newlines.</li>
<li><code>InstRune</code> has a <code>MatchRune</code> method to determine whether it matches a rune.</li>
<li><code>InstRune1</code> matches the rune provided in <code>i.Rune[0]</code> (obviously.)</li>
</ul>
<p>This leaves us with two remaining useful instructions:</p>
<ul>
<li><code>InstCapture</code>: capture a match into a capture group. We won’t bother with this here.</li>
<li><code>InstEmptyWidth</code>: match constrains on the current position in the string. This has a <code>MatchEmptyWidth</code> to determine whether it matches.</li>
</ul>
<p>There’s also <code>InstNop</code> which, well, does nothing.</p>
<p>Of course, the easiest way to do this is a recursive evaluator. We pass in a program, the current instruction, and input, and the current position in the input.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb5-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">func</span> Match<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Prog<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> pc <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> input <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[]</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">rune</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> idx <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span></code></pre></div></div>
<p>Let’s first determine the previous and current rune at the current position, and use <code>-1</code> for the borders of the string (to be consistent with <code>MatchEmptyWidth</code>).</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb6-1">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">var</span> prev <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">rune</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb6-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb6-3">        prev <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb6-4">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb6-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">var</span> cur <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">rune</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb6-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb6-7">        cur <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb6-8">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>And now all that’s left is one fairly large switch (if you look at actual implementations of regex engines, there are also often giant switches, so it’s legit).</p>
<p><code>InstAlt</code> and <code>InstAltMatch</code> are the same, so let’s use the <code>fallthrough</code> statement for go switch statements (this is much more sane than C-style fallthrough by default).</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb7-1">    i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:=</span> p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Inst<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>pc<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb7-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">switch</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Op <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb7-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstAlt<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb7-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fallthrough</span></span>
<span id="cb7-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstAltMatch<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb7-6">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Match<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Out<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">||</span> Match<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Arg<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span></code></pre></div></div>
<p>We don’t care about <code>InstCapture</code> or <code>InstNop</code> here.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb8-1">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstNop<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb8-2">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fallthrough</span></span>
<span id="cb8-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstCapture<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb8-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Match<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Out<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span></code></pre></div></div>
<p>For <code>InstEmptyWidth</code> we use the method that was given to us for this.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb9-1">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstEmptyWidth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb9-2">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>MatchEmptyWidth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>prev<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> cur<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb9-3">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">false</span></span>
<span id="cb9-4">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb9-5">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Match<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Out<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span></code></pre></div></div>
<p>(I could get used to this). <code>InstMatch</code> and <code>InstFail</code> are obvious.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb10-1">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstMatch<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb10-2">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">true</span></span>
<span id="cb10-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstFail<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb10-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">false</span></span></code></pre></div></div>
<p>Then there come the various ways of matching runes. Note that this is the only time we have to increment the index into our input, as this is the only time we actually consume any runes.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb11-1">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstRune<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb11-2">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> cur <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">||</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>MatchRune<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>cur<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb11-3">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">false</span></span>
<span id="cb11-4">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb11-5">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Match<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Out<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb11-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstRune1<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb11-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> cur <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">||</span> cur <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Rune<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb11-8">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">false</span></span>
<span id="cb11-9">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb11-10">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Match<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Out<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb11-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstRuneAny<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb11-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> cur <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb11-13">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">false</span></span>
<span id="cb11-14">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb11-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Match<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Out<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb11-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstRuneAnyNotNL<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb11-17">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> cur <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">||</span> cur <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">'\n'</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb11-18">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">false</span></span>
<span id="cb11-19">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb11-20">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Match<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Out<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> input<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span></code></pre></div></div>
<p>That’s it. Now some due diligence against us being bad programmers, and we’re done.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb12-1">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">default</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb12-2">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">panic</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Invalid instruction."</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb12-3">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb12-4">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">panic</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Fell off the switch."</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb12-5"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>Well, that was fun. But not terribly exciting. But what this gives is a good mental model of what exactly the different instructions mean, which can be used to build more exciting things.</p>
</section>
<section id="do-we-only-match-even-length-strings" class="level1">
<h1>Do we only match even-length strings?</h1>
<p>Now that we can proudly proclaim we have written a regular expression engine (well, maybe we were <em>slightly</em> cheating and someone else helped <em>a bit</em>), let’s take up a bigger challenge. Given a regular expression that possibly matches arbitrarily length strings, determine whether all strings matched have an even size. Sounds like an interview question? A bit, but I also hope I’ll never get this as an actual interview question.</p>
<p>Let’s start with a similar prototype as for our <code>Match</code> function, but instead of our input let’s have something that flips around whether we are at an even or odd step. For reasons that will make sense later, let’s encode this as an integer that flips between <code>0</code> and <code>1</code> (so it’s <code>idx % 2</code>). We also need to keep track of which nodes we have seen before, or we will wait for a long time. But if you think about it a bit, we need to keep track of this for even and odd steps, an even visit and an odd visit are not the same. That results in the beautiful type of <code>map[int]map[uint32]bool</code>, or a map from an integer to a set of <code>uint32</code>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb13-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">func</span> Even<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Prog<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> pc <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> idx <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> visited <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">map</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">map</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span></code></pre></div></div>
<p>Now let’s start with the easy part. I literally copy &amp; pasted the <code>Match</code> code, removed all the stuff that actually does any … matching, plumbed through the visited map and made <code>idx</code> mod 2. That gives us all the rune instructions and <code>InstCapture</code>, <code>InstNop</code> and <code>InstEmptyWidth</code> (which are all, for all intents and purposes, noop).</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb14-1">    i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:=</span> p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Inst<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>pc<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb14-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">switch</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Op <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb14-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstNop<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb14-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fallthrough</span></span>
<span id="cb14-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstCapture<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb14-6">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fallthrough</span></span>
<span id="cb14-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstEmptyWidth<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb14-8">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Even<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Out<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> visited<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb14-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstRune<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb14-10">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fallthrough</span></span>
<span id="cb14-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstRune1<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb14-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fallthrough</span></span>
<span id="cb14-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstRuneAny<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb14-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fallthrough</span></span>
<span id="cb14-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstRuneAnyNotNL<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb14-16">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Even<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Out<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)%</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> visited<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span></code></pre></div></div>
<p><code>InstMatch</code> is straightforward, as we just have to check whether we are at an even step. <code>InstFail</code> confusingly returns <code>true</code>, as we do not care about branches that do not lead to matches.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb15-1">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstMatch<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb15-2">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> idx <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb15-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstFail<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb15-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">true</span> </span></code></pre></div></div>
<p>Now to one of my least favourite parts of Golang, copying nested maps. But here we go. Let’s introduce a helper method, as when we branch for <code>InstAlt</code> we will need a separate copy of the visited map for both branches.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb16-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">func</span> copyVisited<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>visited <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">map</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">map</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">map</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">map</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb16-2">    n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">make</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">map</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">int</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">map</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb16-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> k<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">range</span> visited <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb16-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> n<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>k<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">nil</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb16-5">            n<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>k<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">make</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">map</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb16-6">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb16-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> k2<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> v2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">range</span> v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb16-8">            n<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>k<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">][</span>k2<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> v2</span>
<span id="cb16-9">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb16-10">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb16-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> n</span>
<span id="cb16-12"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>OK, with that out of the way, we can tackle the <code>InstAlt</code> instructions.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb17-1">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstAlt<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb17-2">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fallthrough</span></span>
<span id="cb17-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> syntax<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>InstAltMatch<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb17-4">        branchvisited <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:=</span> copyVisited<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>visited<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb17-5">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Even<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Out<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> visited<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> Even<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> i<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>Arg<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> branchvisited<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span></code></pre></div></div>
<p>This one is different, as we want to make sure we can <em>only</em> match even length strings, so we need to <code>&amp;&amp;</code> the conditions, rather than <code>||</code> them.</p>
<p>Due diligence again.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb18-1">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">default</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span></span>
<span id="cb18-2">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">panic</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Invalid instruction."</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb18-3">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb18-4">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">panic</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Fell off the switch."</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span></code></pre></div></div>
<p>If we stop for a second to see what we’ve built, it’s obvious we’ve built a potential infinite loop. Let’s rectify this. If we arrive back at an instruction that we’ve been before with the same <code>idx % 2</code>, we can just prune this branch and return <code>true</code> as it is exactly the same.</p>
<p>So let’s prepend our switch statement with the following.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb19-1">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> visited<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">][</span>pc<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb19-2">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">true</span></span>
<span id="cb19-3">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>And then, of course, we need to keep track of what we’ve seen before, which again involves one of my least favourite parts of Golang, nested maps.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode go code-with-copy"><code class="sourceCode go"><span id="cb20-1">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> visited<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">nil</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb20-2">        visited<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">make</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">map</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span></span>
<span id="cb20-3">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb20-4">    visited<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">][</span>pc<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">true</span></span></code></pre></div></div>
<p>And that’s done! To see the whole code used in this post head off to this <a href="https://gist.github.com/segfaulthunter/25a8fb5502ebddd413c00eada4ff18bf">Github Gist</a>.</p>
<p>If you have made it this far, it is probably also worth noting that the Z3 SMT solver has a <a href="https://rise4fun.com/z3/tutorialcontent/sequences#h23">Regex Theory</a>. The last time I’ve played with it it was giving obviously incorrect answers, but that seems to have been rectified since. The nice thing about <code>regexp/syntax</code> is that it uses the same library your application uses if you write it in Golang, and can be used in programs with more predictable performance and fewer dependencies than Z3.</p>


</section>

 ]]></description>
  <category>programming</category>
  <guid>https://bitsrc.org/blog/posts/golang-regexp.html</guid>
  <pubDate>Thu, 01 Mar 2018 08:00:00 GMT</pubDate>
</item>
<item>
  <title>More Turing Completeness, or: Somebody is wrong on the Internet</title>
  <link>https://bitsrc.org/blog/posts/someone-is-wrong-on-the-internet.html</link>
  <description><![CDATA[ 




<p>Hello, I am Florian and you might remember me from posts such as <a href="http://bitsrc.org/blog/theoretical-cs/2016/08/27/turing-complete.html">Turing Completeness</a>. Today I am going to return to the topic of Turing Completeness, in a post in similar vein. Today’s post explores the arguments Zed Shaw presents in <a href="https://learnpythonthehardway.org">Learn Python The Hard Way</a> on why <a href="https://learnpythonthehardway.org/book/nopython3.html">Python 3 is the inferior version</a> of the language; in particular, how the concept of Turing Completeness is abused to make a point that is completely unrelated to it. Note that I explicitly do not want to take any position in the Python 2 vs.&nbsp;Python 3 argument, I merely want to expose the flawed logic in this particular line of reasoning.</p>
<p>Let’s go explore the argument presented and why it is flawed.</p>
<blockquote class="blockquote">
<p>Python 3 Is Not Turing Complete</p>
</blockquote>
<p>With the right definition of Python 3, this might actually be technically correct. Any computer language executed on a real physical computer can never be truly Turing complete. Because all resources in a computer are finite, you could theoretically enumerate all possible states. If you have studied a bit of computation theory, Turing Machines are more powerful than that (also, you will know that functions that you can enumerate are usually “boring” from a computation theory point of view).</p>
<blockquote class="blockquote">
<p>In computer science a fundamental law is that if I have one Turing Machine I can build any other Turing Machine.</p>
</blockquote>
<p>I am not completely sure what that even means. If you have a Turing Machine that just does nothing, I can not use that to build any Turing Machine. There is a Turing Machine (also known as the Universal Turing Machine) that can simulate all other Turing machines. Note that this requires the Turing Machines it simulates to be <em>encoded</em> in some suitable way.</p>
<blockquote class="blockquote">
<p>If I have COBOL then I can bootstrap a compiler for FORTRAN (as disgusting as that might be). If I have FORTH, then I can build an interpreter for Ruby.</p>
</blockquote>
<p>If you have Python 3, you can <em>definitely</em> use that to write an interpreter of Python 2 in it, if you really really want to. But even that has no direct correspondence to the point of Turing Completeness. Note how this talks about specific encodings of a program (i.e.&nbsp;programming languages), while the concept of Turing Completeness concerns itself with mathematical (partial) functions.</p>
<p>A mathematical function is just a mapping from input to output, while a program is a procedure to produce said output. It is completely possible that a Turing Complete system is unable to express a <em>program</em> another one can. The Game of Life is Turing Complete, but it will definitely will never be able to parse your Python program from your hard-disk.</p>
<blockquote class="blockquote">
<p>Currently you cannot run Python 2 inside the Python 3 virtual machine. Since I cannot, that means Python 3 is not Turing Complete and should not be used by anyone.</p>
</blockquote>
<p>No, no. It really really does not mean either of these things.</p>
<blockquote class="blockquote">
<p>Note</p>
<p>Yes, that is kind of funny way of saying that there’s no reason why Python 2 and Python 3 can’t coexist other than the Python project’s incompetence and arrogance. Obviously it’s theoretically possible to run Python 2 in Python 3, but until they do it then they have decided to say that Python 3 cannot run one other Turing complete language so logically Python 3 is not Turing complete. I should also mention that as stupid as that sounds, actual Python project developers have told me this, so it’s their position that their own language is not Turing complete.</p>
</blockquote>
<p>I would really like to see these conversations. Either these Python developers are misquoted here, or were wrong (or, as explored above: technically correct – but that has nothing to do with any of the arguments that were made).</p>
<p>The rest of the argument goes on in similar fashion, incorrectly combining concepts of theoretical computer science with implementations, citing how other virtual machines manage to be more general purpose, and so on, and so forth; the latter of which, of course, is true – but invariantly true for CPython 2 and CPython 3.</p>



 ]]></description>
  <category>computer-science</category>
  <guid>https://bitsrc.org/blog/posts/someone-is-wrong-on-the-internet.html</guid>
  <pubDate>Wed, 23 Nov 2016 08:00:00 GMT</pubDate>
</item>
<item>
  <title>Fun with Operator Overloading</title>
  <link>https://bitsrc.org/blog/posts/operator-overloading.html</link>
  <description><![CDATA[ 




<p>The other day I was asked to take a look at code I had written years ago that basically allowed the user to build up logical formulas while always keeping them in CNF (conjunctive normal form – that is, a logical formula where the outermost connective is always a conjunction).</p>
<p>This was done by building a class hierarchy with an abstract class <code>Expr</code> on the top level, two classes <code>ExprAnd</code> and <code>ExprOr</code> that represent conjunction and disjunction respectively and both contain lists of <code>Expr</code>. Various other classes where used to represent various atoms of the formulas, the particular code was about solar physics so the atoms happen to be things like <code>Wavelength(x, y)</code> for selecting observations of a particular wavelength.</p>
<p>The base class <code>Expr</code> defines <code>__and__</code> and <code>__or__</code>, that is the methods that need to be implemented to overload the <code>&amp;</code> and <code>|</code> operations that just return <code>ExprAnd</code> and <code>ExprOr</code> of the object and the left hand operand.</p>
<p><code>ExprAnd</code> and <code>ExprOr</code> also implement the operation corresponding to their node type by just returning a new <code>ExprAnd</code> or <code>ExprOr</code> with the left hand operand added to the list, respectively. They also implement <code>__rand__</code> and <code>__ror__</code>, so their special implementation is also applied if they are used at the right hand side of the operation – or that was the plan. <code>ExprAnd</code> commutes <code>|</code> operations into the conjuction to keep conjunction as the top level connective.</p>
<p>The problem that I asked to help with was that <code>foo &amp; (bar &amp; baz)</code> did not seem to evaluate into <code>ExprAnd(foo, bar, baz)</code>, but rather <code>ExprAnd(foo, ExprAnd(bar, baz))</code>, that is, the automatic transformation to CNF was not working.</p>
<p>Python actually implements logic that when you have an operation <code>foo &amp; bar</code> where the type of <code>bar</code> is a subclass of the type of <code>foo</code> and implements its own version of <code>__rand__</code>, the expression will be evaluating using that. So when you read <code>__rand__</code> (or any of the operators) is used if the left hand side does not implement the operator, that is wrong. For instance,</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">18</span>]: <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Foo(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">object</span>):</span>
<span id="cb1-2">    ...:     <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__add__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x):</span>
<span id="cb1-3">    ...:         <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Foo "</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x</span>
<span id="cb1-4">    ...:         </span>
<span id="cb1-5"></span>
<span id="cb1-6">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">19</span>]: <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Qux(Foo):</span>
<span id="cb1-7">    ...:     <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__radd__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x):</span>
<span id="cb1-8">    ...:         <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Qux "</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x</span>
<span id="cb1-9">    ...:         </span>
<span id="cb1-10"></span>
<span id="cb1-11">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>]: Foo() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> Qux()</span>
<span id="cb1-12">Qux  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>__main__.Qux <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">object</span> at <span class="bn" style="color: #AD0000;
background-color: null;
font-style: inherit;">0x112f9f750</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>__main__.Foo <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">object</span> at <span class="bn" style="color: #AD0000;
background-color: null;
font-style: inherit;">0x112f7e510</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span></code></pre></div></div>
<p>This behaviour was what I was aiming to exploit by making <code>ExprAnd</code> (for instance) implement both <code>__and__</code> and <code>__rand__</code> and make Python use the most specific implementation. Sadly, it does not work this way. If you now introduce a third class that inherits from Foo and does not implement either of the methods itself, the base class’ will be used, for instance</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">21</span>]: <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Bar(Foo):</span>
<span id="cb2-2">    ...:     <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span>
<span id="cb2-3">    ...: </span>
<span id="cb2-4">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22</span>]: Bar() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> Qux()</span>
<span id="cb2-5">Foo  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>__main__.Bar <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">object</span> at <span class="bn" style="color: #AD0000;
background-color: null;
font-style: inherit;">0x112f80890</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>__main__.Qux <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">object</span> at <span class="bn" style="color: #AD0000;
background-color: null;
font-style: inherit;">0x112f93a90</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span></code></pre></div></div>
<p>The semantics of Python operator overloading will <em>only</em> prefer the <code>__rand__</code> method of the right hand side if it is an object of a subclass of the <em>type of the right hand side object</em>. Note that this does not take into account in which class the implementation of the left hand side was actually done, which explains the behaviour above.</p>
<p>If you look at the class layout described above, this was exactly the case that I was hitting. Disclaimer: What follows below is not how it was actually fixed in the code.</p>
<section id="going-crazy" class="level1">
<h1>Going Crazy</h1>
<p>I realized that what I had intended to implement back then was something like commutative <a href="http://clojure.org/reference/multimethods">multimethod</a>. Python’s dynamicity, for better or worse, gives you the tools to do most of such things, so I decided to give it a go.</p>
<p>The gist of the idea is to try to find the most specific implementation of the operation, considering both operands. The operation of the left hand side operand is more specific if it overrides the definition of the operation on the right hand side (and the other way round).</p>
<p>This can conveniently be expressed in terms of Python: The operation of the left hand side operand is more specific if the operation defined by the right hand side is in the MRO (method resolution order – the list of classes, in order, that get consulted when looking up a method in an object).</p>
<p>To implement this, first we define a functions to get all functions. It is important to know that the function is different to the unbound and bound method object and does not contain information about which class it is contained in; the function object can be obtained from an unbound method object by using <code>im_func</code>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> inspect</span>
<span id="cb3-2"></span>
<span id="cb3-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> fn_mro(cls, fn):</span>
<span id="cb3-4">    mro <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> inspect.getmro(cls)</span>
<span id="cb3-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> [<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">getattr</span>(x, fn).im_func <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> mro <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">hasattr</span>(x, fn)]</span></code></pre></div></div>
<p>This can then be used to implement the logic as described above as a decorator that wraps a method. Note that we have to compare whether the left and right side operator is actually the same to prevent an infinite loop.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> most_specific(fn):</span>
<span id="cb4-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> func(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, other):</span>
<span id="cb4-3">        name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fn.<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">__name__</span></span>
<span id="cb4-4">        self_fn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">getattr</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, name).im_func</span>
<span id="cb4-5">        other_fn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">getattr</span>(other, name).im_func</span>
<span id="cb4-6">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> self_fn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> other_fn:</span>
<span id="cb4-7">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> fn(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, other)</span>
<span id="cb4-8">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> self_fn <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> fn_mro(other.<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">__class__</span>, name):</span>
<span id="cb4-9">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># We did not inherit this from something in other's MRO.</span></span>
<span id="cb4-10">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> other_fn <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> fn_mro(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">__class__</span>, name):</span>
<span id="cb4-11">                <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># They didn't either. PANIC!</span></span>
<span id="cb4-12">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">TypeError</span></span>
<span id="cb4-13">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> fn(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, other)</span>
<span id="cb4-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb4-15">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">getattr</span>(other, name)(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>)</span>
<span id="cb4-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> func</span></code></pre></div></div>
<p>If we use the decorator on a slightly modified version of the previous example (we use <code>__add__</code> instead of <code>__radd__</code> because the decorator assumes commutativity and uses the same operations on both sides).</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>]: <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Foo(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">object</span>):</span>
<span id="cb5-2">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@most_specific</span></span>
<span id="cb5-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__add__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x):</span>
<span id="cb5-4">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Foo "</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x</span>
<span id="cb5-5">   ...:         </span>
<span id="cb5-6"></span>
<span id="cb5-7">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>]: <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Qux(Foo):</span>
<span id="cb5-8">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@most_specific</span></span>
<span id="cb5-9">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__add__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x):</span>
<span id="cb5-10">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Qux "</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x</span>
<span id="cb5-11">   ...:         </span>
<span id="cb5-12"></span>
<span id="cb5-13">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>]: Foo() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> Qux()</span>
<span id="cb5-14">Qux  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>__main__.Qux <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">object</span> at <span class="bn" style="color: #AD0000;
background-color: null;
font-style: inherit;">0x103103690</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>__main__.Foo <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">object</span> at <span class="bn" style="color: #AD0000;
background-color: null;
font-style: inherit;">0x103103f50</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb5-15"></span>
<span id="cb5-16">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>]: <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Bar(Foo):</span>
<span id="cb5-17">   ....:     <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span>
<span id="cb5-18">   ....: </span>
<span id="cb5-19"></span>
<span id="cb5-20">In [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>]: Bar() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> Qux()</span>
<span id="cb5-21">Qux  <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>__main__.Qux <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">object</span> at <span class="bn" style="color: #AD0000;
background-color: null;
font-style: inherit;">0x103103e50</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>__main__.Bar <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">object</span> at <span class="bn" style="color: #AD0000;
background-color: null;
font-style: inherit;">0x10310b050</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span></code></pre></div></div>


</section>

 ]]></description>
  <category>python</category>
  <guid>https://bitsrc.org/blog/posts/operator-overloading.html</guid>
  <pubDate>Fri, 14 Oct 2016 07:00:00 GMT</pubDate>
</item>
<item>
  <title>Completeness and decidability</title>
  <link>https://bitsrc.org/blog/posts/completeness.html</link>
  <description><![CDATA[ 




<p>The subtle difference between incompleteness (of a theory), completeness (of a proof system) and indecidability (of a logical system) are a common source of confusion. How come Gödel proved both completeness and incompleteness? How can a proof system be complete (there exists a proof for every true sentence) when the underlying logical system is undecidable (it is impossible to find a proof for every true sentence)?</p>
<p>The first question can be answered by something that should be familiar to everyone working in IT: bad naming. The “completeness” in the two theorems actually refers to two different things: completeness in the completeness theorem relates a formal proof system to model theory and says that a statement is true only if it can be proved (in a proof system for which completeness holds), that is <img src="https://latex.codecogs.com/png.latex?%5CPi%20%5Cmodels%20X%20%5CRightarrow%20%5CPi%20%5Cvdash%20X"> – read <img src="https://latex.codecogs.com/png.latex?X"> follows from <img src="https://latex.codecogs.com/png.latex?%5CPi"> implies <img src="https://latex.codecogs.com/png.latex?X"> is provable from <img src="https://latex.codecogs.com/png.latex?%5CPi">; the completeness in the incompleteness theorem refers to whether a theory <img src="https://latex.codecogs.com/png.latex?%5CPi"> contains every sentence or its negation, i.e.&nbsp;<img src="https://latex.codecogs.com/png.latex?%5Cforall%20X%20(%5CPi%20%5Cmodels%20X%20%5Clor%20%5CPi%20%5Cmodels%20%5Cneg%20X)"> – read for each <img src="https://latex.codecogs.com/png.latex?X">, either <img src="https://latex.codecogs.com/png.latex?X"> or <img src="https://latex.codecogs.com/png.latex?%5Cneg%20X"> follow from <img src="https://latex.codecogs.com/png.latex?%5CPi">. It is not hard to see that those two statements have no direct relationship to each other – one of them talks about a theory (the <img src="https://latex.codecogs.com/png.latex?%5CPi">), the other one about a proof system.</p>
<p>The second question is more subtle and can be explained by the slightly metaphysical definition of truth and existence in classical logic. We can rewrite the statement of the completeness theorem as “for each true statement, there exists a proof”. To do so, let’s define <img src="https://latex.codecogs.com/png.latex?P(x,%20%5CPi,%20%5Cphi)"> to be the predicate that is true iff <img src="https://latex.codecogs.com/png.latex?x"> is a valid proof for <img src="https://latex.codecogs.com/png.latex?%5CPi%20%5Cvdash%20%5Cphi">. Then a formalisation would be <img src="https://latex.codecogs.com/png.latex?%5CPi%20%5Cmodels%20%5Cphi%20%5CRightarrow%20%5Cexists%20p%5C;P(p,%20%5CPi,%20%5Cphi)">. Decidability, which could be expressed as “there exists a procedure with which, for every true statement, we can find a proof”, on the other hand, could be expressed as (for the reader following at home – this definition works because f can just return an invalid proof for <img src="https://latex.codecogs.com/png.latex?%5CPi%20%5Cnot%5Cmodels%20%5Cphi">) <img src="https://latex.codecogs.com/png.latex?%5Cexists%20f,%20P%5C;(%20f%20%5Ctext%7B%20computable%7D%20%5Cland%20%5CPi%20%5Cmodels%20%5Cphi%20%5CLeftrightarrow%20P(f(%5CPi,%20X),%20%5CPi,%20%5Cphi))">.</p>
<p>For a sound proof system (one that only proves true sentences, i.e.&nbsp;<img src="https://latex.codecogs.com/png.latex?%5CPi%20%5Cmodels%20X%20%5CLeftarrow%20%5CPi%20%5Cvdash%20X">), completeness of a proof system would imply decidability if you left out the part about computability. The difference is that explicitly quantifying over the function and requiring it be computable means there has to be a procedure, while a simple exists quantifier introduces an implicit function. The notion of procedure is a lot stronger than function; a function as defined in mathematics is simply a mapping from one set to the other (whereof there are uncountably infinite for infinite sets), while procedure requires a formal (finite) representation that could be executed by a computer (whereof there are countably infinite).</p>
<p>This mirrors the distinction between classical and intuitionistic logic. In classical logic, there is a platonic idea of truth (and thus existence): it is legitimate to refer to an object that one has no procedure on how to produce, if one can infer it has to exist (whatever it is). Intuitionistic logic, however, is a lot stricter and requires there to be a procedure on how to produce the objects.</p>



 ]]></description>
  <category>logic</category>
  <guid>https://bitsrc.org/blog/posts/completeness.html</guid>
  <pubDate>Sun, 25 Sep 2016 07:00:00 GMT</pubDate>
</item>
<item>
  <title>A Paper a Whatever #15: Keystroke Recognition Using WiFi Signals</title>
  <link>https://bitsrc.org/blog/posts/a-paper-a-week-keystroke-recognition-wifi.html</link>
  <description><![CDATA[ 




<p>This paper is about detecting a user’s keypresses using the interference the movements of the fingers cause in WiFi signals. This sounds scary and like something out of a cheesy spy movie; nevertheless it is not quite time to get out your tinfoil hat, as (at least as demonstrated) this is only accurate in controlled conditions where equipment is specifically set-up and the user is instructed not to move their head. It does not seem like there is anything that makes it inherently impossible to do in uncontrolled conditions.</p>
<p>The introduction talks about various other interesting approaches other people have taken to recognize keystrokes, including matching on the distinctive sound different keypresses produce or their electromagnetic signature. There is also prior work in using radio interference patterns, but the authors of this paper took the different approach of only using over-the-counter equipment for doing so. I was not aware at all that there was this much research going on on essentially remote key-logging.</p>
<p>Their approach, however, exploits something known as CSI values – sadly, no, that does not stand for Crime Scene Investigation. CSI stands for Channel State Information and is a set of values that WiFi devices use to optimize their transmission among multiple channels.</p>
<p>They observed that it is possible to find signatures for different movements of the fingers in those CSI values, but they faced the problem that they needed to determine when a key-press started and ended, and noise was also a problem. They would denoise the signal by first applying low-pass filtering and then applying Principal Component Analysis on the data retrieved from the CSI of various channels – they noticed that while the changes were not the same in all of them, they were strongly correlated. So they applied PCA, discarding the highest variance component.</p>
<p>Mean Absolute Deviations are then used to find parts of the timeseries that are high in variance and correspond to keypresses by comparing them to empirically obtained thresholds. The thus found timeseries are then used to train a k Nearest Neighbour model, which would classify each unknown sample with the class that the majority of its k nearest neighbours from the training data-set correspond to. They use Dynamic Time Warping as a distance metric, which tries to align two data-sets by non-linearly warping the time axis until they match. This allows them to compare the signatures of keypresses, even if they are pressed longer or shorter than in the training data.</p>
<p>This model is then trained with 30 data-samples per user per key, and numbers for accuracy are given. This is with the caveat that the experiment was done under controlled conditions, in particular the users were asked to type one key at a time and not to move their heads or other body parts. Training the model independently for each user, they managed to achieve 93.5 % keypress recognition accuracy in continuously typed sentences.</p>
<p>Find the paper <a href="https://www.sigmobile.org/mobicom/2015/papers/p90-aliA.pdf">here</a>.</p>



 ]]></description>
  <category>apaw</category>
  <guid>https://bitsrc.org/blog/posts/a-paper-a-week-keystroke-recognition-wifi.html</guid>
  <pubDate>Sat, 03 Sep 2016 07:00:00 GMT</pubDate>
</item>
<item>
  <title>Turing Completeness</title>
  <link>https://bitsrc.org/blog/posts/turing-complete.html</link>
  <description><![CDATA[ 




<p>This is one of my pet peeves: I have heard many people describe Turing-complete as “a language you can do everything with”. That is untrue and this is a very short post to set this right.</p>
<p>Turing-complete means a language can be used to express a (probably non-proper – if you manage to find a system that is more expressible than the Turing machine, I am sure there is a Turing award or two waiting for you) superset of the pure mathematical functions that a Turing machine can compute. This does not talk about I/O (which is an important part of an actual computer) or the complexity these functions are executed in. So, I am afraid we will not see an operating system written in the Game of Life.</p>
<p>This definition also means an actual computer is technically not Turing complete, given it cannot simulate a Turing machine’s infinite tape.</p>
<p>So, concluding: Turing-complete does not mean a language is useful to do something on an actual computer, while an actual computer is not actually Turing-complete. The two concepts are quite orthogonal.</p>
<p>Elaborating more (it was late yesterday): I/O can be “simulated” with appropriate encoding in the output, but that is one of the points: arithmetic is Turing-complete, so I can, for all Turing-computable functions, produce an integer that <em>somehow encodes</em> its result. This is an extremely important theoretical construct in computation theory, but also useless in a practical context, because I want to write actual data into actual memory of an actual machine.</p>



 ]]></description>
  <category>theoretical-cs</category>
  <guid>https://bitsrc.org/blog/posts/turing-complete.html</guid>
  <pubDate>Sat, 27 Aug 2016 07:00:00 GMT</pubDate>
</item>
<item>
  <title>A Paper a Week-ish #14: GraphLab: A New Framework for Parallel Machine Learning</title>
  <link>https://bitsrc.org/blog/posts/a-paper-a-week-graphlab-framework-parallel-machine-learning.html</link>
  <description><![CDATA[ 




<p>It has been a long time since I last posted one of those, apologies! I have been fairly busy with various things and the time I had for this blog I spent on non paper-related posts to mix things up a bit.</p>
<p>The paper I read for this post is about GraphLab which is a framework for expressing parallel computations based on a graph model that allows to exploit the sparse structure of machine learning algorithms, that is to say that steps of the computation only operate on a subset of the state. In this graph data is associated with each vertex and edge, and a user-supplied update function is used to compute new values. This update function can only access and modify data in the neighbourhood of the node, that is the data of the node, its adjacent edges and vertices.</p>
<p>In addition to the data stored in the graph, there is a shared data table, which contains data which, as the name suggests, can be accessed by all applications of the update function – it can not be modified by them though. To modify data in the shared data table, a fold function that iteratively calculates a value from the data in the vertices and the previous value is specified by the user. Optionally, the user can scale the result of the fold or supply functions to merge results of different fold operations.</p>
<p>By imposing the restriction that the update function only operate on the neighbourhood of a node, the graph encodes the data dependencies between different parts of the computation and allows to determine which updates can be applied concurrently. GraphLab offers different consistency models: <em>full consistency</em> makes sure no data can be accessed concurrently, <em>edge consistency</em> ensures no two updates that access shared edges are executed at the same time, and <em>vertex consistency</em> only ensures only one update is applied to a particular node at a given time. From all I can see, vertex consistency only works correctly for trivially parallelizable problems, that is problems consisting of independent threads of computation that do not interact.</p>
<p>A scheduler determines the sequence of sets of updates that should appear to be applied to the graph at the same time. So, for example, if the sequence is [<img src="https://latex.codecogs.com/png.latex?A">, <img src="https://latex.codecogs.com/png.latex?B">] where <img src="https://latex.codecogs.com/png.latex?A"> and <img src="https://latex.codecogs.com/png.latex?B"> are sets of functions applied to vertices, it is ensured that (modulo the consistency model) it appears that all the operations in <img src="https://latex.codecogs.com/png.latex?A"> were applied to the graph at the same time, then all operations in <img src="https://latex.codecogs.com/png.latex?B">. Different machine learning algorithms require different schedulers.</p>
<p>Note how I said “appear to be applied”, which means that this is not necessarily how they are actually applied. As an example, if vertex consistency is used, and <img src="https://latex.codecogs.com/png.latex?A%20=%20%5C%5C%7Bv_1,%20v_2%5C%5C%7D"> and <img src="https://latex.codecogs.com/png.latex?B%20=%20%5C%5C%7Bv_3,%20v_4%5C%5C%7D">, then <img src="https://latex.codecogs.com/png.latex?f(v_1)">, <img src="https://latex.codecogs.com/png.latex?f(v_2)">, <img src="https://latex.codecogs.com/png.latex?f(v_3)">, <img src="https://latex.codecogs.com/png.latex?f(v_4)"> can be evaluated at the same time, while it still appears that <img src="https://latex.codecogs.com/png.latex?B"> was applied after <img src="https://latex.codecogs.com/png.latex?A">. There is a very strong connection to how databases handle transactions – if the update function does not modify values that are not exclusive to it by the consistency model, we get serializability – that is, the parallel execution produces the same result as some sequential one. Database transactions are also designed to be serializable, and two of them can commit concurrently if they involve disjunct sets of rows.</p>
<p>The paper concludes with case studies of machine learning tasks implemented in GraphLab, which I will skip in this post.</p>
<p>Find the paper here: <a href="http://arxiv.org/pdf/1006.4990v1.pdf">GraphLab: A New Framework For Parallel Machine Learning</a>.</p>



 ]]></description>
  <category>apaw</category>
  <guid>https://bitsrc.org/blog/posts/a-paper-a-week-graphlab-framework-parallel-machine-learning.html</guid>
  <pubDate>Sun, 17 Apr 2016 07:00:00 GMT</pubDate>
</item>
<item>
  <title>Using theorem proving to cheat in logic puzzles</title>
  <link>https://bitsrc.org/blog/posts/theorem-proving-logic-puzzles.html</link>
  <description><![CDATA[ 




<p>I recently got the book <a href="http://www.amazon.co.uk/What-Name-This-Book-Recreational/dp/0486481980">What is the Name of this Book?</a> by the excellent Raymond Smullyan, who is also the author of a book about <a href="http://www.amazon.co.uk/Godels-Incompleteness-Theorems-Oxford-Guides/dp/0195046722">Gödel’s Incompleteness Theorems</a> I could not praise highly enough. The book I purchased is a collection of logical riddles. While recreationally solving logical puzzles oneself can be very rewarding, when I got the book I considered that it would be interesting to try and solve these using formalized logic. Letting a computer find the solution given the formal specification is the obvious next step, which is what I will attempt in this blogpost. To do so, I will first formalize the specification in first-order logic, and then use the <a href="https://z3.codeplex.com">Z3 SMT solver</a> to find satisfying models.</p>
<p>A lot of the book is about a world in which there are two types of people, knights and knaves. Knights always speak the truth, and knaves always lie. This particular puzzle is about finding out information about the one werewolf among people A, B and C that make the following statements.</p>
<ul>
<li>A: C is a werewolf.</li>
<li>B: I am not a werewolf.</li>
<li>C: At least two of us are knaves.</li>
</ul>
<p>We are trying to find answers to the following two questions:</p>
<ul>
<li>Is the werewolf a knight or a knave?</li>
<li>If you have to take one of them as a travelling companion, and it is more important that he be not a werewolf than that he not be a knave, which one would you pick?</li>
</ul>
<p>First we will formalize the fact that there is exactly one werewolf as the two statements “there exists at least one werewolf” and “the werewolf is unique” (we assume that the universe contains only persons, because they are the only objects in this riddle, so we do not need a predicate for “is person”):</p>
<p><span id="eq-firsteqn"><img src="https://latex.codecogs.com/png.latex?%0A%5Cexists%20x%5C,%20Werewolf(x)%0A%5Ctag%7B1%7D"></span></p>
<p><span id="eq-onewerewolf"><img src="https://latex.codecogs.com/png.latex?%0A%5Cforall%20x%5C,%20(Werewolf(x)%20%5Cimplies%20(%5Cforall%20y%5C,%20(x%20%5Cne%20y%20%5Cimplies%20%5Cneg%20Werewolf(y))))%0A%5Ctag%7B2%7D"></span></p>
<p>Then, we introduce the Knight predicate (and an equivalence of negative Knight to Knave for convenience)</p>
<p><span id="eq-knave"><img src="https://latex.codecogs.com/png.latex?%0A%5Cforall%20x%5C,%20(Knight(x)%20%5Cequiv%20%5Cneg%20Knave(x))%0A%5Ctag%7B3%7D"></span></p>
<p>Next we can formalize the three statements, which are true if and only if the person that says them is a Knight.</p>
<p><span id="eq-astate"><img src="https://latex.codecogs.com/png.latex?%0AKnight(A)%20%5Cequiv%20Werewolf(C)%0A%5Ctag%7B4%7D"></span></p>
<p><span id="eq-bstate"><img src="https://latex.codecogs.com/png.latex?%0AKnight(B)%20%5Cequiv%20%5Cneg%20Werewolf(B)%0A%5Ctag%7B5%7D"></span></p>
<p><span id="eq-lasteqn"><img src="https://latex.codecogs.com/png.latex?%0AKnight(C)%20%5Cequiv%20%5Cexists%20x%5C,%20%5Cexists%20y%5C,%20(x%20%5Cne%20y%20%5Cland%20Knave(x)%20%5Cland%20Knave(y))%0A%5Ctag%7B6%7D"></span></p>
<p>If we call the set of equations (Equation&nbsp;1) to (Equation&nbsp;6) <img src="https://latex.codecogs.com/png.latex?%5CPi">, then we want to find out whether</p>
<p><span id="eq-sol1"><img src="https://latex.codecogs.com/png.latex?%0A%5CPi%20%5Cmodels%20%5Cexists%20x%5C,%20(Knight(x)%20%5Cland%20Werewolf(x))%0A%5Ctag%7B7%7D"></span></p>
<p><span id="eq-sol2"><img src="https://latex.codecogs.com/png.latex?%0A%5CPi%20%5Cmodels%20%5Cexists%20x%5C,%20(Knave(x)%20%5Cland%20Werewolf(x))%0A%5Ctag%7B8%7D"></span></p>
<p>Then, to answer the second question, we want to check</p>
<p><span id="eq-sol3"><img src="https://latex.codecogs.com/png.latex?%0A%5CPi%20%5Cmodels%20%5Cneg%20Werewolf(A)%0A%5Ctag%7B9%7D"></span></p>
<p><span id="eq-sol4"><img src="https://latex.codecogs.com/png.latex?%0A%5CPi%20%5Cmodels%20%5Cneg%20Werewolf(B)%0A%5Ctag%7B10%7D"></span></p>
<p><span id="eq-sol5"><img src="https://latex.codecogs.com/png.latex?%0A%5CPi%20%5Cmodels%20%5Cneg%20Werewolf(C)%0A%5Ctag%7B11%7D"></span></p>
<p>So, with that out of the way, let us introduce the tool that will make sure we do not need to do any thinking: the Z3 SMT solver. SMT stands for satisfiability modulo theory and means that you can give it first-order formulas of some theories (like equality, integers, computer arithmetic, …) and it will try to find a satisfying model. Given infinite domains there is no guarantee that will be found (especially the negative answer is particularly challenging – if there is a positive one it will be found by enumeration eventually). If you want to prove <img src="https://latex.codecogs.com/png.latex?%5CPi%20%5Cmodels%20A"> using an SMT solver, in general what you do is apply the deduction theorem to obtain <img src="https://latex.codecogs.com/png.latex?%5Cmodels%20%5Cpi%20%5Cimplies%20A"> (where <img src="https://latex.codecogs.com/png.latex?%5Cpi"> is the conjunction of the elements of <img src="https://latex.codecogs.com/png.latex?%5CPi">). All possible models satisfy this if and only if there is no model satisfying the negation, i.e.&nbsp;<img src="https://latex.codecogs.com/png.latex?%5Cneg%20(%20%5Cpi%20%5Cimplies%20A)">, which can be rewritten as <img src="https://latex.codecogs.com/png.latex?%5Cpi%20%5Cland%20%5Cneg%20A">. In other words, we ask the SMT solver if <img src="https://latex.codecogs.com/png.latex?%5Cpi%20%5Cland%20%5Cneg%20A"> is satisfyable, and if the answer is no, <img src="https://latex.codecogs.com/png.latex?%5CPi%20%5Cmodels%20A"> holds.</p>
<p>Now all that’s left is translating this specification to Z3’s language. First thing we need to do is define a datatype for our objects, that are Persons. By using <code>declare-datatype</code> we get objects that are only equal to themselves, so we can use the equality predicate as above.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode lisp code-with-copy"><code class="sourceCode commonlisp"><span id="cb1-1">(set-option :timeout <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">600</span>)</span>
<span id="cb1-2">(declare-datatypes () ((Person A B C)))</span></code></pre></div></div>
<p>Then, we need to define our three predicates Knight, Knave and Werewolf.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode lisp code-with-copy"><code class="sourceCode commonlisp"><span id="cb2-1">(declare-fun Knight (Person) Bool)</span>
<span id="cb2-2">(declare-fun Knave (Person) Bool)</span>
<span id="cb2-3">(declare-fun Werewolf (Person) Bool)</span></code></pre></div></div>
<p>Then we can formalize the formulas of <img src="https://latex.codecogs.com/png.latex?%5CPi"> into Z3 syntax pretty much verbatim. The statement that there is exactly one werewolf can be expressed with the two assertions that a model has to satisfy</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode lisp code-with-copy"><code class="sourceCode commonlisp"><span id="cb3-1">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> (exists ((x Person)) (Werewolf x)))</span>
<span id="cb3-2">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> (forall ((x Person)) (implies (Werewolf x) (forall ((y Person)) (implies (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x y)) (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> (Werewolf y)))))))</span></code></pre></div></div>
<p>The three statements by A, B and C become the following. Note that <code>=</code> is used for both logical equivalence and equality between objects of the universe in Z3.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode lisp code-with-copy"><code class="sourceCode commonlisp"><span id="cb4-1">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> (forall ((x Person)) (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (Knight x) (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> (Knave x)))))</span>
<span id="cb4-2">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (Knight A) (Werewolf C)))</span>
<span id="cb4-3">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (Knight B) (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> (Werewolf B))))</span>
<span id="cb4-4">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (Knight C) (exists ((x Person) (y Person)) (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x y)) (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> (Knave x) (Knave y))))))</span></code></pre></div></div>
<p>Now we have asserted all we know about the problem, we can begin trying to prove (Equation&nbsp;7) – (Equation&nbsp;11) to see which one the solutions is correct. We use the <code>push</code> and <code>pop</code> operations of Z3 to temporarily add assertions between the two operations. I simplified <img src="https://latex.codecogs.com/png.latex?%5Cneg%20%5Cneg%20Werewolf(%E2%80%A6)"> to <img src="https://latex.codecogs.com/png.latex?Werewolf(%E2%80%A6)"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode lisp code-with-copy"><code class="sourceCode commonlisp"><span id="cb5-1">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">push</span>)</span>
<span id="cb5-2">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> (exists ((x Person)) (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> (Werewolf x) (Knave x)))))</span>
<span id="cb5-3">(check-sat)</span>
<span id="cb5-4">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pop</span>)</span>
<span id="cb5-5"></span>
<span id="cb5-6">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">push</span>)</span>
<span id="cb5-7">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> (exists ((x Person)) (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> (Werewolf x) (Knight x)))))</span>
<span id="cb5-8">(check-sat)</span>
<span id="cb5-9">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pop</span>)</span>
<span id="cb5-10"></span>
<span id="cb5-11">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">push</span>)</span>
<span id="cb5-12">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> (Werewolf A))</span>
<span id="cb5-13">(check-sat)</span>
<span id="cb5-14">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pop</span>)</span>
<span id="cb5-15"></span>
<span id="cb5-16">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">push</span>)</span>
<span id="cb5-17">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> (Werewolf B))</span>
<span id="cb5-18">(check-sat)</span>
<span id="cb5-19">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pop</span>)</span>
<span id="cb5-20"></span>
<span id="cb5-21">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">push</span>)</span>
<span id="cb5-22">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> (Werewolf C))</span>
<span id="cb5-23">(check-sat)</span>
<span id="cb5-24">(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pop</span>)</span></code></pre></div></div>
<p>Z3’s answer to the input we gave it is</p>
<pre class="text"><code>unsat
sat
unsat
sat
sat</code></pre>
<p>This means that (Equation&nbsp;7) and (Equation&nbsp;9) hold in all models, and the others do not. This means that the werewolf is a Knave, and we should take person A as our travelling companion.</p>
<p>While a rather simple example, I think this is a nice demonstration of what one can do with an SMT solver.</p>



 ]]></description>
  <category>logic</category>
  <guid>https://bitsrc.org/blog/posts/theorem-proving-logic-puzzles.html</guid>
  <pubDate>Sun, 03 Apr 2016 07:00:00 GMT</pubDate>
</item>
<item>
  <title>Theorem Proving in Haskell</title>
  <link>https://bitsrc.org/blog/posts/theorem-proving-in-haskell.html</link>
  <description><![CDATA[ 




<p>For some reason that is not completely clear to me either, I decided to go about and implement the <a href="https://en.wikipedia.org/wiki/Sequent_calculus">sequent calculus</a> technique for theorem proving this weekend. Because that alone would be a rather dull exercise, I decided to do it in a language I do not know very well. I first thought about trying to implement it in OCaml, but then decided to go with Haskell because there I at least know some basics.</p>
<p>Before going into the implementation, it is probably worth spending a few words on the sequent calculus. The basic construct of the sequent calculus is a sequent, which looks like this: <img src="https://latex.codecogs.com/png.latex?A,%20B,%20%5Cldots%20%5Cvdash%20C">. This is the assertion that, from the set of assumptions <img src="https://latex.codecogs.com/png.latex?A,%20B,%20%5Cldots">, we can prove <img src="https://latex.codecogs.com/png.latex?C">. The sequent calculus consists of rules that allow to simplify the sequents in a way that the simplified sequents are valid iff the original one is. These rules can be repeatedly applied until only atoms exist in the sequent, at which point it is obvious whether it is valid or not (e.g.&nbsp;<img src="https://latex.codecogs.com/png.latex?A%20%5Cvdash%20A"> is obviously correct, while <img src="https://latex.codecogs.com/png.latex?A%20%5Cvdash%20B"> is not, with <img src="https://latex.codecogs.com/png.latex?A"> and <img src="https://latex.codecogs.com/png.latex?B"> being logical atoms).</p>
<p>One detail I have omitted so far is that I initially wanted to write a prover that works for intuitionistic instead of classical logic. The difference between the two logics is that, intuitionistic logic is stricter than classic logic in that it requires proofs to be constructive. This means that the proofs can be used to construct an object that satisfies the assertion. For instance, <img src="https://latex.codecogs.com/png.latex?P%20=%20NP%20%5Clor%20P%20%5Cne%20NP"> is obviously true in classical logic, but intuitionistically one cannot prove this without knowing which of the two sides hold. If you are only here for the Haskell, it is probably not important that you completely understand this.</p>
<p>My initial attempt (I am very inexperienced in Haskell) was to define two functions to encode the proof with the <em>first operation</em> being on left or the right side of the sequent. It would then call the respective other function on the simplified sequents. At this point I only wanted to encode intuitionistic proofs, so I had the left hand side of the proof as a list of expressions, and the right hand side as a single expression. I had the constructor Nil, only to be used on the right side, to express that it is empty. <code>proveLeft</code> tried to apply a rule to the first expression in the list.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode haskell code-with-copy"><code class="sourceCode haskell"><span id="cb1-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">data</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Implication</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Var</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">String</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Neg</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Nil</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">deriving</span> (<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Eq</span>,<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Show</span>)</span>
<span id="cb1-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">data</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span> [<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span>] <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">deriving</span> (<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Eq</span>,<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Show</span>)</span>
<span id="cb1-3"></span>
<span id="cb1-4"><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">proveLeft ::</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Bool</span></span>
<span id="cb1-5"><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">proveRight ::</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Bool</span></span></code></pre></div></div>
<p>I ran into all sorts of problems, especially with the negation operator on the left side, which can only be applied when the right hand side is empty. Atoms had to be explicitly skipped by putting them to the end of the list. Because of this it was hard to figure out when to terminate, or, as with intuitionistic logic one has the drop the right hand side if the proof is “stuck”, when to do that.</p>
<p>I tried to make this work for a bit, but then realized if I ever got it to work, it will be extremely brittle and probably broken in one corner case or another. I then tried attacking the problem in smaller parts – the first one of which was transforming a sequent into simpler sequents. I also thought always using the first expression in the list as the one to operate on was not helpful, so I came up with the following functions (with rather poor names). I also decided to do classical logic first – in a sense, it is simpler because the left and the right hand side are both sets of expressions.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode haskell code-with-copy"><code class="sourceCode haskell"><span id="cb2-1"><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">expandLeft ::</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Maybe</span> [<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span>]</span>
<span id="cb2-2"><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">expandRight ::</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Maybe</span> [<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span>]</span></code></pre></div></div>
<p>The return value is <code>Maybe [Sequent]</code> so the function can return <code>Nothing</code> if the <code>Expr</code> cannot be operated on, or <code>Just [Sequent]</code> if it can be. For optimization purposes I decided to replace the <code>[Expr]</code> from before with a custom type containing three <code>[Expr]</code> – one for atoms (we need not bother trying to apply rules to them), one for negation (for classical logic, this is not needed, but later for intuitionistic we will want to skip those if there is something on the right hand side), and other composite expressions that we can always apply rules to. This is not strictly needed because of the <code>Maybe [Sequent]</code>, but it felt a bit wasteful to call a function that only returns <code>Nothing</code> for every atom – would be interesting to do profiling on this.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode haskell code-with-copy"><code class="sourceCode haskell"><span id="cb3-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">data</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Implication</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Var</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">String</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Neg</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">deriving</span> (<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Eq</span>,<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Show</span>)</span>
<span id="cb3-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">data</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">ExprSet</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">ExprSet</span> [<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span>] [<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span>] [<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Expr</span>] <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">deriving</span> (<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Eq</span>,<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Show</span>)</span>
<span id="cb3-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">data</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">ExprSet</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">ExprSet</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">deriving</span> (<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Eq</span>,<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Show</span>)</span></code></pre></div></div>
<p>The rest of the program involved a lot of using functions from <code>Data.Maybe</code> to put the pieces together.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode haskell code-with-copy"><code class="sourceCode haskell"><span id="cb4-1"><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">stepRight ::</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Maybe</span> [<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span>]</span>
<span id="cb4-2">stepRight s<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span>(<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span> lhs rhs) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> listToMaybe<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>mapMaybe (expandRight s) ((getComposite rhs) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">++</span> (getNeg rhs))</span></code></pre></div></div>
<p>This runs <code>expandRight</code> for all expressions on the right hand side, and returns the result first one of those that returns a <code>Just [Sequent]</code>, or <code>Nothing</code> if all of them return <code>Nothing</code>. The right hand side is the same idea.</p>
<p>Then, the same idea can be used to apply steps on the left side until there are none more to be taken, then on the right hand side. LK stands for the classical version of the sequent calculus there.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode haskell code-with-copy"><code class="sourceCode haskell"><span id="cb5-1"><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">stepLK ::</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Maybe</span> [<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span>]</span>
<span id="cb5-2">stepLK s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> listToMaybe<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>catMaybes [stepLeft s, stepRight s]</span></code></pre></div></div>
<p>Even though I start with a single sequent, a step on a sequent can result in more than one. We need to apply <code>stepLK</code> to all sequents in a list until it returns <code>Nothing</code> for all of them. To do so a function <code>steps</code> is defined that returns either the derived list of Sequents after taking a step, or <code>Nothing</code> if no steps can be taken any more.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode haskell code-with-copy"><code class="sourceCode haskell"><span id="cb6-1"><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">getFirst ::</span> (<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Maybe</span> a, a) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> a</span>
<span id="cb6-2">getFirst ((<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Just</span> x), _) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> x</span>
<span id="cb6-3">getFirst (_, y) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> y</span>
<span id="cb6-4"></span>
<span id="cb6-5"><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">steps ::</span> [<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span>] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Maybe</span> [<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span>]</span>
<span id="cb6-6">steps xs <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span> (isNothing <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fst</span>) nextIter <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">then</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Nothing</span></span>
<span id="cb6-7">                                             <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Just</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>concat<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>map getFirst nextIter </span>
<span id="cb6-8">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">where</span> nextIter <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span> (\x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> (stepLK x, [x])) xs</span></code></pre></div></div>
<p>Then, to bring this to the logical conclusion, this function is applied until it returns <code>Nothing</code>, and then it is checked whether all sequents in the call before that were axioms.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode haskell code-with-copy"><code class="sourceCode haskell"><span id="cb7-1"><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">iterToNothing ::</span> (a <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Maybe</span> a) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> a <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> a</span>
<span id="cb7-2">iterToNothing fn x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">case</span> fn x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">of</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Nothing</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> x</span>
<span id="cb7-3">                                  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Just</span> y  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> iterToNothing fn y</span>
<span id="cb7-4"></span>
<span id="cb7-5"><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">solve ::</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Sequent</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Bool</span></span>
<span id="cb7-6">solve s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span> isAxiom<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span> iterToNothing steps [s]</span></code></pre></div></div>
<p>Turning this into a solver for LJ (the intuitionistic version of the calculus) is fairly easy at this point. The rules operating on the negation on the left side have to be guarded by a condition that the right hand side be empty, and the <code>stepsLK</code> function has to be changed to drop the right hand side if there are no more steps for a sequent but it is not an axiom yet. In the implementation this leads to two functions being different between the LK and LJ cases, but I have yet to find a way to properly select which of the two to use at runtime: plumbing the functions through the computation by passing them as arguments does not seem the nicest way.</p>



 ]]></description>
  <category>programming</category>
  <guid>https://bitsrc.org/blog/posts/theorem-proving-in-haskell.html</guid>
  <pubDate>Wed, 02 Dec 2015 08:00:00 GMT</pubDate>
</item>
<item>
  <title>A Paper a Week-ish #13: Propositions as Types</title>
  <link>https://bitsrc.org/blog/posts/a-paper-a-week-propositions-as-types.html</link>
  <description><![CDATA[ 




<p>Even though week-ish is an intentionally vague concept, I should apologize for this week-ish to take particularly long. The last month has been very busy and exhausting for me, so even though I read a paper, I never got to finish this post until now.</p>
<p>This paper presents no original insights, but is a very readable introduction into the Curry-Howard isomorphism and concepts related to it. It does not go into the complex technicalities but manages to convey a general intuition and interesting historical context. The appendix of the online edition (the edition I read) also includes an insightful correspondence between the author (Philip Wadler) and Howard about the various people involved in its history.</p>
<p>It introduces the concept in three simple statements.</p>
<ul>
<li><p><em>propositions</em> as <em>types</em></p></li>
<li><p><em>proofs</em> as <em>programs</em></p></li>
<li><p><em>simplification of proofs</em> as <em>evaluation of programs</em></p></li>
</ul>
<p>What does this mean? This means that there is a bijection between proofs in a formal proof system and programs in a formal system of computation, where propositions in the proof correspond to types in the program.</p>
<p>This is a very general statement, and the paper in question shows it for one particular pair of formal proof system and formal system of computation, in particular natural deduction for intuitionistic logic and singly typed lambda calculus. It then notes that it indeed holds in various other cases, the list of which I will not enumerate here.</p>
<p>If one thinks about the Brouwer–Heyting–Kolmogorov interpretation of intuitionistic logic, which is also introduced in the paper, this correspondence becomes intuitively plausible. The BHK interpretation defines the logical connectives by the existence of procedures to turn proofs of a proposition into another proof.</p>
<p>For example, a proposition <img src="https://latex.codecogs.com/png.latex?A%20%5Crightarrow%20B"> holds if there is a procedure that turns proofs of <img src="https://latex.codecogs.com/png.latex?A"> into proofs of <img src="https://latex.codecogs.com/png.latex?B">. So if we look at a bijection between propositions and types, this means that there is a procedure that turns an object of type <img src="https://latex.codecogs.com/png.latex?A"> into one of type <img src="https://latex.codecogs.com/png.latex?B">. Also other propositions are expressed as objects in the BHK interpretation. For example, <img src="https://latex.codecogs.com/png.latex?A%20%5Cland%20B"> holds if there is a tuple <img src="https://latex.codecogs.com/png.latex?%5Clangle%20a,%20b%20%5Crangle">, where <img src="https://latex.codecogs.com/png.latex?a"> is a proof for <img src="https://latex.codecogs.com/png.latex?A"> and <img src="https://latex.codecogs.com/png.latex?b"> is a proof of <img src="https://latex.codecogs.com/png.latex?B">, so it can be seen as a tuple. <img src="https://latex.codecogs.com/png.latex?A%20%5Clor%20B"> can similarly be seen as the option type for an object that is either of type <img src="https://latex.codecogs.com/png.latex?A"> or <img src="https://latex.codecogs.com/png.latex?B">.</p>
<p>The paper does a much better job of explaining this all in a bit more detail than I ever could in the course of a blogpost here, so I will not attempt to, but I hope this will bring across the very basic idea behind the concepts.</p>
<p>I also recommend browsing the titles in the reference section if you are interested in the content provided by this paper, I have highlighted [23], [33], [40], [42], [54], [56] and [59] (which does not mean the other ones are worse, just that they did not immediately catch my eye) for further study (probably I will only get to the papers, not the textbooks).</p>
<p>Find the paper here: <a href="http://homepages.inf.ed.ac.uk/wadler/papers/propositions-as-types/propositions-as-types.pdf">Propositions as Types</a>.</p>



 ]]></description>
  <category>apaw</category>
  <guid>https://bitsrc.org/blog/posts/a-paper-a-week-propositions-as-types.html</guid>
  <pubDate>Fri, 09 Oct 2015 07:00:00 GMT</pubDate>
</item>
<item>
  <title>A Paper a Week-ish #12: Arithmetical Hierarchy and Complexity of Computation</title>
  <link>https://bitsrc.org/blog/posts/a-paper-a-week-arithmetical-hierarchy-and-complexity-of-computation.html</link>
  <description><![CDATA[ 




<p>The paper in question covers something that I have been meaning to read up for months: the arithmetical hierarchy, which was sadly not covered in the university courses I have attended. If you are into theoretical computer science, you might have come across things like <img src="https://latex.codecogs.com/png.latex?%5CSigma_2%5E0"> or <img src="https://latex.codecogs.com/png.latex?%5CPi_1%5E0">; I have, and while I knew that they had <em>something</em> to do with the arithmetical hierarchy (which I did not know what exactly it was, either), I never got around to read up on what exactly they mean. In particular, this paper examines where sets that make interesting statements about computability theory fit into the arithmetical hierarchy.</p>
<p>From all I can tell, the paper does a very unfortunate mistake when defining the meaning of the two concepts, as it wrongly gives the same definition for both of them. The paper defines a set <img src="https://latex.codecogs.com/png.latex?A"> of natural numbers being in <em>both</em> <img src="https://latex.codecogs.com/png.latex?%5CSigma_n%5E0"> and <img src="https://latex.codecogs.com/png.latex?%5CPi_n%5E0"> as <img src="https://latex.codecogs.com/png.latex?i%20%5Cin%20A%20%5CLeftrightarrow%20%5Cforall%20k_1%20%5Cexists%20k_2%20%5Cldots%20R(i,%20k_1,%20k_2,%20%5Cldots)">, where <img src="https://latex.codecogs.com/png.latex?R"> is a computable predicate (otherwise every set would be in <img src="https://latex.codecogs.com/png.latex?%5CSigma_0%5E0"> because every set is representable by a predicate, albeit not by a computable one). Of course, this does not make any sense, and <a href="https://en.wikipedia.org/wiki/Arithmetical_hierarchy#The_arithmetical_hierarchy_of_formulas">Wikipedia</a> offers a much more believable definition thereof: “Also, a <img src="https://latex.codecogs.com/png.latex?%5CSigma%5E0_n"> formula is equivalent to a formula that begins with some existential quantifiers and alternates <img src="https://latex.codecogs.com/png.latex?n-1"> times between series of existential and universal quantifiers; while a <img src="https://latex.codecogs.com/png.latex?%5CPi%5E0_n"> formula is equivalent to a formula that begins with some universal quantifiers and alternates similarly.” In this context formula and set is more or less interchangeable, as a formula describes the set of values that satisfy it.</p>
<p>After clearing up this slight confusion, it also becomes possible to understand the rest of the paper. It defines the concept of a <img src="https://latex.codecogs.com/png.latex?%5CSigma_n%5E0">-complete and <img src="https://latex.codecogs.com/png.latex?%5CPi_n%5E0">-complete set as being a set that all sets of the respective class can be reduced to and that is in that class. Let, for example, <img src="https://latex.codecogs.com/png.latex?B"> be <img src="https://latex.codecogs.com/png.latex?%5CSigma_2%5E0">-complete, then for every set <img src="https://latex.codecogs.com/png.latex?A%20%5Cin%20%5CSigma_2%5E0"> there is a computable function <img src="https://latex.codecogs.com/png.latex?f"> such that <img src="https://latex.codecogs.com/png.latex?i%20%5Cin%20A%20%5CLeftrightarrow%20f(i)%20%5Cin%20B">.</p>
<p>A few complete sets are given (without proof). I will pick out the example of <img src="https://latex.codecogs.com/png.latex?K%20=%20%5C%7Bi:%200%5Ei%20%5Cin%20W_i%20%5C%7D"> where <img src="https://latex.codecogs.com/png.latex?W_i"> is defined in this paper as the set of words for which the Turing machine of index <img src="https://latex.codecogs.com/png.latex?i"> halts. For those unfamiliar with the theory of computation this may be odd, but as every Turing machine can be described by finite string over a finite alphabet, there is a way to enumerate the Turing machines, that is, assign an index to each of them.</p>
<p>It took some time wrapping my head around why this set is <img src="https://latex.codecogs.com/png.latex?%5CSigma_1%5E0">, but essentially it boils down to the fact that it can be expressed by <img src="https://latex.codecogs.com/png.latex?i%20%5Cin%20K%20%5CLeftrightarrow%20%5Cexists%20z%5C;%20Halts_i(0%5Ei,%20z)"> where <img src="https://latex.codecogs.com/png.latex?z"> expresses (the Gödel number of) a trace of a computation of <img src="https://latex.codecogs.com/png.latex?M_i"> and <img src="https://latex.codecogs.com/png.latex?Halts_i(j,%20z)"> is a predicate that is true iff <img src="https://latex.codecogs.com/png.latex?z"> is a trace of a halting computation of <img src="https://latex.codecogs.com/png.latex?M_i"> on input <img src="https://latex.codecogs.com/png.latex?j">; without fancy terms the formula means: an <img src="https://latex.codecogs.com/png.latex?i"> is in <img src="https://latex.codecogs.com/png.latex?K"> if and only if there exists an execution trace of <img src="https://latex.codecogs.com/png.latex?M_i"> that halts on the input <img src="https://latex.codecogs.com/png.latex?0%5Ei">. Well, less fancy terms, I guess.</p>
<p>If you know about computability theory you see I hand-waved a few things. For instance, I just assumed that <img src="https://latex.codecogs.com/png.latex?Halts"> is a computable predicate, but it is not hard to imagine that checking whether a trace of a computation on a Turing machine on an input actually is a halting computation is indeed computable (you check whether the last state is a halting state and then check whether all steps of the trace are allowed in the Turing machine). It is also important to note that the restriction to computable predicates is needed for the definition to make any sense, this is because if non-computable predicates are allowed, every set <img src="https://latex.codecogs.com/png.latex?A"> would trivially be expressible using zero quantifiers by a predicate <img src="https://latex.codecogs.com/png.latex?P(e)%20%5CLeftrightarrow%20e%20%5Cin%20A">.</p>
<p>The paper then shows that the set of (indices of) Turing machines that work in time <img src="https://latex.codecogs.com/png.latex?n%20+%201"> relative to the size of their input is <img src="https://latex.codecogs.com/png.latex?%5CPi_1%5E0">-complete. They first show that the set is in <img src="https://latex.codecogs.com/png.latex?%5CPi_1%5E0"> by showing a formula that represents it. It might be confusing to the reader that their formula is <img src="https://latex.codecogs.com/png.latex?%5Cforall%20n,%20x,%20z%5C;%20(%E2%80%A6)">. At first look one might think “I thought <img src="https://latex.codecogs.com/png.latex?%5CPi_1%5E0"> meant there is one <img src="https://latex.codecogs.com/png.latex?%5Cforall">”. This is a technicality that is not elaborated on in this paper: the universe is assumed to be integers, which are countable. This allows to encode n-tuples as a single integer in various way (e.g.&nbsp;using powers of prime numbers), which are then “decomposed” again by the predicates. The proof that it is complete is done by reducing a set already known to be complete to it (I will omit details to not completely blow the scope of this post).</p>
<p>After this it is also proven that the set of Turing machines that work in polynomial time is <img src="https://latex.codecogs.com/png.latex?%5CSigma_2%5E0">-complete, the details of which I also refer to the paper. The main idea of the proof is again to prove that it is in <img src="https://latex.codecogs.com/png.latex?%5CSigma_2%5E0"> by showing a formula that expresses it and then reduce an already known to be complete set to it.</p>
<p>There are more proofs about properties of Turing machines and their place in the arithmetic hierarchy which I will not elaborate on in the interest of brevity, if you are interested in this sort of stuff I recommend reading the whole paper. One of them sadly references another paper which is behind a paywall, so it might be hard to really grasp what is going on (one has to trust the statement asserted with a reference to that paper is true).</p>
<p>Anyway, the second section of the paper shows corollaries that can be deduced from the previously proved statements about the arithmetical hierarchy. For example, that there is a Turing machine that works in time <img src="https://latex.codecogs.com/png.latex?n%20+%201"> but cannot be proved to. This is simply because Turing machines that provably do so can be enumerated by definition – proofs are finite strings over finite alphabets, hence can be enumerated. The set of Turing machines that have the property has previously been proven to be <img src="https://latex.codecogs.com/png.latex?%5CPi_1%5E0">-complete, which cannot be enumerated. This is, intuitively, because infinitely many elements have to be checked before giving an answer to the <img src="https://latex.codecogs.com/png.latex?%5Cforall">.</p>
<p>I will not enumerate the rest of the proofs and corollaries, so take a look at the paper if this incited interest.</p>
<p>Link to the paper: <a href="http://ac.els-cdn.com/030439757990046X/1-s2.0-030439757990046X-main.pdf?_tid=8d461df0-3af7-11e5-b190-00000aab0f26&amp;acdnat=1438727240_e94cac9c850a1694b487f1d244982147">Arithmetical Hierarchy and Complexity of Computation</a>.</p>



 ]]></description>
  <category>apaw</category>
  <guid>https://bitsrc.org/blog/posts/a-paper-a-week-arithmetical-hierarchy-and-complexity-of-computation.html</guid>
  <pubDate>Wed, 19 Aug 2015 07:00:00 GMT</pubDate>
</item>
<item>
  <title>A Paper a Week-ish #11: Brewer’s Conjecture and the Feasibility of Consistent, Available, Partition-Tolerant Web Services</title>
  <link>https://bitsrc.org/blog/posts/a-paper-a-week-brewers-conjecture.html</link>
  <description><![CDATA[ 




<p>This paper was more discovered than chosen. I decided to write this week-ish’s post sitting in a train without Internet connection, so I scanned my Download folder for the random papers I have accumulated over the months. I discovered this paper, which seemed interesting and brief enough so I could finish reading it on the train.</p>
<p>It is, as is fairly obvious, about Brewer’s conjecture. To be honest, I have never actually heard of this before (and I might just have mistaken it for Brouwer, the logician, back when I downloaded this paper, but I guess I will never know). It seems to state the fact that it is impossible to achieve consistency, availability and partition-tolerance at the same time.</p>
<p>The first section of this paper talks about these properties in a fully asynchronous system – that is a system where every agent must function only based on the messages it has received. Most statements made are fairly self-evident. The main theorem of this part states that if the network is partitioned into two or more parts, a write made in one of them will not be reflected in reads in others’. This isn’t a very deep observation, in my opinion, as the side condition that every request be served eventually is obviously inconsistent with partition-resistant consistency. It cannot even be both available and consistent even in the case where all messages are delivered, because a node has no way of delaying the response to the client until a point where it knows it would have received all messages preceding the request by the client.</p>
<p>The second section is a bit more interesting. It analyzes these properties in a what it calls partially synchronous network. These are networks in which every node has a clock running at the same rate and there are bounds on network latency – mind the difference to systems having the absolute result of clocks synchronized to some degree, like TrueTime used in Google’s Spanner. I am sure a physicist would tell me that having two clocks run at exactly the same rate is technically impossible, but we can probably get close enough for practical purposes (and this is a <em>model</em> anyway).</p>
<p>Anyway, in these networks the main theorem of the previous section obviously still holds. Even such a probably-physically-impossible system is incapable of magically bridging arbitrarily long network partitions in finite time. However, the variant where all messages are delivered does not hold, because assuming a central node that manages the system, a node can always serve a request by waiting for the appropriate amount of time before returning because there are bounds on the network latency (of course in practice there is not much point in having a distributed data-base managed completely by a central node).</p>
<p>A weaker form of consistency is then proposed, which is based on consistency while all messages are delivered, and a bound on re-convergence time after a interval in which not all messages have been delivered. This notion is formalized and then an algorithm that achieves this is shown.</p>
<p>Find the paper here: <a href="https://github.com/papers-we-love/papers-we-love/blob/master/distributed_systems/brewers-conjecture.pdf">Brewers Conjecture paper</a>.</p>



 ]]></description>
  <category>apaw</category>
  <guid>https://bitsrc.org/blog/posts/a-paper-a-week-brewers-conjecture.html</guid>
  <pubDate>Sun, 19 Jul 2015 07:00:00 GMT</pubDate>
</item>
<item>
  <title>A Paper a Week-ish #10: In Search of an Understandable Consensus Algorithm</title>
  <link>https://bitsrc.org/blog/posts/a-paper-a-week-understandable-consensus.html</link>
  <description><![CDATA[ 




<p>I have been meaning to read this paper for quite some time, but for some reason, even though its entire point is proposing an <em>understandable</em> consensus algorithm, Paxos’ (the canonical consensus algorithm previous to this paper) reputation for being impossible to understand kept me from reading this paper whenever I was short on time – that is to say always. Probably I was assuming that an “understandable” replacement for an impossible-to-understand is still very hard to grasp and I would not have time to properly digest it. Thankfully, I could not have been wronger.</p>
<p>Raft, the algorithm proposed in the paper, is a solution to the replicated state machine problem. The basic premise thereof is a cluster of computers running independently but working together in what appears to be a single consistent state machine. Without auxiliary conditions, this is a quite simple goal to achieve: one could simply choose one of these computers to actually do the work and leave the rest idle. Of course this is not the point of the exercise, so we want the state machine to be available as long as the majority of these computers is still up, while still giving only correct result. The paper refers to these properties as <em>availability</em> and <em>safety</em>, respectively.</p>
<p>The problem is simplified vastly by requiring that one of these computers is master at any given time, and clients only talking to this master. This is achieved by a fairly simple protocol where, upon detecting the current master has failed, a server initiates an election by talking to all other servers, asking them to vote for it. Other servers will vote only for other servers that are more up-to-date. If more than half of the servers vote for it, it becomes the new master. The protocol also shows that simplicity was the main design goal of Raft: to prevent servers from competing for the vote, which may lead to elections that need to be repeated for lack of winner, the server simply waits for a random time before calling the election, which makes it unlikely that two or more servers do so at the same time.</p>
<p>This server is then responsible for dealing with users requests. If a user wants to update the state, this change is written into the so-called log of the master and replicated onto the other servers called followers. Under normal operation, it will be considered to be committed and persistently in the system when it is written to more than half of the cluster (some caveats apply). Any data that was committed will be available as long as more than half the servers are up at any given point. The master always makes sure that when writing an entry on another server, the entry immediately before the one written matches the one in its logs. By induction, this means the follower’s log is complete up to the newly written entry.</p>
<p>If any of the servers except the master fails, nothing interesting happens. The master will just no longer be able to talk to it, it will no longer write data, but updates will be resent in case it comes back. Simple failover on master failure is equally straightforward. The master dies, the remaining servers elect a new master that has the same state as the previous master (because, remember that the updates are replicated to more than half of the servers). This new master takes the place of the old one, and nothing particularly interesting happens either.</p>
<p>Of course, no one would care if the paper was simply about trivial failover. The interesting case arises, of course, due to more complicated series of master failures. But because of the simplicity of the algorithm this is, in fact, not much harder to understand than the trivial cases above. In this blog-post I have hand-waved “more up to date“ and “committed” a bit earlier, these two concepts are important to understand the general case. All log entries are identified by two integers: the term (the term increases every time the mastership changes), and a sequence number within that term. A server can only win the mastership election if either its term is higher than more than half of the others, or it is in the same term but has a longer (or equally long) log in it. This makes sure that the elected master always has a complete log of committed entries. An entry is committed only after the current master has written a log-entry in its term to ensure that more than half of the followers catch up with the master.</p>
<p>Find the paper here: <a href="https://ramcloud.stanford.edu/raft.pdf">Raft Algorithm Paper</a>.</p>



 ]]></description>
  <category>apaw</category>
  <guid>https://bitsrc.org/blog/posts/a-paper-a-week-understandable-consensus.html</guid>
  <pubDate>Mon, 06 Jul 2015 07:00:00 GMT</pubDate>
</item>
<item>
  <title>A Paper a Week-ish #9: Two Simplified Algorithms for Maintaining Order in a List</title>
  <link>https://bitsrc.org/blog/posts/a-paper-a-week-algorithms-for-maintaining-order-in-a-list.html</link>
  <description><![CDATA[ 




<p>Looking around for papers to cover in this series, I remember a <a href="https://www.youtube.com/watch?v=WlO80TOMK7Y&amp;feature=youtu.be">talk</a> about folding algorithms one <a href="http://erikdemaine.org">Erik Demaine</a> gave at my former university as the annual Vienna Gödel Lecture, where once a year major contributors to the field of computer science (other guest lecturers were Don Knuth and Peter Norvig) are invited to give a talk about their work. I skimmed through his very impressively long <a href="http://erikdemaine.org/papers/">list of papers</a> and this one caught my eye. If you have a bit of time on your hands and are interested in algorithms (he seems to specialise a lot in folding and puzzles), I recommend you do the same.</p>
<p>Anyway, I picked this paper more or less at random from the seemingly endless list, and it, as the title says, proposes two algorithms for maintaining order in a list. As is usual, the first part of the paper is dedicated to giving a general introduction into the problem, its history and the solutions that have previously been proposed to solve it. Then, they justify the first of their two algorithms which, even though it does not offer theoretical improvements (i.e.&nbsp;lower complexity bounds – which is impossible considering that the best solution has <img src="https://latex.codecogs.com/png.latex?O(1)"> worst-time on all operations), has two characteristics that make it useful: their analysis is easier to follow, and their practical experiments suggest that its real-world performance is superior. In fact the theoretic performance is arguably worse: the proposed data structure has <img src="https://latex.codecogs.com/png.latex?O(1)"> <em>amortised</em> time complexity, while the best known one has <img src="https://latex.codecogs.com/png.latex?O(1)"> <em>worst-case</em>. Anyway, as is sometimes the case, there are cases where the theoretically worse data-structure has better real-world performance; as computers always work with finite data, asymptotic performance is sometimes an oversimplification.</p>
<p>The first algorithm is a solution to the Order-Maintenance Problem, which has “the objective … to maintain a total order subject to insertions, deletions and precedence queries”. It does that by assigning tags to elements such that the order of the tags corresponds to the order of the elements. Then, the analysis proceeds on the virtual trie that can be obtained using the binary expansion of the tags. Roughly the algorithm makes sure that the density (that is, the number of “occupied” tags per available tag) does not exceed a threshold for every node in the implicit trie. The analysis is a bit handwavey at times, for instance it states that “Thus, we pick a u [comment: maximum tag] that works for any value from n/2 to 2n. If at any point we have too few or too many list elements, we rebuild the data structure for the new value of n.&nbsp;This rebuilding introduces only a constant amortized overhead.” I can see this statement being true in analogy to how amortized analysis of dynamic arrays works (that is, always doubling the size of the array when it is full results in amortized <img src="https://latex.codecogs.com/png.latex?O(1)">), but it is not immediately obvious that the statement is true, because there could be subtle differences.</p>
<p>An important detail of the complexity analysis is that it does not do any assumption about which tag is chosen for a newly inserted element. If there are multiple tags free between the elements <img src="https://latex.codecogs.com/png.latex?e"> and <img src="https://latex.codecogs.com/png.latex?f"> adjacent to the newly inserted one, one would assume that it is best to chose the new tag such that it is as far from both as possible. This not being represented in the theoretical analysis could be a sign that the bound is simply not tight enough (i.e., that one could achieve a better bound by considering this), but their experimental evaluation suggests otherwise. It seems to make no difference where the new element is inserted, in their own words “Consecutive inserts trigger relabels after every insert, but the number of elements relabeled is small. … average inserts have fewer triggers, and the number of elements relabeled is larger.”</p>
<p>The second algorithm is a solution to the File-Maintenance Problem, which is similar to the Order-Maintenance Problem but also requires that it is possible to traverse the elements in order. The solution keeps the elements in order in an array. Again, the algorithm works on an implicit tree where <img src="https://latex.codecogs.com/png.latex?a%20%5Clog%20n"> elements of the array are bundled into one leaf node, for some <img src="https://latex.codecogs.com/png.latex?a">. The algorithm then makes sure that two invariants are preserved, such that there is always space to insert a new item. Firstly, adjacent intervals (on every level of the implicit tree) must only differ by a certain amount. Secondly, every interval (on every level of the implicit tree) must have sufficient space to accommodate new items. The algorithms that make sure this is the case are too sophisticated to be covered in this summary, so consult the full paper for these details.</p>
<p>Find the <a href="http://erikdemaine.org/papers/DietzSleator_ESA2002/paper.pdf">paper here</a>.</p>



 ]]></description>
  <category>apaw</category>
  <guid>https://bitsrc.org/blog/posts/a-paper-a-week-algorithms-for-maintaining-order-in-a-list.html</guid>
  <pubDate>Tue, 16 Jun 2015 07:00:00 GMT</pubDate>
</item>
<item>
  <title>A Paper a Week-ish #8: Reflections on Trusting Trust</title>
  <link>https://bitsrc.org/blog/posts/a-paper-a-week-reflections-on-trusting-trust.html</link>
  <description><![CDATA[ 




<p>So, I feel like cheating a bit again as this paper is only three pages long, but I guess it <em>is</em> an ACM Turing Award lecture paper, so it deserves a spot here, at least for historical significance. Also, the paper is written by the highly influential (well – which goes without saying considering the Turing Award) Ken Thompson.</p>
<p>In the introduction he argues that while people may expect him to talk about UNIX, because this is what he is most famous for, he will not because he feels that he is getting undeserved credit for the work of a multitude of people where for his contributions luck and fortunate timing played as much part as skill. He also promises to show the “cutest program” he has written, but I am not sure how that is followed up on in the paper.</p>
<p>It talks about self-printing programs before concerning itself with self-hosting compilers, that is, compilers for a language that are written in that same language, for instance a C compiler written in C. This reminded me a bit of assembling an IKEA desk yesterday that required a table for assembly, so you have the same chicken-and-egg problem. The solution, of course, is relatively straightforward and consists of writing an initial version of the compiler in another language (or getting an table that is not this IKEA desk – or indeed in this case not following the instructions, but that is irrelevant to a discussion about computers), and then using existing binaries of the compiler to compile subsequent versions.</p>
<p>The example he shows is a bit more interesting. He considers a high-level idealized section of C compiler that treats string escape sequences, basically as a sequence of ifs like</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode c code-with-copy"><code class="sourceCode c"><span id="cb1-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>c <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">'n'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-3"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>This is interesting for itself, as once again this is a self-reference that expects this to be compiled by a thing that already understands what <code>'\n'</code> means. Now consider the case when you want to add a new escape sequence that is not available in your current compiler. Obviously the above will fail, as your compiler will complain that it does not know what to do with <code>'\n'</code>. However, what you can do is add the following to the compiler, creating a version that understands the meaning of <code>'\n'</code>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode c code-with-copy"><code class="sourceCode c"><span id="cb2-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">(</span>c <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">'n'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">)</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// 10 is the ASCII code for \n.</span></span>
<span id="cb2-3"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>You can now, in any subsequent version of the compiler that is compiled by this (or a newer one), refer to <code>'\n'</code> instead of 10. He claims that ‘It is as close to a “learning” program as I have seen’, which I would take with a grain of salt (especially honouring the fact that this paper was written in the 70s) considering recent advances in machine learning, whereas this is more of a matter of where a particular piece of data was introduced (the compiler, the compiler’s compiler, …) than anything that has genuinely to do with learning – the fact that it should return 10 for <code>c == 'n'</code> is in the compiler’s binary, either way.</p>
<p>Then he, as is quite obvious, applies these ideas to information security. How, in face of this ridiculous matryoshka doll situation, can one be sure what a program does – in particular, that it does not do anything malicious? The only way would be to go up the chain of compilers until the root, which does not appear tractable. He suggests the alternative is trusting the people that wrote the program, thus the title of the paper (as the trust, indeed, has to be recursive – you implicitly trust the compiler that was used to compile your compiler).</p>
<p>He then ends with a few political comments about persecution of “hackers” and the two-facedness of considering them wiz kids and criminals at the same time, which sadly still seem current now over 40 years later.</p>
<p>Find the paper <a href="https://www.ece.cmu.edu/~ganger/712.fall02/papers/p761-thompson.pdf">here</a>.</p>



 ]]></description>
  <category>apaw</category>
  <guid>https://bitsrc.org/blog/posts/a-paper-a-week-reflections-on-trusting-trust.html</guid>
  <pubDate>Sun, 24 May 2015 07:00:00 GMT</pubDate>
</item>
<item>
  <title>A Paper a Week-ish #7: The Complexity of Theorem-Proving Procedures</title>
  <link>https://bitsrc.org/blog/posts/a-paper-a-week-complexity-of-theorem-proving.html</link>
  <description><![CDATA[ 




<p>First of all, sorry for the delay! I have moved this weekend (with a few complications) and am currently without Internet at home, and Three are actively trying to prevent me tethering from my phone (and I don’t want to violate the contract).</p>
<p>This is actually, for computer science, a fairly old paper, written by no less than Stephen Cook, about whom you might have heard, for instance regarding the Cook(–Levin) theorem, which in fact is closely related to the content of this paper. Essentially, Cook’s theorem states that the propositional case of satisfiability is NP-complete.</p>
<p>For those not familiar with complexity theory (very roughly the theory for determining the relative hardness in terms of computational effort of different problems), NP-complete problems are those that are mostly believed to be hard to solve (that is, there exists no polynomial algorithm), but no proof exists for that statement. Solving – as in coming up with an algorithm of polynomial running time, one would immediately solve the whole class. This is due to the observation that is also expressed in the paper that there exist polynomial reductions between the problems (a reduction is a transformation of an instance of one problem into an instance of another, whereby one can solve the initial problem).</p>
<p>The first half of the paper talks about the complexity of theorem proving in the propositional case, which is essentially the same as satisfiability in classical logic (something is a tautology iff its negation is unsatisfiable)</p>
<p>The second half of the paper concerns itself with the complexity of theorem-proving first-order (i.e.&nbsp;predicate) logic and presents lesser known ideas. It is generally known that theorem proving is undecidable, that is, there is no algorithm that can proof all valid theorems of first-order logic. Thus, the definition of complexity is a bit more evolved than in the propositional case. How can one analyze an algorithm that can possibly go on forever without halting? Cook essentially proposed setting an order on the Herbrand instances (essentially instantiating every function and predicate in every possible way) to analyze the complexity relative to the highest index of the instances used in a proof (this is a bit of a handwavey explanation). He presents two bounds on this measure.</p>
<p>Find the paper <a href="http://www.chell.co.uk/media/product/_master/1/files/cook_complexity_of_theorem_proving_procedures_19711.pdf">here</a> (actually, this is a re-typeset version, because the <a href="https://www.cs.toronto.edu/~sacook/homepage/1971.pdf">original one</a> was written on a typewriter and this is, in my opinion, nicer to read).</p>



 ]]></description>
  <category>apaw</category>
  <guid>https://bitsrc.org/blog/posts/a-paper-a-week-complexity-of-theorem-proving.html</guid>
  <pubDate>Thu, 07 May 2015 07:00:00 GMT</pubDate>
</item>
</channel>
</rss>
