Repository navigation
Expand file tree
/
Copy pathclient.py
More file actions
54 lines (50 loc) · 1.65 KB
/
Copy pathclient.py
File metadata and controls
54 lines (50 loc) · 1.65 KB
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
"""Stack-Based Bytecode Virtual Machine Engine
100% Python Standard Library.
"""
class StackVM:
"""Stack virtual machine execution engine."""
def __init__(self):
self.stack = []
self.variables = {}
self.ip = 0
def run(self, bytecode):
self.stack = []
self.ip = 0
while self.ip < len(bytecode):
inst = bytecode[self.ip]
op = inst[0]
if op == "LOAD_CONST":
self.stack.append(inst[1])
elif op == "STORE_VAR":
self.variables[inst[1]] = self.stack.pop()
elif op == "LOAD_VAR":
self.stack.append(self.variables[inst[1]])
elif op == "ADD":
b = self.stack.pop()
a = self.stack.pop()
self.stack.append(a + b)
elif op == "SUB":
b = self.stack.pop()
a = self.stack.pop()
self.stack.append(a - b)
elif op == "MUL":
b = self.stack.pop()
a = self.stack.pop()
self.stack.append(a * b)
elif op == "DIV":
b = self.stack.pop()
a = self.stack.pop()
self.stack.append(a / b)
elif op == "JUMP_IF_ZERO":
val = self.stack.pop()
if val == 0:
self.ip = inst[1]
continue
elif op == "HALT":
break
self.ip += 1
return {
"result": self.stack[-1] if self.stack else None,
"variables": self.variables,
"stack_depth": len(self.stack)
}