+/lc3tools
git clone https://git.julia.blue/+/lc3tools
4e1c082
master
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 = ( 62list (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 ): 72global line_num 73temp = "" 74while not temp : 75line_num += 1 76raw = f .readline () 77if not raw : 78return None 79temp = raw .split (";" )[0 ].strip () 80const_str = "" 81if '"' in temp : 82const_str = temp .split ('"' )[- 2 ] 83temp = temp .split ('"' )[0 ] 84temp = temp .replace ("," ," " ).upper ().split () 85if const_str : 86temp += [const_str ] 87return temp 88 89 90def error (e ): 91global line_num 92"Error at line " + str (line_num )+ ": " + e + "." ) 93sys .exit () 94 95 96def parse_constant (c ,limit = 16 ): 97value = 0 98if c [0 ]== "X" : 99try : 100value = int (c [1 :],16 ) 101except ValueError : 102error ("Invalid hex constant" ) 103else : 104try : 105value = int (c .replace ("#" ,"" )) 106except ValueError : 107error ("Invalid constant" ) 108if value < 2 ** limit : 109return value 110error ('Constant "' + c + "\" doesn't fit in " + str (limit )+ " bits" ) 111 112 113def valid_label (s ): 114if s [0 ]not in "0123456789" and s .replace ("_" ,"" ).isalnum (): 115return s not in reserved 116return False 117 118 119def generate_symbol_table (f ): 120current = get_next_line (f ) 121if not current : 122error ("No code found in file" ) 123elif current [0 ]!= ".ORIG" : 124error (".ORIG required at beginning of file" ) 125 126current_address = parse_constant (current [1 ]) 127 128while True : 129current = get_next_line (f ) 130if current [0 ]== ".END" : 131break 132if not current : 133error (".END required at end of file" ) 134 135if valid_label (current [0 ]): 136if current [0 ]in symbol_table : 137error ("Symbol already defined" ) 138symbol_table [current [0 ]]= current_address 139if len (current )> 1 and current [- 2 ]== ".BLKW" : 140current_address += parse_constant (current [- 1 ]) 141elif len (current )> 1 and current [- 2 ]== ".STRINGZ" : 142current_address += len (current [- 1 ])+ 1 143else : 144current_address += 1 145 146 147def generate_register (r ): 148if r not in register : 149error ("Expected register, got " + r ) 150return register [r ] 151 152 153def write_bin (s ,outf ): 154# print(s, hex(int(s, 2))) 155outf .write (bytes (chr (int (s [:8 ],2 ))+ chr (int (s [8 :],2 )),"utf-8" )) 156 157 158def itob (value ,bits = 16 ): 159if value < 0 : 160value = (1 << bits )+ value 161formatstr = "{:0%ib}" % bits 162return formatstr .format (value ) 163 164 165def generate_machine_code (inf ,outf ): 166current = get_next_line (inf ) 167current_address = parse_constant (current [1 ]) 168write_bin (itob (current_address ),outf ) 169while True : 170current = get_next_line (inf ) 171if current [0 ]== ".END" : 172break 173 174if current [0 ]in symbol_table : 175del current [0 ] 176if not current : 177continue 178 179instruction = "" 180 181if current [0 ]in service_routine : 182current = ["TRAP" ,service_routine [current [0 ]]] 183 184if current [0 ]in arithmetic : 185instruction = arithmetic [current [0 ]] 186instruction += generate_register (current [1 ]) 187instruction += generate_register (current [2 ]) 188if current [0 ]== "NOT" : 189instruction += "111111" 190else : 191if current [3 ][0 ]in "0123456789X#" : 192instruction += "1" + itob (parse_constant (current [3 ],5 ),5 ) 193else : 194instruction += "000" + generate_register (current [3 ]) 195elif current [0 ]in branch : 196instruction = "0000" + branch [current [0 ]] 197if current [1 ]in symbol_table : 198instruction += itob (symbol_table [current [1 ]]- current_address - 1 ,9 ) 199else : 200instruction += itob (parse_constant (current [1 ],9 ),9 ) 201elif current [0 ]in load_store : 202instruction = load_store [current [0 ]] 203instruction += generate_register (current [1 ]) 204if current [0 ][- 1 ]== "R" : 205instruction += generate_register (current [2 ]) 206instruction += itob (parse_constant (current [3 ],6 ),6 ) 207else : 208if current [2 ]in symbol_table : 209instruction += itob ( 210symbol_table [current [2 ]]- current_address - 1 ,9 211 ) 212else : 213instruction += itob (parse_constant (current [2 ],9 ),9 ) 214elif current [0 ]in function : 215instruction = function [current [0 ]] 216if current [0 ]== "JSR" : 217if current [1 ]in symbol_table : 218instruction += itob ( 219symbol_table [current [1 ]]- current_address - 1 ,11 220 ) 221else : 222instruction += itob (parse_constant (current [1 ],11 ),11 ) 223elif current [0 ]in ("JMP" ,"JSRR" ): 224instruction += "000" + generate_register (current [1 ])+ "000000" 225elif current [0 ]== "RET" : 226instruction += "000111000000" 227elif current [0 ]== "RTI" : 228instruction += "000000000000" 229elif current [0 ]== "TRAP" : 230instruction += "0000" + itob (parse_constant (current [1 ],8 ),8 ) 231elif current [0 ]in directive : 232if current [0 ]== ".FILL" : 233if current [1 ]in symbol_table : 234instruction = itob (symbol_table [current [1 ]]) 235else : 236instruction = itob (parse_constant (current [1 ])) 237elif current [0 ]== ".BLKW" : 238for i in range (parse_constant (current [1 ])- 1 ): 239write_bin ("0000000000000000" ,outf ) 240current_address += 1 241instruction = "0000000000000000" 242elif current [0 ]== ".STRINGZ" : 243for i in current [1 ]: 244write_bin ("00000000" + itob (ord (i ),8 ),outf ) 245current_address += 1 246instruction = "0000000000000000" 247else : 248error ('Unknown op code "' + current [0 ]+ '"' ) 249 250# print(str(current).ljust(30), hex(current_address)) 251write_bin (instruction ,outf ) 252current_address += 1 253 254 255def assemble (f ): 256of = open (sys .argv [1 ].split ("." )[0 ]+ ".obj" ,"wb" ) 257generate_symbol_table (f ) 258f .seek (0 ) 259generate_machine_code (f ,of ) 260of .close () 261 262 263if __name__ == "__main__" : 264f = None 265if len (sys .argv )> 1 : 266try : 267f = open (sys .argv [1 ]) 268except Exception : 269error ("Couldn't find " + sys .argv [1 ]) 270else : 271"usage: assemble.py sourceFile.asm\n" ) 272sys .exit () 273 274assemble (f ) 275f .close ()