« All posts

Implement a Bytecode Machine

Posted On 11.05.2022

Alright, Iā€™m back.

In this commit, I implemented a stack-based bytecode machine so we can execute the
code that was generated by the compiler.

It supports a very small instruction set right now, enough for working with i32 numbers,
storing and loading global and local variables, if expressions, function calls.

No string support for now.

Example usage:

let program = vec![
    // print(10 + 5)
    OpCode::PUSH as i32, 10,            // 000
    OpCode::PUSH as i32, 5,             // 002
    OpCode::ADD as i32,                 // 003
    OpCode::PRINT as i32,               // 004
    OpCode::HALT as i32,                // 005
];
let mut vm = VirtualMachine::new();
vm.load_program(program, 0);
vm.run(&mut io::stdout());

We can pass a struct that implements the std::io::Write trait in to the VirtualMachine::run
method to act as the output device, for example, std::io::stdout().