-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathassembler.py
44 lines (32 loc) · 1.25 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
from syntax import syntax_check, is_label_decl, is_r_type, is_mem, is_beq
from translator import translate
def get_label(line):
"""Returns the label string of a label declaration. Does not check that the
given string is indeed a label declaration or not."""
return line[:-1]
def map_labels(args, lines):
"""Pass through the input lines once and create a map from label names to
the offset in number of bytes from the first instruction of the input. This
assumes that each instruction is 4 bytes long."""
offset = 0
result = {}
for line in lines:
if is_label_decl(line):
result[get_label(line)] = offset
else:
offset += 4
if args.debug:
print("Labels map:", result)
return result
def assemble(args, lines):
"""Converts the given list of RISC-V assembly lines into a list of RISC-V
machine codes, one for each line. Each machine code is a string containing
the machine code in hexadecimal representation (8 hex digits, no separation,
no new lines).
Returns None on failure."""
lines = syntax_check(args, lines)
if lines is None:
return None
labels_map = map_labels(args, lines)
lines = translate(args, lines, labels_map)
return lines