An emulator, assembler, and disassembler for the Sega Game Gear
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

412 lines
14 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright (C) 2014-2015 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. # Released under the terms of the MIT License. See LICENSE for details.
  5. """
  6. This script generates 'src/assembler/instructions.inc.c' from
  7. 'src/assembler/instructions.yml'. It should be run automatically by make
  8. when the latter is modified, but can also be run manually.
  9. """
  10. from __future__ import print_function
  11. from itertools import product
  12. import re
  13. import time
  14. SOURCE = "src/assembler/instructions.yml"
  15. DEST = "src/assembler/instructions.inc.c"
  16. ENCODING = "utf8"
  17. TAB = " " * 4
  18. try:
  19. import yaml
  20. except ImportError:
  21. print("Error: PyYAML is required (https://pypi.python.org/pypi/PyYAML)\n"
  22. "If you don't want to rebuild {0}, do:\n`make -t {0}`".format(DEST))
  23. exit(1)
  24. re_date = re.compile(r"^(\s*@AUTOGEN_DATE\s*)(.*?)$", re.M)
  25. re_inst = re.compile(
  26. r"(/\* @AUTOGEN_INST_BLOCK_START \*/\n*)(.*?)"
  27. r"(\n*/\* @AUTOGEN_INST_BLOCK_END \*/)", re.S)
  28. re_lookup = re.compile(
  29. r"(/\* @AUTOGEN_LOOKUP_BLOCK_START \*/\n*)(.*?)"
  30. r"(\n*/\* @AUTOGEN_LOOKUP_BLOCK_END \*/)", re.S)
  31. class Instruction(object):
  32. """
  33. Represent a single ASM instruction mnemonic.
  34. """
  35. ARG_TYPES = {
  36. "register": "AT_REGISTER",
  37. "immediate": "AT_IMMEDIATE",
  38. "indirect": "AT_INDIRECT",
  39. "indexed": "AT_INDEXED",
  40. "condition": "AT_CONDITION",
  41. "port": "AT_PORT"
  42. }
  43. PSEUDO_TYPES = {
  44. "indirect_hl_or_indexed": ["AT_INDIRECT", "AT_INDEXED"]
  45. }
  46. def __init__(self, name, data):
  47. self._name = name
  48. self._data = data
  49. self._has_optional_args = False
  50. def _get_arg_parse_mask(self, num):
  51. """
  52. Return the appropriate mask to parse_args() for the num-th argument.
  53. """
  54. types = set()
  55. optional = False
  56. for case in self._data["cases"]:
  57. if num < len(case["type"]):
  58. atype = case["type"][num]
  59. if atype in self.ARG_TYPES:
  60. types.add(self.ARG_TYPES[atype])
  61. else:
  62. types.update(self.PSEUDO_TYPES[atype])
  63. else:
  64. optional = True
  65. if not types:
  66. return "AT_NONE"
  67. if optional:
  68. types.add("AT_OPTIONAL")
  69. self._has_optional_args = True
  70. return "|".join(sorted(types))
  71. def _handle_return(self, ret, indent=1):
  72. """
  73. Return code to handle an instruction return statement.
  74. """
  75. data = ", ".join("0x%02X" % byte if isinstance(byte, int) else byte
  76. for byte in ret)
  77. return TAB * indent + "INST_RETURN({0}, {1})".format(len(ret), data)
  78. def _build_case_type_check(self, args):
  79. """
  80. Return the test part of an if statement for an instruction case.
  81. """
  82. conds = ["INST_TYPE({0}) == {1}".format(i, self.ARG_TYPES[cond])
  83. for i, cond in enumerate(args)]
  84. check = " && ".join(conds)
  85. if self._has_optional_args:
  86. return "INST_NARGS == {0} && ".format(len(args)) + check
  87. return check
  88. def _build_register_check(self, num, cond):
  89. """
  90. Return an expression to check for a particular register value.
  91. """
  92. return "INST_REG({0}) == REG_{1}".format(num, cond.upper())
  93. def _build_immediate_check(self, num, cond):
  94. """
  95. Return an expression to check for a particular immediate value.
  96. """
  97. if "." in cond:
  98. itype, value = cond.split(".", 1)
  99. try:
  100. value = int(value)
  101. except ValueError:
  102. value = int(value, 16)
  103. vtype = "sval" if itype.upper() in ["S8", "REL"] else "uval"
  104. test1 = "INST_IMM({0}).mask & IMM_{1}".format(num, itype.upper())
  105. if (itype.upper() == "U16"):
  106. test1 += " && !INST_IMM({0}).is_label".format(num)
  107. test2 = "INST_IMM({0}).{1} == {2}".format(num, vtype, value)
  108. return "({0} && {1})".format(test1, test2)
  109. return "INST_IMM({0}).mask & IMM_{1}".format(num, cond.upper())
  110. def _build_indirect_check(self, num, cond):
  111. """
  112. Return an expression to check for a particular indirect value.
  113. """
  114. if cond.startswith("reg."):
  115. test1 = "INST_INDIRECT({0}).type == AT_REGISTER".format(num)
  116. test2 = "INST_INDIRECT({0}).addr.reg == REG_{1}".format(
  117. num, cond[len("reg."):].upper())
  118. return "({0} && {1})".format(test1, test2)
  119. if cond == "imm" or cond == "immediate":
  120. return "INST_INDIRECT({0}).type == AT_IMMEDIATE".format(num)
  121. err = "Unknown condition for indirect argument: {0}"
  122. return RuntimeError(err.format(cond))
  123. def _build_indexed_check(self, num, cond):
  124. """
  125. Return an expression to check for a particular indexed value.
  126. """
  127. raise RuntimeError("The indexed arg type does not support conditions")
  128. def _build_condition_check(self, num, cond):
  129. """
  130. Return an expression to check for a particular condition value.
  131. """
  132. return "INST_COND({0}) == COND_{1}".format(num, cond.upper())
  133. def _build_port_check(self, num, cond):
  134. """
  135. Return an expression to check for a particular port value.
  136. """
  137. if cond == "reg" or cond == "reg.c":
  138. return "INST_PORT({0}).type == AT_REGISTER".format(num)
  139. if cond == "imm" or cond == "immediate":
  140. return "INST_PORT({0}).type == AT_IMMEDIATE".format(num)
  141. err = "Unknown condition for port argument: {0}"
  142. return RuntimeError(err.format(cond))
  143. _SUBCASE_LOOKUP_TABLE = {
  144. "register": _build_register_check,
  145. "immediate": _build_immediate_check,
  146. "indirect": _build_indirect_check,
  147. "indexed": _build_indexed_check,
  148. "condition": _build_condition_check,
  149. "port": _build_port_check
  150. }
  151. def _build_subcase_check(self, types, conds):
  152. """
  153. Return the test part of an if statement for an instruction subcase.
  154. """
  155. conds = [self._SUBCASE_LOOKUP_TABLE[types[i]](self, i, cond)
  156. for i, cond in enumerate(conds) if cond != "_"]
  157. return " && ".join(conds)
  158. def _iter_permutations(self, types, conds):
  159. """
  160. Iterate over all permutations of the given subcase conditions.
  161. """
  162. def split(typ, cond):
  163. if "|" in cond:
  164. splits = [split(typ, c) for c in cond.split("|")]
  165. merged = [choice for s in splits for choice in s]
  166. if len(merged) != len(set(merged)):
  167. msg = "Repeated conditions for {0}: {1}"
  168. raise RuntimeError(msg.format(typ, cond))
  169. return merged
  170. if typ == "register":
  171. if cond == "i":
  172. return ["ix", "iy"]
  173. if cond == "ih":
  174. return ["ixh", "iyh"]
  175. if cond == "il":
  176. return ["ixl", "iyl"]
  177. return [cond]
  178. splits = [split(typ, cond) for typ, cond in zip(types, conds)]
  179. num = max(len(cond) for cond in splits)
  180. if any(1 < len(cond) < num for cond in splits):
  181. msg = "Invalid condition permutations: {0}"
  182. raise RuntimeError(msg.format(conds))
  183. choices = [cond * num if len(cond) == 1 else cond for cond in splits]
  184. return zip(*choices)
  185. def _adapt_return(self, types, conds, ret):
  186. """
  187. Return a modified byte list to accomodate for prefixes and immediates.
  188. """
  189. ret = ret[:]
  190. for i, byte in enumerate(ret):
  191. if not isinstance(byte, int):
  192. if byte == "u8":
  193. try:
  194. index = types.index("immediate")
  195. imm = "INST_IMM({0})".format(index)
  196. except ValueError:
  197. index = types.index("port")
  198. imm = "INST_PORT({0}).port.imm".format(index)
  199. ret[i] = imm + ".uval"
  200. elif byte == "u16":
  201. if i < len(ret) - 1:
  202. raise RuntimeError("U16 return byte must be last")
  203. try:
  204. index = types.index("immediate")
  205. imm = "INST_IMM({0})".format(index)
  206. except ValueError:
  207. indir = types.index("indirect")
  208. if not conds[indir].startswith("imm"):
  209. msg = "Passing non-immediate indirect as immediate"
  210. raise RuntimeError(msg)
  211. imm = "INST_INDIRECT({0}).addr.imm".format(indir)
  212. ret[i] = "INST_IMM_U16_B1({0})".format(imm)
  213. ret.append("INST_IMM_U16_B2({0})".format(imm))
  214. break
  215. elif byte == "rel":
  216. index = types.index("immediate")
  217. ret[i] = "INST_IMM({0}).sval - 2".format(index)
  218. elif byte.startswith("bit(") and byte.endswith(")"):
  219. index = types.index("immediate")
  220. off = byte[4:-1]
  221. ret[i] = "{0} + 8 * INST_IMM({1}).uval".format(off, index)
  222. else:
  223. msg = "Unsupported return byte: {0}"
  224. raise RuntimeError(msg.format(byte))
  225. for i, cond in enumerate(conds):
  226. if types[i] == "register" and cond[0] == "i":
  227. prefix = "INST_I{0}_PREFIX".format(cond[1].upper())
  228. if ret[0] != prefix:
  229. ret.insert(0, prefix)
  230. elif types[i] == "indexed":
  231. ret.insert(0, "INST_INDEX_PREFIX({0})".format(i))
  232. ret.insert(2, "INST_INDEX({0}).offset".format(i))
  233. return ret
  234. def _handle_null_case(self, case):
  235. """
  236. Return code to handle an instruction case that takes no arguments.
  237. """
  238. return [
  239. TAB + "if (INST_NARGS == 0) {",
  240. self._handle_return(case["return"], 2),
  241. TAB + "}"
  242. ]
  243. def _handle_pseudo_case(self, pseudo, case):
  244. """
  245. Return code to handle an instruction pseudo-case.
  246. Pseudo-cases are cases that have pseudo-types as arguments. This means
  247. they are expanded to cover multiple "real" argument types.
  248. """
  249. index = case["type"].index(pseudo)
  250. if pseudo == "indirect_hl_or_indexed":
  251. case["type"][index] = "indexed"
  252. indexed = self._handle_case(case)
  253. case["type"][index] = "indirect"
  254. indirect = self._handle_case(case)
  255. base_cond = self._build_case_type_check(case["type"])
  256. hl_reg = TAB * 3 + self._build_indirect_check(index, "reg.hl")
  257. indirect[0] = TAB + "if ({0} &&\n{1}) {{".format(base_cond, hl_reg)
  258. return indirect + indexed
  259. raise RuntimeError("Unknown pseudo-type: {0}".format(pseudo))
  260. def _handle_case(self, case):
  261. """
  262. Return code to handle an instruction case.
  263. """
  264. ctype = case["type"]
  265. if not ctype:
  266. return self._handle_null_case(case)
  267. for pseudo in self.PSEUDO_TYPES:
  268. if pseudo in ctype:
  269. return self._handle_pseudo_case(pseudo, case)
  270. lines = []
  271. cond = self._build_case_type_check(ctype)
  272. lines.append(TAB + "if ({0}) {{".format(cond))
  273. subcases = [(perm, sub["return"]) for sub in case["cases"]
  274. for perm in self._iter_permutations(ctype, sub["cond"])]
  275. for cond, ret in subcases:
  276. check = self._build_subcase_check(ctype, cond)
  277. ret = self._adapt_return(ctype, cond, ret)
  278. if check:
  279. lines.append(TAB * 2 + "if ({0})".format(check))
  280. lines.append(self._handle_return(ret, 3))
  281. else:
  282. lines.append(self._handle_return(ret, 2))
  283. break # Unconditional subcase
  284. else:
  285. lines.append(TAB * 2 + "INST_ERROR(ARG_VALUE)")
  286. lines.append(TAB + "}")
  287. return lines
  288. def render(self):
  289. """
  290. Convert data for an individual instruction into a C parse function.
  291. """
  292. lines = []
  293. if self._data["args"]:
  294. lines.append("{tab}INST_TAKES_ARGS(\n{tab2}{0},\n{tab2}{1},"
  295. "\n{tab2}{2}\n{tab})".format(
  296. self._get_arg_parse_mask(0), self._get_arg_parse_mask(1),
  297. self._get_arg_parse_mask(2), tab=TAB, tab2=TAB * 2))
  298. else:
  299. lines.append(TAB + "INST_TAKES_NO_ARGS")
  300. if "return" in self._data:
  301. lines.append(self._handle_return(self._data["return"]))
  302. elif "cases" in self._data:
  303. for case in self._data["cases"]:
  304. lines.extend(self._handle_case(case))
  305. lines.append(TAB + "INST_ERROR(ARG_TYPE)")
  306. else:
  307. msg = "Missing return or case block for {0} instruction"
  308. raise RuntimeError(msg.format(self._name))
  309. contents = "\n".join(lines)
  310. return "INST_FUNC({0})\n{{\n{1}\n}}".format(self._name, contents)
  311. def build_inst_block(data):
  312. """
  313. Return the instruction parser block, given instruction data.
  314. """
  315. return "\n\n".join(
  316. Instruction(k, v).render() for k, v in sorted(data.items()))
  317. def build_lookup_block(data):
  318. """
  319. Return the instruction lookup block, given instruction data.
  320. """
  321. macro = TAB + "HANDLE({0})"
  322. return "\n".join(macro.format(inst) for inst in sorted(data.keys()))
  323. def process(template, data):
  324. """
  325. Return C code generated from a source template and instruction data.
  326. """
  327. inst_block = build_inst_block(data)
  328. lookup_block = build_lookup_block(data)
  329. date = time.asctime(time.gmtime())
  330. result = re_date.sub(r"\1{0} UTC".format(date), template)
  331. result = re_inst.sub(r"\1{0}\3".format(inst_block), result)
  332. result = re_lookup.sub(r"\1{0}\3".format(lookup_block), result)
  333. return result
  334. def main():
  335. """
  336. Main script entry point.
  337. """
  338. with open(SOURCE, "r") as fp:
  339. text = fp.read().decode(ENCODING)
  340. with open(DEST, "r") as fp:
  341. template = fp.read().decode(ENCODING)
  342. data = yaml.load(text)
  343. result = process(template, data)
  344. with open(DEST, "w") as fp:
  345. fp.write(result.encode(ENCODING))
  346. if __name__ == "__main__":
  347. main()