This project is built to explore how lexers, parsers, compilers and virtual machines work.
This project doesn't have any dependency and is built from scratch.
This project has unit tests for many of its modules.
Virtual machine implementation is like below.
pub struct VirtualMachine {
stack: Vec<Value>,
register: [Value; REGISTER_SIZE],
bytecode: Vec<u8>,
program_counter: usize,
}A sample program is below.
PUSH 10
PUSH 40
ADD
RETOpcode: PUSH
Pushes a value to the stack of the virtual machine.
PUSH <value> // type of value is `i64` Opcode: POP
Removes the last value from the stack.
POP Opcode: STORE
Stores the last value from the stack at specified index in the register of the virtual machine.
STORE <index> // type of index is `u8` Opcode: LOAD
Pushes the value at the specified index in the register to the stack.
LOAD <index> // type of index is `u8` Opcode: ADD
Removes the last 2 values from the stack. And pushes the sum of them back.
ADDOpcode: SUB
Removes the last 2 values from the stack. And pushes the subtraction of them back.
SUBOpcode: MUL
Removes the last 2 values from the stack. And pushes the multiplication of them back.
MULOpcode: DIV
Removes the last 2 values from the stack. And pushes the division of them back.
DIVOpcode: MOD
Removes the last 2 values from the stack. And pushes the modulo of them back.
MODOpcode: RET
Stops the execution of the program. And returns the values in the stack.
RETYou need Rust Language installed.
Or you can use Dev Containers to easily setup a development environment.
Run the command below to clone the repository.
git clone https://github.com/BerzanXYZ/bytecode-compiler.gitRun the command below to set your working directory to bytecode-compiler/.
cd bytecode-compiler/Run the command below to build the program.
cargo build --releaseRun the command below to run the examples.
./target/release/bytecode-compiler examples/adding.code # or examples/complex.code