CS Theory - A proof that Sed is turing complete

    author Robert Kotcher
    originally posted 7-13-13
    

Motivation

For those of you unfamiliar, Sed is Unix utility for parsing text streams. I can't quite say for sure what drove me to write a proof that Sed is turing complete. Before writing this post, I had never even used Sed more than a handful of times before. I ran across the following post on the Internet http://www.catonmat.net/blog/proof-that-sed-is-turing-complete/, but wondered if there was maybe a different way to show that Sed is turing-complete. A short google search later, I was on the wikipedia page for turing completeness.

Anyway, if you'd like to skip all of the theory and go straight to the proof, you can jump right to it. Otherwise, read on! (obviously). Oh yeah, and if you just want to see something cool that you can do with Sed, go here.

Turing Machines

Ok, so I'm going to copy a line (but just one) from wikipedia: "In computability theory, a system of data-manipulation rules (such as a computer's instruction set, a programming language, or a cellular automaton) is said to be Turing complete or computationally universal if it can be used to simulate any single-taped Turing machine", i.e. it has rules, branching, and some type form of memory. In theory we have infinite memory, but it's obvious that this isn't possible in real life. Therefore, a turing machine is theoretical machine, but is the basis for modern computing.

If we could implement a turing machine with a system (without the infinite memory, of course), then we can say that our system is turing complete. We would have to devise a set of syntactic rules for manipulating memory. But there's another important concept that is important for us to indirectly know that devising such a machine is possible.

Two machines A and B are turing equivalent if A can implement B and B can implement A.

Recursive functions

It turns out there's a class of recursive functions whose elements are precisely computable by a turing-complete system, called μ-recursive functions. A μ-recursive function is similar, but more demanding than primitive-recursive functions. Let me quickly explain each of these classes of functions:
  1. Primitive-recursive functions: The set of primitive-recursive functions can defined by the following axioms:
    1. Constant function: A 0-ary (function with 0 arguments) function is primitive-recursive.
    2. Successor function: The 1-ary function S(n) computes and returns n+1. For a bit of fun, here's a successor function written in Sed:
    3. # Computes S(n), where n (decimal) is represented by a
      # string of n 1s.
      ~%echo '111' | sed -e 's/1*/&1/'
      1111
                
    4. Projection function: For 0 ≤ i ≤ n-1, projection function Pi(a0, a1, ..., an-1) returns the ith argument passed to P.

    We can build any primitive-recursive function using these axioms. The reason why implementing a primitive-recursive function is insufficient in proving that a system is turing-complete (i.e. why primitive-recursive functions aren't turing complete), is that primitive recursive functions must always halt.

    If we refer to the three axioms, this makes sense. With primitive-recursive functions, we must eventually be able to represent a function as some finite composition of these axioms, all of which are equivalent to a constant.

  2. μ-recursive functions: The set of all μ-recursive functions is a strict superset of the set of primitive recursive functions. What is the distinguishing factor, then?

    Basically, we need to be able to write a function that can compute a minimization operator. The minimization operator finds the smallest argument to a function that causes that function to return 0. Because such an argument may not exist, it requires that the system attempting to compute it have the ability to not halt, provided it has unlimited memory.

    As an aside, there is a special class of functions known as the Ackermann functions whos members are computable functions (μ-recursive) that are not primitive recursive. Here is a proof that the Ackerman functions are not primitive recursive. Maybe I'll summarize it here later.

    Proof that Sed is turing complete. A system that is capable of implementing a minimization operator is turing complete. Here is the minimization operator written using a Sed script:

          1  #!/bin/sh 
          2 
          3  echo "" | /bin/sed -nEe '
          4 
          5  # initialize registers
          6  s/$/eax1ecx/;
          7 
          8  b mu
          9 
          10 b
          11 :mu
          12   s/eax1*ecx1*/&1/
          13   /eax1ecx1*/t hallo
          14   b leave
          15 
          16 b
          17 :hallo
          18   s/eax1ecx1*/eaxecx11/
          19   b mu
          20 
          21 b
          22 :leave
          23   q;
          24 
          25 '
          
    ͸

    And that's it. Sed is turing complete. The next bit will explain what's going on here.

    It's important to understand that Sed's control flow is very different than that of your typical turing-complete language. Let me defend that statement. Labels (:label) do not explicitly return to the command following their invocation. Also, variables do not exist - we need to define our own variable space using Sed's hold buffer.

    • Line 3: I'm running sed with -E modern regex and -n explicity silencing output
    • Line 6: Sed has something called a hold buffer. This is a special piece of memory that I'm using to store register values. I used x86 naming conventions. %eax will contain return values and %ecx will increment and be passed as an argument to :hallo, the function whose output we are minimizing.
    • Line 11: :mu increments %ecx and calls :hallo if %eax ≠ 0.
    • Line 17: :hallo can do whatever we'd like - it's behavior is irrelevant to proving turing-completeness.

Fibonacci Numbers

For fun, here is a sed script that computes the nth Fibonacci number:
      1 #!/usr/bin/sed -nf
      2 #Fib in sed
      3 
      4 binit
      5 
      6 b
      7 :init
      8   h;
      9   s/\(1{0,1}\)/\1/; t base
      10   x;
      11   s/\(1*\)11$/(\1\,\11)/
      12   x;
      13   b split
      14 
      15 b
      16 :split
      17   x; s/\(1*\)11/(\1\,\11)/; t split
      18   x; 
      19   b reduce
      20   
      21 b 
      22 :base
      23 p;
      24 
      25 b
      26 :reduce
      27   x;
      28   s/\((\,1)\)/[1]/; x; t reduce
      29   s/\((1\,\))/[1]/; x; t reduce
      30   s/(\(1*\)\,\[\(1*\)\])/[\1\2]/; x; t reduce
      31   s/(\[\(1*\)\]\,\(1*\))/[\1\2]/; x; t reduce
      32   x;
      33   b total
      34   
      35 b
      36 :total
      37   x;
      38   s/\[//g
      39   s/\]//g
      40   s/(//g
      41   s/)//g
      42   s/\,//g
      43   p;
      

I figured I'd just write down what I did - at the very least for my own record.

fib(n) = fib(n-1) + fib(n-2) It's pretty famous, and a simple implementation usually involves recursion. Because labels in Sed do not return control in the same way that most languages do, I computed fib(n) using a bit of a different model.

In my model, I use a string of characters to represent a pending fibonacci calculation. In this representation:
Using this model, we can compute fib(n) in the following way:
  1. Map 1{n} to its tree representation if n ≠ 1 or n ≠ 0. Otherwise, return n. (Below are a few examples of a fibonacci tree representations)
            fib_tree("11") = "(1,)"
            fib_tree("111") = fib_tree(fib_tree("11"),"1") = "((1,),1)"
            fib_tree("1111") = fib_tree("111","11") = ...
            You get the idea
            
  2. Reduce the final fib tree by first replacing all leaves, that is (1,) (,1) with [1]. Then remove the following characters: "1{}[]". This will be fib(n)
            reduce("((1,),1)") = reduce("([1],1)" = 11
            
    1. Here's sample output from fib(5), annotated with a few comments :)
              /* Map phase */
              (11111)
              (111,1111)
              ((1,11),1111)
              (111,1111)
              ((1,(,1)),1111)
              ((1,11),1111)
              ((1,(,1)),(11,111))
              ((1,(,1)),1111)
              ((1,(,1)),((,1),111))
              ((1,(,1)),(11,111))
              ((1,(,1)),((,1),(1,11)))
              ((1,(,1)),((,1),111))
              ((1,(,1)),((,1),(1,(,1))))
              ((1,(,1)),((,1),(1,11)))
              ((1,(,1)),((,1),(1,(,1))))
      
              /* Reduce phase */
              ((1,(,1)),((,1),(1,(,1))))
              ((1,[1]),((,1),(1,(,1))))
              ((1,[1]),([1],(1,(,1))))
              ((1,[1]),([1],(1,[1])))
              ([11],([1],(1,[1])))
              ([11],([1],[11]))
              
              /* Parse out [\(\[,] */
              11111
      
              The 5th fibonacci number is 5.