brainfuck 0.5.0
brainfuck: ^0.5.0 copied to clipboard
A sample command-line Brainfuck interpreter.
A command-line Brainfuck interpreter implemented with Dart language.
Installation #
You can install the command-line tool via dart pub. Just run the command below.
dart pub global activate brainfuck
Usage #
brainfuck "YOUR_BRAINFUCK_CODE"
For example, to print "Hi":
brainfuck "++++++++++[>++++++++<-]>+++++++.---.--------------."
Technical Details #
The Brainfuck Language #
Brainfuck operates on an array of memory cells (this interpreter uses 65,535 cells, each initialized to zero) and a data pointer that starts at the first cell. The language has eight commands:
| Command | Description |
|---|---|
> |
Move the data pointer to the next cell. |
< |
Move the data pointer to the previous cell. |
+ |
Increment the value at the current cell by 1. |
- |
Decrement the value at the current cell by 1. |
. |
Output the byte at the current cell as an ASCII character. |
, |
Read one byte of input and store it in the current cell. |
[ |
If the value at the current cell is zero, jump forward to the matching ]. |
] |
If the value at the current cell is non-zero, jump back to the matching [. |
Any other characters in the source string are treated as comments and ignored.
Interpreter Architecture #
The interpreter works in two phases:
- Compile – The
compile()method parses the source string and converts it into an internal list ofInstructionobjects. During this phase the matching jump targets for[and]are pre-computed so that branching at runtime is an O(1) operation. - Run – The
run()method executes the compiled instruction list. Ifcompile()has not been called beforehand,run()calls it automatically.
Both methods return a Status value (Status.success or Status.failed). Compilation fails when a ] is encountered without a matching [.
Using the Library #
The interpreter can be used as a Dart library:
import 'package:brainfuck/brainfuck.dart';
void main() {
final interpreter = Brainfuck('++++++++++[>++++++++<-]>+++++++.---.--------------.');
final status = interpreter.run();
if (status == Status.failed) {
print('Program failed to run.');
}
}