+/lc3tools

git clone https://git.julia.blue/+/lc3tools

Joseph RyanUpdate assembler to python34e1c082

master
7.5 KiB275 linesraw
1#!/usr/bin/env python3
2import sys
3
4line_num = 0
5symbol_table = {}
6
7register = {
8    "R0": "000",
9    "R1": "001",
10    "R2": "010",
11    "R3": "011",
12    "R4": "100",
13    "R5": "101",
14    "R6": "110",
15    "R7": "111",
16}
17
18load_store = {
19    "LD": "0010",
20    "LDR": "0110",
21    "LDI": "1010",
22    "ST": "0011",
23    "STR": "0111",
24    "STI": "1011",
25    "LEA": "1110",
26}
27
28arithmetic = {"ADD": "0001", "AND": "0101", "NOT": "1001"}
29
30branch = {
31    "BR": "111",
32    "BRN": "100",
33    "BRZ": "010",
34    "BRP": "001",
35    "BRNZ": "110",
36    "BRNP": "101",
37    "BRZP": "011",
38    "BRNZP": "111",
39}
40
41function = {
42    "JSR": "01001",
43    "JSRR": "0100",
44    "TRAP": "1111",
45    "RTI": "1000",
46    "JMP": "1100",
47    "RET": "1100",
48}
49
50service_routine = {
51    "GETC": "X20",
52    "OUT": "X21",
53    "PUTS": "X22",
54    "IN": "X23",
55    "PUTSP": "X24",
56    "HALT": "X25",
57}
58
59directive = (".ORIG", ".FILL", ".STRINGZ", ".BLKW", ".END")
60
61reserved = (
62    list(register)
63    + list(load_store)
64    + list(arithmetic)
65    + list(branch)
66    + list(function)
67    + list(service_routine)
68)
69
70
71def get_next_line(f):
72    global line_num
73    temp = ""
74    while not temp:
75        line_num += 1
76        raw = f.readline()
77        if not raw:
78            return None
79        temp = raw.split(";")[0].strip()
80        const_str = ""
81        if '"' in temp:
82            const_str = temp.split('"')[-2]
83            temp = temp.split('"')[0]
84        temp = temp.replace(",", " ").upper().split()
85        if const_str:
86            temp += [const_str]
87    return temp
88
89
90def error(e):
91    global line_num
92    print("Error at line " + str(line_num) + ": " + e + ".")
93    sys.exit()
94
95
96def parse_constant(c, limit=16):
97    value = 0
98    if c[0] == "X":
99        try:
100            value = int(c[1:], 16)
101        except ValueError:
102            error("Invalid hex constant")
103    else:
104        try:
105            value = int(c.replace("#", ""))
106        except ValueError:
107            error("Invalid constant")
108    if value < 2 ** limit:
109        return value
110    error('Constant "' + c + "\" doesn't fit in " + str(limit) + " bits")
111
112
113def valid_label(s):
114    if s[0] not in "0123456789" and s.replace("_", "").isalnum():
115        return s not in reserved
116    return False
117
118
119def generate_symbol_table(f):
120    current = get_next_line(f)
121    if not current:
122        error("No code found in file")
123    elif current[0] != ".ORIG":
124        error(".ORIG required at beginning of file")
125
126    current_address = parse_constant(current[1])
127
128    while True:
129        current = get_next_line(f)
130        if current[0] == ".END":
131            break
132        if not current:
133            error(".END required at end of file")
134
135        if valid_label(current[0]):
136            if current[0] in symbol_table:
137                error("Symbol already defined")
138            symbol_table[current[0]] = current_address
139        if len(current) > 1 and current[-2] == ".BLKW":
140            current_address += parse_constant(current[-1])
141        elif len(current) > 1 and current[-2] == ".STRINGZ":
142            current_address += len(current[-1]) + 1
143        else:
144            current_address += 1
145
146
147def generate_register(r):
148    if r not in register:
149        error("Expected register, got " + r)
150    return register[r]
151
152
153def write_bin(s, outf):
154    # print(s, hex(int(s, 2)))
155    outf.write(bytes(chr(int(s[:8], 2)) + chr(int(s[8:], 2)), "utf-8"))
156
157
158def itob(value, bits=16):
159    if value < 0:
160        value = (1 << bits) + value
161    formatstr = "{:0%ib}" % bits
162    return formatstr.format(value)
163
164
165def generate_machine_code(inf, outf):
166    current = get_next_line(inf)
167    current_address = parse_constant(current[1])
168    write_bin(itob(current_address), outf)
169    while True:
170        current = get_next_line(inf)
171        if current[0] == ".END":
172            break
173
174        if current[0] in symbol_table:
175            del current[0]
176            if not current:
177                continue
178
179        instruction = ""
180
181        if current[0] in service_routine:
182            current = ["TRAP", service_routine[current[0]]]
183
184        if current[0] in arithmetic:
185            instruction = arithmetic[current[0]]
186            instruction += generate_register(current[1])
187            instruction += generate_register(current[2])
188            if current[0] == "NOT":
189                instruction += "111111"
190            else:
191                if current[3][0] in "0123456789X#":
192                    instruction += "1" + itob(parse_constant(current[3], 5), 5)
193                else:
194                    instruction += "000" + generate_register(current[3])
195        elif current[0] in branch:
196            instruction = "0000" + branch[current[0]]
197            if current[1] in symbol_table:
198                instruction += itob(symbol_table[current[1]] - current_address - 1, 9)
199            else:
200                instruction += itob(parse_constant(current[1], 9), 9)
201        elif current[0] in load_store:
202            instruction = load_store[current[0]]
203            instruction += generate_register(current[1])
204            if current[0][-1] == "R":
205                instruction += generate_register(current[2])
206                instruction += itob(parse_constant(current[3], 6), 6)
207            else:
208                if current[2] in symbol_table:
209                    instruction += itob(
210                        symbol_table[current[2]] - current_address - 1, 9
211                    )
212                else:
213                    instruction += itob(parse_constant(current[2], 9), 9)
214        elif current[0] in function:
215            instruction = function[current[0]]
216            if current[0] == "JSR":
217                if current[1] in symbol_table:
218                    instruction += itob(
219                        symbol_table[current[1]] - current_address - 1, 11
220                    )
221                else:
222                    instruction += itob(parse_constant(current[1], 11), 11)
223            elif current[0] in ("JMP", "JSRR"):
224                instruction += "000" + generate_register(current[1]) + "000000"
225            elif current[0] == "RET":
226                instruction += "000111000000"
227            elif current[0] == "RTI":
228                instruction += "000000000000"
229            elif current[0] == "TRAP":
230                instruction += "0000" + itob(parse_constant(current[1], 8), 8)
231        elif current[0] in directive:
232            if current[0] == ".FILL":
233                if current[1] in symbol_table:
234                    instruction = itob(symbol_table[current[1]])
235                else:
236                    instruction = itob(parse_constant(current[1]))
237            elif current[0] == ".BLKW":
238                for i in range(parse_constant(current[1]) - 1):
239                    write_bin("0000000000000000", outf)
240                    current_address += 1
241                instruction = "0000000000000000"
242            elif current[0] == ".STRINGZ":
243                for i in current[1]:
244                    write_bin("00000000" + itob(ord(i), 8), outf)
245                    current_address += 1
246                instruction = "0000000000000000"
247        else:
248            error('Unknown op code "' + current[0] + '"')
249
250        # print(str(current).ljust(30), hex(current_address))
251        write_bin(instruction, outf)
252        current_address += 1
253
254
255def assemble(f):
256    of = open(sys.argv[1].split(".")[0] + ".obj", "wb")
257    generate_symbol_table(f)
258    f.seek(0)
259    generate_machine_code(f, of)
260    of.close()
261
262
263if __name__ == "__main__":
264    f = None
265    if len(sys.argv) > 1:
266        try:
267            f = open(sys.argv[1])
268        except Exception:
269            error("Couldn't find " + sys.argv[1])
270    else:
271        print("usage: assemble.py sourceFile.asm\n")
272        sys.exit()
273
274    assemble(f)
275    f.close()