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,516 @@
1
+ """`apply`: store an agent's fix for one TODO, behind the anti-cheat gate and the ladder."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from contextlib import ExitStack
7
+ from dataclasses import replace
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from python2rust.agent.patches import (
12
+ STATE_DIR,
13
+ PatchStore,
14
+ SpliceError,
15
+ check_id,
16
+ constant_body_violations,
17
+ constant_body_warnings,
18
+ function_span,
19
+ gate,
20
+ gate_allowlist,
21
+ index_lookup,
22
+ py_function_ids,
23
+ replace_function_body,
24
+ sha,
25
+ splice,
26
+ )
27
+ from python2rust.agent.review import apply_floor
28
+ from python2rust.cli import inputs, ops
29
+ from python2rust.errors import EXIT_COMPILE, EXIT_FINDINGS, EXIT_OK, UsageError
30
+ from python2rust.verify import ladder, testrun
31
+ from python2rust.verify.check import CheckModule
32
+ from python2rust.workflow import project as scoping
33
+
34
+
35
+ def _doc(todo_id: str, status: str, code: int, **fields: Any) -> tuple[dict[str, Any], int]:
36
+ base: dict[str, Any] = {
37
+ "file": None,
38
+ "function": None,
39
+ "gate": {"passed": None, "violations": [], "allowed": [], "warnings": []},
40
+ "verification": None,
41
+ "patch_path": None,
42
+ "reason": None,
43
+ "verified_level": None,
44
+ "equiv": {"status": "not-run"},
45
+ }
46
+ return ops.envelope(
47
+ "apply", ok=code == EXIT_OK, todo_id=todo_id, status=status, **{**base, **fields}
48
+ ), code
49
+
50
+
51
+ def _meta(todo: dict[str, Any], src: Any, author: str, rungs: dict[str, Any]) -> dict[str, Any]:
52
+ return {
53
+ "python_snippet_sha256": sha(todo["python_snippet"]),
54
+ "file": src.display,
55
+ "code": todo["code"],
56
+ "author": author,
57
+ "verified_level": "check",
58
+ "fmt": rungs.get("fmt"),
59
+ }
60
+
61
+
62
+ def _test_failure(tested: dict[str, Any]) -> str:
63
+ named = [
64
+ f"{t['test']}" + (f" [{t['py_id']}]" if t["py_id"] else "") + f": {t['message']}"
65
+ for t in tested["failed"][:3]
66
+ ]
67
+ return "; ".join(named) or tested["detail"] or "unknown"
68
+
69
+
70
+ ROOTS_FILE = "roots.json"
71
+
72
+
73
+ def remember_roots(root: Path, sources: list[Any]) -> None:
74
+ """Remember the directories `translate` was given, so `apply ID` can translate the whole
75
+ project (and run every test that uses the patched module), not only the file holding the TODO."""
76
+ found = {s.root for s in sources if s.root}
77
+ if not found:
78
+ return
79
+ path = root / STATE_DIR / "cache" / ROOTS_FILE
80
+ known = _read_roots(path)
81
+ path.parent.mkdir(parents=True, exist_ok=True)
82
+ path.write_text(json.dumps({"roots": sorted({*known, *found})}, indent=1) + "\n", "utf-8")
83
+
84
+
85
+ def _read_roots(path: Path) -> list[str]:
86
+ if not path.exists():
87
+ return []
88
+ try:
89
+ roots = json.loads(path.read_text(encoding="utf-8"))["roots"]
90
+ if not isinstance(roots, list):
91
+ raise TypeError("`roots` is not a list")
92
+ return [str(r) for r in roots]
93
+ except (OSError, ValueError, KeyError, TypeError) as exc:
94
+ raise UsageError(
95
+ f"{path} is unreadable or corrupt ({exc}); delete it and re-run translate -o DIR"
96
+ ) from exc
97
+
98
+
99
+ def project_root_of(root: Path, file: str) -> str | None:
100
+ """The outermost remembered translate directory that contains `file` (None: it was a lone file)."""
101
+ here = Path(file).resolve()
102
+ inside = [
103
+ r
104
+ for r in _read_roots(root / STATE_DIR / "cache" / ROOTS_FILE)
105
+ if Path(r).is_dir() and here.is_relative_to(Path(r).resolve())
106
+ ]
107
+ return min(inside, key=lambda r: len(Path(r).resolve().parts), default=None)
108
+
109
+
110
+ def _scope(
111
+ sources: list[Any], entries: list[dict[str, Any]], index: int, patched: CheckModule
112
+ ) -> tuple[list[CheckModule], int]:
113
+ """The modules compiled and tested together for the patched one, and its position among them.
114
+
115
+ Flat translation: the module alone. Project mode: its connected component in the import graph,
116
+ so the tests of every module that uses it (and of what those use) run against the fix, in the
117
+ real crate tree.
118
+ """
119
+ mod = entries[index].get("module")
120
+ if mod is None:
121
+ return [patched], 0
122
+ by_name = {e["module"]["name"]: i for i, e in enumerate(entries) if e.get("module")}
123
+ edges: dict[int, set[int]] = {i: set() for i in by_name.values()}
124
+ for i in by_name.values():
125
+ for dep in entries[i]["module"]["depends_on"]:
126
+ if (j := by_name.get(dep)) is not None:
127
+ edges[i].add(j)
128
+ edges[j].add(i)
129
+ seen, todo = {index}, [index]
130
+ while todo:
131
+ for j in edges[todo.pop()] - seen:
132
+ seen.add(j)
133
+ todo.append(j)
134
+ keep = [i for i in sorted(seen) if i == index or entries[i]["rust"]]
135
+ mods = [patched if i == index else _module_of(sources[i], entries[i]) for i in keep]
136
+ return mods, keep.index(index)
137
+
138
+
139
+ def _module_of(src: Any, entry: dict[str, Any]) -> CheckModule:
140
+ return ops.modules_for([src], [entry])[0]
141
+
142
+
143
+ def _function_needs_review(python: str | None, function: str) -> bool:
144
+ """The review floor applied to the whole Python function, not only the TODO's snippet."""
145
+ fn = next((f for f in ladder.py_functions(python) if f["name"] == function), None)
146
+ if fn is None or python is None:
147
+ return False
148
+ text = "\n".join(python.splitlines()[fn["start"] - 1 : fn["end"]])
149
+ return bool(apply_floor({"python_snippet": text}).get("needs_review"))
150
+
151
+
152
+ def _stored(store: PatchStore, todo_id: str, patch: str, meta: dict[str, Any], status: str) -> str:
153
+ return store.save(todo_id, patch, {**meta, "status": status}).as_posix()
154
+
155
+
156
+ def _level(tested: dict[str, Any], equiv: dict[str, Any]) -> str:
157
+ """What was established for an accepted fix, in words (stored with the patch)."""
158
+ base = "check+tests" if tested["status"] == "pass" else "check"
159
+ status = equiv["status"]
160
+ if status == "passed":
161
+ return f"{base}+equivalence"
162
+ if status == "passed-judged":
163
+ return f"{base}+equivalence (judged)"
164
+ if status == "opted-out":
165
+ return f"{base}, not equivalence"
166
+ return f"{base} (equivalence not applicable)"
167
+
168
+
169
+ def _equivalence(
170
+ modules: list[CheckModule],
171
+ index: int,
172
+ files: list[dict[str, Any]],
173
+ function: str,
174
+ *,
175
+ equiv: Any,
176
+ no_equiv: bool,
177
+ needs_review: bool,
178
+ acked: bool,
179
+ ) -> tuple[dict[str, Any], str | None]:
180
+ """The equivalence rung of `apply`: (equiv document, why-not-accepted).
181
+
182
+ Equivalence is required whenever it is applicable (a pure function with a JSON-able signature).
183
+ Running the Python needs consent (`--run-python`), so without it an applicable function is
184
+ `unverified`; `--no-equiv` is the explicit opt-out and is recorded as such.
185
+ """
186
+ from python2rust.verify import equiv as eqv
187
+
188
+ if function == ladder.MODULE:
189
+ inapplicable = "the TODO is outside every Python function (module-level code)"
190
+ else:
191
+ inapplicable = eqv.static_applicability(modules[index], files[index], function)
192
+ if inapplicable:
193
+ return {"status": "not-applicable", "reason": inapplicable, "decision": "accepted"}, None
194
+ if no_equiv:
195
+ why = "--no-equiv: the fix was not compared with the Python"
196
+ return {"status": "opted-out", "reason": why, "decision": "accepted"}, None
197
+ if equiv is None:
198
+ why = (
199
+ f"equivalence applies to {function} but was not checked: pass --run-python (it executes "
200
+ "the Python in a sandbox) to compare outputs, or --no-equiv to accept at check+tests only"
201
+ )
202
+ return {"status": "not-run", "reason": why, "decision": "unverified"}, why
203
+ eq = eqv.equiv_for_function(modules, index, files, function, equiv)
204
+ decision, why = eqv.apply_decision(eq, needs_review=needs_review, acked=acked, comparable=True)
205
+ vouched = eqv.judged_accepted_by(
206
+ eq, needs_review=needs_review, acked=acked, accept_judged=equiv.accept_judged
207
+ )
208
+ doc = {**eq, "decision": decision, "needs_review": needs_review, "judged_accepted_by": vouched}
209
+ return doc, why if decision != "accepted" else None
210
+
211
+
212
+ def _plan_owner(root: Path, plan: dict[str, Any], file: str) -> bool:
213
+ """Is `file` (a path as given) one of the planned modules or one of their tests?"""
214
+ try:
215
+ rel = Path(file).resolve().relative_to(root.resolve()).as_posix()
216
+ except ValueError:
217
+ return False
218
+ return rel in {f for u in plan["units"] for f in (*u["files"], *u["tests"])}
219
+
220
+
221
+ def _open_sources(
222
+ stack: ExitStack, root: Path, todo_id: str, paths: list[str], unit: str | None
223
+ ) -> tuple[list[Any], bool]:
224
+ """(sources, scoped): what `apply` translates for the TODO.
225
+
226
+ A fix is judged against the project graph, never against one file: with a workflow plan the
227
+ sources are every planned module and test (`--unit`, or any `--source` that is a planned file, or
228
+ no `--source` at all); without one, the directory `translate -o DIR` remembered, else the paths
229
+ as given. `scoped` says the sources came from the plan (the scratch layout lives in `stack`).
230
+ """
231
+ from python2rust.workflow import state
232
+
233
+ plan = state.load_plan(root)
234
+ if unit is not None:
235
+ if plan is None:
236
+ raise UsageError("--unit needs a plan: run `python2rust plan` first")
237
+ return stack.enter_context(
238
+ scoping.open_unit(root, plan, scoping.unit_of(plan, unit))
239
+ ).sources, True
240
+ if plan is not None and (not paths or all(_plan_owner(root, plan, p) for p in paths)):
241
+ scope = stack.enter_context(scoping.open_unit(root, plan, plan["units"][0]))
242
+ return scope.sources, True
243
+ if not paths:
244
+ known = index_lookup(root, todo_id)
245
+ if known is None or not Path(known).exists():
246
+ raise UsageError(
247
+ f"do not know which Python file holds {todo_id}: pass --source PATH, "
248
+ "or run `python2rust translate -o DIR` first so the TODO is indexed"
249
+ )
250
+ paths = [known]
251
+ # a single file that lives in a project `translate` was given is part of that project
252
+ widened = [project_root_of(root, p) or p if Path(p).is_file() else p for p in paths]
253
+ return inputs.collect(list(dict.fromkeys(widened))), False
254
+
255
+
256
+ FUNCTION_ID = "fn-" # ids of the function-body fixes `port` stores (not a core TODO id)
257
+
258
+
259
+ def _function_target(
260
+ sources: list[Any], entries: list[dict[str, Any]], fid: str, legacy_file: str | None
261
+ ) -> tuple[int, dict[str, Any], dict[str, Any]] | None:
262
+ """(source index, the function, a stand-in TODO) for a `port` function-body fix, or None.
263
+
264
+ The stand-in carries what the pipeline reads of a TODO: the Rust function header (the
265
+ constant-body rule reads its parameters), the Python function, and whether it needs review.
266
+ """
267
+ for i, (src, entry) in enumerate(zip(sources, entries, strict=True)):
268
+ info = py_function_ids(src.text, src.display).get(fid)
269
+ if info is None and src.display == legacy_file:
270
+ info = py_function_ids(src.text).get(fid)
271
+ span = (
272
+ function_span(entry["rust"], entry["source_map"], info["start"], info["end"])
273
+ if info and entry["rust"]
274
+ else None
275
+ )
276
+ if info is None or span is None:
277
+ continue
278
+ start, b0, _ = span
279
+ inside = [t for t in entry["todos"] if info["start"] <= t["line"] <= info["end"]]
280
+ todo = {
281
+ "id": fid, "kind": "function-body", "code": "function-body",
282
+ "rust_context": entry["rust"][start:b0], "python_snippet": info["snippet"],
283
+ "rust_line": entry["rust"].count("\n", 0, start) + 1,
284
+ "needs_review": any(t["needs_review"] for t in inside),
285
+ } # fmt: skip
286
+ return i, info, todo
287
+ return None
288
+
289
+
290
+ def apply_patch(
291
+ todo_id: str,
292
+ patch: str | None,
293
+ *,
294
+ paths: list[str],
295
+ config_path: str | None,
296
+ project: str,
297
+ author: str,
298
+ deps_from: str | None = None,
299
+ offline: bool = False,
300
+ timeout: float = 300,
301
+ target_dir: str | None = None,
302
+ equiv: Any = None,
303
+ ack_review: str | None = None,
304
+ require_equiv: bool = False,
305
+ no_equiv: bool = False,
306
+ allow_constant_body: bool = False,
307
+ unit: str | None = None,
308
+ ) -> tuple[dict[str, Any], int]:
309
+ """Gate, splice and verify one fix, then store it. Exit: 0 accepted, 1 rejected by the gate,
310
+ refused (a TODO inside tests) or unverified, 2 unknown TODO, 4 the Rust does not compile, a
311
+ test fails or the output differs from the Python.
312
+
313
+ Accepted means: the patched function compiles, every translated test that lives in the module
314
+ or reaches its functions passes (tests that reach another open TODO are listed, not run), and
315
+ the output equals the Python's wherever that can be compared. The comparison needs `equiv` (an
316
+ `EquivOptions`, i.e. `--run-python`); without it an applicable function is `unverified`, unless
317
+ `no_equiv` (`--no-equiv`) opts out, which is recorded and lowers `verified_level`.
318
+ `require_equiv` is the old spelling of the default and changes nothing.
319
+ """
320
+ check_id(todo_id)
321
+ store = PatchStore(project)
322
+ found = store.load(todo_id) if patch is None or todo_id.startswith(FUNCTION_ID) else None
323
+ if patch is None:
324
+ if found is None or not store.authentic(todo_id, *found):
325
+ raise UsageError(f"no --patch given and no authenticated stored patch for {todo_id}")
326
+ patch = found[0]
327
+ if not patch.strip():
328
+ raise UsageError("the patch is empty")
329
+ if no_equiv and (equiv is not None or require_equiv):
330
+ raise UsageError("--no-equiv contradicts --run-python and --require-equiv")
331
+ root = Path(project)
332
+ with ExitStack() as stack:
333
+ sources, scoped = _open_sources(stack, root, todo_id, paths, unit)
334
+ entries = ops.run_translate(
335
+ sources, config_path, project=project, skip=frozenset({todo_id}),
336
+ builtin_errors=ops.WORKFLOW_BUILTIN_ERRORS,
337
+ ) # fmt: skip
338
+ info: dict[str, Any] | None = None
339
+ if todo_id.startswith(FUNCTION_ID):
340
+ legacy_file = found[1].get("file") if found and store.authentic(todo_id, *found) else None
341
+ target = _function_target(sources, entries, todo_id, legacy_file)
342
+ hit = (target[0], target[2]) if target else None
343
+ info = target[1] if target else None
344
+ else:
345
+ hit = next(
346
+ ((i, t) for i, e in enumerate(entries) for t in e["todos"] if t["id"] == todo_id), None
347
+ )
348
+ if hit is None:
349
+ where = f"unit {unit}" if unit else ", ".join(paths) or "the planned project"
350
+ raise UsageError(
351
+ f"no TODO or function with id {todo_id} in {where}: ids change when the Python snippet "
352
+ "changes; run `python2rust todos` for the current ids"
353
+ )
354
+ pi, todo = hit
355
+ src, entry = sources[pi], entries[pi]
356
+
357
+ if testrun.is_test_file(src.display) or testrun.todo_in_tests(
358
+ entry["rust"] or "", todo["rust_line"]
359
+ ):
360
+ return _doc(
361
+ todo_id, "rejected", EXIT_FINDINGS, file=src.display,
362
+ reason="the TODO is inside translated test code: a fix must not be applied to tests "
363
+ "(a test is the oracle; fix the code under test, or leave the test TODO for a human)",
364
+ ) # fmt: skip
365
+ allow = gate_allowlist(config_path)
366
+ violations = gate(patch, allow)
367
+ warnings: list[dict[str, Any]] = []
368
+ if todo["kind"] == "function-body":
369
+ violations += constant_body_violations(
370
+ patch,
371
+ todo["rust_context"],
372
+ todo["python_snippet"],
373
+ [*allow, *(["constant-body"] if allow_constant_body else [])],
374
+ )
375
+ warnings = constant_body_warnings(patch, todo["rust_context"], todo["python_snippet"])
376
+ if allow: # never silent: a relaxed gate is part of the record
377
+ warnings.append(
378
+ {
379
+ "token": "gate-relaxed",
380
+ "line": 0,
381
+ "message": f"anti-cheat rules disabled by [patch_gate] allow in {config_path}: {', '.join(allow)}",
382
+ }
383
+ )
384
+ gate_doc = {
385
+ "passed": not violations,
386
+ "violations": violations,
387
+ "allowed": allow,
388
+ "warnings": warnings,
389
+ }
390
+ if violations:
391
+ first = violations[0]
392
+ return _doc(
393
+ todo_id, "rejected", EXIT_FINDINGS, file=src.display, gate=gate_doc,
394
+ reason=f"anti-cheat gate: {first['token']} at patch line {first['line']}: {first['message']}",
395
+ ) # fmt: skip
396
+
397
+ try:
398
+ if info is None:
399
+ rust, smap, todos = splice(
400
+ entry["rust"], entry["source_map"], entry["todos"], todo, patch
401
+ )
402
+ marker_line = rust[: rust.index(f"python2rust:{todo_id}{{")].count("\n") + 1
403
+ # the spliced TODO is fixed now: only other open todo!()s still stub a function or panic
404
+ todos = [{**t, "state": "patched"} if t["id"] == todo_id else t for t in todos]
405
+ else: # a whole function body: every TODO inside it goes with it
406
+ rust, smap, todos = replace_function_body(
407
+ entry["rust"],
408
+ entry["source_map"],
409
+ entry["todos"],
410
+ info["start"],
411
+ info["end"],
412
+ patch,
413
+ )
414
+ marker_line = 0
415
+ todos = [
416
+ {**t, "state": "patched"} if info["start"] <= t["line"] <= info["end"] else t
417
+ for t in todos
418
+ ]
419
+ except SpliceError as exc:
420
+ raise UsageError(str(exc)) from exc
421
+ module = CheckModule(
422
+ src.display, rust, todos, src.text, smap, entry.get("required_crates"),
423
+ (entry.get("module") or {}).get("crate_path"), entry.get("tests") or [],
424
+ ) # fmt: skip
425
+ if scoped: # the file, what it imports and the tests that import it, in the real crate tree
426
+ keep = scoping.compile_scope(sources, entries, frozenset({src.display}))
427
+ modules = [module if i == pi else _module_of(sources[i], entries[i]) for i in keep]
428
+ mi = keep.index(pi)
429
+ else:
430
+ modules, mi = _scope(sources, entries, pi, module)
431
+ verdict = ladder.verify_units(
432
+ modules,
433
+ "check",
434
+ deps_from=deps_from,
435
+ offline=offline,
436
+ timeout=timeout,
437
+ target_dir=target_dir,
438
+ )
439
+ fl = verdict["files"][mi]
440
+ function = info["name"] if info else ladder.Unit(module).fn_of(marker_line) or ladder.MODULE
441
+ fn = next((f for f in fl["functions"] if f["function"] == function), None)
442
+ rungs = fn["rungs"] if fn else {k: v["status"] for k, v in fl["rungs"].items()}
443
+ verification = {
444
+ "level": "check",
445
+ "rungs": rungs,
446
+ "fmt_advisory": rungs.get("fmt"),
447
+ "errors": (fn["messages"] if fn else [])[:20],
448
+ "tools": verdict["tools"],
449
+ }
450
+ common = {
451
+ "file": src.display,
452
+ "function": function,
453
+ "gate": gate_doc,
454
+ "verification": verification,
455
+ }
456
+ if "fail" in (rungs.get("parse"), rungs.get("check")):
457
+ return _doc(
458
+ todo_id, "failed", EXIT_COMPILE, **common,
459
+ reason="the patched function does not pass the ladder; nothing was stored",
460
+ ) # fmt: skip
461
+ meta = _meta(todo, src, author, rungs)
462
+ if info is not None:
463
+ meta = {**meta, "kind": "function-body", "function": function}
464
+ if rungs.get("check") != "pass":
465
+ why = fl["rungs"]["check"]["detail"] or "cargo is not available"
466
+ return _doc(
467
+ todo_id, "unverified", EXIT_FINDINGS, **common,
468
+ patch_path=_stored(store, todo_id, patch, meta, "unverified"),
469
+ reason=f"could not verify ({why}); stored but NOT accepted and NOT applied by translate",
470
+ ) # fmt: skip
471
+ cargo = {
472
+ "deps_from": deps_from,
473
+ "offline": offline,
474
+ "timeout": timeout,
475
+ "target_dir": target_dir,
476
+ }
477
+ tested = testrun.run_tests(modules, mi, **cargo)
478
+ verification["test_rung"] = tested["status"]
479
+ if tested.get("scope"):
480
+ verification["tests"] = {
481
+ k: tested[k] for k in ("scope", "passed", "failed", "skipped_todo", "out_of_scope")
482
+ }
483
+ if tested["status"] == "fail":
484
+ return _doc(
485
+ todo_id, "failed", EXIT_COMPILE, **common,
486
+ reason=f"the project's tests fail with this fix ({_test_failure(tested)}); nothing was stored",
487
+ ) # fmt: skip
488
+ if tested["status"] == "unverified":
489
+ return _doc(
490
+ todo_id, "unverified", EXIT_FINDINGS, **common,
491
+ patch_path=_stored(store, todo_id, patch, meta, "unverified"),
492
+ reason=f"the module has tests but they could not run ({tested['detail']}); stored but NOT "
493
+ "accepted and NOT applied by translate",
494
+ ) # fmt: skip
495
+ # a plan names files from the project root: the Python is loaded from an absolute path
496
+ named = [replace(m, name=str(root.resolve() / m.name)) for m in modules] if scoped else modules
497
+ eq_doc, why = _equivalence(
498
+ named, mi, verdict["files"], function, equiv=equiv, no_equiv=no_equiv,
499
+ needs_review=bool(todo["needs_review"]) or _function_needs_review(src.text, function),
500
+ acked=ack_review == todo_id,
501
+ ) # fmt: skip
502
+ common["equiv"] = eq_doc
503
+ if eq_doc["decision"] == "failed":
504
+ return _doc(todo_id, "failed", EXIT_COMPILE, **common, reason=why)
505
+ if eq_doc["decision"] == "unverified":
506
+ return _doc(
507
+ todo_id, "unverified", EXIT_FINDINGS, **common,
508
+ patch_path=_stored(store, todo_id, patch, meta, "unverified"),
509
+ reason=f"{why}; stored but NOT accepted and NOT applied by translate",
510
+ ) # fmt: skip
511
+ level = _level(tested, eq_doc)
512
+ meta = {**meta, "verified_level": level, "equiv": eq_doc["status"]}
513
+ return _doc(
514
+ todo_id, "accepted", EXIT_OK, **common, verified_level=level,
515
+ patch_path=_stored(store, todo_id, patch, meta, "accepted"),
516
+ ) # fmt: skip