# py2c.py - translates the instruction methods of BrickEmuPy's SPLB32 core (cores/SPLB32.py, CC0) into C. # python3 py2c.py > ../src/core/v3ops.inc # Each method becomes "static int op_XX(void)" on the state macros of v3cpu.c (A, X, Y, SP, PC, NF ... RD, WR). import re, sys, inspect sys.path.insert(0, sys.argv[1]) from cores.SPLB32 import SPLB32 src = open(sys.argv[1] + '/cores/SPLB32.py').read() t = src[src.index('self._execute = ('):src.index('def _get_rom_addr')] ops = [] for a, n, b in re.findall(r'\*\(\[SPLB32\.(_\w+)\] \* (\d+)\)|SPLB32\.(_\w+)', t): ops += [a] * int(n) if a else [b] assert len(ops) == 256 def expr(e): e = e.strip() e = re.sub(r'(? 0', r'(((\1) & \2) > 0)', e) e = re.sub(r'\bnot\s*\(', '!(', e) e = re.sub(r'\bnot\s+([\w.]+)', r'!(\1)', e) e = e.replace(' and ', ' && ').replace(' or ', ' || ') return e out = [] done = {} for i, name in enumerate(ops): if name == '_dummy' or name in done: continue lines = inspect.getsource(getattr(SPLB32, name)).split('\n')[1:] body = []; stack = [8] for l in lines: if not l.strip(): continue ind = len(l) - len(l.lstrip()); s = l.strip() while ind < stack[-1]: stack.pop(); body.append(' ' * (len(stack)) + '}') pre = ' ' * len(stack) m = re.match(r'(if|elif|while) \((.*)\):$', s) or re.match(r'(if|elif|while) (.*):$', s) if m: kw = {'if': 'if', 'elif': 'else if', 'while': 'while'}[m.group(1)] body.append(pre + '%s (%s) {' % (kw, expr(m.group(2)))); stack.append(ind + 4); continue if s == 'else:': body.append(pre + 'else {'); stack.append(ind + 4); continue m = re.match(r'return (.*)$', s) if m: body.append(pre + 'return (int)(%s);' % expr(m.group(1))); continue m = re.match(r'([\w.]+) *(\|=|\^=|&=|\+=|-=|=) *(.*)$', s) if m: lhs = expr(m.group(1)); rhs = expr(m.group(3)) if lhs in ('zp', 'addr', 'base', 'new_value', 'prev_value', 'test_value', 'm', 'rel', 'prev_PC', 'pc', 'opcode', 'value') and m.group(2) == '=' and lhs not in done.get('_vars_' + name, set()): done.setdefault('_vars_' + name, set()).add(lhs) body.append(pre + 'int %s = %s;' % (lhs, rhs)) else: body.append(pre + '%s %s %s;' % (lhs, m.group(2), rhs)) continue body.append(pre + expr(s) + ';') while len(stack) > 1: stack.pop(); body.append(' ' * len(stack) + '}') done[name] = 1 out.append('static int op%s(void)\n{\n%s\n}' % (name, '\n'.join(body))) print('/* generated by v3/gen/py2c.py from BrickEmuPy cores/SPLB32.py (azya52, CC0) */') print('\n'.join(out)) print('static int (*const v3_op[256])(void) = {') print(',\n'.join(' ' + ('op_dummy' if n == '_dummy' else 'op' + n) for n in ops)) print('};')