python2rust 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. python2rust/__init__.py +8 -0
  2. python2rust/__main__.py +5 -0
  3. python2rust/_core.py +44 -0
  4. python2rust/agent/__init__.py +0 -0
  5. python2rust/agent/agents.py +333 -0
  6. python2rust/agent/apply.py +516 -0
  7. python2rust/agent/finish.py +295 -0
  8. python2rust/agent/fixers.py +229 -0
  9. python2rust/agent/loop.py +441 -0
  10. python2rust/agent/patches.py +1165 -0
  11. python2rust/agent/port.py +579 -0
  12. python2rust/agent/prompts/judge_v2.md +96 -0
  13. python2rust/agent/review.py +34 -0
  14. python2rust/agent/rustlex.py +232 -0
  15. python2rust/cli/__init__.py +0 -0
  16. python2rust/cli/doctor.py +62 -0
  17. python2rust/cli/inputs.py +105 -0
  18. python2rust/cli/main.py +1162 -0
  19. python2rust/cli/ops.py +642 -0
  20. python2rust/cli/workflow.py +178 -0
  21. python2rust/core/__init__.py +38 -0
  22. python2rust/core/config.py +263 -0
  23. python2rust/core/constructs.py +124 -0
  24. python2rust/core/diagnostics.py +280 -0
  25. python2rust/core/emit/__init__.py +5 -0
  26. python2rust/core/emit/crates.py +51 -0
  27. python2rust/core/emit/render.py +561 -0
  28. python2rust/core/emit/schema.py +168 -0
  29. python2rust/core/emit/translate.py +304 -0
  30. python2rust/core/frontend/__init__.py +1 -0
  31. python2rust/core/frontend/module.py +896 -0
  32. python2rust/core/frontend/names.py +129 -0
  33. python2rust/core/frontend/project.py +277 -0
  34. python2rust/core/frontend/project_imports.py +173 -0
  35. python2rust/core/frontend/symbols.py +132 -0
  36. python2rust/core/frontend/walrus.py +59 -0
  37. python2rust/core/ir/__init__.py +1 -0
  38. python2rust/core/ir/nodes.py +675 -0
  39. python2rust/core/ir/rtypes.py +122 -0
  40. python2rust/core/ir/types.py +326 -0
  41. python2rust/core/lower/__init__.py +1 -0
  42. python2rust/core/lower/calls.py +1125 -0
  43. python2rust/core/lower/context.py +223 -0
  44. python2rust/core/lower/exceptions.py +317 -0
  45. python2rust/core/lower/exprs.py +845 -0
  46. python2rust/core/lower/fstrings.py +141 -0
  47. python2rust/core/lower/funcs.py +276 -0
  48. python2rust/core/lower/lowerer.py +366 -0
  49. python2rust/core/lower/modelcalls.py +195 -0
  50. python2rust/core/lower/models.py +645 -0
  51. python2rust/core/lower/stmts.py +722 -0
  52. python2rust/core/lower/testing.py +601 -0
  53. python2rust/core/lower/validation.py +253 -0
  54. python2rust/core/passes/__init__.py +1 -0
  55. python2rust/core/passes/aliasing.py +311 -0
  56. python2rust/core/passes/analysis.py +207 -0
  57. python2rust/core/passes/devirt.py +329 -0
  58. python2rust/core/passes/ownership.py +259 -0
  59. python2rust/core/passes/raises.py +275 -0
  60. python2rust/core/rt_lib.rs +2071 -0
  61. python2rust/data/README.md +81 -0
  62. python2rust/data/py2many_builtins.toml +4744 -0
  63. python2rust/errors.py +28 -0
  64. python2rust/py.typed +0 -0
  65. python2rust/report/__init__.py +0 -0
  66. python2rust/report/constructs.py +31 -0
  67. python2rust/report/contract.py +688 -0
  68. python2rust/report/corpus.py +323 -0
  69. python2rust/report/explain.py +168 -0
  70. python2rust/report/schemas.py +914 -0
  71. python2rust/server/__init__.py +0 -0
  72. python2rust/server/mcp_server.py +289 -0
  73. python2rust/server/mcp_workflow.py +100 -0
  74. python2rust/skill/SKILL.md +214 -0
  75. python2rust/verify/__init__.py +0 -0
  76. python2rust/verify/check.py +1135 -0
  77. python2rust/verify/equiv/__init__.py +1264 -0
  78. python2rust/verify/equiv/compare.py +455 -0
  79. python2rust/verify/equiv/harness.py +505 -0
  80. python2rust/verify/equiv/judge.py +358 -0
  81. python2rust/verify/equiv/procs.py +255 -0
  82. python2rust/verify/equiv/runner.py +248 -0
  83. python2rust/verify/equiv/types.py +543 -0
  84. python2rust/verify/keystore.py +76 -0
  85. python2rust/verify/ladder.py +396 -0
  86. python2rust/verify/sandbox.py +370 -0
  87. python2rust/verify/testrun.py +280 -0
  88. python2rust/workflow/__init__.py +0 -0
  89. python2rust/workflow/brief.py +312 -0
  90. python2rust/workflow/interview.py +366 -0
  91. python2rust/workflow/layout.py +103 -0
  92. python2rust/workflow/planner.py +409 -0
  93. python2rust/workflow/project.py +134 -0
  94. python2rust/workflow/schemas.py +265 -0
  95. python2rust/workflow/state.py +392 -0
  96. python2rust/workflow/staticscan.py +209 -0
  97. python2rust-0.1.0.dist-info/METADATA +395 -0
  98. python2rust-0.1.0.dist-info/RECORD +102 -0
  99. python2rust-0.1.0.dist-info/WHEEL +4 -0
  100. python2rust-0.1.0.dist-info/entry_points.txt +4 -0
  101. python2rust-0.1.0.dist-info/licenses/LICENSE +21 -0
  102. python2rust-0.1.0.dist-info/licenses/NOTICE +65 -0
@@ -0,0 +1,1165 @@
1
+ """The patch overlay: agent fixes live in `.python2rust/patches/`, keyed by stable TODO id.
2
+
3
+ Generated Rust is never edited by hand. An agent submits the replacement for one `todo!()`
4
+ (`python2rust apply`); it is stored here, and every later `translate` splices it back in after
5
+ generation, so re-translating is always safe. A patch is stored as accepted only if it passes the
6
+ anti-cheat gate and the verification ladder; the gate rejects the usual ways of "fixing" a TODO
7
+ without solving it (`todo!`, `unwrap(`, `#[allow`, ...).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import ast
13
+ import hashlib
14
+ import json
15
+ import operator
16
+ import re
17
+ import time
18
+ from collections.abc import Callable, Sequence
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from python2rust import __version__
24
+ from python2rust.agent import rustlex
25
+ from python2rust.errors import UsageError
26
+ from python2rust.verify import keystore
27
+ from python2rust.verify.check import map_line
28
+
29
+ STATE_DIR = ".python2rust"
30
+ _ID = re.compile(r"[A-Za-z0-9_-]{1,64}")
31
+
32
+ # token name (as written in a config allow-list) -> (regex on comment/string-free code, reason)
33
+ GATE_RULES: dict[str, str] = {
34
+ "todo!": "todo!() is the problem being fixed, not a fix",
35
+ "unimplemented!": "unimplemented!() is a stub, not a fix",
36
+ "unreachable!": "unreachable!() claims a case cannot happen instead of handling it",
37
+ "unwrap(": "unwrap() (also as Option::unwrap / Result::unwrap) turns an unhandled case into a panic; propagate or handle it",
38
+ "expect(": "expect() (also as Option::expect / Result::expect) turns an unhandled case into a panic; propagate or handle it",
39
+ "unwrap_unchecked": "unwrap_unchecked is undefined behaviour on the unhandled case",
40
+ "panic!": "panic!()/panic_any()/assert!(false) hide a missing translation behind a crash",
41
+ "process::exit": "std::process::abort/exit ends the program instead of handling the case",
42
+ "loop {}": "an empty loop hangs instead of computing the result",
43
+ "#[allow": "#[allow] / #[expect] silence the compiler instead of fixing the code",
44
+ "Default::default()": "Default::default() / T::default() / unwrap_or_default() as a stand-in value hides missing logic (struct update `..Default::default()` is fine)",
45
+ "unsafe": "unsafe code is never an acceptable automatic fix",
46
+ "transmute": "mem::transmute reinterprets memory; it is never an acceptable automatic fix",
47
+ "asm!": "inline assembly is never an acceptable automatic fix",
48
+ # host access: these make the compiler read files or run code from the build machine
49
+ "include!": "include!/include_str!/include_bytes! make the compiler read a file from the host",
50
+ "env!": "env!/option_env! read the host's environment at compile time",
51
+ "#[path": "#[path] makes the compiler read a module from an arbitrary file",
52
+ "build.rs": "build scripts run arbitrary code on the host when the crate is compiled",
53
+ "concat_idents": "concat_idents! builds macro names the scan cannot see",
54
+ "std::fs": "std::fs reads or writes files of the machine that compiles or tests the code",
55
+ "std::process": "std::process starts programs on the host",
56
+ "std::net": "std::net opens network connections from the host",
57
+ "std::env": "std::env reads the host's environment",
58
+ "std::os": "std::os reaches platform APIs (raw file descriptors, unix extensions)",
59
+ "macro_rules": "macro definitions (macro_rules!, macro) can rename a denied macro past the scan",
60
+ "extern": "extern blocks and `extern crate` reach libc or rename std past the scan",
61
+ "std-alias": "aliasing the std/core/alloc crate root hides host-access paths from the scan",
62
+ "#[cfg_attr": "#[cfg_attr] applies another attribute (path, link, ...) conditionally, past the scan",
63
+ "#[export_name": "#[export_name] / #[no_mangle] / #[used] place symbols the linker or loader may run",
64
+ "#[link": "#[link], #[link_name] and #[link_section] pull in native code",
65
+ "#[proc_macro": "#[proc_macro...] defines compile-time code that runs on the host",
66
+ "#![": "inner attributes (#![...]) change crate-wide behaviour; only the tool's own header is allowed",
67
+ "cfg": "cfg!(...), #[cfg(...)], std::thread::current() and std::backtrace make a patch behave "
68
+ "differently under test or in another configuration: the code that is tested must be the "
69
+ "code that ships",
70
+ "unlexable": "the Rust cannot be tokenised with certainty (unterminated or malformed literal or "
71
+ "comment, reserved prefix, stray character), so no scan of it can be trusted",
72
+ "structure": "a patch must be exactly one function body or expression: unbalanced braces or brackets, "
73
+ "or items (fn, struct, impl, mod, trait, enum, a late `use`) outside the body, are not part of a fix",
74
+ "constant-body": "the replacement ignores every parameter the Python uses and is only a constant "
75
+ "(literals, unit, Default-like values): it compiles without translating anything",
76
+ }
77
+
78
+ _RAW_BUILD = re.compile(r"\bbuild\.rs\b|\bcargo:(?:rustc|rerun|warning|include)")
79
+
80
+ # The subset that must hold even for whole modules written by a model (not only for fixes): code
81
+ # that is merely compiled must not read the host's files or run host code. It is a deny-list on
82
+ # NAMES (not call shapes), so aliasing (`use std::include_str as i`) and macros cannot get around it;
83
+ # the real boundary for such code is the compile sandbox (verify/sandbox.py).
84
+ HOST_ACCESS = (
85
+ "include!",
86
+ "env!",
87
+ "#[path",
88
+ "build.rs",
89
+ "asm!",
90
+ "concat_idents",
91
+ "std::fs",
92
+ "std::process",
93
+ "std::net",
94
+ "std::env",
95
+ "std::os",
96
+ "macro_rules",
97
+ "extern",
98
+ "std-alias",
99
+ "#[cfg_attr",
100
+ "#[export_name",
101
+ "#[link",
102
+ "#[proc_macro",
103
+ "#![",
104
+ "unlexable",
105
+ )
106
+
107
+
108
+ def host_access_violations(code: str) -> list[dict[str, Any]]:
109
+ """Violations of the host-access rules in `code` (comments and string literals are ignored)."""
110
+ return gate(code, allow=[t for t in GATE_RULES if t not in HOST_ACCESS])
111
+
112
+
113
+ _STD_ROOTS = frozenset({"std", "core", "alloc"})
114
+ _HOST_MODULES = frozenset({"fs", "process", "net", "env", "os"})
115
+ _ALWAYS_DENIED = {
116
+ "include_str": "include!",
117
+ "include_bytes": "include!",
118
+ "option_env": "env!",
119
+ "concat_idents": "concat_idents",
120
+ "global_asm": "asm!",
121
+ "naked_asm": "asm!",
122
+ }
123
+ # plain words that are only denied as a macro call, a std path or inside a `use std...` statement
124
+ _MACRO_NAMES = {"include": "include!", "env": "env!", "asm": "asm!", "cfg": "cfg"}
125
+ _ATTR_NAMES = {
126
+ "cfg": "cfg",
127
+ "cfg_attr": "#[cfg_attr",
128
+ "path": "#[path",
129
+ "export_name": "#[export_name",
130
+ "no_mangle": "#[export_name",
131
+ "used": "#[export_name",
132
+ "link": "#[link",
133
+ "link_name": "#[link",
134
+ "link_section": "#[link",
135
+ }
136
+
137
+
138
+ def tokenize(code: str, *, strict: bool = True) -> list[tuple[str, int]]:
139
+ """(token, line) of the code in `code`: no comments, strings or char literals, and `r#name`
140
+ is `name`. Strict: raises `rustlex.LexError` when rustc's tokenisation cannot be established."""
141
+ toks = rustlex.code_tokens(code, strict=strict)
142
+ lines = [0] * len(toks)
143
+ line, pos = 1, 0
144
+ for k, t in enumerate(toks):
145
+ line += code.count("\n", pos, t.start)
146
+ pos = t.start
147
+ lines[k] = line
148
+ return [(t.text, lines[k]) for k, t in enumerate(toks)]
149
+
150
+
151
+ def _host_hits(toks: list[tuple[str, int]]) -> list[tuple[str, int]]:
152
+ """The HOST_ACCESS token rules: denied names anywhere, std host modules, macro/attr escapes."""
153
+ from python2rust.verify.check import LIB_ALLOW
154
+
155
+ header = [t for t, _ in tokenize(LIB_ALLOW)]
156
+ hits: list[tuple[str, int]] = []
157
+ n = len(toks)
158
+
159
+ def t(i: int) -> str:
160
+ return toks[i][0] if 0 <= i < n else ""
161
+
162
+ for i, (x, line) in enumerate(toks):
163
+ if x in _ALWAYS_DENIED:
164
+ hits.append((_ALWAYS_DENIED[x], line))
165
+ elif x in _HOST_MODULES and t(i - 1) == "::" and t(i - 2) in _STD_ROOTS:
166
+ hits.append((f"std::{x}", line))
167
+ elif x in _MACRO_NAMES and (
168
+ t(i + 1) == "!" or (t(i - 1) == "::" and t(i - 2) in _STD_ROOTS)
169
+ ):
170
+ hits.append((_MACRO_NAMES[x], line))
171
+ elif x == "macro_rules" or x == "macro":
172
+ hits.append(("macro_rules", line))
173
+ elif x == "extern":
174
+ hits.append(("extern", line))
175
+ elif x == "use":
176
+ end = next((j for j in range(i, n) if t(j) == ";"), n)
177
+ stmt = [toks[j][0] for j in range(i + 1, end)]
178
+ if _STD_ROOTS.intersection(stmt):
179
+ for j in range(i + 1, end):
180
+ y = t(j)
181
+ if y in _HOST_MODULES:
182
+ hits.append((f"std::{y}", toks[j][1]))
183
+ elif y in _MACRO_NAMES:
184
+ hits.append((_MACRO_NAMES[y], toks[j][1]))
185
+ elif y == "as" and (t(j - 1) in _STD_ROOTS or t(j - 1) == "self"):
186
+ hits.append(("std-alias", toks[j][1]))
187
+ elif x == "#":
188
+ j = i + 1 + (t(i + 1) == "!")
189
+ if t(j) != "[":
190
+ continue
191
+ k, depth = j, 0
192
+ while k < n:
193
+ depth += (t(k) == "[") - (t(k) == "]")
194
+ if depth == 0:
195
+ break
196
+ k += 1
197
+ body = [toks[m][0] for m in range(j, k + 1)]
198
+ if t(i + 1) == "!" and [toks[m][0] for m in range(i, k + 1)] != header:
199
+ hits.append(("#![", line))
200
+ idents = [y for y in body if y[:1].isalpha() or y[:1] == "_"]
201
+ lead = idents[1:2] if idents[:1] == ["unsafe"] else idents[:1]
202
+ if lead and lead[0] in _ATTR_NAMES:
203
+ hits.append((_ATTR_NAMES[lead[0]], line))
204
+ elif lead and lead[0].startswith("proc_macro"):
205
+ hits.append(("#[proc_macro", line))
206
+ return hits
207
+
208
+
209
+ def _scan_tokens(toks: list[tuple[str, int]]) -> list[tuple[str, int]]:
210
+ """Token-sequence rules on comment/string-free code, so spacing and line breaks cannot hide a call."""
211
+ hits: list[tuple[str, int]] = []
212
+ n = len(toks)
213
+
214
+ def t(i: int) -> str:
215
+ return toks[i][0] if 0 <= i < n else ""
216
+
217
+ # `use std::process as p;` makes `p::exit(..)` a process exit
218
+ aliases = {t(i + 2) for i in range(n) if t(i) == "process" and t(i + 1) == "as"} - {""}
219
+ for i, (x, line) in enumerate(toks):
220
+ prv, nxt = t(i - 1), t(i + 1)
221
+ bang = nxt == "!"
222
+ if x == "todo" and bang:
223
+ hits.append(("todo!", line))
224
+ elif x == "unimplemented" and bang:
225
+ hits.append(("unimplemented!", line))
226
+ elif x in ("unreachable", "unreachable_unchecked") and (bang or nxt == "("):
227
+ hits.append(("unreachable!", line))
228
+ elif x in ("unwrap", "unwrap_err") and prv in (".", "::"):
229
+ hits.append(("unwrap(", line))
230
+ elif x in ("expect", "expect_err") and prv in (".", "::"):
231
+ hits.append(("expect(", line))
232
+ elif x in ("unwrap_unchecked", "unwrap_err_unchecked"):
233
+ hits.append(("unwrap_unchecked", line))
234
+ elif x == "current" and prv == "::" and t(i - 2) == "thread":
235
+ hits.append(("cfg", line)) # thread::current().name() is "m::tests::t" under cargo test
236
+ elif x in ("Backtrace", "backtrace") and (x == "Backtrace" or prv == "::"):
237
+ hits.append(("cfg", line)) # a backtrace shows the test harness' frames
238
+ elif x == "use":
239
+ end = next((j for j in range(i, n) if t(j) == ";"), n)
240
+ stmt = {toks[j][0] for j in range(i + 1, end)}
241
+ if "thread" in stmt and stmt & {"current", "*"}:
242
+ hits.append(("cfg", line))
243
+ elif (
244
+ (x == "panic" and bang)
245
+ or (x == "panic_any" and nxt == "(")
246
+ or (x == "resume_unwind" and (nxt == "(" or prv == "::"))
247
+ ):
248
+ hits.append(("panic!", line))
249
+ elif x in ("abort", "exit") and (
250
+ (prv == "::" and (t(i - 2) in ("process", "intrinsics", "libc") or t(i - 2) in aliases))
251
+ or (nxt == "(" and prv not in (".", "::"))
252
+ ):
253
+ hits.append(("process::exit", line))
254
+ elif x == "unsafe":
255
+ hits.append(("unsafe", line))
256
+ elif x.startswith("transmute"):
257
+ hits.append(("transmute", line))
258
+ elif x == "Default" and nxt == "::" and t(i + 2) == "default" and prv != "..":
259
+ hits.append(("Default::default()", line))
260
+ elif x == "default" and prv == "::" and nxt in ("(", ",", ")") and t(i - 2) != "Default":
261
+ if t(i - 3) != "..": # `..Config::default()` is a struct update, not a stand-in
262
+ hits.append(("Default::default()", line))
263
+ elif x == "unwrap_or_default" and prv == ".":
264
+ hits.append(("Default::default()", line))
265
+ elif x == "#":
266
+ j = i + 1 + (t(i + 1) == "!")
267
+ if t(j) == "[":
268
+ depth, k, idents = 0, j, []
269
+ while k < n:
270
+ if t(k) == "[":
271
+ depth += 1
272
+ elif t(k) == "]":
273
+ depth -= 1
274
+ if depth == 0:
275
+ break
276
+ elif toks[k][0][:1].isalpha() or toks[k][0][:1] == "_":
277
+ idents.append(toks[k][0])
278
+ k += 1
279
+ if idents[:1] == ["path"]:
280
+ hits.append(("#[path", line))
281
+ if "allow" in idents or "expect" in idents:
282
+ hits.append(("#[allow", line))
283
+ return hits
284
+
285
+
286
+ _CLOSE = {"(": ")", "[": "]", "{": "}"}
287
+ _NUMBER = re.compile(r"(\d[\d_]*(?:\.\d+)?)(?:[iuf](?:8|16|32|64|128|size))?")
288
+ _COMPARE: dict[type[ast.cmpop], Callable[[Any, Any], bool]] = {
289
+ ast.Eq: operator.eq, ast.NotEq: operator.ne, ast.Lt: operator.lt,
290
+ ast.LtE: operator.le, ast.Gt: operator.gt, ast.GtE: operator.ge,
291
+ } # fmt: skip
292
+ _ASSERT_EQ = {
293
+ "assert_eq": True,
294
+ "debug_assert_eq": True,
295
+ "assert_ne": False,
296
+ "debug_assert_ne": False,
297
+ }
298
+
299
+
300
+ def _group(toks: list[tuple[str, int]], i: int) -> tuple[int, list[str]] | None:
301
+ """(index of the matching close, inner tokens) of the bracket opened at toks[i], or None."""
302
+ stack: list[str] = []
303
+ for j in range(i, len(toks)):
304
+ x = toks[j][0]
305
+ if x in _CLOSE:
306
+ stack.append(_CLOSE[x])
307
+ elif x in _CLOSE.values():
308
+ if not stack or stack.pop() != x:
309
+ return None
310
+ if not stack:
311
+ return j, [w for w, _ in toks[i + 1 : j]]
312
+ return None
313
+
314
+
315
+ def _args(inner: list[str]) -> list[list[str]]:
316
+ """Top-level comma-separated argument token lists."""
317
+ out: list[list[str]] = [[]]
318
+ depth = 0
319
+ for w in inner:
320
+ depth += w in _CLOSE
321
+ depth -= w in _CLOSE.values()
322
+ if w == "," and depth == 0:
323
+ out.append([])
324
+ else:
325
+ out[-1].append(w)
326
+ return out
327
+
328
+
329
+ def _const_value(words: list[str]) -> bool | int | float | None:
330
+ """Value of an expression made only of number/bool literals, `!`, `&&`, `||`, comparisons."""
331
+ parts = []
332
+ for w in words:
333
+ m = _NUMBER.fullmatch(w)
334
+ if m:
335
+ parts.append(m.group(1))
336
+ elif w in ("true", "false"):
337
+ parts.append(w.capitalize())
338
+ else:
339
+ parts.append({"!": " not ", "&&": " and ", "||": " or "}.get(w, w))
340
+ try:
341
+ tree = ast.parse(" ".join(parts).strip(), mode="eval").body
342
+ except SyntaxError:
343
+ return None
344
+
345
+ def ev(node: ast.expr) -> Any:
346
+ if isinstance(node, ast.Constant) and isinstance(node.value, bool | int | float):
347
+ return node.value
348
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not | ast.USub):
349
+ v = ev(node.operand)
350
+ return (not v) if isinstance(node.op, ast.Not) else -v
351
+ if isinstance(node, ast.BoolOp):
352
+ vals = [ev(v) for v in node.values]
353
+ return all(vals) if isinstance(node.op, ast.And) else any(vals)
354
+ if isinstance(node, ast.Compare):
355
+ left, ok = ev(node.left), True
356
+ for op, right in zip(node.ops, node.comparators, strict=True):
357
+ r = ev(right)
358
+ ok = ok and _COMPARE[type(op)](left, r)
359
+ left = r
360
+ return ok
361
+ raise ValueError(node)
362
+
363
+ try:
364
+ return ev(tree)
365
+ except ValueError, TypeError, KeyError:
366
+ return None
367
+
368
+
369
+ _NO_EFFECT_WORDS = frozenset({"continue", "true", "false", "let", "mut"})
370
+
371
+
372
+ def _trivial(body: list[str]) -> bool:
373
+ """A loop body without a real name: it computes and reads nothing. `continue`, literals and
374
+ `let _x = 0;` bind and discard a constant, which is the same as an empty body."""
375
+ return not any(w[:1].isalpha() and w not in _NO_EFFECT_WORDS for w in body)
376
+
377
+
378
+ def _stand_in_fallback(first: list[str]) -> bool:
379
+ """A fallback argument that only builds an empty or default value, however it is spelled:
380
+ `String::new`, `<String>::new`, `Vec::<i64>::new`, `|| String::new()`, `|_| { Vec::new() }`.
381
+ A closure that returns a literal (`|| 0`) is a visible, deliberate choice and passes."""
382
+ body = first[1:] if first[:1] == ["move"] else first
383
+ closure = False
384
+ if body[:1] == ["||"]:
385
+ body, closure = body[1:], True
386
+ elif body[:1] == ["|"] and "|" in body[1:]:
387
+ body, closure = body[body.index("|", 1) + 1 :], True
388
+ if body[:1] == ["{"] and body[-1:] == ["}"]:
389
+ body = body[1:-1]
390
+ if closure and body[-2:] == ["(", ")"]:
391
+ body = body[:-2]
392
+ if not body:
393
+ return False
394
+ path = all(w in ("::", "<", ">", "as") or w[:1].isalpha() or w[:1] == "_" for w in body)
395
+ return path and len(body) >= 3 and body[-1] in ("new", "default") and body[-2] == "::"
396
+
397
+
398
+ def _shape_hits(toks: list[tuple[str, int]]) -> list[tuple[str, int]]:
399
+ """Rules that need the shape of the code: constant-false asserts, empty infinite loops,
400
+ constant stand-ins passed as a fallback, process exit imports, and the patch's structure."""
401
+ hits: list[tuple[str, int]] = []
402
+ n = len(toks)
403
+
404
+ def t(i: int) -> str:
405
+ return toks[i][0] if 0 <= i < n else ""
406
+
407
+ in_use: set[int] = set() # token indices that belong to a `use ...;` declaration
408
+ for i, (x, _) in enumerate(toks):
409
+ if x == "use":
410
+ in_use.update(range(i, next((j for j in range(i, n) if t(j) == ";"), n - 1) + 1))
411
+ stack: list[tuple[str, int]] = []
412
+ leading_use = True # still inside the block of `use` declarations that may open a body
413
+ for i, (x, line) in enumerate(toks):
414
+ nxt = t(i + 1)
415
+ if x in _CLOSE:
416
+ stack.append((_CLOSE[x], line))
417
+ elif x in _CLOSE.values() and (not stack or stack.pop()[0] != x):
418
+ return [*hits, ("structure", line)] # nothing after an extra closer can be trusted
419
+ if not stack:
420
+ item = x in ("struct", "enum", "impl", "mod", "trait") or (x == "fn" and nxt != "(")
421
+ if item or (x == "use" and not leading_use):
422
+ hits.append(("structure", line))
423
+ if i not in in_use:
424
+ leading_use = False
425
+ if x in ("assert", "debug_assert") and nxt == "!" and t(i + 2) in _CLOSE:
426
+ if (g := _group(toks, i + 2)) and _const_value(_args(g[1])[0]) is False:
427
+ hits.append(("panic!", line))
428
+ elif x in _ASSERT_EQ and nxt == "!" and t(i + 2) in _CLOSE:
429
+ if (g := _group(toks, i + 2)) and len(a := _args(g[1])) >= 2:
430
+ left, right = _const_value(a[0]), _const_value(a[1])
431
+ if left is not None and right is not None and (left == right) != _ASSERT_EQ[x]:
432
+ hits.append(("panic!", line))
433
+ elif x in ("loop", "while", "for"):
434
+ k = i + 1
435
+ while k < n and t(k) != "{" and t(k) != ";":
436
+ k += 1
437
+ body = _group(toks, k) if t(k) == "{" else None
438
+ if body is None:
439
+ continue
440
+ head = [w for w, _ in toks[i + 1 : k]]
441
+ if x == "loop":
442
+ forever = not head
443
+ elif x == "while":
444
+ forever = _const_value(head) is True
445
+ else: # `for _ in 0.. {}`: an open-ended range
446
+ forever = "in" in head and "".join(head[head.index("in") + 1 :]).endswith("..")
447
+ if forever and _trivial(body[1]) and not {"break", "return"} & set(body[1]):
448
+ hits.append(("loop {}", line))
449
+ elif x in ("unwrap_or_else", "map_or_else") and nxt == "(":
450
+ if (g := _group(toks, i + 1)) and _stand_in_fallback(_args(g[1])[0]):
451
+ hits.append(("Default::default()", line))
452
+ elif x == "use":
453
+ end = next((j for j in range(i, n) if t(j) == ";"), n)
454
+ stmt = {toks[j][0] for j in range(i + 1, end)}
455
+ if "process" in stmt and stmt & {"exit", "abort"}:
456
+ hits.append(("process::exit", line))
457
+ if stack:
458
+ hits.append(("structure", stack[-1][1]))
459
+ return hits
460
+
461
+
462
+ def sha(text: str) -> str:
463
+ return hashlib.sha256(text.strip().encode()).hexdigest()
464
+
465
+
466
+ # --- anti-cheat gate ----------------------------------------------------------------------------
467
+
468
+
469
+ def strip_noise(code: str) -> str:
470
+ """Blank out comments, string and char literals (keeping newlines) so tokens only match code.
471
+
472
+ Lenient (never raises) and the same length as `code`; the gate itself lexes strictly."""
473
+ return rustlex.blank_noise(code)
474
+
475
+
476
+ def gate(patch: str, allow: Sequence[str] = ()) -> list[dict[str, Any]]:
477
+ """Violations of the anti-cheat gate in `patch` (empty list = passed). `allow` names tokens.
478
+
479
+ The Rust is tokenised after comments and string literals are blanked, so whitespace, line
480
+ breaks and path-call forms (`Option::unwrap(x)`, `todo !()`) match like their plain spelling.
481
+ """
482
+ unknown = [a for a in allow if a not in GATE_RULES]
483
+ if unknown:
484
+ raise UsageError(
485
+ f"patch_gate.allow has unknown tokens {unknown}; known: {sorted(GATE_RULES)}"
486
+ )
487
+ try:
488
+ toks = tokenize(patch)
489
+ except rustlex.LexError as exc: # never allowable: the scans below cannot be trusted
490
+ return [
491
+ {
492
+ "token": "unlexable",
493
+ "line": exc.line,
494
+ "message": f"{GATE_RULES['unlexable']}: {exc.message}",
495
+ }
496
+ ]
497
+ hits = _scan_tokens(toks) + _host_hits(toks) + _shape_hits(toks)
498
+ hits += [("build.rs", patch.count("\n", 0, m.start()) + 1) for m in _RAW_BUILD.finditer(patch)]
499
+ found = {
500
+ (token, line): {"token": token, "line": line, "message": GATE_RULES[token]}
501
+ for token, line in hits
502
+ if token not in allow
503
+ }
504
+ return sorted(found.values(), key=lambda v: (v["line"], v["token"]))
505
+
506
+
507
+ def constant_body_warnings(patch: str, signature: str, python_snippet: str) -> list[dict[str, Any]]:
508
+ """Warn (not reject) when a replacement body ignores every parameter although the Python uses them.
509
+
510
+ A body that is just a constant of the return type is the classic way to make a function
511
+ compile without translating it. Fuzzy by nature, so this is a warning for the reviewer.
512
+ """
513
+ head = re.search(r"\bfn\s+\w+\s*(?:<[^>]*>)?\s*\((.*?)\)\s*(?:->|\{|where)", signature, re.S)
514
+ params = [
515
+ p
516
+ for p in re.findall(r"(?:^|,)\s*(?:mut\s+)?(\w+)\s*:", head.group(1) if head else "")
517
+ if p != "self"
518
+ ]
519
+ used_in_python = [
520
+ p for p in params if len(re.findall(rf"\b{re.escape(p)}\b", python_snippet)) >= 2
521
+ ]
522
+ idents = {tok for tok, _ in tokenize(patch, strict=False)}
523
+ if used_in_python and not any(p in idents for p in used_in_python):
524
+ return [
525
+ {
526
+ "token": "constant-body",
527
+ "line": 1,
528
+ "message": f"the replacement never uses {', '.join(used_in_python)}, which the Python uses: "
529
+ "a body that ignores its inputs is probably a placeholder",
530
+ }
531
+ ]
532
+ return []
533
+
534
+
535
+ # names that may appear in a body that is "only a constant": literals, unit, Default-like values
536
+ _CONSTANT_WORDS = frozenset({
537
+ "None",
538
+ "Some",
539
+ "Ok",
540
+ "Err",
541
+ "Default",
542
+ "default",
543
+ "new",
544
+ "String",
545
+ "Vec",
546
+ "HashMap",
547
+ "HashSet",
548
+ "BTreeMap",
549
+ "BTreeSet",
550
+ "VecDeque",
551
+ "IndexMap",
552
+ "from",
553
+ "to_string",
554
+ "to_owned",
555
+ "into",
556
+ "vec",
557
+ "return",
558
+ "as",
559
+ "true",
560
+ "false",
561
+ "bool",
562
+ "str",
563
+ "char",
564
+ "i8",
565
+ "i16",
566
+ "i32",
567
+ "i64",
568
+ "i128",
569
+ "isize",
570
+ "u8",
571
+ "u16",
572
+ "u32",
573
+ "u64",
574
+ "u128",
575
+ "usize",
576
+ "f32",
577
+ "f64",
578
+ }) # fmt: skip
579
+
580
+
581
+ def constant_body_violations(
582
+ patch: str, signature: str, python_snippet: str, allow: Sequence[str] = ()
583
+ ) -> list[dict[str, Any]]:
584
+ """Hard failure (token `constant-body`) for a body that ignores every parameter the Python uses
585
+ AND is only literals, unit or Default-like constructors (`0`, `None`, `Vec::new()`, `Ok(())`).
586
+
587
+ That is the cheapest way to make a function compile without translating it. `constant_body_warnings`
588
+ still covers the fuzzy case (any body that ignores its inputs). The override is a human decision:
589
+ `constant-body` in `[patch_gate] allow`, or the apply flag `--allow-constant-body` (the caller adds
590
+ the token to `allow`).
591
+ """
592
+ if "constant-body" in allow:
593
+ return []
594
+ ignores = constant_body_warnings(patch, signature, python_snippet)
595
+ words = [w for w, _ in tokenize(patch, strict=False) if w[:1].isalpha() or w[:1] == "_"]
596
+ if ignores and all(w in _CONSTANT_WORDS for w in words):
597
+ return [{**ignores[0], "message": GATE_RULES["constant-body"]}]
598
+ return []
599
+
600
+
601
+ def gate_allowlist(config_path: str | None) -> list[str]:
602
+ """`[patch_gate] allow = [...]` from the config file (a table owned by the CLI, not the core)."""
603
+ if not config_path:
604
+ return []
605
+ import tomllib
606
+
607
+ try:
608
+ data = tomllib.loads(Path(config_path).read_text(encoding="utf-8"))
609
+ except (OSError, tomllib.TOMLDecodeError) as exc:
610
+ raise UsageError(f"cannot read config {config_path}: {exc}") from exc
611
+ allow = data.get("patch_gate", {}).get("allow", [])
612
+ if not isinstance(allow, list) or not all(isinstance(a, str) for a in allow):
613
+ raise UsageError("patch_gate.allow must be a list of token strings")
614
+ return allow
615
+
616
+
617
+ # --- store --------------------------------------------------------------------------------------
618
+
619
+
620
+ def check_id(todo_id: str) -> str:
621
+ if not _ID.fullmatch(todo_id):
622
+ raise UsageError(f"invalid TODO id {todo_id!r}")
623
+ return todo_id
624
+
625
+
626
+ class PatchStore:
627
+ """`<root>/.python2rust/patches/<todo_id>.rs` + `<todo_id>.json` metadata."""
628
+
629
+ def __init__(self, root: str | Path = ".", allow: Sequence[str] = ()):
630
+ self.root = Path(root)
631
+ self.dir = self.root / STATE_DIR / "patches"
632
+ self.allow = list(
633
+ allow
634
+ ) # the project's `[patch_gate] allow`, used when stored patches re-run the gate
635
+
636
+ def exists(self) -> bool:
637
+ return self.dir.is_dir()
638
+
639
+ @staticmethod
640
+ def _signed(todo_id: str, record: dict[str, Any], patch: str) -> bytes:
641
+ """What the MAC covers: the whole record (status, verified level, snippet and function
642
+ hashes, author, ...) except the tag itself, the TODO id and the patch body."""
643
+ body = {k: v for k, v in record.items() if k != "mac"}
644
+ canonical = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
645
+ return json.dumps([todo_id, canonical, patch.strip()]).encode()
646
+
647
+ def authentic(self, todo_id: str, patch: str, meta: dict[str, Any]) -> bool:
648
+ """True when the record carries a valid MAC of this machine's secret for exactly this
649
+ id, body and metadata. Editing any of them, deleting the tag, or copying the store from
650
+ another machine (another secret) makes it False."""
651
+ if meta.get("todo_id") != todo_id:
652
+ return False
653
+ try:
654
+ return keystore.verify_mac("patch", self._signed(todo_id, meta, patch), meta.get("mac"))
655
+ except TypeError, ValueError:
656
+ return False
657
+
658
+ def save(self, todo_id: str, patch: str, meta: dict[str, Any]) -> Path:
659
+ check_id(todo_id)
660
+ self.dir.mkdir(parents=True, exist_ok=True)
661
+ path = self.dir / f"{todo_id}.rs"
662
+ path.write_text(patch.strip() + "\n", encoding="utf-8")
663
+ record = {
664
+ "todo_id": todo_id,
665
+ "tool_version": __version__,
666
+ "created": _now(),
667
+ **meta,
668
+ "patch_sha256": sha(patch), # a later edit of the .rs is detected, never spliced
669
+ }
670
+ record = json.loads(json.dumps(record)) # exactly what `load` will read back
671
+ record["mac"] = keystore.mac("patch", self._signed(todo_id, record, patch))
672
+ (self.dir / f"{todo_id}.json").write_text(
673
+ json.dumps(record, indent=2) + "\n", encoding="utf-8"
674
+ )
675
+ return path
676
+
677
+ def trusted(self, todo_id: str) -> dict[str, Any] | None:
678
+ """The metadata of a stored patch if (and only if) its MAC verifies; else None."""
679
+ found = self.load(todo_id)
680
+ return found[1] if found and self.authentic(todo_id, *found) else None
681
+
682
+ def verify_all(self) -> list[dict[str, Any]]:
683
+ """One entry per stored patch: `ok` says whether its MAC verifies. `done` calls this (via
684
+ `patches.verify_all(root)`) before it trusts any `status` or `verified_level`; an entry
685
+ that is not `ok` carries no status and no level, whatever the file claims."""
686
+ out: list[dict[str, Any]] = []
687
+ for pid in self.ids():
688
+ try:
689
+ found = self.load(pid)
690
+ except UsageError as exc:
691
+ out.append(_unverified(pid, str(exc)))
692
+ continue
693
+ if found is None or not self.authentic(pid, *found):
694
+ out.append(_unverified(pid, _MAC_REFUSAL))
695
+ continue
696
+ meta = found[1]
697
+ out.append(
698
+ {
699
+ "todo_id": pid,
700
+ "ok": True,
701
+ "status": meta.get("status"),
702
+ "verified_level": meta.get("verified_level"),
703
+ "reason": None,
704
+ }
705
+ )
706
+ return out
707
+
708
+ def load(self, todo_id: str) -> tuple[str, dict[str, Any]] | None:
709
+ check_id(todo_id)
710
+ rs, js = self.dir / f"{todo_id}.rs", self.dir / f"{todo_id}.json"
711
+ if rs.is_file() != js.is_file():
712
+ raise UsageError(
713
+ f"stored patch {todo_id} is incomplete: {rs.name} and {js.name} must both exist"
714
+ )
715
+ if not rs.is_file():
716
+ return None
717
+ try:
718
+ return rs.read_text(encoding="utf-8").strip(), json.loads(
719
+ js.read_text(encoding="utf-8")
720
+ )
721
+ except (OSError, ValueError) as exc:
722
+ raise UsageError(
723
+ f"stored patch {todo_id} is unreadable or corrupt ({exc}); fix or delete {rs} and {js}"
724
+ ) from exc
725
+
726
+ def ids(self) -> list[str]:
727
+ return sorted(p.stem for p in self.dir.glob("*.json")) if self.dir.is_dir() else []
728
+
729
+
730
+ _MAC_REFUSAL = (
731
+ "the stored patch has no valid MAC (edited by hand, copied from another machine, or written "
732
+ "by a version without MACs): re-run `apply`"
733
+ )
734
+
735
+
736
+ def _unverified(todo_id: str, reason: str) -> dict[str, Any]:
737
+ return {
738
+ "todo_id": todo_id,
739
+ "ok": False,
740
+ "status": None,
741
+ "verified_level": None,
742
+ "reason": reason,
743
+ }
744
+
745
+
746
+ def verify_all(root: str | Path = ".") -> list[dict[str, Any]]:
747
+ """`PatchStore(root).verify_all()`: the MAC check of every stored patch below `root`."""
748
+ return PatchStore(root).verify_all()
749
+
750
+
751
+ def _now() -> str:
752
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
753
+
754
+
755
+ def _read_index(path: Path) -> dict[str, str]:
756
+ """The TODO index; a missing file is empty, a corrupt one is an error (never silently reset)."""
757
+ if not path.exists():
758
+ return {}
759
+ try:
760
+ todos = json.loads(path.read_text(encoding="utf-8"))["todos"]
761
+ if not isinstance(todos, dict):
762
+ raise TypeError("`todos` is not an object")
763
+ return todos
764
+ except (OSError, ValueError, KeyError, TypeError) as exc:
765
+ raise UsageError(
766
+ f"the TODO index {path} is unreadable or corrupt ({exc}); delete it and re-run translate"
767
+ ) from exc
768
+
769
+
770
+ def update_index(root: Path, entries: list[dict[str, Any]]) -> None:
771
+ """Remember which Python file each TODO id lives in, so `apply ID` needs no path."""
772
+ path = root / STATE_DIR / "cache" / "index.json"
773
+ known = _read_index(path)
774
+ for e in entries:
775
+ known.update({t["id"]: e["file"] for t in e["todos"]})
776
+ path.parent.mkdir(parents=True, exist_ok=True)
777
+ path.write_text(
778
+ json.dumps({"todos": dict(sorted(known.items()))}, indent=1) + "\n", encoding="utf-8"
779
+ )
780
+
781
+
782
+ def index_lookup(root: Path, todo_id: str) -> str | None:
783
+ return _read_index(root / STATE_DIR / "cache" / "index.json").get(todo_id)
784
+
785
+
786
+ # --- splicing a patch into generated Rust -------------------------------------------------------
787
+
788
+
789
+ class SpliceError(Exception):
790
+ pass
791
+
792
+
793
+ @dataclass
794
+ class Span:
795
+ start: int
796
+ end: int
797
+ kind: (
798
+ str # "marker": inside /*python2rust:ID{*/ ... /*}python2rust:ID*/ | "macro": a todo!(...)
799
+ )
800
+
801
+
802
+ def _macro_end(text: str, open_paren: int) -> int:
803
+ depth, i = 0, open_paren
804
+ while i < len(text):
805
+ c = text[i]
806
+ if c == '"':
807
+ i += 1
808
+ while i < len(text) and text[i] != '"':
809
+ i += 2 if text[i] == "\\" else 1
810
+ elif c == "(":
811
+ depth += 1
812
+ elif c == ")":
813
+ depth -= 1
814
+ if depth == 0:
815
+ return i + 1
816
+ i += 1
817
+ raise SpliceError("unbalanced todo!(...) in the generated Rust")
818
+
819
+
820
+ _TAIL_SEMICOLON = re.compile(r"\s*;(?=\s*\})")
821
+ _ONLY_SEMICOLON = re.compile(r"\s*;\s*")
822
+ _UNREACHABLE = re.compile(r"\bunreachable\s*!\s*\([^()]*\)\s*;?")
823
+ # The message of the filler the core appends after a function whose `return` became a todo!().
824
+ _FILLER_MESSAGE = "the body ended without a return"
825
+ _TODO_CALL = re.compile(r"\btodo\s*!\s*\(")
826
+ _ANY_ID = re.compile(r"python2rust[ :]*(?:fn-)?[0-9A-Za-z]{6,}")
827
+
828
+
829
+ def find_span(rust: str, todo: dict[str, Any]) -> Span | None:
830
+ """Locate the todo to replace.
831
+
832
+ The id is the anchor: the marker pair carrying it, else the todo!(...) call whose message holds
833
+ the core's marker `python2rust <ID> PY2RS0xx: ...` (the id is matched whole, so `t1` never
834
+ matches `t1-2`; item-level TODOs are real `todo!()` calls inside a stub fn, so they splice too).
835
+ Only real code is searched (comments and string literals are blanked first), so a `todo!(` that
836
+ sits inside a comment or a string can never be spliced. The recorded `rust_line` is a hint
837
+ used only when no todo!() carries any id at all; it never overrides an id that points elsewhere.
838
+ """
839
+ tid = re.escape(todo["id"])
840
+ marker = re.compile(rf"python2rust[ :]+{tid}(?![\w-])")
841
+ if m := re.search(
842
+ rf"/\*\s*python2rust:{tid}\{{\s*\*/(.*?)/\*\s*\}}python2rust:{tid}\s*\*/", rust, re.S
843
+ ):
844
+ return Span(m.start(1), m.end(1), "marker")
845
+ code = strip_noise(rust) # same length as `rust`; comments and strings are spaces
846
+ calls = []
847
+ for m in _TODO_CALL.finditer(code):
848
+ end = _macro_end(rust, m.end() - 1)
849
+ calls.append((m.start(), end))
850
+ if marker.search(rust[m.start() : end]):
851
+ return Span(m.start(), end, "macro")
852
+ line = todo.get("rust_line") or 0
853
+ for start, end in calls: # hint: the todo!() on the recorded line, if it names no other id
854
+ if rust.count("\n", 0, start) + 1 == line and not _ANY_ID.search(rust[start:end]):
855
+ return Span(start, end, "macro")
856
+ return None
857
+
858
+
859
+ def _core_filler(rust: str, code: str, span: Span) -> tuple[int, int] | None:
860
+ """The core's `unreachable!(..)` filler of the function holding `span`, if fixing `span` makes it
861
+ obsolete (no other todo!() is left in that function).
862
+
863
+ A todo!() diverges, so the core can end such a function with a filler. Left in place after the fix
864
+ it would compile and panic at run time; removed, rustc checks that every path returns a value.
865
+ """
866
+ for m in _UNREACHABLE.finditer(code, span.end):
867
+ if _FILLER_MESSAGE not in rust[m.start() : m.end()]:
868
+ continue
869
+ if re.search(r"\bfn\s", code[span.end : m.start()]):
870
+ return None # that filler belongs to a later function
871
+ start = max((f.start() for f in re.finditer(r"\bfn\s", code[: span.start])), default=0)
872
+ others = code[start : span.start] + code[span.end : m.start()]
873
+ return None if _TODO_CALL.search(others) else (m.start(), m.end())
874
+ return None
875
+
876
+
877
+ def replace_range(
878
+ rust: str,
879
+ source_map: list[dict[str, Any]] | None,
880
+ todos: list[dict[str, Any]],
881
+ start: int,
882
+ end: int,
883
+ new: str,
884
+ ) -> tuple[str, list[dict[str, Any]] | None, list[dict[str, Any]]]:
885
+ """Replace rust[start:end] with `new`, moving source-map entries and todo lines that follow."""
886
+ first = rust.count("\n", 0, start) + 1
887
+ last = rust.count("\n", 0, end) + 1
888
+ delta = new.count("\n") - (last - first)
889
+ out = rust[:start] + new + rust[end:]
890
+ new_map = None
891
+ if source_map is not None:
892
+ covering = map_line(sorted(source_map, key=lambda e: e["rust_line"]), first)
893
+ new_map = [e for e in source_map if e["rust_line"] < first]
894
+ if covering:
895
+ new_map.append({**covering, "rust_line": first})
896
+ new_map += [
897
+ {**e, "rust_line": e["rust_line"] + delta} for e in source_map if e["rust_line"] > last
898
+ ]
899
+ new_todos = [
900
+ {**t, "rust_line": t["rust_line"] + delta} if t["rust_line"] > last else t for t in todos
901
+ ]
902
+ return out, new_map, new_todos
903
+
904
+
905
+ def splice(
906
+ rust: str,
907
+ source_map: list[dict[str, Any]] | None,
908
+ todos: list[dict[str, Any]],
909
+ todo: dict[str, Any],
910
+ patch: str,
911
+ ) -> tuple[str, list[dict[str, Any]] | None, list[dict[str, Any]]]:
912
+ """Replace the todo's span with `patch`; returns new (rust, source_map, todos) with lines shifted."""
913
+ span = find_span(rust, todo)
914
+ if span is None:
915
+ raise SpliceError(
916
+ f"cannot find a todo!() carrying id {todo['id']} in the generated Rust (comments and "
917
+ "strings are not searched); re-run translate so ids and output agree"
918
+ )
919
+ tid, body = todo["id"], patch.strip()
920
+ if span.kind == "macro":
921
+ code = strip_noise(rust)
922
+ filler = _core_filler(rust, code, span)
923
+ if filler and _ONLY_SEMICOLON.fullmatch(code, span.end, filler[0]):
924
+ span = Span(span.start, filler[1], span.kind) # tail statement: `;` and filler go
925
+ else:
926
+ if filler: # not the tail, but it was the last todo: rustc must now check every path
927
+ rust, source_map, todos = replace_range(rust, source_map, todos, *filler, "")
928
+ code = strip_noise(rust)
929
+ # A statement TODO is emitted as `todo!(..);`. As the last statement of its block, that
930
+ # `;` would throw the patch's value away, so it is replaced together with the macro.
931
+ if tail := _TAIL_SEMICOLON.match(code, span.end):
932
+ span = Span(span.start, tail.end(), span.kind)
933
+ if span.kind == "marker":
934
+ new = f"\n{body}\n"
935
+ else:
936
+ new = f"/*python2rust:{tid}{{*/{{\n{body}\n}}/*}}python2rust:{tid}*/"
937
+ return replace_range(rust, source_map, todos, span.start, span.end, new)
938
+
939
+
940
+ # --- function-body patches (written by `port`) ---------------------------------------------------
941
+
942
+
943
+ def unhealed_not_clean(entry: dict[str, Any], python: str) -> list[str]:
944
+ """The items the core counts not clean, minus those with a TODO of their own (reported as `todo`)
945
+ and those an accepted patch has since replaced.
946
+
947
+ The core cannot see patches: after a stored fix replaces a TODO, its item is still listed.
948
+ An item is healed when a patched TODO sits in it (found through the source map) or a
949
+ function-body patch was applied to the Python function of that name.
950
+ """
951
+ from python2rust.verify.check import map_line
952
+
953
+ healed: set[str] = set()
954
+ smap = sorted(entry.get("source_map") or [], key=lambda e: e["rust_line"])
955
+ for t in entry["todos"]:
956
+ # a patched TODO healed its item; an open one is already reported as a `todo` finding
957
+ if smap and (hit := map_line(smap, t["rust_line"])):
958
+ healed.add(str(hit.get("item") or ""))
959
+ names = {**py_function_ids(python), **py_function_ids(python, entry.get("file"))}
960
+ for p in entry.get("patches", ()):
961
+ if p["status"] == "applied" and p["todo_id"] in names:
962
+ healed.add(names[p["todo_id"]]["name"].split(".")[-1])
963
+ return [i for i in entry.get("not_clean", ()) if i not in healed]
964
+
965
+
966
+ def py_function_ids(python: str | None, file: str | None = None) -> dict[str, dict[str, Any]]:
967
+ """Hash the file and normalised function source. Omit file to read legacy patch IDs."""
968
+ if not python:
969
+ return {}
970
+ try:
971
+ tree = ast.parse(python)
972
+ except SyntaxError:
973
+ return {}
974
+ out: dict[str, dict[str, Any]] = {}
975
+
976
+ def add(node: ast.FunctionDef | ast.AsyncFunctionDef, prefix: str) -> None:
977
+ name = prefix + node.name
978
+ source = f"{name}\n{ast.unparse(node)}"
979
+ digest = sha(source if file is None else f"{file}\n{source}")[:10]
980
+ start = min([node.lineno, *(d.lineno for d in node.decorator_list)])
981
+ out[f"fn-{digest}"] = {
982
+ "name": name,
983
+ "start": start,
984
+ "end": node.end_lineno or node.lineno,
985
+ "snippet": "\n".join(python.splitlines()[start - 1 : node.end_lineno]),
986
+ }
987
+
988
+ for node in tree.body:
989
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
990
+ add(node, "")
991
+ elif isinstance(node, ast.ClassDef):
992
+ for sub in node.body:
993
+ if isinstance(sub, ast.FunctionDef | ast.AsyncFunctionDef):
994
+ add(sub, f"{node.name}.")
995
+ return out
996
+
997
+
998
+ def function_span(
999
+ rust: str, source_map: list[dict[str, Any]] | None, py_start: int, py_end: int
1000
+ ) -> tuple[int, int, int] | None:
1001
+ """(fn_start, body_start, body_end) char offsets of the Rust function made from Python lines.
1002
+
1003
+ body_start/body_end delimit the text between the function's outer braces. None when no source
1004
+ map entry points into the Python function or no braces can be found.
1005
+ """
1006
+ if not source_map:
1007
+ return None
1008
+ lines = [e["rust_line"] for e in source_map if py_start <= e["py_line"] <= py_end]
1009
+ if not lines:
1010
+ return None
1011
+ offsets = [0]
1012
+ for ln in rust.splitlines(keepends=True):
1013
+ offsets.append(offsets[-1] + len(ln))
1014
+ first = min(lines)
1015
+ if first > len(offsets) - 1:
1016
+ return None
1017
+ start = offsets[first - 1]
1018
+ clean = strip_noise(rust)
1019
+ depth, i, open_at = 0, start, -1
1020
+ while i < len(clean):
1021
+ c = clean[i]
1022
+ if c == "{":
1023
+ if depth == 0:
1024
+ open_at = i
1025
+ depth += 1
1026
+ elif c == "}":
1027
+ depth -= 1
1028
+ if depth == 0 and open_at >= 0:
1029
+ return start, open_at + 1, i
1030
+ if depth < 0:
1031
+ return None
1032
+ elif c == ";" and depth == 0 and open_at < 0:
1033
+ return None # a declaration without a body
1034
+ i += 1
1035
+ return None
1036
+
1037
+
1038
+ def replace_function_body(
1039
+ rust: str,
1040
+ source_map: list[dict[str, Any]] | None,
1041
+ todos: list[dict[str, Any]],
1042
+ py_start: int,
1043
+ py_end: int,
1044
+ body: str,
1045
+ ) -> tuple[str, list[dict[str, Any]] | None, list[dict[str, Any]]]:
1046
+ span = function_span(rust, source_map, py_start, py_end)
1047
+ if span is None:
1048
+ raise SpliceError(f"cannot locate the Rust function for Python lines {py_start}-{py_end}")
1049
+ _, b0, b1 = span
1050
+ return replace_range(rust, source_map, todos, b0, b1, f"\n{body.strip()}\n")
1051
+
1052
+
1053
+ def _stored_refusal(
1054
+ patch: str, meta: dict[str, Any], allow: Sequence[str]
1055
+ ) -> dict[str, Any] | None:
1056
+ """Why a stored patch must not be spliced (report fields), or None when it may be."""
1057
+ if meta.get("patch_sha256") != sha(patch):
1058
+ return {
1059
+ "status": "tampered",
1060
+ "detail": "the stored patch no longer matches the hash recorded when it was saved "
1061
+ "(or has none): re-run `apply`",
1062
+ }
1063
+ if violations := gate(patch, allow):
1064
+ v = violations[0]
1065
+ return {
1066
+ "status": "rejected-by-gate",
1067
+ "detail": f"{v['token']} at patch line {v['line']}: {v['message']}",
1068
+ }
1069
+ return None
1070
+
1071
+
1072
+ def apply_overlay(
1073
+ rust: str,
1074
+ source_map: list[dict[str, Any]] | None,
1075
+ todos: list[dict[str, Any]],
1076
+ store: PatchStore,
1077
+ file: str,
1078
+ skip: frozenset[str] = frozenset(),
1079
+ python: str | None = None,
1080
+ allow: Sequence[str] | None = None,
1081
+ ) -> tuple[str, list[dict[str, Any]] | None, list[dict[str, Any]], list[dict[str, Any]]]:
1082
+ """Re-apply stored accepted patches whose TODO still exists; returns (rust, map, todos, report).
1083
+
1084
+ `skip` names TODO ids to leave unpatched (`apply` re-fixes one TODO from the raw output).
1085
+
1086
+ The store is not trusted: its files are plain text anyone can edit. Every patch about to be
1087
+ spliced must still match the hash recorded when it was saved (else status `tampered`), match its
1088
+ Python snippet (else `stale`) and pass the anti-cheat gate under `allow` (default: the store's
1089
+ allow-list; else `rejected-by-gate`). Such a patch is reported with the reason, never applied.
1090
+ """
1091
+ gate_allow = store.allow if allow is None else list(allow)
1092
+ report: list[dict[str, Any]] = []
1093
+ present = {t["id"] for t in todos}
1094
+ for todo in list(todos):
1095
+ if todo["id"] in skip:
1096
+ continue
1097
+ found = store.load(todo["id"])
1098
+ if found is None:
1099
+ continue
1100
+ patch, meta = found
1101
+ if not store.authentic(todo["id"], patch, meta): # before anything in `meta` is believed
1102
+ report.append({"todo_id": todo["id"], "status": "tampered", "detail": _MAC_REFUSAL})
1103
+ continue
1104
+ if meta.get("python_snippet_sha256") != sha(todo["python_snippet"]):
1105
+ report.append(
1106
+ {"todo_id": todo["id"], "status": "stale", "detail": "python snippet changed"}
1107
+ )
1108
+ continue
1109
+ if meta.get("status") != "accepted":
1110
+ report.append(
1111
+ {"todo_id": todo["id"], "status": "not-applied-unverified", "detail": None}
1112
+ )
1113
+ continue
1114
+ if refused := _stored_refusal(patch, meta, gate_allow):
1115
+ report.append({"todo_id": todo["id"], **refused})
1116
+ continue
1117
+ try:
1118
+ rust, source_map, todos = splice(rust, source_map, todos, todo, patch)
1119
+ except SpliceError as exc:
1120
+ report.append({"todo_id": todo["id"], "status": "failed", "detail": str(exc)})
1121
+ continue
1122
+ todos = [{**t, "state": "patched"} if t["id"] == todo["id"] else t for t in todos]
1123
+ report.append({"todo_id": todo["id"], "status": "applied", "detail": None})
1124
+ fn_ids = {**py_function_ids(python), **py_function_ids(python, file)}
1125
+ for pid in store.ids():
1126
+ found = store.load(pid)
1127
+ if not found or found[1].get("file") != file or pid in skip:
1128
+ continue
1129
+ patch, meta = found
1130
+ if meta.get("kind") != "function-body" and pid in present:
1131
+ continue # a TODO patch: reported above
1132
+ if not store.authentic(pid, patch, meta):
1133
+ report.append({"todo_id": pid, "status": "tampered", "detail": _MAC_REFUSAL})
1134
+ continue
1135
+ if meta.get("kind") == "function-body":
1136
+ info = fn_ids.get(pid)
1137
+ if info is None:
1138
+ report.append(
1139
+ {"todo_id": pid, "status": "orphaned", "detail": "function changed or removed"}
1140
+ )
1141
+ elif meta.get("status") != "accepted":
1142
+ report.append({"todo_id": pid, "status": "not-applied-unverified", "detail": None})
1143
+ elif meta.get("python_snippet_sha256") not in (None, sha(info["snippet"])):
1144
+ report.append(
1145
+ {"todo_id": pid, "status": "stale", "detail": "python snippet changed"}
1146
+ )
1147
+ elif refused := _stored_refusal(patch, meta, gate_allow):
1148
+ report.append({"todo_id": pid, **refused})
1149
+ else:
1150
+ try:
1151
+ rust, source_map, todos = replace_function_body(
1152
+ rust, source_map, todos, info["start"], info["end"], patch
1153
+ )
1154
+ todos = [
1155
+ {**t, "state": "patched"}
1156
+ if info["start"] <= t["line"] <= info["end"]
1157
+ else t
1158
+ for t in todos
1159
+ ]
1160
+ report.append({"todo_id": pid, "status": "applied", "detail": "function body"})
1161
+ except SpliceError as exc:
1162
+ report.append({"todo_id": pid, "status": "failed", "detail": str(exc)})
1163
+ elif pid not in present:
1164
+ report.append({"todo_id": pid, "status": "orphaned", "detail": "TODO no longer exists"})
1165
+ return rust, source_map, todos, sorted(report, key=lambda r: r["todo_id"])