-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parser.py
89 lines (66 loc) · 1.86 KB
/
Parser.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
#!/usr/bin/python
# hack parser
class Command():
A_COMMAND = 0 # @Xxx
C_COMMAND = 1 # dest=comp;jump
L_COMMAND = 2 # (Xxx) ie label
class Parser():
def __init__(self, fname):
self.infile = open(fname, 'r') # Woohoo memory leaks
self.currentLine = ''
def hasMoreCommands(self):
# This is stupid and inefficient
line = self.infile.readline()
self.infile.seek(-1*len(line), 1)
return line != ''
def advance(self):
# Totally unpythonic
self.currentLine = self.infile.readline().strip()
def commandType(self):
# Parse currentLine and decide which type of command it is
if self.currentLine[0] == '@':
return Command.A_COMMAND
elif ('=' in self.currentLine) or (';' in self.currentLine):
# Yay stupid generalizations
return Command.C_COMMAND
elif self.currentLine[0] == '(':
return Command.L_COMMAND
else:
raise SyntaxError
def symbol(self):
if self.commandType() == Command.A_COMMAND:
sym = self.currentLine[1:] # cut off @
elif self.commandType() == Command.L_COMMAND:
sym = self.currentLine[1:-1] # trim out ( )
else:
raise SyntaxError
return sym
def dest(self):
if (self.commandType() == Command.C_COMMAND) and ('=' in self.currentLine):
dest = self.currentLine.split('=')[0]
else:
raise SyntaxError
return dest
def comp(self):
if self.commandType() == Command.C_COMMAND:
if '=' in self.currentLine:
part = self.currentLine.split('=')[1]
if ';' in part:
comp = part.split(';')[0]
else:
comp = part
elif ';' in self.currentLine:
comp = self.currentLine.split(';')[0]
else:
raise SyntaxError
return comp
else:
raise SyntaxError
def jump(self):
if self.commandType() == Command.C_COMMAND and (';' in self.currentLine):
jump = self.currentLine.split(';')[-1]
else:
raise SyntaxError
return jump
def __del__(self):
self.infile.close()