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,323 @@
1
+ """`eval`: translate and verify a corpus, and report numbers that can go in a README.
2
+
3
+ A corpus is a directory of `.py` files, optionally with an `expected.json` such as
4
+ `{"min": {"functions_check_clean_pct": 60}, "max": {"todos_per_100_lines": 4}}` over the metric
5
+ names below. `--baseline FILE` compares with an earlier `eval --json` document; `--baseline py2many`
6
+ runs py2many on the same files and counts the ones with usable output (it parses with rustfmt).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import shlex
14
+ import shutil
15
+ import subprocess
16
+ import sys
17
+ import tempfile
18
+ from collections import Counter
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from python2rust.cli import inputs, ops
23
+ from python2rust.errors import EXIT_FINDINGS, EXIT_INTERNAL, EXIT_OK, UsageError
24
+ from python2rust.verify import ladder
25
+
26
+ # metric -> True when a higher value is better (used for baseline regressions)
27
+ DIRECTION = {
28
+ "functions_check_clean_pct": True,
29
+ "functions_translated": True,
30
+ "files_fully_clean": True,
31
+ "todos_per_100_lines": False,
32
+ }
33
+
34
+
35
+ def code_lines(text: str | None) -> int:
36
+ return sum(
37
+ 1 for ln in (text or "").splitlines() if ln.strip() and not ln.strip().startswith("#")
38
+ )
39
+
40
+
41
+ def load_expected(corpus: Path) -> dict[str, dict[str, float]]:
42
+ path = corpus / "expected.json"
43
+ if not path.is_file():
44
+ return {}
45
+ try:
46
+ data = json.loads(path.read_text(encoding="utf-8"))
47
+ except ValueError as exc:
48
+ raise UsageError(f"{path} is not valid JSON: {exc}") from exc
49
+ return {k: v for k, v in data.items() if k in ("min", "max") and isinstance(v, dict)}
50
+
51
+
52
+ def _per_100(count: int, lines: int) -> float:
53
+ return round(100.0 * count / lines, 2) if lines else 0.0
54
+
55
+
56
+ def metrics(
57
+ sources: list[inputs.Source], entries: list[dict[str, Any]], ladder_doc: dict[str, Any]
58
+ ) -> dict[str, Any]:
59
+ summary = ladder.verify_summary(ladder_doc["files"], ladder_doc["level"])
60
+ by_file = {f["file"]: f for f in ladder_doc["files"]}
61
+ lines = sum(code_lines(s.text) for s in sources)
62
+ open_todos = [t for e in entries for t in e["todos"] if t["state"] == "open"]
63
+ verified = summary["functions_check_clean"] is not None
64
+
65
+ def fully_clean(e: dict[str, Any]) -> bool:
66
+ fl = by_file.get(e["file"])
67
+ if e["status"] != "clean" or fl is None:
68
+ return False
69
+ return (
70
+ verified
71
+ and fl["rungs"]["check"]["status"] == "pass"
72
+ and all(f["check_clean"] for f in fl["functions"] if f["kind"] == "function")
73
+ )
74
+
75
+ parses = sum(
76
+ 1 for fl in ladder_doc["files"] if fl["rungs"].get("parse", {}).get("status") == "pass"
77
+ )
78
+ return {
79
+ "files": len(entries),
80
+ "python_lines": lines,
81
+ "functions_total": summary["functions_total"],
82
+ "functions_translated": summary["functions_translated"],
83
+ "functions_check_clean": summary["functions_check_clean"],
84
+ "functions_check_clean_pct": summary["functions_check_clean_pct"],
85
+ "functions_unverified": summary["functions_unverified"],
86
+ "files_fully_clean": sum(fully_clean(e) for e in entries) if verified else None,
87
+ "files_with_parsing_rust": parses,
88
+ "todos_open": len(open_todos),
89
+ "todos_per_100_lines": _per_100(len(open_todos), lines),
90
+ "todos_per_100_lines_by_code": {
91
+ k: _per_100(v, lines) for k, v in sorted(Counter(t["code"] for t in open_todos).items())
92
+ },
93
+ "todos_per_100_lines_by_kind": {
94
+ k: _per_100(v, lines) for k, v in sorted(Counter(t["kind"] for t in open_todos).items())
95
+ },
96
+ "needs_review": sum(t["needs_review"] for e in entries for t in e["todos"]),
97
+ "drift_count": ops.summarize(entries)["drift_count"],
98
+ "drift_by_code": ops.summarize(entries)["drift_by_code"],
99
+ }
100
+
101
+
102
+ # --- baselines ----------------------------------------------------------------------------------
103
+
104
+
105
+ PY2MANY_TESTED = "0.9"
106
+ PY2MANY_WARNING = (
107
+ "py2many EXECUTES code derived from its input while transpiling (it evals input-derived text), "
108
+ "so --run-py2many may only be used on corpora you trust; python2rust itself never does this"
109
+ )
110
+
111
+
112
+ def py2many_command(explicit: str | None = None) -> list[str] | None:
113
+ """py2many from --py2many-cmd, else `py2many` on PATH. Never fetched implicitly (no uvx)."""
114
+ if explicit:
115
+ return shlex.split(explicit)
116
+ if exe := shutil.which("py2many"):
117
+ return [exe]
118
+ return None
119
+
120
+
121
+ def _scrubbed_env() -> dict[str, str]:
122
+ keep = ("PATH", "HOME", "LANG", "LC_ALL", "TMPDIR", "PYTHONUTF8")
123
+ return {k: v for k, v in os.environ.items() if k in keep}
124
+
125
+
126
+ def run_py2many(
127
+ sources: list[inputs.Source], timeout: float = 60, command: str | None = None
128
+ ) -> dict[str, Any]:
129
+ """Run py2many (--rust) on each file; a file is usable if it exits 0 and rustfmt parses the output.
130
+
131
+ Opt-in only (see PY2MANY_WARNING): each file runs in its own subprocess with a timeout, a scratch
132
+ working directory and a scrubbed environment.
133
+ """
134
+ base: dict[str, Any] = {"name": "py2many", "available": False, "reason": None, "files": []}
135
+ cmd = py2many_command(command)
136
+ if cmd is None:
137
+ base["reason"] = (
138
+ f"py2many is not installed; install the tested version (uv tool install py2many=={PY2MANY_TESTED}) "
139
+ "or pass --py2many-cmd"
140
+ )
141
+ return base
142
+ try:
143
+ probe = subprocess.run(
144
+ [*cmd, "--help"], capture_output=True, text=True, timeout=300, env=_scrubbed_env()
145
+ )
146
+ except (OSError, subprocess.SubprocessError) as exc:
147
+ base["reason"] = f"cannot run py2many: {exc}"
148
+ return base
149
+ if probe.returncode != 0:
150
+ base["reason"] = f"py2many --help failed: {probe.stderr.strip()[-200:]}"
151
+ return base
152
+ base["available"] = True
153
+ for src in sources:
154
+ with tempfile.TemporaryDirectory(prefix="python2rust-py2many-") as tmp:
155
+ work = Path(tmp)
156
+ (work / "in").mkdir()
157
+ py = work / "in" / "case.py"
158
+ py.write_text(src.text or "", encoding="utf-8")
159
+ try:
160
+ p = subprocess.run(
161
+ [*cmd, "--rust", "--outdir", str(work / "out"), str(py)],
162
+ capture_output=True, text=True, timeout=timeout, cwd=work, env=_scrubbed_env(),
163
+ ) # fmt: skip
164
+ rc = p.returncode
165
+ except subprocess.TimeoutExpired:
166
+ rc = None
167
+ out = next((work / "out").glob("*.rs"), None) if (work / "out").is_dir() else None
168
+ out = out or next(work.glob("*.rs"), None)
169
+ text = out.read_text(encoding="utf-8", errors="replace") if out else ""
170
+ usable, reason = False, None
171
+ if rc is None:
172
+ reason = "timeout"
173
+ elif rc != 0 or text.strip() in ("", "FAILED"):
174
+ reason = (
175
+ "no output" if not text.strip() or text.strip() == "FAILED" else f"exit {rc}"
176
+ )
177
+ else:
178
+ fmt = ladder.rustfmt_run(text)
179
+ usable = fmt["ok"] if fmt["available"] else False
180
+ reason = (
181
+ None
182
+ if usable
183
+ else (
184
+ fmt.get("error")
185
+ or (
186
+ "rustfmt not found" if not fmt["available"] else "output does not parse"
187
+ )
188
+ )
189
+ )
190
+ base["files"].append({"file": src.display, "usable": usable, "reason": reason})
191
+ usable_n = sum(f["usable"] for f in base["files"])
192
+ base.update(files_total=len(sources), files_usable=usable_n)
193
+ base["files_usable_pct"] = round(100.0 * usable_n / len(sources), 1) if sources else 0.0
194
+ return base
195
+
196
+
197
+ def compare_baseline(current: dict[str, Any], path: str) -> dict[str, Any]:
198
+ try:
199
+ old = json.loads(Path(path).read_text(encoding="utf-8"))["metrics"]
200
+ except OSError, ValueError, KeyError, TypeError:
201
+ raise UsageError(
202
+ f"--baseline {path} is not an `eval --json` document (or py2many)"
203
+ ) from None
204
+ deltas, regressions = {}, []
205
+ for key, higher_better in DIRECTION.items():
206
+ a, b = old.get(key), current.get(key)
207
+ if a is None or b is None:
208
+ continue
209
+ deltas[key] = {"baseline": a, "current": b, "delta": round(b - a, 2)}
210
+ if (b < a) if higher_better else (b > a):
211
+ regressions.append(key)
212
+ return {"kind": "file", "path": path, "deltas": deltas, "regressions": regressions}
213
+
214
+
215
+ def check_expected(current: dict[str, Any], expected: dict[str, dict[str, float]]) -> list[str]:
216
+ failed = []
217
+ for bound, op in (("min", lambda v, e: v < e), ("max", lambda v, e: v > e)):
218
+ for key, limit in expected.get(bound, {}).items():
219
+ value = current.get(key)
220
+ if value is None or op(value, limit):
221
+ failed.append(f"{key}={value} violates {bound} {limit}")
222
+ return failed
223
+
224
+
225
+ def markdown(m: dict[str, Any], py2many: dict[str, Any] | None) -> str:
226
+ def pct(part: Any, whole: int) -> str:
227
+ return (
228
+ "n/a (cargo missing)"
229
+ if part is None
230
+ else f"{part} / {whole} ({round(100.0 * part / whole, 1) if whole else 100.0}%)"
231
+ )
232
+
233
+ rows = [
234
+ "| metric | value |",
235
+ "|---|---:|",
236
+ f"| files / Python lines | {m['files']} / {m['python_lines']} |",
237
+ f"| functions total | {m['functions_total']} |",
238
+ f"| functions translated (Rust output, no todo!()) | {m['functions_translated']} |",
239
+ f"| **functions check-clean** (no todo!(), passes `cargo check`) | {pct(m['functions_check_clean'], m['functions_total'])} |",
240
+ f"| files fully clean | {pct(m['files_fully_clean'], m['files'])} |",
241
+ f"| open TODOs per 100 lines | {m['todos_per_100_lines']} |",
242
+ f"| drift notes (may behave differently) | {m['drift_count']} |",
243
+ ]
244
+ rows += [
245
+ f"| TODOs per 100 lines, `{k}` | {v} |" for k, v in m["todos_per_100_lines_by_code"].items()
246
+ ]
247
+ rows += [
248
+ f"| files with Rust that parses (python2rust) | {m['files_with_parsing_rust']} / {m['files']} |"
249
+ ]
250
+ if py2many is not None:
251
+ if py2many["available"]:
252
+ rows.append(
253
+ f"| files with usable output (py2many) | {py2many['files_usable']} / {py2many['files_total']} ({py2many['files_usable_pct']}%) |"
254
+ )
255
+ else:
256
+ rows.append(f"| files with usable output (py2many) | n/a ({py2many['reason']}) |")
257
+ return "\n".join(rows) + "\n"
258
+
259
+
260
+ def eval_corpus(
261
+ corpus_dir: str,
262
+ *,
263
+ level: str,
264
+ config_path: str | None,
265
+ baseline: str | None,
266
+ deps_from: str | None,
267
+ offline: bool,
268
+ timeout: float,
269
+ target_dir: str | None,
270
+ run_py2many_baseline: bool = False,
271
+ py2many_cmd: str | None = None,
272
+ ) -> tuple[dict[str, Any], int]:
273
+ corpus = Path(corpus_dir)
274
+ if not corpus.is_dir():
275
+ raise UsageError(f"corpus directory does not exist: {corpus_dir}")
276
+ expected = load_expected(corpus)
277
+ sources = inputs.collect([corpus_dir])
278
+ entries = ops.run_translate(sources, config_path)
279
+ modules = ops.modules_for(sources, entries)
280
+ ladder_doc = ladder.verify_units(
281
+ modules, level, deps_from=deps_from, offline=offline, timeout=timeout, target_dir=target_dir
282
+ )
283
+ m = metrics(sources, entries, ladder_doc)
284
+ base_doc: dict[str, Any] | None = None
285
+ py2many: dict[str, Any] | None = None
286
+ if baseline == "py2many":
287
+ if not run_py2many_baseline:
288
+ raise UsageError(
289
+ "--baseline py2many runs py2many, which executes code derived from the corpus: add --run-py2many to confirm the corpus is trusted"
290
+ )
291
+ print(f"python2rust: warning: {PY2MANY_WARNING}", file=sys.stderr)
292
+ py2many = run_py2many(sources, command=py2many_cmd)
293
+ base_doc = {"kind": "py2many", **py2many}
294
+ elif baseline:
295
+ base_doc = compare_baseline(m, baseline)
296
+ failed = check_expected(m, expected)
297
+ regressions = base_doc["regressions"] if base_doc and base_doc["kind"] == "file" else []
298
+ code = EXIT_OK
299
+ if any(e["status"] == "internal_error" for e in entries):
300
+ code = EXIT_INTERNAL
301
+ elif failed or regressions:
302
+ code = EXIT_FINDINGS
303
+ files = [
304
+ {
305
+ "file": e["file"],
306
+ "status": e["status"],
307
+ "todos_open": sum(t["state"] == "open" for t in e["todos"]),
308
+ "functions_total": e["stats"]["functions_total"],
309
+ }
310
+ for e in entries
311
+ ]
312
+ doc = ops.envelope(
313
+ "eval",
314
+ ok=code == EXIT_OK,
315
+ level=level,
316
+ corpus=corpus.as_posix(),
317
+ metrics=m,
318
+ expectations_failed=failed,
319
+ baseline=base_doc,
320
+ files=files,
321
+ markdown=markdown(m, py2many),
322
+ )
323
+ return doc, code
@@ -0,0 +1,168 @@
1
+ """`explain CODE`: what a diagnostic means, why it happens, how to fix it, with an example."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from python2rust._core import get_core
8
+ from python2rust.cli.ops import envelope
9
+ from python2rust.errors import UsageError
10
+
11
+ # Hand-written explanations for the documented codes. A code the core defines but this table
12
+ # does not know still explains itself from the core's one-line text (documented = false).
13
+ _DOCS: dict[str, dict[str, Any]] = {
14
+ "PY2RS001": {
15
+ "why": "ast.parse rejected the file (python2rust parses with the Python 3.14 grammar), so "
16
+ "no Rust could be produced; the output is a one-line comment holding the error.",
17
+ "fix": "Fix the syntax error at the reported line, or run the file through the Python "
18
+ "version it was written for. Nothing else in the file is reported until it parses.",
19
+ "example": {
20
+ "python": "def f(x: int) -> int\n return x",
21
+ "rust_before": "// python2rust PY2RS001: syntax error: expected ':' (m.py)",
22
+ "rust_after": "pub fn f(x: i64) -> i64 {\n x\n}",
23
+ },
24
+ },
25
+ "PY2RS003": {
26
+ "why": "This statement kind has no translation yet. It will not guess: it became a "
27
+ "todo!() whose message carries the TODO id, so the Rust fails loudly if reached.",
28
+ "fix": "Read the todo's python_snippet and rust_context, write the Rust for that one "
29
+ "statement, submit it with `python2rust apply ID --patch FILE`, then run `python2rust check`.",
30
+ "example": {
31
+ "python": "def f(xs: list[int]) -> int:\n for x in xs:\n pass\n else:\n return 1\n return 0",
32
+ "rust_before": 'todo!("python2rust t74c171c3 PY2RS003: for/else at m.py:2");',
33
+ "rust_after": "for _x in xs {}\nreturn 1; // no `break`, so the else branch always runs",
34
+ },
35
+ },
36
+ "PY2RS004": {
37
+ "why": "This expression kind (or a name that cannot be resolved, for example an unmapped "
38
+ "import) has no translation yet and became a todo!().",
39
+ "fix": "If the name comes from an unmapped import, add it to `library_map` / `import_map` in "
40
+ "your config (--config) and re-translate; otherwise write the expression by hand with "
41
+ "`python2rust apply ID --patch FILE`.",
42
+ "example": {
43
+ "python": "import humanize\n\ndef size(n: int) -> str:\n return humanize.naturalsize(n)",
44
+ "rust_before": 'todo!("python2rust t9004bbb4 PY2RS004: unresolved name humanize at m.py:4")',
45
+ "rust_after": "humansize::format_size(n as u64, humansize::DECIMAL)",
46
+ },
47
+ },
48
+ "PY2RS005": {
49
+ "why": "A type annotation has no Rust mapping. An undefined placeholder type "
50
+ "(`Py2rsUnmapped_<name>`) marks the place, so `cargo check` reports it as unresolved-type "
51
+ "until it is replaced. This TODO has no todo!() to patch.",
52
+ "fix": "Map the type in `type_map` in your config and re-translate, or define the type "
53
+ "yourself in the Rust file.",
54
+ "example": {
55
+ "python": "def g(x: Frob) -> int:\n return 1",
56
+ "rust_before": "pub fn g(x: Py2rsUnmapped_Frob) -> i64 { 1 }",
57
+ "rust_after": 'pub fn g(x: Frob) -> i64 { 1 } // with `type_map = { Frob = "Frob" }`',
58
+ },
59
+ },
60
+ "PY2RS006": {
61
+ "why": "A parameter or return annotation is missing, so the Rust signature cannot be "
62
+ "written. The whole function became a stub `fn py2rs_todo_<id>() { todo!(...) }`.",
63
+ "fix": "Add precise annotations in the Python source and re-translate (preferred), or "
64
+ "write the whole function in Rust with `python2rust apply ID --patch FILE`.",
65
+ "example": {
66
+ "python": "def scale(x, k: float):\n return x * k",
67
+ "rust_before": 'fn py2rs_todo_te64483ba() {\n todo!("python2rust te64483ba PY2RS006: missing annotation for parameter x of scale() at m.py:1")\n}',
68
+ "rust_after": "def scale(x: float, k: float) -> float: # then re-translate",
69
+ },
70
+ },
71
+ "PY2RS007": {
72
+ "why": "Any, object or an unparameterised list/dict maps to serde_json::Value, so type "
73
+ "information is lost (informational: the Rust compiles).",
74
+ "fix": "Give the Python a precise type (`list[int]` instead of `list`) and re-translate.",
75
+ "example": {
76
+ "python": "def f(x: list) -> int:\n return 1",
77
+ "rust_before": "pub fn f(x: Vec<serde_json::Value>) -> i64 { 1 }",
78
+ "rust_after": "pub fn f(x: Vec<i64>) -> i64 { 1 }",
79
+ },
80
+ },
81
+ "PY2RS010": {
82
+ "why": "An import is not mapped to a Rust crate or module; every use of the imported name "
83
+ "becomes a TODO.",
84
+ "fix": "Add the module to `library_map` / `import_map` in your config file (--config) and "
85
+ "re-translate, or write the `use` line by hand.",
86
+ "example": {
87
+ "python": "import humanize",
88
+ "rust_before": 'fn py2rs_todo_tdb0782a0() {\n todo!("python2rust tdb0782a0 PY2RS010: import humanize at m.py:1")\n}',
89
+ "rust_after": "use humansize::{format_size, DECIMAL};",
90
+ },
91
+ },
92
+ "PY2RS019": {
93
+ "why": "A call or method could not be resolved: unknown callee, or a receiver whose type "
94
+ "is not known. It became a todo!() instead of a guess.",
95
+ "fix": "If it is a library call, add it to `library_map` in your config; otherwise write the "
96
+ "Rust for the call with `python2rust apply ID --patch FILE`.",
97
+ "example": {
98
+ "python": "def get(o: Item, name: str) -> str:\n return getattr(o, name)",
99
+ "rust_before": 'todo!("python2rust teb7ba511 PY2RS019: call to unknown function getattr() at m.py:15");',
100
+ "rust_after": 'match name {\n "id" => o.id.to_string(),\n _ => String::new(),\n}',
101
+ },
102
+ },
103
+ "PY2RS041": {
104
+ "why": "Drift, not an error: Python ints are unbounded, Rust's i64 is not. With the default "
105
+ '`int_overflow = "checked"` an overflow panics; `wrapping` and `native` wrap silently. '
106
+ "The Rust compiles and agrees with Python for every value that fits.",
107
+ "fix": "Decide per call site whether values can exceed i64. If they can, use a wider "
108
+ "type or a bigint crate by hand; otherwise keep the checked arithmetic and add a test.",
109
+ "example": {
110
+ "python": "def add(a: int, b: int) -> int:\n return a + b",
111
+ "rust_before": "pub fn add(a: i64, b: i64) -> i64 {\n rt::add(a, b) // panics on overflow\n}",
112
+ "rust_after": "pub fn add(a: i64, b: i64) -> i64 {\n rt::add(a, b) // reviewed: inputs are small\n}",
113
+ },
114
+ },
115
+ }
116
+
117
+
118
+ def normalize_code(raw: str) -> str:
119
+ """Accept `PY2RS001`, `py2rs001`, `PY2RS1`, `001` and `1`."""
120
+ s = raw.strip().upper()
121
+ s = s.removeprefix("PY2RS").lstrip("-_ ")
122
+ return f"PY2RS{int(s):03d}" if s.isdigit() else raw.strip().upper()
123
+
124
+
125
+ def codes() -> dict[str, str]:
126
+ from python2rust.report.contract import CODES
127
+
128
+ contract = {code: f"[contract, {sev}] {text}" for code, (sev, text) in CODES.items()}
129
+ return dict(sorted({**get_core().DIAGNOSTIC_CODES, **contract}.items()))
130
+
131
+
132
+ def explain_doc(raw_code: str) -> dict[str, Any]:
133
+ table = codes()
134
+ code = normalize_code(raw_code)
135
+ if code not in table:
136
+ raise UsageError(f"unknown diagnostic code {raw_code!r}; known codes: {', '.join(table)}")
137
+ doc = _DOCS.get(code)
138
+ return envelope(
139
+ "explain",
140
+ code=code,
141
+ summary=table[code],
142
+ documented=doc is not None,
143
+ why=doc["why"] if doc else table[code],
144
+ fix=doc["fix"]
145
+ if doc
146
+ else (
147
+ "Find the diagnostic's location in the translate output, read its hint, fix the Rust or "
148
+ "the Python source, then re-run `python2rust translate` and `python2rust check`."
149
+ ),
150
+ example=doc["example"] if doc else None,
151
+ )
152
+
153
+
154
+ def explain_text(doc: dict[str, Any]) -> str:
155
+ out = [f"{doc['code']}: {doc['summary']}", "", f"Why: {doc['why']}", "", f"Fix: {doc['fix']}"]
156
+ if (ex := doc["example"]) is not None:
157
+ out += [
158
+ "",
159
+ "Python:",
160
+ ex["python"],
161
+ "",
162
+ "Rust before:",
163
+ ex["rust_before"],
164
+ "",
165
+ "Rust after:",
166
+ ex["rust_after"],
167
+ ]
168
+ return "\n".join(out) + "\n"