Skip to content

About

Stack-based VM, custom ISA, and two-pass bytecode assembler in modern Python. Zero runtime dependencies.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Latest commit

 

History

48 Commits

Folders and files

Repository files navigation

stack-vm-py

Python Tests Dependencies License

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.

Overview

The toolchain consists of two decoupled components:

  1. 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 using struct.
  2. 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.

Key Characteristics

  • Binary Format: Big-Endian (>B opcodes, >i 32-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: MOD computes the remainder, NEG changes a value's sign, and GT, LE, GE, NEQ complement EQ and LT. Comparisons produce integer flags (1 or 0) 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).

Usage

1. Assemble source to binary

mkdir -p build
python3 assembler.py examples/num_is_even.asm -o build/num_is_even.bin

2. Execute bytecode

python3 vm.py build/num_is_even.bin

Example

Computing 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
    halt

Testing

The 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

License

MIT

About

Stack-based VM, custom ISA, and two-pass bytecode assembler in modern Python. Zero runtime dependencies.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Contributors

Languages