-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAspen VM.py
107 lines (70 loc) · 2.4 KB
/
Aspen VM.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class VM(): #Where the magic happens
def __init__(self, args): #args is an array of: code, ip, sp, fp, data, datasize
self.ip = args[1]
self.sp = args[2]
self.fp = args[3]
self.data = args[4]
self.datasize = args[5]
self.code = args[0]
self.stack = []
def cpu(self):
# Starting the list of all the operations =============
def halt():
return
def pop():
self.stack.pop(self.sp)
self.sp -= 1
def iConst():
self.ip += 1
self.stack.append(self.code[self.ip])
self.sp += 1
def iAdd():
sum = int(self.stack[-1]) + int(self.stack[-2])
pop()
pop()
self.stack.append(sum)
def iMult():
product = int(self.stack[-1]) * int(self.stack[-2])
pop()
pop()
self.stack.append(product)
def iMult():
product = int(self.stack[-1]) * int(self.stack[-2])
pop()
pop()
self.stack.append(product)
def iDiv():
quotient = int(self.stack[-1]) / int(self.stack[-2])
pop()
pop()
self.stack.append(quotient)
def iSub():
difference = int(self.stack[-1]) - int(self.stack[-2]) #subtract the lower item in the stack from the higher item!
pop()
pop()
self.stack.append(difference)
def cout():
print(self.stack[-1])
pop()
decoder = {
"HALT": halt,
"POP": pop,
"ICONST": iConst,
"IADD": iAdd,
"ISUB": iSub,
"IMULT": iMult,
"IDIV": iDiv,
"PRINT": cout,
}
# Ending the operations list ====================
def picker(codeName):
decoder[codeName]()
while self.ip < len(self.code) - 1: #Ok, all that other stuff was just buildup, this is where the REAL magic happens
self.ip += 1
op = self.code[self.ip]
#print("OPCODE: " + str(op) + "\n IP: " + str(self.ip) + "\n STACK: " + str(self.stack))
picker(self.code[self.ip])
aspenVM = VM([
["ICONST", "12", "ICONST", "60", "IDIV", "PRINT", "HALT"],
-1, -1, 4, 12, 2]) #code, IP, SP, FP, data, datasize
aspenVM.cpu()