An efficient Brainfuck-to-C compiler written in Python, featuring parsing, loop optimizations, dead-code elimination, and C code generation for fast execution.
- Parsing & Tokenization: Reads standard Brainfuck code (
+ - < > . , [ ]) and ignores all other characters. - Instruction Simplification: Merges consecutive increments/decrements and pointer moves.
- Loop Optimization: Detects common patterns (e.g.,
[-]) and replaces them with direct memory operations. - Dead Code Elimination: Removes redundant assignments and combines operations on the same cell.
- C Code Generation: Translates optimized commands into readable, portable C code.
- Customizable Tape: Defaults to a 10,000‐cell tape with adjustable starting pointer offset.
- Python 3.6 or higher
- A C compiler (e.g.,
gcc,clang)
-
Clone this repository:
git clone https://github.com/BehradTabatabaee/BF-Compiler.git cd BF-Compiler -
(Optional) Create a virtual environment:
python3 -m venv env source env/bin/activate
Compile a Brainfuck file (.bf) to C:
python compiler.py path/to/program.bf path/to/output.cCompile the generated C:
gcc -O2 path/to/output.c -o ./program Run your program:
./programGiven a Brainfuck file hello.bf:
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>--.<<+.>++.
------.--------.>+.>.Generate and build:
python compiler.py hello.bf hello.c
gcc -O2 hello.c -o ./hello
./hello
# Output: Hello World!-
Parsing: Removes non‐command characters and builds a command stream.
-
Optimization Pass:
- Linear Merging: Combines successive
+/-and</>into single operations. - Loop Simplification: Transforms patterns like
[-]into direct cell assignmentcell = 0. - Multiply‐Add Detection: Converts nested loops that transfer values into
tape[dest] += tape[src] * factoroperations. - Dead Code Elimination: Removes overwritten assignments and redundant adds.
- Linear Merging: Combines successive
-
Code Generation: Walks the optimized command list to emit clean C, using
while (*ptr)for loops and direct pointer arithmetic.
Contributions, issues, and feature requests are welcome! Please open an issue or submit a pull request.
This project is licensed under the MIT License. See the LICENSE file for details.