A minimalist stack-based process virtual machine and a two-pass bytecode assembler implemented in Python with zero external runtime dependencies. Built for fun as a systems programming experiment and architectural showcase.
The toolchain consists of two decoupled components:
- Two-Pass Assembler (
assembler.py): Tokenizes assembly source files, resolves forward-referenced labels via a symbol table, validates instruction arity, and emits Big-Endian binary bytecode usingstruct. - Virtual Machine (
vm.py): Performs ahead-of-time decoding of the binary stream into an intermediate tuple representation and executes it in a fetch-execute loop using structural pattern matching (match/case).
Full binary layout and instruction semantics are documented in ISA.md.
- Binary Format: Big-Endian (
>Bopcodes,>i32-bit signed immediate operands). - Stack Primitives: Includes Forth-style stack manipulation (
DUP,SWAP,OVER,ROT) alongside standard arithmetic, comparisons, and conditional jumps. - Arithmetic and Comparisons:
MODcomputes the remainder,NEGchanges a value's sign, andGT,LE,GE,NEQcomplementEQandLT. Comparisons produce integer flags (1or0) for conditional jumps. - Fault Isolation: Dedicated exception hierarchies (
AssemblerError,VMError) covering compile-time syntax/label errors and runtime faults (stack underflow, division by zero, invalid opcodes, segmentation faults).
mkdir -p build
python3 assembler.py examples/num_is_even.asm -o build/num_is_even.binpython3 vm.py build/num_is_even.binComputing 5! (120) using stack manipulation and conditional branching:
push 1 ; accumulator
push 5 ; counter
loop:
dup
jz done
swap
over
mul
swap
dec
jmp loop
done:
pop ; discard counter
print ; outputs 120
haltThe project includes 32+ unit and end-to-end tests covering instruction semantics, signed integer edge cases, boundary checks, label resolution, and error handling.
python3 -m venv .venv
source .venv/bin/activate
pip install pytest
python -m pytest -v