VMCrypt is a tiny virtual machine with a compiler that turns a decent chunk of Python into bytecode that the VM can run.
This is a project I wrote for fun to see how far a tiny 8 register VM can be pushed.
- Virtual Machine: A register based VM that can do math, logic, comparisons, jumps, and printing.
- Compiler: Turns a small subset of Python source into VMCrypt bytecode using the
astmodule. - Logging: Run with
-debugto print detailed messages about what the virtual machine and compiler are doing.
VMCrypt is the core part of this project. It can do operations like:
- Math: Adding, subtracting, multiplying, dividing, and modulo.
- Logic: Bitwise operations like AND, OR, XOR, NOT, and shifts/rotates.
- Comparisons: Less than, greater than, equal, not equal, and their inclusive variants.
- Memory: Variables, strings and lists all live in a flat byte addressable memory, with both immediate and register computed addressing.
- Jumping: Move to different parts of the program, conditionally or not, plus
CALL/RETfor function calls. - Output: Print numbers with
PRINTor decode and print strings withPRINT_STR.
The Compiler class parses Python source with ast, then walks the tree emitting VMCrypt bytecode. Variables live in VM memory (not registers), so theres no hard cap on how many a program can use.
Supported:
- ✅ Integer variables, assignment, and augmented assignment (
x = 3,x += 1) - ✅ Arithmetic (
+ - * // %) and bitwise (& | ^ << >>) operators, unary- - ✅ Comparisons (
< > == != <= >=), including chained comparisons (1 < x < 10) - ✅ Boolean
and/or/not - ✅
if/elif/else,while,break,continue - ✅
for x in range(...)andfor x in <list> - ✅ Functions:
def, positional parameters,return - ✅ String literals and string variables,
print(s) - ✅ Lists of integers, indexing (read and write),
len(...)
If your program only uses whats supported it should compile and run just fine. Anything else will raise a CompileError rather than silently doing the wrong thing.
from src import Compiler, VMCrypt
source = """
x = 3
y = 4
z = x + y * 2
print(z)
i = 0
while i < 5:
print(i)
i = i + 1
if z > 10:
print(1)
else:
print(0)
"""
compiler = Compiler()
program = compiler.compile(source)
vm = VMCrypt()
vm.load_program(program)
vm.run()
print(vm.output)Run your script with -debug (or --debug) on the command line to see instruction and compile debug output.
-
Clone the repository:
git clone https://github.com/dexvnd/VMCrypt.git cd VMCrypt -
Install the packages:
pip install -r requirements.txt
