-
Notifications
You must be signed in to change notification settings - Fork 0
/
assembler.py
executable file
·339 lines (280 loc) · 10.3 KB
/
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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
#!/bin/env python3
from more_itertools import peekable
from opcodes import opcodes
class SyntaxError(Exception):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
class UndefinedSection(Exception):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
class UnexpectedEOF(Exception):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
class pf:
@staticmethod
def is_comment(s):
return s.peek() == "#"
@staticmethod
def is_label(s):
return s.peek() == "."
@staticmethod
def is_assembler_instruction(s):
return s.peek() == "%"
@staticmethod
def consume2lf(s):
while (char := next(s)) != "\n":pass
return None
@staticmethod
def consume_comment(s,line_number):
return ("c",pf.consume2lf(s))
@staticmethod
def consume_label_argument(s):
valid_literals = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"
literal = ""
while s.peek() in valid_literals:
char = next(s)
literal += char
return literal
@staticmethod
def consume_argument(s):
if s.peek().isnumeric():
return pf.consume_number(s)
else:
label = pf.consume_label_argument(s)
return label
@staticmethod
def consume_label(s,line_number):
valid_literals = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"
label = ""
next(s)
while s.peek() in valid_literals:
label += next(s)
if next(s) != ":":
raise SyntaxError(f"Not valid label at line {line_number}")
return ("l",label)
@staticmethod
def consume_assembler_instruction(s,line_number):
valid_literals = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"
instruction = ""
next(s)
while s.peek() in valid_literals:
instruction += next(s)
pf.consume_whs(s)
argument = pf.consume_argument(s)
return (instruction,argument)
@staticmethod
def consume_number(s):
base = 10
valid_literals = "1234567890xb"
literal = []
while s.peek() in valid_literals:
char = next(s)
literal.append(char)
if len(literal) != 2:
continue
if literal[1] == "x":
base = 16
elif literal[1] == "b":
base = 2
return int("".join(literal),base)
@staticmethod
def consume_whs(s):
new_line = False
while s.peek().isspace():
if next(s) == "\n":
new_line = True
return new_line
@staticmethod
def consume_opcode(s):
opcode = ""
while s.peek().isalpha():
opcode += next(s)
return opcode
@staticmethod
def parse_opcode(s,line_number):
pf.consume_whs(s)
opcode = pf.consume_opcode(s)
pf.consume_whs(s)
argument = None
if s.peek() != ";":
argument = pf.consume_argument(s)
if next(s) != ";":
raise SyntaxError(f"Syntax error at line {line_number}")
return ("o",opcode,argument)
class Parser:
def __init__(self,file_path : str):
self.stream = open(file_path,"r")
self.raw_data = peekable(self._stream_iterator(self.stream))
self.parse_tree = {
pf.is_comment : pf.consume_comment,
pf.is_label : pf.consume_label,
pf.is_assembler_instruction : self.assembler_instruction,
lambda _: True : pf.parse_opcode
}
self._line = 1
self.opcode_index = 0
self.result = []
self.labels = {}
self.main_label = "start"
self.base = 0
self.padding = None
self.static_memory_size = 512
#Iterator to iterate char by char from file
def _stream_iterator(self,stream):
for line in stream:
yield from iter(line)
yield "\n"
stream.close()
#Using respective parser
def _use_parser(self,parser):
result = parser(self.raw_data,self._line)
if result == None: return
if result[0] == "l":
if result[1] in self.labels:
raise SyntaxError(f"Second declaration of label {result[1]} at line {self._line}")
self.labels[result[1]] =\
(self._line,self.opcode_index,*result)
elif result[0] == "o":
self.result.append( (self._line,self.opcode_index,*result) )
self.opcode_index += 1
#Parse an assembler instruction
def assembler_instruction(self,s,line_number):
instruction,argument = pf.consume_assembler_instruction(s,line_number)
if instruction == "base":
self.base = argument
elif instruction == "main_label":
self.main_label = argument
elif instruction == "size":
self.static_memory_size = argument
elif instruction == "padding":
self.padding = argument
else:
raise SyntaxError(f"Unknown assembler instruction at line {line_number}")
return None
#Find valid parser
def check_parser(self,check,parser):
if check(self.raw_data):
self._use_parser(parser)
return True
return False
#Is it eof
def _is_eof(self):
try:
if pf.consume_whs(self.raw_data):
self._line += 1
return False
except Exception:
return True
# Single phase of pharsing
def _single_parse(self):
for check,parser in self.parse_tree.items():
if self.check_parser(check,parser):
return
raise SyntaxError(f"Syntax error at line {self._line}")
#Whole parser
def parse(self):
while not self._is_eof():
try:
self._single_parse()
except Exception as e:
self.stream.close()
if isinstance(e,StopIteration):
raise UnexpectedEOF(f"Unexpected EOF at {self._line}")
else:
raise e
if 2*len(self.result) + self.base > self.static_memory_size:
raise OverflowError(b"Out of static memory to program, program may not exceed {self.static_memory_size} bytes")
return self.result, self.labels, self.main_label, self.base, self.static_memory_size, self.padding
class Assembler:
#Write opcode to file
def write_op(self,data : tuple,stream,base_offset : int):
line,index,type,*info = data
if type != "o": return
opcode,argument = info
has_argument,opcode_value = opcodes.get(opcode,(None,None))
if opcode_value == None:
raise SyntaxError(f"Unknown opcode {opcode} at line {line}")
if has_argument and argument == None:
raise SyntaxError(f"Opcode {opcode} at line {line} requires an argument")
elif not has_argument and argument != None:
raise SyntaxError(f"Opcode {opcode} at line {line} can't have an argument")
elif argument == None:
argument = 0
elif argument > 255:
raise SyntaxError(f"Argument of opcode {opcode} at line {line} must be one byte (0-255)")
stream.seek(index*2)
stream.write(bytes([argument,opcode_value]))
#Calculate offset based on main label
def calculate_base_label(self,parsed,labels : dict,main_label : str):
label = labels.get(main_label)
line,instruction_index,type,name = label
start = instruction_index
stop = len(parsed)
size = stop-start
if len(labels) == 1:
return start,stop,size
label_names = list(labels.keys())
next_label_index = label_names.index(main_label) + 1
if next_label_index >= len(labels):
return start,stop,size
_,index,*_ = list(labels.values())[next_label_index]
stop = index
size = stop-start
return start,stop,size
#Move everything by offset calculater earlier
def move2base_label(self,parsed : list,labels : dict,main_label : str,base_offset : int):
start,stop,size = self.calculate_base_label(parsed,labels,main_label)
new_base_label_index = 0
for i,data in enumerate(parsed[:stop]):
line,index,type,*info = data
if index >= start and index < stop:
parsed[i] = (line,new_base_label_index+base_offset,type,*info)
new_base_label_index += 1
else:
parsed[i] = (line,index+size+base_offset,type,*info)
#Replace label arguments by position
def _replace_labels(self,part : tuple,labels):
if part[2] != "o": return part
if not isinstance(part[-1],str): return part
label = labels.get(part[-1],None)
if label == None:
raise SyntaxError(f"Unknow label at line {part[0]}")
return (*part[:-1],label[1])
#Replace label arguments by position
def swap_labels(self,main_label,labels,parsed):
if not main_label in labels:
raise UndefinedSection(f"No main_label named {self.main_label}")
parsed = list(
map(
lambda p : self._replace_labels(p,labels),
parsed
)
)
return parsed
def padd(self,stream,mem_size : int,padding : int):
for i in range(0,mem_size):
stream.seek(i)
stream.write(bytes([padding]))
stream.flush()
stream.seek(0)
#Assemble a file from input
def assemble(self,input_file_path : str,output_file_path : str):
p = Parser(input_file_path)
output_stream = open(output_file_path,"wb+")
parsed, labels, main_label, base_offset, mem_size, padding = p.parse()
if padding != None:
self.padd(output_stream,mem_size,padding)
print(parsed)
self.move2base_label(parsed,labels,main_label,base_offset)
parsed = self.swap_labels(main_label,labels,parsed)
print(parsed)
try:
for data in parsed:
self.write_op(data,output_stream,base_offset)
except Exception as e:
raise e
finally:
output_stream.close()
if __name__ == "__main__":
a = Assembler()
a.assemble("program.ebt","program.bin")