#!/usr/bin/env python3 import sys line_num = 0 symbol_table = {} register = { "R0": "000", "R1": "001", "R2": "010", "R3": "011", "R4": "100", "R5": "101", "R6": "110", "R7": "111", } load_store = { "LD": "0010", "LDR": "0110", "LDI": "1010", "ST": "0011", "STR": "0111", "STI": "1011", "LEA": "1110", } arithmetic = {"ADD": "0001", "AND": "0101", "NOT": "1001"} branch = { "BR": "111", "BRN": "100", "BRZ": "010", "BRP": "001", "BRNZ": "110", "BRNP": "101", "BRZP": "011", "BRNZP": "111", } function = { "JSR": "01001", "JSRR": "0100", "TRAP": "1111", "RTI": "1000", "JMP": "1100", "RET": "1100", } service_routine = { "GETC": "X20", "OUT": "X21", "PUTS": "X22", "IN": "X23", "PUTSP": "X24", "HALT": "X25", } directive = (".ORIG", ".FILL", ".STRINGZ", ".BLKW", ".END") reserved = ( list(register) + list(load_store) + list(arithmetic) + list(branch) + list(function) + list(service_routine) ) def get_next_line(f): global line_num temp = "" while not temp: line_num += 1 raw = f.readline() if not raw: return None temp = raw.split(";")[0].strip() const_str = "" if '"' in temp: const_str = temp.split('"')[-2] temp = temp.split('"')[0] temp = temp.replace(",", " ").upper().split() if const_str: temp += [const_str] return temp def error(e): global line_num print("Error at line " + str(line_num) + ": " + e + ".") sys.exit() def parse_constant(c, limit=16): value = 0 if c[0] == "X": try: value = int(c[1:], 16) except ValueError: error("Invalid hex constant") else: try: value = int(c.replace("#", "")) except ValueError: error("Invalid constant") if value < 2 ** limit: return value error('Constant "' + c + "\" doesn't fit in " + str(limit) + " bits") def valid_label(s): if s[0] not in "0123456789" and s.replace("_", "").isalnum(): return s not in reserved return False def generate_symbol_table(f): current = get_next_line(f) if not current: error("No code found in file") elif current[0] != ".ORIG": error(".ORIG required at beginning of file") current_address = parse_constant(current[1]) while True: current = get_next_line(f) if current[0] == ".END": break if not current: error(".END required at end of file") if valid_label(current[0]): if current[0] in symbol_table: error("Symbol already defined") symbol_table[current[0]] = current_address if len(current) > 1 and current[-2] == ".BLKW": current_address += parse_constant(current[-1]) elif len(current) > 1 and current[-2] == ".STRINGZ": current_address += len(current[-1]) + 1 else: current_address += 1 def generate_register(r): if r not in register: error("Expected register, got " + r) return register[r] def write_bin(s, outf): # print(s, hex(int(s, 2))) outf.write(bytes(chr(int(s[:8], 2)) + chr(int(s[8:], 2)), "utf-8")) def itob(value, bits=16): if value < 0: value = (1 << bits) + value formatstr = "{:0%ib}" % bits return formatstr.format(value) def generate_machine_code(inf, outf): current = get_next_line(inf) current_address = parse_constant(current[1]) write_bin(itob(current_address), outf) while True: current = get_next_line(inf) if current[0] == ".END": break if current[0] in symbol_table: del current[0] if not current: continue instruction = "" if current[0] in service_routine: current = ["TRAP", service_routine[current[0]]] if current[0] in arithmetic: instruction = arithmetic[current[0]] instruction += generate_register(current[1]) instruction += generate_register(current[2]) if current[0] == "NOT": instruction += "111111" else: if current[3][0] in "0123456789X#": instruction += "1" + itob(parse_constant(current[3], 5), 5) else: instruction += "000" + generate_register(current[3]) elif current[0] in branch: instruction = "0000" + branch[current[0]] if current[1] in symbol_table: instruction += itob(symbol_table[current[1]] - current_address - 1, 9) else: instruction += itob(parse_constant(current[1], 9), 9) elif current[0] in load_store: instruction = load_store[current[0]] instruction += generate_register(current[1]) if current[0][-1] == "R": instruction += generate_register(current[2]) instruction += itob(parse_constant(current[3], 6), 6) else: if current[2] in symbol_table: instruction += itob( symbol_table[current[2]] - current_address - 1, 9 ) else: instruction += itob(parse_constant(current[2], 9), 9) elif current[0] in function: instruction = function[current[0]] if current[0] == "JSR": if current[1] in symbol_table: instruction += itob( symbol_table[current[1]] - current_address - 1, 11 ) else: instruction += itob(parse_constant(current[1], 11), 11) elif current[0] in ("JMP", "JSRR"): instruction += "000" + generate_register(current[1]) + "000000" elif current[0] == "RET": instruction += "000111000000" elif current[0] == "RTI": instruction += "000000000000" elif current[0] == "TRAP": instruction += "0000" + itob(parse_constant(current[1], 8), 8) elif current[0] in directive: if current[0] == ".FILL": if current[1] in symbol_table: instruction = itob(symbol_table[current[1]]) else: instruction = itob(parse_constant(current[1])) elif current[0] == ".BLKW": for i in range(parse_constant(current[1]) - 1): write_bin("0000000000000000", outf) current_address += 1 instruction = "0000000000000000" elif current[0] == ".STRINGZ": for i in current[1]: write_bin("00000000" + itob(ord(i), 8), outf) current_address += 1 instruction = "0000000000000000" else: error('Unknown op code "' + current[0] + '"') # print(str(current).ljust(30), hex(current_address)) write_bin(instruction, outf) current_address += 1 def assemble(f): of = open(sys.argv[1].split(".")[0] + ".obj", "wb") generate_symbol_table(f) f.seek(0) generate_machine_code(f, of) of.close() if __name__ == "__main__": f = None if len(sys.argv) > 1: try: f = open(sys.argv[1]) except Exception: error("Couldn't find " + sys.argv[1]) else: print("usage: assemble.py sourceFile.asm\n") sys.exit() assemble(f) f.close()