asm_compiler.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. #!/usr/bin/python3
  2. import sys
  3. import argparse
  4. from os import path
  5. def decode_byte(val: str):
  6. try:
  7. if val.endswith('h'):
  8. return int(val[:-1], 16)
  9. if val.startswith('0x'):
  10. return int(val[2:], 16)
  11. if val.startswith('b'):
  12. return int(val.replace('_', '')[1:], 2)
  13. except ValueError:
  14. raise ValueError(f"Invalid binary '{val}'")
  15. if val.isdigit():
  16. i = int(val)
  17. if i > 255 or i < 0:
  18. raise ValueError(f"Invalid binary '{val}', unsigned int out of bounds")
  19. return i
  20. if (val.startswith('+') or val.startswith('-')) and val[1:].isdigit():
  21. i = int(val)
  22. if i > 127 or i < -128:
  23. raise ValueError(f"Invalid binary '{val}', signed int out of bounds")
  24. if i < 0: # convert to unsigned
  25. i += 2**8
  26. return i
  27. if len(val) == 3 and ((val[0] == "'" and val[2] == "'") or (val[0] == '"' and val[2] == '"')):
  28. return ord(val[1])
  29. raise ValueError(f"Invalid binary '{val}'")
  30. def is_reg(r):
  31. if r.startswith('$'):
  32. r = r[1:]
  33. return len(r) == 2 and (r == 'ra' or r == 'rb' or r == 'rc' or r == 're')
  34. def decode_reg(r):
  35. rl = r.lower()
  36. if rl.startswith('$'):
  37. rl = rl[1:]
  38. if rl == 'ra':
  39. return 0
  40. if rl == 'rb':
  41. return 1
  42. if rl == 'rc':
  43. return 2
  44. if rl == 're':
  45. return 3
  46. raise ValueError(f"Invalid register name '{r}'")
  47. def assemble(file):
  48. odata = []
  49. afile = open(file, 'r')
  50. failed = False
  51. refs = dict()
  52. for lnum, line in enumerate(afile.readlines()):
  53. lnum += 1 # Line numbers start from 1, not 0
  54. if '//' in line:
  55. line = line[:line.index('//')]
  56. if ':' in line:
  57. rsplit = line.split(':', 1)
  58. ref = rsplit[0]
  59. if not ref.isalnum():
  60. print(f"{file}:{lnum}: Invalid pointer reference '{ref}'")
  61. failed = True
  62. continue
  63. if ref in refs:
  64. print(f"{file}:{lnum}: Pointer reference '{ref}' is duplicated with {file}:{refs[ref][0]}")
  65. failed = True
  66. continue
  67. refs[ref] = [lnum, len(odata)]
  68. line = rsplit[1]
  69. line = line.replace('\n', '').replace('\r', '').replace('\t', '')
  70. line = line.strip(' ')
  71. if line == '':
  72. continue
  73. ops = line.split()
  74. instr = ops[0].upper()
  75. rops = 3
  76. if instr == 'CPY' or instr == 'COPY':
  77. iname = 'COPY'
  78. inibb = 0
  79. elif instr == 'ADD':
  80. iname = 'ADD'
  81. inibb = 1
  82. elif instr == 'SUB':
  83. iname = 'SUB'
  84. inibb = 2
  85. elif instr == 'AND':
  86. iname = 'AND'
  87. inibb = 3
  88. elif instr == 'OR':
  89. iname = 'OR'
  90. inibb = 4
  91. elif instr == 'XOR':
  92. iname = 'XOR'
  93. inibb = 5
  94. elif instr == 'GT' or instr == 'GRT':
  95. iname = 'GT'
  96. inibb = 6
  97. elif instr == 'EX' or instr == 'EXT':
  98. iname = 'EXT'
  99. inibb = 7
  100. elif instr == 'LW':
  101. iname = 'LW'
  102. inibb = 8
  103. elif instr == 'SW':
  104. iname = 'SW'
  105. inibb = 9
  106. elif instr == 'JEQ':
  107. iname = 'JEQ'
  108. rops = 4
  109. inibb = 10
  110. elif instr == 'JMP' or instr == 'JUMP':
  111. iname = 'JUMP'
  112. rops = 2
  113. inibb = 11
  114. else:
  115. if len(ops) == 1:
  116. try:
  117. odata.append(decode_byte(ops[0]))
  118. continue
  119. except ValueError:
  120. pass
  121. print(f"{file}:{lnum}: Instruction '{ops[0]}' not recognised")
  122. failed = True
  123. continue
  124. if len(ops) != rops:
  125. print(f"{file}:{lnum}: {iname} instruction requires {rops - 1} arguments")
  126. failed = True
  127. continue
  128. try:
  129. if iname == 'JUMP':
  130. odata.append(inibb << 4)
  131. try:
  132. odata.append(decode_byte(ops[1]))
  133. except ValueError:
  134. if not ops[1].isalnum():
  135. print(f"{file}:{lnum}: Invalid pointer reference '{ops[1]}'")
  136. failed = True
  137. continue
  138. if ops[1] in refs:
  139. odata.append(refs[ops[1]][1])
  140. else:
  141. refs[ops[1]] = [lnum, None]
  142. odata.append(ops[1])
  143. continue
  144. rd = decode_reg(ops[1])
  145. if iname == 'COPY' and not is_reg(ops[2]):
  146. imm = decode_byte(ops[2])
  147. odata.append((inibb << 4) | (rd << 2) | rd)
  148. odata.append(int(imm))
  149. continue
  150. rs = decode_reg(ops[2])
  151. if iname == 'COPY' and rd == rs:
  152. print(f"{file}:{lnum}: {iname} cannot copy register to itself")
  153. failed = True
  154. continue
  155. odata.append((inibb << 4) | (rd << 2) | rs)
  156. if iname == 'JEQ':
  157. try:
  158. odata.append(decode_byte(ops[3]))
  159. except ValueError:
  160. if not ops[3].isalnum():
  161. print(f"{file}:{lnum}: Invalid pointer reference '{ops[3]}'")
  162. failed = True
  163. continue
  164. if ops[3] in refs:
  165. odata.append(refs[ops[3]][1])
  166. else:
  167. refs[ops[3]] = [lnum, None]
  168. odata.append(ops[3])
  169. continue
  170. except ValueError as e:
  171. print(f"{file}:{lnum}: {e}")
  172. failed = True
  173. continue
  174. afile.close()
  175. # Convert jumps
  176. for i, l in enumerate(odata):
  177. if isinstance(l, str):
  178. if refs[l][1] is None:
  179. print(f"{file}:{refs[l][0]}: Pointer reference '{l}' does not exist!")
  180. failed = True
  181. continue
  182. odata[i] = refs[l][1]
  183. return not failed, odata
  184. if __name__ == '__main__':
  185. parser = argparse.ArgumentParser(description='Assembly compiler', add_help=True)
  186. parser.add_argument('file', help='Files to compile')
  187. parser.add_argument('-t', '--output_type', choices=['bin', 'mem', 'binary'], default='mem', help='Output type')
  188. parser.add_argument('-o', '--output', help='Output file')
  189. parser.add_argument('-f', '--force', action='store_true', help='Force override output file')
  190. args = parser.parse_args(sys.argv[1:])
  191. if not path.isfile(args.file):
  192. print(f'No file {args.file}!')
  193. sys.exit(1)
  194. output = args.output
  195. if not output:
  196. opath = path.dirname(args.file)
  197. bname = path.basename(args.file).rsplit('.', 1)[0]
  198. ext = '.out'
  199. if args.output_type == 'mem':
  200. ext = '.mem'
  201. elif args.output_type == 'bin':
  202. ext = '.bin'
  203. output = path.join(opath, bname + ext)
  204. if not args.force and path.isfile(output):
  205. print(f'Output file already exists {output}!')
  206. sys.exit(1)
  207. success, data = assemble(args.file)
  208. if success:
  209. print(f"Saving {args.output_type} data to {output}")
  210. with open(output, 'wb') as of:
  211. if args.output_type == 'binary':
  212. a = '\n'.join([format(i, '08b') for i in data])
  213. of.write(a.encode())
  214. elif args.output_type == 'mem':
  215. a = [format(i, '02x') for i in data]
  216. for i in range(int(len(a)/8)+1):
  217. of.write((' '.join(a[i*8:(i+1)*8]) + '\n').encode())
  218. elif args.output_type == 'bin':
  219. of.write(bytes(data))
  220. else:
  221. print(f'Failed to compile {args.file}!')
  222. sys.exit(1)
  223. sys.exit(0)