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,396 @@
1
+ """The verification ladder behind `verify`, `coverage` and `apply`.
2
+
3
+ Rungs, in order: parse (rustfmt can read it), fmt (rustfmt would not change it), check
4
+ (`cargo check`), clippy (`cargo clippy`, no warnings), test (`cargo test`). Every Python function
5
+ gets a verdict: the result of each rung and the highest rung reached before the first failure.
6
+
7
+ `functions_check_clean` is the honest headline: functions that have Rust output, contain no
8
+ `todo!()`, and pass `cargo check`. Merely having no TODO proves nothing (the Rust may not compile),
9
+ and a function whose `todo!()` compiles has not been translated.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import ast
15
+ import difflib
16
+ import re
17
+ import shutil
18
+ import subprocess
19
+ from collections import Counter
20
+ from collections.abc import Sequence
21
+ from typing import Any
22
+
23
+ from python2rust.verify import check as chk
24
+ from python2rust.verify.check import CheckModule
25
+
26
+ LEVELS = ("parse", "fmt", "check", "clippy", "test", "equiv")
27
+ MODULE = "<module>" # pseudo-function for errors outside any Python function
28
+ _STUB_CALL = re.compile(r"\b(?:todo|unimplemented)!\s*\(")
29
+ _RUSTFMT_LOC = re.compile(r"-->\s*\S+:(\d+):\d+")
30
+
31
+
32
+ def py_functions(source: str | None) -> list[dict[str, Any]]:
33
+ """Top-level functions and class methods as `{name, start, end}` (qualified `Class.method`)."""
34
+ if not source:
35
+ return []
36
+ try:
37
+ tree = ast.parse(source)
38
+ except SyntaxError:
39
+ return []
40
+ out: list[dict[str, Any]] = []
41
+
42
+ def add(node: ast.FunctionDef | ast.AsyncFunctionDef, prefix: str) -> None:
43
+ out.append(
44
+ {
45
+ "name": prefix + node.name,
46
+ "start": node.lineno,
47
+ "end": node.end_lineno or node.lineno,
48
+ }
49
+ )
50
+
51
+ for node in tree.body:
52
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
53
+ add(node, "")
54
+ elif isinstance(node, ast.ClassDef):
55
+ for sub in node.body:
56
+ if isinstance(sub, ast.FunctionDef | ast.AsyncFunctionDef):
57
+ add(sub, f"{node.name}.")
58
+ return out
59
+
60
+
61
+ class Unit:
62
+ """One Rust module plus everything needed to attribute a Rust line to a Python function."""
63
+
64
+ def __init__(self, module: CheckModule):
65
+ self.module = module
66
+ self.funcs = py_functions(module.python)
67
+ self.defs = chk._python_defs(module.python)
68
+ self.lines = module.rust.splitlines()
69
+ self.by_name = {f["name"] for f in self.funcs}
70
+
71
+ def fn_of(self, rust_line: int) -> str | None:
72
+ loc = chk.locate(self.module, rust_line, self.defs)
73
+ pl = loc["python_line"]
74
+ if pl is not None:
75
+ inner = [f for f in self.funcs if f["start"] <= pl <= f["end"]]
76
+ if inner:
77
+ return max(inner, key=lambda f: f["start"])["name"]
78
+ item = loc["item"]
79
+ if (
80
+ item and not self.funcs
81
+ ): # no Python source (a .rs input): the source map's item names it
82
+ return item
83
+ return None
84
+
85
+ def present(self) -> set[str]:
86
+ return {
87
+ fn for n, line in enumerate(self.lines, 1) if line.strip() and (fn := self.fn_of(n))
88
+ }
89
+
90
+ def stubbed(self) -> set[str]:
91
+ """Functions whose Rust still contains todo!() / unimplemented!() (or an open core todo)."""
92
+ clean = _strip(self.module.rust).splitlines()
93
+ hits = {
94
+ fn
95
+ for n, line in enumerate(clean, 1)
96
+ if _STUB_CALL.search(line) and (fn := self.fn_of(n))
97
+ }
98
+ for t in self.module.todos:
99
+ if t.get("state") != "patched" and (fn := self.fn_of(t["rust_line"])):
100
+ hits.add(fn)
101
+ return hits
102
+
103
+
104
+ def _strip(rust: str) -> str:
105
+ from python2rust.agent.patches import strip_noise
106
+
107
+ return strip_noise(rust) # code only: strings and comments blanked
108
+
109
+
110
+ # --- rustfmt rungs ------------------------------------------------------------------------------
111
+
112
+
113
+ def rustfmt_run(rust: str) -> dict[str, Any]:
114
+ exe = shutil.which("rustfmt")
115
+ if exe is None:
116
+ return {"available": False, "ok": False, "formatted": None, "error_lines": []}
117
+ try:
118
+ p = subprocess.run(
119
+ [exe, "--edition", "2024", "--emit", "stdout"],
120
+ input=rust, capture_output=True, text=True, timeout=60,
121
+ ) # fmt: skip
122
+ except subprocess.TimeoutExpired: # present but unusable: reported as such, not as "missing"
123
+ return {
124
+ "available": True,
125
+ "ok": False,
126
+ "formatted": None,
127
+ "error_lines": [],
128
+ "error": "rustfmt timed out after 60s",
129
+ }
130
+ except (OSError, subprocess.SubprocessError) as exc:
131
+ return {
132
+ "available": True,
133
+ "ok": False,
134
+ "formatted": None,
135
+ "error_lines": [],
136
+ "error": f"rustfmt could not be run: {exc}",
137
+ }
138
+ lines = [int(m.group(1)) for m in _RUSTFMT_LOC.finditer(p.stderr)]
139
+ return {"available": True, "ok": p.returncode == 0, "formatted": p.stdout, "error_lines": lines}
140
+
141
+
142
+ def _changed_lines(original: str, formatted: str) -> list[int]:
143
+ a, b = original.splitlines(), formatted.splitlines()
144
+ out: list[int] = []
145
+ for tag, i1, i2, _, _ in difflib.SequenceMatcher(None, a, b, autojunk=False).get_opcodes():
146
+ if tag != "equal":
147
+ out += list(range(i1 + 1, max(i2, i1 + 1) + 1))
148
+ return out
149
+
150
+
151
+ # --- the ladder ---------------------------------------------------------------------------------
152
+
153
+
154
+ def _rung(status: str, **extra: Any) -> dict[str, Any]:
155
+ return {"status": status, "errors": 0, "detail": None, **extra}
156
+
157
+
158
+ def _clippy_available() -> bool:
159
+ try:
160
+ return chk.clippy_version() is not None
161
+ except chk.ToolError:
162
+ return True # installed but failing: the clippy rung itself will report why
163
+
164
+
165
+ def verify_units(
166
+ modules: list[CheckModule],
167
+ level: str = "check",
168
+ *,
169
+ deps_from: str | None = None,
170
+ offline: bool = False,
171
+ timeout: float = 300,
172
+ target_dir: str | None = None,
173
+ equiv: Any = None,
174
+ only: Sequence[str] | None = None,
175
+ ) -> dict[str, Any]:
176
+ """Run the ladder up to `level` over `modules` (or just the rungs named in `only`); returns the `files` part of the verify document.
177
+
178
+ `equiv` (an `equiv.EquivOptions`) is what lets the `equiv` rung execute the module's Python;
179
+ without it that rung is reported `unverified` and nothing runs.
180
+ """
181
+ wanted = tuple(only) if only else LEVELS[: LEVELS.index(level) + 1]
182
+ units = [Unit(m) for m in modules]
183
+ # per module: {rung: {"result": rung-dict, "fails": {function-or-MODULE: [messages]}}}
184
+ results: list[dict[str, dict[str, Any]]] = [{} for _ in units]
185
+ tools = {
186
+ "rustfmt": shutil.which("rustfmt") is not None,
187
+ "cargo": shutil.which("cargo") is not None,
188
+ "clippy": _clippy_available() if "clippy" in wanted else None,
189
+ }
190
+
191
+ def record(
192
+ i: int,
193
+ rung: str,
194
+ status: str,
195
+ fails: dict[str, list[str]],
196
+ detail: str | None = None,
197
+ **x: Any,
198
+ ):
199
+ results[i][rung] = {
200
+ "result": _rung(status, errors=sum(map(len, fails.values())), detail=detail, **x),
201
+ "fails": fails,
202
+ }
203
+
204
+ if "parse" in wanted or "fmt" in wanted:
205
+ for i, u in enumerate(units):
206
+ fmt = rustfmt_run(u.module.rust)
207
+ if not fmt["available"] or fmt.get("error"):
208
+ why = fmt.get("error") or "rustfmt not found on PATH"
209
+ for rung in ("parse", "fmt"):
210
+ if rung in wanted:
211
+ record(i, rung, "unverified", {}, why)
212
+ continue
213
+ parse_fails: dict[str, list[str]] = {}
214
+ if not fmt["ok"]:
215
+ for line in fmt["error_lines"] or [0]:
216
+ parse_fails.setdefault(u.fn_of(line) or MODULE if line else MODULE, []).append(
217
+ f"line {line}"
218
+ )
219
+ record(i, "parse", "pass" if fmt["ok"] else "fail", parse_fails)
220
+ if "fmt" in wanted:
221
+ if not fmt["ok"]:
222
+ record(i, "fmt", "skipped", {}, "does not parse")
223
+ else:
224
+ fails: dict[str, list[str]] = {}
225
+ for line in _changed_lines(u.module.rust, fmt["formatted"]):
226
+ fails.setdefault(u.fn_of(line) or MODULE, []).append(f"line {line}")
227
+ record(i, "fmt", "fail" if fails else "pass", fails)
228
+
229
+ def cargo_rung(sub: str, rung: str, levels: tuple[str, ...]) -> None:
230
+ run = chk.run_cargo(
231
+ modules,
232
+ sub,
233
+ deps_from=deps_from,
234
+ offline=offline,
235
+ timeout=timeout,
236
+ target_dir=target_dir,
237
+ )
238
+ if run.status != "ran":
239
+ for i in range(len(units)):
240
+ record(i, rung, "unverified", {}, run.reason)
241
+ return
242
+ diags = chk.diagnostics_from(run.messages, modules, run.names, levels=levels)
243
+ failure = chk.cargo_failure(run, diags)
244
+ if failure and not diags:
245
+ for i in range(len(units)):
246
+ record(i, rung, "unverified", {}, failure)
247
+ return
248
+ by_file = {f"src/{n}.rs": i for i, n in enumerate(run.names)}
249
+ fails: list[dict[str, list[str]]] = [{} for _ in units]
250
+ for d in diags:
251
+ i = by_file.get(d["rust_file"] or "")
252
+ if i is None:
253
+ continue
254
+ fn = units[i].fn_of(d["rust_line"]) if d["rust_line"] else None
255
+ fails[i].setdefault(fn or MODULE, []).append(
256
+ f"{d['code'] or d['category']}: {d['message']}"
257
+ )
258
+ unmapped = [d for d in diags if (d["rust_file"] or "") not in by_file]
259
+ for i in range(len(units)):
260
+ extra = {"diagnostics": [d for d in diags if by_file.get(d["rust_file"] or "") == i]}
261
+ if unmapped and i == 0:
262
+ fails[0].setdefault(MODULE, []).extend(d["message"] for d in unmapped)
263
+ record(i, rung, "fail" if fails[i] else "pass", fails[i], None, **extra)
264
+ if rung == "test":
265
+ _record_tests(run, units, results, record)
266
+
267
+ if "check" in wanted:
268
+ cargo_rung("check", "check", ("error",))
269
+ if "clippy" in wanted:
270
+ cargo_rung("clippy", "clippy", ("error", "warning"))
271
+ if "test" in wanted:
272
+ cargo_rung("test", "test", ("error",))
273
+
274
+ files = []
275
+ for u, res in zip(units, results, strict=True):
276
+ files.append(_file_verdict(u, res, wanted))
277
+ doc: dict[str, Any] = {"level": level, "tools": tools, "files": files}
278
+ if "equiv" in wanted and equiv is not None:
279
+ from python2rust.verify import equiv as eq
280
+
281
+ doc.update(eq.run_equiv(units, files, equiv))
282
+ return doc
283
+
284
+
285
+ def _record_tests(
286
+ run: chk.CargoRun, units: list[Unit], results: list[dict[str, Any]], record: Any
287
+ ) -> None:
288
+ tests = chk.TEST_LINE.findall(run.text)
289
+ ran = [t for t in tests if t[1] != "ignored"]
290
+ if not ran:
291
+ for i in range(len(units)):
292
+ if results[i]["test"]["result"]["status"] == "pass":
293
+ record(i, "test", "skipped", {}, "no tests in the generated Rust")
294
+ return
295
+ for path, outcome in ran:
296
+ if outcome != "FAILED":
297
+ continue
298
+ mod = path.split("::")[0]
299
+ i = run.names.index(mod) if mod in run.names else 0
300
+ leaf = path.split("::")[-1]
301
+ fn = next(
302
+ (
303
+ n
304
+ for n in sorted(units[i].by_name, key=len, reverse=True)
305
+ if n.split(".")[-1] in leaf
306
+ ),
307
+ MODULE,
308
+ )
309
+ res = results[i]["test"]
310
+ res["fails"].setdefault(fn, []).append(f"test failed: {path}")
311
+ res["result"].update(status="fail", errors=sum(map(len, res["fails"].values())))
312
+ for i in range(len(units)):
313
+ res = results[i]["test"]
314
+ res["result"]["detail"] = (
315
+ f"{sum(1 for t in ran if t[1] == 'ok')} passed, {sum(1 for t in ran if t[1] == 'FAILED')} failed"
316
+ )
317
+
318
+
319
+ def _file_verdict(
320
+ u: Unit, res: dict[str, dict[str, Any]], wanted: tuple[str, ...]
321
+ ) -> dict[str, Any]:
322
+ present, stubbed = u.present(), u.stubbed()
323
+ names = [f["name"] for f in u.funcs] or sorted(present)
324
+ starts = {f["name"]: f["start"] for f in u.funcs}
325
+ functions = []
326
+ for name in names + ([MODULE] if any(MODULE in r["fails"] for r in res.values()) else []):
327
+ rungs = {}
328
+ for rung in wanted:
329
+ r = res.get(rung)
330
+ if r is None:
331
+ rungs[rung] = "unverified"
332
+ elif name in r["fails"]:
333
+ rungs[rung] = "fail"
334
+ else:
335
+ rungs[rung] = r["result"]["status"] if r["result"]["status"] != "fail" else "pass"
336
+ highest = None
337
+ for rung in wanted:
338
+ if rungs[rung] != "pass":
339
+ break
340
+ highest = rung
341
+ has_item = name in present
342
+ has_todo = name in stubbed
343
+ check_status = rungs.get("check")
344
+ functions.append(
345
+ {
346
+ "function": name,
347
+ "kind": "module" if name == MODULE else "function",
348
+ "py_line": starts.get(name),
349
+ "has_item": has_item,
350
+ "has_todo": has_todo,
351
+ "rungs": rungs,
352
+ "highest_rung": highest,
353
+ "check_clean": name != MODULE
354
+ and has_item
355
+ and not has_todo
356
+ and check_status == "pass",
357
+ "messages": sorted({m for r in res.values() for m in r["fails"].get(name, [])})[
358
+ :20
359
+ ],
360
+ }
361
+ )
362
+ return {
363
+ "file": u.module.name,
364
+ "rungs": {r: res[r]["result"] if r in res else _rung("unverified") for r in wanted},
365
+ "functions": functions,
366
+ }
367
+
368
+
369
+ def verify_summary(files: list[dict[str, Any]], wanted_level: str) -> dict[str, Any]:
370
+ funcs = [f for fl in files for f in fl["functions"] if f["kind"] == "function"]
371
+ checks = Counter(f["rungs"].get("check") for f in funcs)
372
+ # numbers are only claimed when every function was actually compiled (cargo present and working)
373
+ has_check = LEVELS.index(wanted_level) >= LEVELS.index("check") and checks["unverified"] == 0
374
+ reached_check = LEVELS.index(wanted_level) >= LEVELS.index("check")
375
+ out: dict[str, Any] = {
376
+ "files": len(files),
377
+ "functions_total": len(funcs),
378
+ "functions_with_rust": sum(f["has_item"] for f in funcs),
379
+ "functions_translated": sum(f["has_item"] and not f["has_todo"] for f in funcs),
380
+ "functions_check_pass": checks["pass"] if has_check else None,
381
+ "functions_check_clean": sum(f["check_clean"] for f in funcs) if has_check else None,
382
+ "functions_unverified": checks["unverified"] if reached_check else None,
383
+ "failing_functions": sum(
384
+ 1 for fl in files for f in fl["functions"] if "fail" in f["rungs"].values()
385
+ ),
386
+ "highest_rung_counts": dict(Counter(f["highest_rung"] or "none" for f in funcs)),
387
+ }
388
+ clean = sum(f["check_clean"] for f in funcs)
389
+ out["functions_check_clean_pct"] = (
390
+ round(100.0 * clean / len(funcs), 1) if has_check and funcs else None
391
+ )
392
+ if wanted_level == "equiv":
393
+ from python2rust.verify.equiv import summary_fields
394
+
395
+ out.update(summary_fields(files))
396
+ return out