Skip to content

Commit 0d8ddee

Browse files
refactor: the permuter's rewrites move to decomprepair 0.3.0
The simple rewrites (permuter.py), local ordering hypotheses and the uninitialized-read guard (app/permuter_local.py, app/permuter_initialization.py) and the decomp-permuter generator with its guards (permuter_gen.py, permuter_capture.py, permuter_dependencies.py, permuter_formatting.py) only propose C, so they now live in decomp-repair, where new permuter rewrites go (AGENTS.md). Their names here are aliases of the library modules. app/permute.py starts the library's permuter_gen.py. The worker's revision and claim_stalls' rule digests read a name from the library when it lives there; before, nine watched names that had already moved were read as missing, so updating them never restarted the worker. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent bed4939 commit 0d8ddee

14 files changed

Lines changed: 88 additions & 1001 deletions

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ dependencies = [
1818
"spimdisasm>=1.42.4",
1919
"rabbitizer>=1.16.2",
2020
# the repair families, RetroReversing/decomp-repair: a tagged archive, so installing needs no git
21-
"decomprepair @ https://github.com/RetroReversing/decomp-repair/archive/refs/tags/v0.2.0.tar.gz",
21+
"decomprepair @ https://github.com/RetroReversing/decomp-repair/archive/refs/tags/v0.3.0.tar.gz",
2222
"httpx>=0.28",
2323
"uvicorn>=0.30",
2424
"ninja>=1.11", # builds GameCube/Wii (dtk) and other ninja-based decomp projects

‎src/decompnet/app/permute.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@
3434
from dataclasses import dataclass, field
3535
from pathlib import Path
3636

37+
import decomprepair
38+
3739
from .. import compile_timing, consoles, m2cfix, permuter_claims, scoring, seeds, toolchains
3840
from ..candidate_work import trial
3941
from ..compile_sessions import batched
@@ -52,7 +54,7 @@
5254
MAX_TURNS = 4 # turns per function before it's left to agents (counted in the database: functions.permuted)
5355
CANDIDATES = 20 # near misses looked up at a time, for the workers to share
5456
TOOL = "decomp-permuter"
55-
GENERATOR = Path(__file__).resolve().parent.parent / "permuter_gen.py"
57+
GENERATOR = Path(decomprepair.__file__).resolve().parent / "permuter_gen.py" # with its sibling modules
5658
BATCH = 64 # variants per run of the generator: about 0.15 s to write, a few seconds to judge
5759
GENERATOR_SECONDS = 30 # a batch that takes longer is stuck: its randomizer retries until a rewrite applies
5860
READ_BYTES = 1 << 16
Lines changed: 5 additions & 261 deletions
Original file line numberDiff line numberDiff line change
@@ -1,264 +1,8 @@
1-
"""Reject new uninitialized reads in generated integer and pointer locals.
1+
"""Moved to `decomprepair.permuter_initialization`, the standalone repair library; this name stays for the rest of the app
2+
(both names are one module, so a patch through either is seen by both)."""
23

3-
This is neither a C undefined-behavior checker nor a semantic equivalence proof. Unknown syntax,
4-
qualified/shadowed/escaped locals receive no verdict. Existing bindings are rejected only when
5-
the parent has a supported initialized verdict for that binding. Use the bounded local CFG,
6-
with separate initialization transfer rules: its liveness definitions include bare declarations.
7-
"""
8-
import re
9-
from functools import lru_cache
4+
import sys
105

11-
from decomprepair import local_flow
12-
from decomprepair.integer_repair_support import IDENT, INTEGER, NUMBER, view
13-
from decomprepair.pattern_repairs import close
14-
from decomprepair.pointer_pair_repairs import qualified_types
6+
from decomprepair import permuter_initialization
157

16-
# Pointer captures need the same must-initialization check as integer captures.
17-
# Keep unknown pointee aliases, qualifiers, arrays and function pointers opaque.
18-
_TYPE = rf'(?:{INTEGER}(?=\s)|(?:{INTEGER}|void)(?:\s*\*)+)'
19-
_DECL = re.compile(rf'\b(?P<type>{_TYPE})\s*(?P<name>{IDENT})\s*(?:=(?P<initial>[^;{{}}]*))?;')
20-
21-
22-
def unsafe_temporary(parent, candidate, name, header=""):
23-
"""Whether a new local is unsafe, or an existing local loses proven initialization."""
24-
original = view(parent, name)
25-
if not original:
26-
return False
27-
old_names = set(re.findall(IDENT, original.clean))
28-
verdicts = _initialization_verdicts(candidate, name, header)
29-
unsafe = {variable for variable, verdict in verdicts.items() if verdict is True}
30-
if unsafe-old_names:
31-
return True
32-
if not unsafe:
33-
return False
34-
previous = _parent_verdicts(parent, name, header)
35-
return any(previous.get(variable) is False for variable in unsafe)
36-
37-
38-
@lru_cache(maxsize=8)
39-
def _parent_verdicts(source, name, header):
40-
# A batch shares its parent. Do not rebuild its CFG for each rejected proposal.
41-
return _initialization_verdicts(source, name, header)
42-
43-
44-
def _initialization_verdicts(candidate, name, header):
45-
part = view(candidate, name)
46-
if not part:
47-
return {}
48-
combined = header+"\n"+candidate
49-
macros = set(re.findall(r"^\s*#\s*define\s+("+IDENT+r")", combined, re.M))
50-
# This guard excludes both const and volatile aliases, including alias chains.
51-
qualified = qualified_types(re.sub(r"\bconst\b", "volatile", combined))
52-
records = []
53-
for record in re.finditer(r"\b(?:struct|union)(?:\s+"+IDENT+r")?\s*{", part.body):
54-
start = part.opening+1+record.end()-1
55-
end = close(part.clean, start, "{", "}")
56-
if end:
57-
records.append((start, end))
58-
declarations = []
59-
for decl in _DECL.finditer(part.clean, part.opening+1, part.end):
60-
prefix = part.clean[part.opening+1:decl.start()].rstrip()
61-
variable = decl['name']
62-
if any(start < decl.start() < end for start, end in records):
63-
continue
64-
if (set(re.findall(IDENT, decl['type'])) | {variable}) & (qualified | macros):
65-
continue
66-
if prefix and prefix[-1] not in ';{}':
67-
continue
68-
if len(re.findall(rf'\b(?:{INTEGER}|void|float|double)(?:\s+|(?:\s*\*)+\s*)'
69-
rf'{variable}\s*(?=[;=,\[])', part.body)) != 1:
70-
continue
71-
if re.search(rf'&\s*(?:\(\s*)*{variable}\b', part.body):
72-
continue
73-
declarations.append(decl)
74-
if not declarations or re.search(r"\bfor\s*\([^;]*;\s*;", part.body):
75-
return {}
76-
flow = local_flow.analyze(_without_type_only_records(candidate, part, macros), name,
77-
declarations=declarations)
78-
if not flow or flow.entry is None:
79-
return {}
80-
# The native walk commonly wraps a single statement in do {...} while (0).
81-
# Prune only its literal-zero back edge; other constant controls receive no verdict.
82-
one_shot_conditions = set()
83-
for hit in re.finditer(r'\bdo\b', part.body):
84-
body = flow.skip(part.opening+1+hit.end(), part.end-1)
85-
end = flow.statement_end(body, part.end-1)
86-
opening, stop = flow.condition(end)
87-
if re.fullmatch(r'\s*0[uUlL]*\s*', part.clean[opening+1:stop-1]):
88-
for index, node in enumerate(flow.nodes):
89-
if node.start == opening+1 and node.end == stop-1:
90-
node.successors = {n for n in node.successors if not body <= flow.nodes[n].start < end}
91-
one_shot_conditions.add(index)
92-
# Unsupported writes to one temporary must not hide a separate unsafe capture.
93-
# Reuse the bounded CFG, but keep each binding's initialization verdict independent.
94-
return {decl['name']: _unsafe_binding(part, candidate, flow, decl, macros, combined, one_shot_conditions)
95-
for decl in declarations}
96-
97-
98-
def _without_type_only_records(candidate, part, macros):
99-
"""Hide only inert record typedefs from the statement CFG, preserving every offset.
100-
101-
The CFG deliberately rejects braced expressions. Literal-sized scalar fields in a local
102-
typedef are not executable statements; VLA bounds, macros and other declarations stay opaque.
103-
This is private to the initialization guard, not permission for lifetime repairs to move code.
104-
"""
105-
scalar = rf'(?:{INTEGER}|float|double|f32|f64)'
106-
field = rf'{scalar}\s+{IDENT}(?:\s*\[\s*{NUMBER}\s*\])?\s*;'
107-
result = list(candidate)
108-
for hit in re.finditer(r'\btypedef\s+struct(?:\s+'+IDENT+r')?\s*{', part.body):
109-
start = part.opening+1+hit.start()
110-
opening = part.opening+1+hit.end()-1
111-
stop = close(part.clean, opening, '{', '}')
112-
if not stop:
113-
continue
114-
tail = re.match(r'\s*('+IDENT+r')\s*;', part.clean[stop:])
115-
if not tail:
116-
continue
117-
end = stop+tail.end()
118-
fields = part.clean[opening+1:stop-1]
119-
if (not re.fullmatch(rf'(?:\s*{field})+\s*', fields)
120-
or set(re.findall(IDENT, part.clean[start:end])) & macros):
121-
continue
122-
# The final semicolon becomes an empty statement. All declaration/read positions survive.
123-
for index in range(start, end-1):
124-
if result[index] != '\n':
125-
result[index] = ' '
126-
return ''.join(result)
127-
128-
129-
def _embedded_pointer_copy(text, variable, local_names=()):
130-
"""Recognize one unconditional pointer copy in two bounded expression forms.
131-
132-
Retain the ordinary indirect store-address copy, or accept a single capture
133-
in another plain local assignment's arithmetic RHS. Calls, conditional
134-
evaluation and other reads/writes of the copied binding remain opaque.
135-
"""
136-
if len(re.findall(rf'\b{variable}\b', text)) != 1:
137-
return False
138-
if not text.lstrip().startswith('*'):
139-
# A single unconditional capture in another plain local's arithmetic RHS.
140-
# No sequencing inference: the copied binding occurs only at this write.
141-
assignment = re.fullmatch(rf'\s*({IDENT})\s*=(?!=)(.*?)\s*;?\s*', text, re.S)
142-
if not assignment or assignment[1] not in local_names or assignment[1] == variable:
143-
return False
144-
rhs = assignment[2]
145-
if (re.search(r'[,?;]|&&|\|\||\+\+|--|(?:<<|>>|[+*/%&|^\-])=', rhs)
146-
or re.search(rf'\b{IDENT}\s*\(', rhs)
147-
or re.search(r'\b(?:sizeof|_Alignof|typeof|__typeof__)\b', rhs)):
148-
return False
149-
capture = re.search(rf'\(\s*{variable}\s*=(?!=)\s*{IDENT}(?:\s*[+\-]\s*(?:{NUMBER}|{IDENT}))?\s*\)', rhs)
150-
if capture is None:
151-
return False
152-
remaining = rhs[:capture.start()]+'0'+rhs[capture.end():]
153-
# Other writes, member/index accesses and calls remain unknown. This is
154-
# an initialization transfer, not an expression purity proof: arithmetic
155-
# (including unary *) may evaluate operands in either order, but none
156-
# reads/writes this p outside its single capture.
157-
return (not re.search(r'=(?!=)|->|[\[\].]', remaining)
158-
and re.fullmatch(r'[\s()A-Za-z_0-9+*/%&|^~<>\-]+', remaining) is not None)
159-
depth = 0
160-
for pos, char in enumerate(text):
161-
if char in '([':
162-
depth += 1
163-
elif char in ')]':
164-
depth -= 1
165-
elif (char == '=' and depth == 0 and text[pos+1:pos+2] != '='
166-
and text[pos-1:pos] not in '<>!=+-*/%&|^'):
167-
address = text[:pos]
168-
return (not re.search(rf'\b{IDENT}\s*\(', address)
169-
and re.search(rf'\(\s*{variable}\s*=(?!=)\s*{IDENT}\s*\)', address) is not None)
170-
return False
171-
172-
173-
def _unsafe_binding(part, candidate, flow, decl, macros, combined, one_shot_conditions):
174-
"""True for a possible uninitialized read, False for initialized reads, None for unknown flow."""
175-
names = {decl['name']}
176-
declarations = [decl]
177-
pointers = names if '*' in decl['type'] else set()
178-
from decomprepair.permuter_macro_effects import transparent_macros
179-
opaque_macros = macros - transparent_macros(combined, names)
180-
local_names = set(flow.names)
181-
transfers = []
182-
for index, node in enumerate(flow.nodes):
183-
text = part.clean[node.start:node.end]
184-
# The shared CFG does not prune constant conditions or expand macros.
185-
numbers_only = re.sub(rf'(?<![\w.]){NUMBER}(?![\w.])', '0', text)
186-
if ((index not in one_shot_conditions and re.search(r'\d', text)
187-
and re.fullmatch(r'[\s0()+*/%<>=!&|^~.-]+', numbers_only))
188-
or (not text.strip() and "'" in candidate[node.start:node.end])
189-
or set(re.findall(IDENT, text)) & opaque_macros
190-
or re.search(r'\b(?:sizeof|_Alignof|typeof|__typeof__|true|false)\b', text)):
191-
return None
192-
# A field named x is not the local x. Preserve the base and index expressions,
193-
# but hide member identifiers from the binding-specific write/sequence checks.
194-
text = re.sub(r'(\.|->)(\s*)('+IDENT+r')',
195-
lambda hit: hit[1]+hit[2]+' '*len(hit[3]), text)
196-
# Expression sequencing, embedded writes and macro-like calls are beyond this guard.
197-
if names & set(re.findall(IDENT, text)) and re.search(r'\?|&&|\|\||\b(?:sizeof|_Alignof|typeof|__typeof__)\b|\b[A-Z_][A-Z_0-9]*\s*\(', text):
198-
return None
199-
uses = set(node.uses) & names
200-
generates, kills = set(), set()
201-
contained = [d for d in declarations if node.start <= d.start() and d.end() <= node.end]
202-
for decl in contained:
203-
variable = decl['name']
204-
kills.add(variable)
205-
uses.discard(variable)
206-
if decl['initial'] is not None:
207-
initializer = decl['initial']
208-
if ',' in initializer or re.search(rf'\b(?:{"|".join(map(re.escape, names))})\s*=(?!=)', initializer):
209-
return None
210-
initial = {hit[0] for hit in re.finditer(IDENT, initializer)
211-
if not re.search(r'(?:\.|->)\s*$', initializer[:hit.start()])} & names
212-
uses |= initial
213-
generates.add(variable)
214-
assignment = re.fullmatch(rf'\s*({IDENT})\s*=(?!=)(.*?);?\s*', text, re.S)
215-
indirect = re.fullmatch(rf'\s*\*\s*({IDENT})\s*=(?!=)(.*?);?\s*', text, re.S)
216-
if indirect and indirect[1] in pointers:
217-
if ',' in indirect[2] or re.search(rf'\b(?:{"|".join(map(re.escape, names))})\s*=(?!=)', indirect[2]):
218-
return None
219-
# Writing through a pointer reads its value; it does not assign that local.
220-
uses.add(indirect[1])
221-
elif assignment and assignment[1] in names:
222-
if ',' in assignment[2] or re.search(rf'\b(?:{"|".join(map(re.escape, names))})\s*=(?!=)', assignment[2]):
223-
return None
224-
generates.add(assignment[1])
225-
elif not contained and re.search(rf'\b(?:{"|".join(map(re.escape, names))})\s*=(?!=)', text):
226-
if decl['name'] not in pointers or not _embedded_pointer_copy(text, decl['name'], local_names):
227-
return None
228-
# Completing this supported expression necessarily evaluates its capture.
229-
# Track the copy on this CFG edge, not on paths bypassing the statement.
230-
uses.discard(decl['name'])
231-
generates.add(decl['name'])
232-
transfers.append((uses, generates, kills))
233-
reachable, pending = set(), [flow.entry]
234-
while pending:
235-
index = pending.pop()
236-
if index not in reachable:
237-
reachable.add(index)
238-
pending.extend(flow.nodes[index].successors)
239-
predecessors = {index: set() for index in reachable}
240-
for index in reachable:
241-
for successor in flow.nodes[index].successors:
242-
predecessors[successor].add(index)
243-
# Greatest fixed point for a must analysis; the entry also has the empty initial state.
244-
outgoing = {index: set(names) for index in reachable}
245-
changed = True
246-
while changed:
247-
changed = False
248-
for index in reachable:
249-
incoming = set.intersection(*(outgoing[p] for p in predecessors[index])) if predecessors[index] else set()
250-
if index == flow.entry:
251-
incoming = set()
252-
_, generates, kills = transfers[index]
253-
result = (incoming-kills) | generates
254-
if result != outgoing[index]:
255-
outgoing[index] = result
256-
changed = True
257-
for index in reachable:
258-
incoming = set.intersection(*(outgoing[p] for p in predecessors[index])) if predecessors[index] else set()
259-
if index == flow.entry:
260-
incoming = set()
261-
uses, _, kills = transfers[index]
262-
if uses - (incoming-kills):
263-
return True
264-
return False
8+
sys.modules[__name__] = permuter_initialization
Lines changed: 5 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,8 @@
1-
"""Cheap local ordering hypotheses before random drift; only the normal judge can accept one."""
2-
import re
1+
"""Moved to `decomprepair.permuter_local`, the standalone repair library; this name stays for the rest of the app
2+
(both names are one module, so a patch through either is seen by both)."""
33

4-
from ..forks.csource import _blank, find
4+
import sys
55

6+
from decomprepair import permuter_local
67

7-
def variants(source, name):
8-
span = find(source, name)
9-
if not span:
10-
return []
11-
clean = _blank(source)
12-
opening = clean.find('{', *span)
13-
if opening < 0 or re.search(r'\bvolatile\b|^\s*#', clean[span[0]:span[1]], re.M):
14-
return []
15-
result = []
16-
# Adjacent constant stores through the same pointer often differ only in scheduling. Do not
17-
# cross statements, branches, indentation levels or a call; preserve the original lines verbatim.
18-
store = re.compile(r'(?m)^([ \t]+)([A-Za-z_]\w*)->([A-Za-z_]\w*)\s*=\s*'
19-
r'(-?(?:0[xX][0-9a-fA-F]+|[0-9]+(?:\.[0-9]+)?)[uUlLfF]*)\s*;[ \t]*$')
20-
matches = list(store.finditer(clean, opening, span[1]))
21-
for left, right in zip(matches, matches[1:]):
22-
if (clean[left.end():right.start()] != '\n' or (left[1], left[2]) != (right[1], right[2])
23-
or left[3] == right[3] or left[4] != right[4]):
24-
continue
25-
result.append(('adjacent_constant_stores', source[:left.start()] + source[right.start():right.end()] + '\n'
26-
+ source[left.start():left.end()] + source[right.end():]))
27-
# A common integer multiply-by-33 idiom: operand order can choose which value occupies the
28-
# destination register. Both operands remain once each; the compiler/link judge remains mandatory.
29-
for match in re.finditer(r'\b([A-Za-z_]\w*)\s*\+\s*\(\s*\1\s*<<\s*([0-9]+)\s*\)', clean[opening:span[1]]):
30-
a, b = opening + match.start(), opening + match.end()
31-
result.append(('shift_add_order', source[:a] + f'({match[1]} << {match[2]}) + {match[1]}' + source[b:]))
32-
return result[:8]
8+
sys.modules[__name__] = permuter_local

‎src/decompnet/app/permuter_worker.py‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,19 @@ def empty_status(state):
4040
"current": "", "started_at": time.time(), "repairs": 0, "threads": max(1, workers.WORKERS - 1)}
4141

4242

43+
def _library() -> Path:
44+
import decomprepair
45+
46+
return Path(decomprepair.__file__).resolve().parent
47+
48+
4349
def revision() -> tuple:
4450
root = Path(__file__).resolve().parents[1]
51+
library = _library()
4552
result = []
46-
for path in sorted(root / name for name in WATCHED):
47-
name = path.relative_to(root).as_posix()
53+
for name in sorted(WATCHED):
54+
# the permuter's rewrites live in decomprepair now: their names here are aliases, so watch the library's file
55+
path = library / Path(name).name if (library / Path(name).name).exists() else root / name
4856
try:
4957
stat = path.stat()
5058
result.append((name, stat.st_mtime_ns, stat.st_size))

‎src/decompnet/claim_stalls.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,8 @@ def _repair_rules():
4343
# there, and the library's own families count like app/'s (same names, so fingerprints keep their keys).
4444
import decomprepair
4545
library = Path(decomprepair.__file__).parent
46-
paths = [p if p.exists() else library / p.name for p in paths]
46+
# a name in the library is read there (the app's file of that name, if any, is only an alias of it)
47+
paths = [library / p.name if (library / p.name).exists() else p for p in paths]
4748
paths = sorted(set(paths) | set(library.glob('*repairs.py')), key=lambda p: p.name)
4849
return [(p.name,file_digest(p)) for p in paths]
4950

0 commit comments

Comments
 (0)