Skip to content

Brainfuck

Tip

Try out brainfuck for yourself in the Brainjuice | Brainfuck System

Advent of Code is coming around again and it's something I look forward to every year, more so this year than most because it's a chance to write some code myself. Over the years I've used AoC as a chance to learn new languages; some years in Rust, one in Zig, and the last year in Elixir.

This year I'm still not 100% sure what I'm going to use but I've always been intrigued by people doing them in esolangs. The one that catches my eye most often being brainfuck.

Before I can do any challenges in brainfuck I'll need a way to run it. The main Homebrew one seems to have some bugs and I don't like the look of a lot of the online ones. I had a feeling I was going to need some decent tooling to help me out, so I decided to build my own interpreter and debugger.

brainfuck

Before looking at my interpreter or debugger, a quick overview of brainfuck will be useful.

brainfuck is a tape based language with only 8 instructions. Tape based meaning that it operates on a range of cells that store values (much like memory) but without support for random access. The tape head must move one cell at a time to each location.

The instruction set focusses on moving the tape head, incrementing values, and basic input and output. The final piece of the puzzle is the two jump instructions.

Operator Instruction
< Move the tape head one to the left
> Move the tape head one to the right
+ Increment the value at the current head by 1
- Decrement the value at the current head by 1
, Read one value from input as ASCII
. Write one value to the output as ASCII
[ Jump past the matching ] if the value at the head is 0
] Jump to the matching [ if the value at the head is not zero
# The de-facto symbol for breakpoints in many interpreters

Every other character is ignored and so implicitly can be used as comments.

Interpreter

The interpreter is written in Elixir and can be found in my AoC repo here.

I chose Elixir for two reasons:

  1. It's the language I'm enjoying most at the moment
  2. There's a bunch of features that make it really pleasant to do parsing style work

The flow of the interpreter is pretty simple.

source
|> Parser.parse() # produces %Program{}
|> Machine.new(input, opts)
|> Machine.run()

Source code is taken in and first parsed by the parser into a Program which holds instructions, their positions, and a list of jump locations to support the two jump operations. This is then passed to a Machine which additionally accepts the input to the program and any options.

The Machine is the module that is responsible for the bulk of the interpreting work, most of it a case of applying the next instruction to the current machine state and then deciding if the program has finished. At its core is the Tape module which abstracts over operations on the raw tape state.

As for options, brainfuck is not completely specified and there's a number of variants that are common in the community. The first, and currently only, option in this interpreter, is the size of each cell. In the original implementation it's 8 bit but for a lot of AoC problems this means you spend most of your time trying to fit large numbers across small cells and so the community generally uses 32 bit cells. Other common things that differ in interpreters are EOF behaviour, tape length (mine has an infinite tape), and left of start behaviour (mine considers this an error).

Parsing

Parsing produces the Program struct.

defmodule Brainjuice.Program do
defstruct ops: {}, jumps: %{}, positions: {}
end

Ops and positions are kept separately in order to map operations to their real positions in the source accounting for ignored characters. This means my debugger can accurately display the current program counter's instruction while still displaying comment characters.

Parsing itself is a fairly standard tail recursive scan but making the most out of Elixir's support for pattern matching in function heads as well as binary (string) <<>> pattern matching. This makes it very easy to see how each operation is parsed without a bunch of nesting.

defmodule Brainjuice.Parser do
# Common practice to keep state as a child for complex state
defmodule State do
defstruct op_index: 0, position: 0, open: [], ops: [], positions: [], jumps: %{}
end
def parse(source) when is_binary(source), do: do_parse(source, %State{})
# Convention for recursion is your public function and then a do_thing that contains the state
defp do_parse(<<>>, %State{open: []} = state),
do: %Brainjuice.Program{
ops: state.ops |> Enum.reverse() |> List.to_tuple(),
jumps: state.jumps,
positions: state.positions |> Enum.reverse() |> List.to_tuple()
}
...
# Here we pattern match the first byte from the binary, and retain the rest for recursion
defp do_parse(<<"+", rest::binary>>, state), do: do_parse(rest, push_op(state, :inc))
defp do_parse(<<"-", rest::binary>>, state), do: do_parse(rest, push_op(state, :dec))
...
defp push_op(%State{} = state, op) do
%State{
state
| op_index: state.op_index + 1,
position: state.position + 1,
ops: [op | state.ops],
positions: [state.position | state.positions]
}
end
end

Jumping is only slightly harder to parse. Successful parsing of jumps relies on knowing the current list of open jumps and finding the latest one to close out. If there isn't one then the source is bad. Again this makes use of pattern matching, this time pattern matching out of structs and lists.

...
# Each [ is pushed onto the stack of open jumps, along with its source position for errors
defp do_parse(<<"[", rest::binary>>, %State{} = state) do
state = %State{state | open: [{state.op_index, state.position} | state.open]}
do_parse(rest, push_op(state, :jump_if_zero))
end
defp do_parse(<<"]", _::binary>>, %State{open: [], position: position}),
do: raise(ArgumentError, "no matching [ for ] found at position #{position}")
# [head | tail] lets you pattern match the head straight out of a list
defp do_parse(<<"]", rest::binary>>, %State{open: [{start, _} | open]} = state) do
jumps = Map.merge(state.jumps, %{start => state.op_index, state.op_index => start})
do_parse(rest, push_op(%State{state | open: open, jumps: jumps}, :jump_not_zero))
end
...

Machine

Outside of its constructor Machine only has two functions.

  • run: executes the program until it halts
  • step: executes a single instruction

run is a consumer of step, and simply recurses until step informs it that it's halted or stopped for any other reason.

defmodule Brainjuice.Machine do
...
def run(%Machine{} = machine) do
case step(machine) do
{:ok, machine} -> run(machine)
{:breakpoint, machine} -> run(machine)
{:halted, machine} -> {:ok, machine}
{:error, _reason, _machine} = error -> error
end
end
def step(%Machine{} = machine) do
if halted?(machine) do
{:halted, machine}
else
case elem(machine.program.ops, machine.pc) do
:left when machine.tape.head == 0 -> {:error, :left_of_cell_zero, machine}
:breakpoint -> {:breakpoint, %Machine{machine | pc: machine.pc + 1}}
op -> {:ok, exec(machine, op)}
end
end
end
...
end

Then the private functions are mostly pattern matches on instructions as with the parser and applying changes to its core state.

...
defstruct program: %Program{}, pc: 0, tape: %Tape{}, input: "", output: ""
...
defp exec(%Machine{} = machine, :inc),
do: %Machine{machine | pc: machine.pc + 1, tape: Tape.inc(machine.tape)}
defp exec(%Machine{} = machine, :dec),
do: %Machine{machine | pc: machine.pc + 1, tape: Tape.dec(machine.tape)}
...

Debugger

The debugger is then a consumer of the interpreter. It chooses how to display source code, how to handle breakpoints, what to do on halts and failures, and how to display outputs.

I originally intended to create a practical debugger to help me actually deal with the complex brainfuck I'll need to solve an AoC challenge, and ultimately did get around to slopping one out as a localhost LiveView application. However most of my attention was turned towards building something more fun.

The LiveView debugger

Back in secondary school in GCSE Computer Science I remember using a piece of software called the Little Man Computer. It had a limited set of opcodes and was very similar to the kind of thinking you need for brainfuck, where you have to combine low level operations that are normally far below the abstraction level you're used to working at.

The website we used seems to be gone now but I remember it having a somewhat skeuomorphic design. Many years later I played both Human Resource Machine and SHENZHEN I/O which both took this style of programming and gamified it. The tactile feel of designing micro-code for circuitry in SHENZHEN I find particularly satisfying and I wanted to create something similar.

I do not have the CSS chops for this, but over the course of a few days and lots of help from the CSS clanker, I created the Brainjuice | Brainfuck System. Inspired by early games consoles with their beige plastic and chunky thonky buttons, it's a mechanical and satisfying way to bring brainfuck to life.

Try it for yourself

The Brainjuice Brainfuck System