Created
September 16, 2019 05:31
-
-
Save g10guang/c81c5075dcc0272197aac5a97aedc6f3 to your computer and use it in GitHub Desktop.
A stupid virtual machine.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import enum | |
class Instruction(enum.Enum): | |
HLT = 0 | |
ADD = 1 | |
POP = 2 | |
PSH = 3 | |
SET = 4 | |
Get = 5 | |
JMP = 6 | |
class CommonRegister(enum.Enum): | |
A = 0 | |
B = 1 | |
C = 2 | |
D = 3 | |
# instruction pointer of program variable | |
IP = 0 | |
# the program instrution code to do what you want | |
program = [ | |
Instruction.PSH, 100, | |
Instruction.PSH, 200, | |
Instruction.ADD, | |
Instruction.SET, CommonRegister.A, | |
Instruction.Get, CommonRegister.A, | |
Instruction.POP, | |
Instruction.HLT, | |
] | |
# stack of the content | |
stack = [] | |
register = {CommonRegister.A: 0, CommonRegister.B: 0, CommonRegister.C: 0, CommonRegister.D: 0} | |
runing = True | |
def loop(): | |
while runing: | |
x = fetch() | |
if x == Instruction.HLT: | |
halt() | |
elif x == Instruction.ADD: | |
add() | |
elif x == Instruction.POP: | |
pop() | |
elif x == Instruction.PSH: | |
push() | |
elif x == Instruction.SET: | |
set_() | |
elif x == Instruction.Get: | |
get() | |
elif x == Instruction.JMP: | |
jump() | |
else: | |
raise Exception('Unknown instruction') | |
# fetch instruction and incr IP | |
def fetch(): | |
global IP, program | |
r = program[IP] | |
IP += 1 | |
return r | |
def halt(): | |
global runing | |
runing = False | |
def add(): | |
global stack | |
stack.append(stack.pop() + stack.pop()) | |
def pop(): | |
global stack | |
print(stack.pop()) | |
def push(): | |
global stack | |
stack.append(fetch()) | |
def set_(): | |
global stack, register | |
r = fetch() | |
register[r] = stack.pop() | |
def get(): | |
global stack, register | |
r = fetch() | |
stack.append(register[r]) | |
def jump(): | |
global IP | |
IP = fetch() | |
if __name__ == "__main__": | |
loop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment