-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvm.py
More file actions
105 lines (84 loc) · 3.01 KB
/
vm.py
File metadata and controls
105 lines (84 loc) · 3.01 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
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
95
96
97
98
99
100
101
102
103
104
105
import sys
import time
DEBUG=False
class WM(object):
def __init__(self, file):
self.file = file
self.program = self.file.read()
self.program = self.program.split(' ')
self.Ram = [0]*1024
self.stack = [0]*1024
self.sp = -1
self.pc = 0
def push(self, val):
if self.sp == 1023:
raise Exception('stack overflow')
self.sp += 1
self.stack[self.sp] = val
def pop(self):
if self.sp == -1:
raise Exception('stack empty')
val = self.stack[self.sp]
self.sp -= 1
return val
def Run(self):
while True:
if self.program[self.pc] == 'EOP':
break
elif self.program[self.pc] == 'push':
self.push(int(self.program[self.pc + 1]))
self.pc += 2
elif self.program[self.pc] == 'pop':
self.pop()
self.pc += 1
elif self.program[self.pc] == 'load':
self.push(self.Ram[int(self.program[self.pc + 1])])
self.pc += 2
elif self.program[self.pc] == 'store':
self.Ram[int(self.program[self.pc + 1])] = self.pop()
self.pc += 2
elif self.program[self.pc] == 'sum':
self.push(self.pop() + self.pop())
self.pc += 1
elif self.program[self.pc] == 'sub':
self.push(self.pop() - self.pop())
self.pc += 1
elif self.program[self.pc] == 'mult':
self.push(self.pop() * self.pop())
self.pc += 1
elif self.program[self.pc] == 'div':
self.push(int(self.pop() / self.pop()))
self.pc += 1
elif self.program[self.pc] == 'ilt':
if self.pop() < self.pop():
self.push(1)
else:
self.push(0)
self.pc += 1
elif self.program[self.pc] == 'jme':
adr = self.pop()
if self.pop() == self.pop():
self.pc = adr
else:
self.pc += 1
elif self.program[self.pc] == 'jma':
self.pc = self.pop()
elif self.program[self.pc] == 'printch':
print(chr(self.pop()), end='')
self.pc += 1
elif self.program[self.pc] == 'printnum':
print(self.pop(), end='')
self.pc += 1
else:
print('Unknown command!')
print(self.program[self.pc])
print(self.pc)
sys.exit(-1)
if DEBUG:
print(self.stack[:self.sp+1])
with open("program.txt",'r') as file:
wm = WM(file)
start_time = time.time()
wm.Run()
print("--- %s seconds ---" % (time.time() - start_time))
file.close()