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
RET
Opcode: 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.
ADD
Opcode: SUB
Removes the last 2 values from the stack. And pushes the subtraction of them back.
SUB
Opcode: MUL
Removes the last 2 values from the stack. And pushes the multiplication of them back.
MUL
Opcode: DIV
Removes the last 2 values from the stack. And pushes the division of them back.
DIV
Opcode: MOD
Removes the last 2 values from the stack. And pushes the modulo of them back.
MOD
Opcode: RET
Stops the execution of the program. And returns the values in the stack.
RET
You 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.git
Run the command below to set your working directory to bytecode-compiler/
.
cd bytecode-compiler/
Run the command below to build the program.
cargo build --release
Run the command below to run the examples.
./target/release/bytecode-compiler examples/adding.code # or examples/complex.code