Interpreting brainfuck in C

Esoteric programming languages come in an astonishing magnitude of variety — golfing languages, Turing tarpits, obfuscation languages, one-time joke languages and plenty more. However, among all of them brainfuck is by far one of the most intriguing to me — an elegant combination of syntactic brevity, apparent lack of functionality and the theorectical might of a Turing machine.
Combined with its seemingly trivially realizable implementation, I have implemented brainfuck in Python 2, a brainfuck flavour in Python 2, and even written an interpreter in DrRacket.
However, like Cristofani writes in their The Epistle to the Implementors, writing a satisfactory brainfuck interpreter is no easy task.
Therefore I have designed another brainfuck command-line interpreter, written in pure C (brainfuck.c).

Key features of this implementation are a large tape size, source code pre-processing — instruction condensing and loop matching –, apt command-line flags and C execution speed.
For further detail on the interpreter’s usage, compile the interpreter (e.g. gcc -O2 brainfuck.c -o brainfuck) and run ./brainfuck -h.

To better demonstrate brainfuck’s true power, I wrote a non-Kolmogorov-complexity program; a palindrome tester.

[ A palindrome tester written in brainfuck. ]
[ Jonathan Frech, 21st of August 2018.      ]
[ Tape layout: (STR ... STR NUL FLG ACC)    ]

,[>,]             read in STR
>+                set FLG to true
<<<[              while STR is of length at least two
 [<]>             go to the first byte
 [[>]>>+<<<[<]>-] transfer first byte to ACC
 >[>]<            go to last byte
 [->>>-<<<]       subtract last byte from ACC
 >>>[             if ACC is not zero
  <[-]            set FLG to false
  >-]             clear ACC
 <[<+>-]          move FLG over
 <<<<             go to last byte
]>>>.             output FLG
% echo ",[>,]>+<<<[[<]>[[>]>>+<<<[<]>-]>[>]<[->>>-<<<\]>>>[<[-]>-]<[<+>-]<<<<]>>>.\!existence" > palindrome.b
% ./brainfuck -x palindrome.b
00000000: 00                                       .               

% echo ",[>,]>+<<<[[<]>[[>]>>+<<<[<]>-]>[>]<[->>>-<<<\]>>>[<[-]>-]<[<+>-]<<<<]>>>.\!hubbibbuh" > palindrome.b
% ./brainfuck -x palindrome.b
00000000: 01                                       .
Advertisements

Brainfuck X

While browsing StackExchange PCG questions and answers, I came across a challenge regarding drawing the swiss flag. In particular, I was interested in benzene’s answer, in which they showcased a Brainfuck dialect capable of creating two-dimensional 24-bit color images. In this post I present this dialect with slight changes of my own, as well as an interpreter I wrote in Python 2.7 (source code is listed below and can also be downloaded).

Brainfuck X generated Swiss flagUrban Müller’s original Brainfuck (my vanilla Brainfuck post can be found here) works similar to a Turing machine, in that the memory consists of a theoretically infinitely large tape with individual cells which can be modified. What allows Brainfuck X (or Braindraw, as benzene called their dialect) to create color images is, that instead of a one-dimensional tape, a three-dimensional tape is used. This tape extends infinitely in two spacial dimensions and has three color planes. Each cell’s value is limited to a byte (an integer value from 0 to 255) which results in a 24-bit color depth.

Adding to Brainfucks eight commands (+-<>[].,), there are two characters to move up and down the tape (^v) and one character to move forwards in the color dimension (*). Starting on the red color plane, continuing with the green and ending in the blue. After the blue color plane, the color planes cycle and the red color plane is selected. benzene’s original language design which I altered slightly had three characters (rgb) to directly select a color plane. Whilst this version is supported by my interpreter (the flag --colorletters is necessary for that functionality), I find my color star more Brainfucky — directly calling color planes by their name seems nearly readable.
Brainfuck’s vanilla eight characters still work in the same way, Brainfuck X can thereby execute any vanilla Brainfuck program. Also, there still is a plaintext output — the tape’s image is a program’s secondary output.

Having executed the final Brainfuck instruction, the interpreter prints out the tape to the terminal — using ANSI escape codes. Because of this, the color depth is truncated in the terminal view, as there are only 216 colors supported.
For the full 24-bit color depth output, I use the highly inefficient Portable Pixmap Format (.ppm) as an output image file format. To open .ppm files, I recommend using the GNU Image Manipulation Program; specifying the output file name is done via the --output flag.

The Swiss flag image above was generated by benzene’s Braindraw code (see their StackExchange answer linked to above); the resulting .ppm file was then scaled and converted using GIMP.
Interpreter command: python brainfuckx.py swiss.bfx -l -o swiss.ppm

Usage

  • Being written in pure Python, the interpreter is completely controlled via the command line. The basic usage is python brainfuckx.py <source code file>; by using certain flags the functionality can be altered.
  • --input <input string>-i <input string> specifies Brainfuck’s input and is given as a byte stream (string).
  • --simplify, -s outputs the source code’s simplified version; the source code with all unnecessary characters removed.
  • --colorstar selects the color star color plane change model which is the default.
  • --colorletters, -l selects the color letter color plane change model.
  • --silent stops the interpreter from outputting warnings, infos and the final tape.
  • --maxcycles <cycles>, -m <cycles> defines the maximum number of cycles the Brainfuck program can run; the default is one million.
  • --watch, -w allows the user to watch the program’s execution.
  • --watchdelay <delay> defines the time in seconds the interpreter sleeps between each watch frame.
  • --watchskip <N> tells the interpreter to only show every Nth cycle of the execution.
  • --output <output file name>, -o <output file name> saves the final tape as a .ppm image file.

# Python 2.7 Code; Jonathan Frech, 24th, 25th of August 2017

Continue reading

Brainfuck

Usually, programming languages are designed to be efficient, understandable and usable. Their concepts are well thought-out, giving the programmer powerful tools to create their application.
Esoteric programming languages have a slightly different aim. Instead of focusing on the product, they focus on the programmer’s journey and try new approaches to building a program.
One well-known esoteric programming language is Urban Müller’s brainfuck. It is a Turing-complete programming language – meaning that it could with infinite memory do what a Turing machine can do –, which practices extreme minimalism. The language knows of only eight characters (“<>+-[].,”).
The language’s usage is very similar to a Turing machine. Starting the program, the pointer is at cell zero and can be moved left (“<“) or right (“>”) by one cell.
The cells’ values are all starting at 0, but can be either increased (“+”) or decreased (“-“) by one. Because the cells can only store one unsigned byte, adding one to 255 yields in 0 and subtracting one from 0 yields in 255.
Also, a loop is possible by using square brackets. An open square bracket (“[“) starts a loop and a closed square bracket (“]”) ends a loop. When the end of a loop is reached, the interpreter will jump back to its start if and only if the currently selected cell’s value is 0.
The only way to communicate with the user is to print the currently selected cell’s ASCII character to the screen (“.”) and get a user input which will be stored in the currently selected cell as its ASCII value (“,”).

Because of its minimalistic design, writing an interpreter is not particularly hard. Listed below is the Python code of my interpreter, which I used to execute my own brainfuck “Hello World.” program (118 characters).
Online interpreters include for example bf.doleczek.pl and sange.fi.

Useful Wikipedia articles include Esoteric Programming Language, Brainfuck and Turing Machine.

$ python brainfuck.py
Hello World.

# Python 2.7.7 Code
# Jonathan Frech 27th of October , 2016
#         edited  1st of November, 2016
#         edited  3rd of November, 2016
#         edited  9th of May     , 2017
#          * bug fix: '[' with current cell equaling
#            0 will jump to matching ']'
#          * bug fix: brackets now have to match

Continue reading