Repository navigation
Expand file tree
/
Copy pathassembler.py
More file actions
100 lines (77 loc) · 3.48 KB
/
Copy pathassembler.py
File metadata and controls
100 lines (77 loc) · 3.48 KB
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
import argparse
import struct
from io import TextIOWrapper
from typing import Generator
from src.exception import (ArgumentOutOfRangeError, DuplicateLabelError, InvalidArgumentError,
MissingArgumentError, UnexpectedArgumentError,
UnknownInstructionError)
from src.opcodes import ArgOpcode, BasicOpcode
class Assembler:
def __init__(self) -> None:
self._label_table: dict = {}
def assemble(self, filename: str) -> bytes:
with open(filename, "r", encoding="utf-8") as f:
tokens = list(self._parse_asm_file(f))
self._parse_labels(tokens)
res = list(self._translate_file(tokens))
return b"".join(res)
def _parse_asm_file(self, file: TextIOWrapper) -> Generator[list, None, None]:
line_num = 0
raw_line_num = 0
for raw_line in file:
raw_line_num += 1
line = raw_line.split(";")[0].strip()
if not line:
continue
tokens = line.split()
mnemonic = tokens[0].upper()
if mnemonic in ArgOpcode.__members__ and len(tokens)>2:
raise UnexpectedArgumentError(mnemonic, raw_line_num)
argument = tokens[1] if len(tokens) >= 2 else None
yield [raw_line_num, line_num, mnemonic, argument]
if not mnemonic.endswith(":"):
line_num += 1
def _parse_labels(self, data: list[list]) -> None:
self._label_table = {}
for raw_line_num, line_num, mnemonic, _ in data:
if mnemonic.endswith(":"):
label_name = mnemonic[:-1]
if label_name not in self._label_table:
self._label_table[label_name] = line_num
else:
raise DuplicateLabelError(label_name, raw_line_num)
def _translate_file(self, data: list[list]) -> Generator[bytes, None, None]:
for raw_line_num, _, mnemonic, argument in data:
if mnemonic.endswith(":"):
continue
if mnemonic in BasicOpcode.__members__:
if argument:
raise UnexpectedArgumentError(mnemonic, raw_line_num)
raw_byte = struct.pack(">B", BasicOpcode[mnemonic])
yield raw_byte
elif mnemonic in ArgOpcode.__members__:
if not argument:
raise MissingArgumentError(mnemonic, raw_line_num)
if argument.upper() in self._label_table:
argument = self._label_table[argument.upper()]
try:
operand = int(argument)
except ValueError:
raise InvalidArgumentError(argument, raw_line_num) from None
if not (-2147483648 <= operand <= 2147483647):
raise ArgumentOutOfRangeError(operand, raw_line_num)
raw_bytes = struct.pack(">Bi", ArgOpcode[mnemonic], operand)
yield raw_bytes
else:
raise UnknownInstructionError(mnemonic, raw_line_num)
def main(args) -> None:
a = Assembler()
with open(args.output, "wb") as f:
f.write(a.assemble(args.filename))
print(f"Success compiled! Binary file path: {args.output}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Compile .asm file to .bin format")
parser.add_argument(dest="filename")
parser.add_argument("-o", dest="output", type=str)
args = parser.parse_args()
main(args)