-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvirtual_machine.py
39 lines (36 loc) · 1.46 KB
/
virtual_machine.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
class VirtualMachine:
def __init__(self):
self.stack = []
def execute(self, bytecode):
print("Starting VM execution...")
for instruction in bytecode:
print(f"Executing instruction: {instruction}")
if instruction.startswith("PUSH"):
_, value = instruction.split()
self.stack.append(int(value))
print(f"Stack after PUSH {value}: {self.stack}")
elif instruction == "ADD":
b = self.stack.pop()
a = self.stack.pop()
self.stack.append(a + b)
print(f"Stack after ADD: {self.stack}")
elif instruction == "SUB":
b = self.stack.pop()
a = self.stack.pop()
self.stack.append(a - b)
print(f"Stack after SUB: {self.stack}")
elif instruction == "MUL":
b = self.stack.pop()
a = self.stack.pop()
self.stack.append(a * b)
print(f"Stack after MUL: {self.stack}")
elif instruction == "DIV":
b = self.stack.pop()
a = self.stack.pop()
self.stack.append(a // b) # Integer division
print(f"Stack after DIV: {self.stack}")
else:
raise Exception(f"Unknown instruction: {instruction}")
result = self.stack.pop()
print(f"Final result: {result}")
return result