-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathVMWriter.py
55 lines (43 loc) · 1.66 KB
/
VMWriter.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
#VM Writer
class VMWriter(object):
def __init__(self, outfile):
self.vm = open(outfile, "w+")
def writePush(self, segment, index):
if segment == "field":
self.vm.write('push this %d\n' %(index))
else:
self.vm.write('push %s %d\n' %(segment, index))
def writePop(self, segment, index):
if segment == "field":
self.vm.write('pop this %d\n' %(index))
else:
self.vm.write('pop %s %d\n' %(segment, index))
def writeArithmetic(self, command):
self.vm.write(command.lower()+'\n')
def writeLabel(self, label):
self.vm.write ('label %s\n' %(label))
def writeGoto(self, label):
self.vm.write('goto '+label+'\n')
def writeIf(self, label):
self.vm.write('if-goto '+label+'\n')
def writeCall(self, name, nArgs):
self.vm.write('call %s %d\n' %(name, nArgs))
def writeFunction(self, name, nLocals):
self.vm.write('function %s %d\n' %(name, nLocals))
def writeReturn(self):
self.vm.write('return\n')
def close(self):
self.vm.close()
'''
v = VMWriter('vmcode.txt')
v.writePush('local', 0)
v.writePop('argument', 0)
v.writeArithmetic('ADD')
v.writeLabel('LOOP')
v.writeGoto('LOOP')
v.writeIf('END')
v.writeCall('foo', 2)
v.writeFunction('bar', 1)
v.writeReturn()
v.close()
'''