Skip to content

Instantly share code, notes, and snippets.

@kigawas
Last active August 2, 2019 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kigawas/e86bb9300e6d7ce1876c to your computer and use it in GitHub Desktop.
Save kigawas/e86bb9300e6d7ce1876c to your computer and use it in GitHub Desktop.
Simple stack virtual machine in Python
# -*- coding: utf-8 -*-
"""
A very simple stack-based virtual machine in Python
Example:
PSH 1 # push 1 into the stack
PSH 2 # push 2 into the stack
ADD # add the topest 2 values and pop them
POP # pop the top of the stack and print 3
HLT # end the program
"""
ins_set = ('PSH', 'ADD', 'POP', 'HLT') # the instruction set
running = True # the program is running?
ip = 0 # the instruction pointer
sp = -1 # the stack pointer
stack = [0] * 256 # size = 256
program = [
"PSH", 1,
"PSH", 2,
"ADD",
"POP",
"HLT"
]
def fetch():
global ip
return program[ip]
def execute(instr):
global ip
global sp
global running
if instr not in ins_set:
error("Illegal instruction")
running = False
return
if instr == "HLT":
running = False
print("Program ends")
elif instr == "PSH":
sp += 1
ip += 1
stack[sp] = program[ip] # push next value into the stack
elif instr == "POP":
top = stack[sp]
sp -= 1
print(f"You popped {top}")
elif instr == "ADD":
val1 = stack[sp]
sp -= 1
val2 = stack[sp]
sp -= 1
result = val1 + val2
sp += 1
stack[sp] = result
else:
pass
def error(msg):
print(f"Error: {msg}")
def run():
global ip
while running:
execute(fetch())
ip += 1
if __name__ == '__main__':
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment