Learn Rust by building a Brainfuck interpreter, part 2: the execution engine
Introduction¶
In the last post, we created the first building blocks for our Brainfuck interpreter in Rust:
-
A data structure for the tape, which supports four operations:
-
left
andright
move the data pointer, -
get
returns theu8
value that is stored in the current cell, -
set
assigns a newu8
value to the current cell.
-
-
A data type for the instructions. It is based on Rust's enums, which are much more powerful than enums in C or C++ because they allow to build algebraic data types:
#[derive(Debug)] enum Instruction { Inc, // + Dec, // - Left, // < Right, // > Read, // , Write, // . Loop(Vec<Instruction>) // [...] }
This definition allows to represent a Brainfuck program as an abstract syntax tree, which makes program execution simple. However, it requires a bit more work when parsing the program, as we will see in a later post in this series.
In this post, we will implement the next part of the interpreter: an execution engine which applies instructions to the state of the tape, and performs input and output.