Files
isaac-port/scripts/locals_round.py
T
shweetandClaude Opus 5.5 24098479e7 ApplyProtos: read the purge from the RETs when Ghidra has none, trust db/ prototypes past that; log what it skips
Purge unknown 139 -> 11, prototypes applied 3032 -> 3163 (round 24's 12 included), param_N lines 33145 -> 31116,
in_ECX 35059 -> 32432; Room::Update/Render get a typed this. ApplyLocals: a same-name row with a type retypes in place,
and an unparseable type fails only its row. notes/decomp_issues.md collects what the round 23-24 agents found wrong.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 18:16:18 -05:00

106 lines
6.0 KiB
Python

# Agent rounds that name local variables (db/locals.tsv) and write prototypes (db/protos.zhl). Run from the repo root.
# locals_round.py pick <round> <min_left> <max_lines> [<prev_round>]
# <round>/all_snapshot.c must be a copy of dump/all.c. Writes <round>/l_<agent>.tsv: named game functions with at least
# <min_left> default-named locals, biggest backlog first, at most <max_lines> lines per agent. Functions whose
# prototypes <prev_round> wrote (and their callers) are skipped: they renumber once those prototypes are applied.
# So are <prev_round>'s own targets.
# locals_round.py locals <round> agents' l_out_*.tsv -> db/locals.tsv, checked against the snapshot (apply in the next build)
# locals_round.py protos <round> agents' lp_out_*.zhl -> db/protos.zhl (only AFTER the build that applied <round>'s locals)
# Agents write l_out_<agent>.tsv (address, decompiler name, new name[, C type]) and lp_out_<agent>.zhl (REPENTOGON syntax).
import collections, glob, re, sys
AGENT_COUNT = 8
DEFAULT_NAME = re.compile(r'\b(?:[a-z]{1,4}Var\d+|[a-zA-Z]{0,4}Stack_[0-9a-f]+|local_[0-9a-f]+)\b')
NOT_RENAMEABLE = re.compile(r'param_\d|in_|extraout|unaff')
LIBRARY = re.compile(r'^(FUN_|Catch|Unwind|std::|png_|jpeg_|jinit|vorbis|_vorbis|ov_|ogg|th_|oc_|theora|stb_|tdefl|tinfl|mz_|'
r'inflate|deflate|lua|luaL|luabridge|glfw|_glfw|mi_|_mi_|rapidxml|json|EOS_|SteamAPI|Steam|steamstub|__|_|`|'
r'FID_|libyuv|I420|ARGB|curl|sha1|crc32|zlib|clown|Clown|VideoClip|TheoraVideo|tolua|utf8|Gamepad_|KHR|epoxy|wgl|gl[A-Z])')
PROTOTYPE = re.compile(r'^\s*(?:static\s+)?(?:cleanup\s+)?(?:__\w+call\s+)?.+?\s*((?:[\w:]+::)?~?\w+)\s*\(.*?\)\s*;')
def snapshot_load(roundDir):
bodies = collections.defaultdict(list)
current = None
for line in open(roundDir + '/all_snapshot.c', errors='replace'):
if line.startswith('//@@ '):
current = tuple(line.split()[1:3])
continue
if current: bodies[current].append(line)
return {key: ''.join(lines) for key, lines in bodies.items()}
def protos_load(roundDir):
known = {line.split('\t')[1] for line in open('dump/functions.tsv')}
for path in sorted(glob.glob(roundDir + '/lp_out_*.zhl')):
for line in open(path):
match = PROTOTYPE.match(line)
if match and not line.lstrip().startswith('//') and match.group(1) in known:
yield match.group(1), line.rstrip('\n') + '\n'
def round_pick(roundDir, minLeft, maxLines, prevRound=None):
held = {name for name, _ in protos_load(prevRound)} if prevRound else set()
heldAddrs = {line.split('\t')[0] for line in open('dump/functions.tsv') if line.split('\t')[1] in held}
skipped = heldAddrs | {line.split()[0] for line in open('dump/calls.tsv') if line.split()[1] in heldAddrs}
if prevRound: # what the last round left is mostly reused slots its agents chose to skip
skipped |= {line.split('\t')[1] for path in glob.glob(prevRound + '/l_[0-9].tsv') for line in open(path) if not line.startswith('#')}
rows = []
for (addr, name), body in snapshot_load(roundDir).items():
if addr in skipped or LIBRARY.match(name) or 'decompile failed' in body[:500]: continue
left = len(set(DEFAULT_NAME.findall(body)))
if left >= minLeft: rows.append((left, body.count('\n'), addr, name))
rows.sort(reverse=True)
bins = [[0, []] for _ in range(AGENT_COUNT)]
for left, lineCount, addr, name in rows:
target = min(bins, key=lambda b: b[0])
if target[0] + lineCount > maxLines: continue
target[0] += lineCount
target[1].append(f'{lineCount}\t{addr}\t{name}\t{left}\n')
for agent, (_, picked) in enumerate(bins):
open(f'{roundDir}/l_{agent}.tsv', 'w').writelines(['# lines\taddress\tname\tdefault names left\n'] + picked)
print(len(rows), 'eligible,', sum(len(b[1]) for b in bins), 'picked:', [b[1][0].split('\t')[2] for b in bins if b[1]])
def locals_merge(roundDir):
bodies = {addr: body for (addr, _), body in snapshot_load(roundDir).items()}
seen = {tuple(line.split('\t')[:2]) for line in open('db/locals.tsv') if not line.startswith('#')}
newNames = collections.defaultdict(set)
rows, rejected = [], collections.Counter()
for path in sorted(glob.glob(roundDir + '/l_out_*.tsv')):
for line in open(path):
cols = line.rstrip('\n').split('\t')
if len(cols) < 3 or line.startswith('#'): continue
addr = cols[0].lower().replace('0x', '').zfill(8)
body = bodies.get(addr, '')
isRetypeOnly = cols[1] == cols[2] and len(cols) > 3 and cols[3].strip()
reason = ('nofunc' if not body else
'noname' if not re.search(r'\b%s\b' % re.escape(cols[1]), body) else
'param' if NOT_RENAMEABLE.match(cols[1]) else
'dup' if (addr, cols[1]) in seen else
'badname' if not re.fullmatch(r'[A-Za-z_]\w*', cols[2]) else
'clash' if not isRetypeOnly and (cols[2] in newNames[addr] or re.search(r'\b%s\b' % re.escape(cols[2]), body)) else None)
if reason:
rejected[reason] += 1
continue
seen.add((addr, cols[1]))
newNames[addr].add(cols[2])
rows.append('\t'.join([addr] + cols[1:4]) + '\n')
open('db/locals.tsv', 'a').writelines(rows)
print(len(rows), 'locals merged in', len(newNames), 'functions; rejected', dict(rejected))
def protos_merge(roundDir):
existing = {line.split('//')[0].strip() for line in open('db/protos.zhl')}
rows = [line for _, line in protos_load(roundDir) if line.split('//')[0].strip() not in existing]
open('db/protos.zhl', 'a').writelines(dict.fromkeys(rows))
print(len(dict.fromkeys(rows)), 'protos merged')
if __name__ == '__main__':
command, args = sys.argv[1], sys.argv[2:]
if command == 'pick': round_pick(args[0], int(args[1]), int(args[2]), *args[3:])
elif command == 'locals': locals_merge(*args)
elif command == 'protos': protos_merge(*args)