Brainfuck Compiler in 8051 Assembly
What is Brainfuck?
Brainfuck is an esoteric language Urban Müller made in 1993. A program works on a long array of unsigned bytes using just eight commands: + and - change the current cell, < and > move left and right, . prints, , reads input, and [ ] loop. For a class project I wrote a compiler for it in 8051 assembly that runs right on the microcontroller.
How it works
Very stupidly. 8051 assembly is limited, so the compiler is basically a pile of branches on the ASCII value of each character. It reads the input one character at a time and runs whatever command it finds.
Loops were the tricky part. When it hits a [, it reads ahead without running anything until it finds the matching ], and handles nested [s the same way recursively. If every [ has exactly one ], it stores the outermost loop (the first [ to the last ]) and runs it as many times as needed.
Input
The board has no keyboard, just four push buttons:
- two move left and right in the input box,
- one cycles through the commands,
- one submits, compiles and runs the code.
If a program asks for input with ,, it stops and waits for me to enter a number with the same buttons.
A quick rant about 8051
On the 8051 the stack pointer increments when you push. You don’t know how annoying that is until you’re actually writing code for it. Some subroutines also need a long jump because they’re too far away in the code. Imagine calling a function in C and the compiler saying “sorry, too many lines in between, you can’t call that.”
Try it
+++[>+++[.-]<.-]
Guess what this one prints.