-
Notifications
You must be signed in to change notification settings - Fork 2
/
pl1_assembler.py
executable file
·52 lines (41 loc) · 994 Bytes
/
pl1_assembler.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
#!/usr/bin/env python
import pl1_machine
import sys
import StringIO
import re
label_re = re.compile('\s*(.*?):')
whitespace_re = re.compile('\s+')
comment_re = re.compile('^\s*#.*$')
def is_integer(string):
try:
int(string)
except ValueError:
return False
return True
def assemble(input):
buffer = []
labels = {}
for line in input:
if comment_re.match(line):
continue
match = label_re.match(line)
line = line.strip()
if line == '':
continue
if match:
labels[match.group(1)] = len(buffer)
else:
command = re.split(whitespace_re, line.strip())
for argument in command:
if is_integer(argument):
buffer.append(int(argument))
elif pl1_machine.OPCODES.has_key(argument):
buffer.append(pl1_machine.OPCODES[argument])
else:
# A label
buffer.append(argument)
# This updates any indirect labels
return list(labels.get(x, x) for x in buffer)
if __name__ == '__main__':
code = assemble(sys.stdin)
print `code`