-
Notifications
You must be signed in to change notification settings - Fork 1
/
assembler.py
100 lines (79 loc) · 2.13 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
"""
Assembler for the CPU
Generates a hex file from an assembly file
There are two formats of instructions:
type1:
MNEMONIC OPERAND
type2:
MNEMONIC
"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', type=str, help='file to be assembled')
file_name = parser.parse_args().file
"""
Instruction definitions
"""
type_1 = {"LDA": "1",
"ADD": "2",
"SUB": "3",
"STA": "4",
"LDI": "5",
"JMP": "6",
"JZ": "7",
"JC": "8",
}
type_2 = {"NOP": "0",
"OUT": "e",
"HLT": "f",
}
"""
Parse the file
"""
class Error(Exception):
pass
class AssemblerError(Error):
"""
Exception raised for errors in the syntax
"""
def __init__(self, lnum, message):
self.lnum = lnum
self.message = message + " line: " + str(lnum)
def __str__(self):
return self.message
def formatter(item):
def custom(foo):
return str(hex(foo))[2:]
item = int(item)
nibbles = [(item & 0xf00) >> 8,
(item & 0xf0) >> 4,
(item & 0xf)]
return ''.join(map(custom, nibbles))
line_number = 0
file = open(file_name, 'r')
lines = file.read().strip().split('\n')
file.close()
data = "v2.0 raw\n"
for line in lines:
line = line.split(';')[0].strip()
if line == "":
continue
tokens = line.split(' ')
if len(tokens) == 0:
continue
elif len(tokens) == 1:
if tokens[0].upper() not in type_2.keys():
raise AssemblerError(line_number, "Invalid syntax")
data += (type_2[tokens[0].upper()] + "000 ")
elif len(tokens) == 2:
if tokens[0].upper() not in type_1.keys():
raise AssemblerError(line_number, "Invalid syntax")
if not tokens[1].isdigit() or int(tokens[1]) >= (2 ** 12):
raise AssemblerError(line_number, "Invalid syntax")
data += (type_1[tokens[0].upper()] + formatter(tokens[1]) + " ")
else:
raise AssemblerError(line_number, "Invalid syntax")
line_number += 1
file = open(file_name.split('/')[-1] + ".bin", 'w+')
file.write(data)
file.close()