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,312 @@
1
+ """`python2rust next`: one unit as a self-contained brief, and the PORTING.md that records the decisions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import shlex
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from python2rust.workflow.interview import agent_flags
11
+
12
+ PORTING = "PORTING.md"
13
+ CONFIG = "python2rust.toml"
14
+
15
+ _CRATES = {
16
+ "requests": "reqwest", "httpx": "reqwest", "aiohttp": "reqwest (client) or axum (server)",
17
+ "flask": "axum", "fastapi": "axum", "starlette": "axum", "pydantic": "serde derives",
18
+ "numpy": "ndarray", "pandas": "polars", "yaml": "serde_yaml", "dateutil": "chrono",
19
+ "pytz": "chrono-tz", "click": "clap", "sqlalchemy": "sqlx", "psycopg2": "sqlx",
20
+ "redis": "redis", "jwt": "jsonwebtoken", "bcrypt": "bcrypt", "tqdm": "indicatif",
21
+ "orjson": "serde_json", "lxml": "quick-xml", "attrs": "structs with derives",
22
+ } # fmt: skip
23
+ _STD = {
24
+ "json": "serde_json", "re": "regex", "datetime": "chrono", "logging": "tracing",
25
+ "argparse": "clap", "sqlite3": "rusqlite", "random": "rand", "uuid": "uuid",
26
+ "asyncio": "tokio", "subprocess": "std::process", "pathlib": "std::path",
27
+ "collections": "std::collections or indexmap", "hashlib": "sha2 and friends",
28
+ "base64": "base64", "csv": "csv", "decimal": "rust_decimal", "tempfile": "tempfile",
29
+ "threading": "std::thread", "zlib": "flate2", "heapq": "BinaryHeap",
30
+ } # fmt: skip
31
+
32
+
33
+ def _type_notes(a: dict[str, Any]) -> list[str]:
34
+ maps = {"insertion": "IndexMap", "maps-ordered": "IndexMap", "hash": "HashMap"}[a["ordering"]]
35
+ sets = {"insertion": "IndexSet", "maps-ordered": "HashSet", "hash": "HashSet"}[a["ordering"]]
36
+ errors = (
37
+ "one crate-level error enum"
38
+ if a["error_style"] == "crate-enum"
39
+ else "one error type per module"
40
+ )
41
+ return [
42
+ f"`int` -> `i64` ({a['int_overflow']} arithmetic); `float` -> `f64`; `bool` -> `bool`; `bytes` -> `Vec<u8>`",
43
+ "`str` -> `String` (`&str` for borrowed parameters); `list[T]` -> `Vec<T>`; `tuple` -> tuple",
44
+ f"`dict[K, V]` -> `{maps}`; `set[T]` -> `{sets}`; `Optional[T]` -> `Option<T>`",
45
+ "classes and dataclasses -> structs; inheritance -> traits or an enum (decide per unit)",
46
+ f"exceptions -> {errors}",
47
+ ]
48
+
49
+
50
+ def unit_decisions(u: dict[str, Any], a: dict[str, Any]) -> list[dict[str, str]]:
51
+ def d(qid: str, text: str) -> dict[str, str]:
52
+ return {"id": qid, "decision": text}
53
+
54
+ out = [
55
+ d("output_tier", f"finish to the `{a['output_tier']}` tier"),
56
+ d("equivalence", f"output equality: {a['equivalence']}"),
57
+ d("int_overflow", f"integer arithmetic: {a['int_overflow']}"),
58
+ d("ordering", f"dict and set ordering: {a['ordering']}"),
59
+ ]
60
+ if u["async_functions"]:
61
+ out.append(d("async_http", f"async and HTTP stack: {a['async_http']}"))
62
+ if u["try_blocks"] or u["exception_classes"]:
63
+ out.append(d("error_style", f"errors: {a['error_style']}"))
64
+ if u["risk"]["areas"]:
65
+ out.append(d("review_areas", "a human reviews: " + ", ".join(u["risk"]["areas"])))
66
+ return out
67
+
68
+
69
+ def mapping_notes(u: dict[str, Any], a: dict[str, Any]) -> dict[str, Any]:
70
+ crates = [{"python": m, "rust": _CRATES[m]} for m in u["third_party"] if m in _CRATES]
71
+ crates += [{"python": m, "rust": _STD[m]} for m in u["stdlib"] if m in _STD]
72
+ unmapped = [m for m in u["third_party"] if m not in _CRATES]
73
+ return {
74
+ "types": _type_notes(a),
75
+ "crates": sorted(crates, key=lambda c: c["python"]),
76
+ "unmapped_imports": unmapped,
77
+ "exception_classes": u["exception_classes"],
78
+ }
79
+
80
+
81
+ def open_questions(u: dict[str, Any], a: dict[str, Any]) -> list[str]:
82
+ qs = [
83
+ f"Third-party import `{m}` has no suggested crate: which crate replaces it?"
84
+ for m in mapping_notes(u, a)["unmapped_imports"]
85
+ ]
86
+ if u["exception_classes"]:
87
+ qs.append(
88
+ "Exception classes "
89
+ + ", ".join(u["exception_classes"])
90
+ + ": confirm the variant names and fields."
91
+ )
92
+ if u["depends_on_python"]:
93
+ qs.append(
94
+ "Imports Python that stays Python ("
95
+ + ", ".join(u["depends_on_python"])
96
+ + "): port that API or bridge it?"
97
+ )
98
+ if u["risk"]["dynamic"]:
99
+ qs.append(
100
+ "Dynamic features ("
101
+ + ", ".join(u["risk"]["dynamic"])
102
+ + ") have no static Rust form: redesign or leave a TODO?"
103
+ )
104
+ if not u["tests"]:
105
+ qs.append("No tests reference this unit: which cases define correct behaviour?")
106
+ if u["risk"]["cycle"]:
107
+ qs.append("Import cycle: which module owns the shared types?")
108
+ return qs
109
+
110
+
111
+ def needs_equiv(a: dict[str, Any]) -> bool:
112
+ """The tier includes the equivalence rung and the user allowed running their Python."""
113
+ return a["output_tier"] != "draft" and a["run_python"] == "yes"
114
+
115
+
116
+ def done_command(unit_id: str, answers: dict[str, Any]) -> str:
117
+ """The exact `done` call for a unit; it carries `--run-python` when the tier needs equivalence
118
+ and the human allowed it (the flag, given at run time, is what lets Python run)."""
119
+ flag = ["--run-python"] if needs_equiv(answers) else []
120
+ return sh("python2rust", "done", unit_id, "--project", ".", *flag, "--json")
121
+
122
+
123
+ def sh(*argv: str) -> str:
124
+ """One shell-safe command line: every word goes through shlex.quote."""
125
+ return shlex.join(argv)
126
+
127
+
128
+ def commands(u: dict[str, Any], a: dict[str, Any], root: Path) -> list[dict[str, str]]:
129
+ # every command works on the whole planned project and narrows to this unit with --unit: the
130
+ # unit's imports of other units resolve, the crate lists every module, the tests that import the
131
+ # unit run (a unit translated alone would flatten its paths and orphan the units done before it)
132
+ unit = [f"--unit={u['id']}"] if u["id"].startswith("-") else ["--unit", u["id"]]
133
+ crate = f"rust/{a['crate_name']}"
134
+ cfg = ["--project", ".", "--config", CONFIG]
135
+ flags = agent_flags(a)
136
+ if flags and a["budget_tokens"]:
137
+ flags += ["--budget-tokens", str(a["budget_tokens"])]
138
+ if flags and a["budget_seconds"]:
139
+ flags += ["--budget-seconds", str(a["budget_seconds"])]
140
+ equiv = needs_equiv(a)
141
+ level = (
142
+ "equiv"
143
+ if equiv
144
+ else {"draft": "check", "verified": "check", "production": "test"}[a["output_tier"]]
145
+ )
146
+ vflags: list[str] = []
147
+ if equiv:
148
+ compare = "strict" if a["equivalence"] == "strict" else "functional"
149
+ vflags = ["--run-python", "--compare", compare]
150
+ vflags += flags if a["equivalence"] == "functional-judge" else []
151
+ deps = ["--deps-from", f"{crate}/Cargo.toml"] if (root / crate / "Cargo.toml").is_file() else []
152
+ # equivalence runs the user's Python: `--run-python` only with their consent; with run_python=no
153
+ # the fix is accepted at check+tests and records that equivalence was not compared (--no-equiv)
154
+ patch_flag = ["--run-python"] if a["run_python"] == "yes" else ["--no-equiv"]
155
+ return [
156
+ {"step": "port", "purpose": "translate the project, compile and repair this unit into the crate"
157
+ + ("" if flags else " (no backend: a dry run that lists the repair tasks for you)"),
158
+ "command": sh("python2rust", "port", *unit, "-o", crate, *cfg, *flags, "--json")},
159
+ {"step": "todos", "purpose": "the work list; needs_review ones are for a human",
160
+ "command": sh("python2rust", "todos", *unit, *cfg, "--json")},
161
+ {"step": "apply", "purpose": "store the fix for one todo (never edit generated Rust); also promotes a fix `port` stored unverified: its id is fn-..., --patch .python2rust/patches/ID.rs",
162
+ "command": sh("python2rust", "apply", "TODO_ID", "--patch", "FILE", *unit, *cfg, *deps, *patch_flag, "--json")},
163
+ {"step": "verify", "purpose": f"run the ladder up to `{level}`",
164
+ "command": sh("python2rust", "verify", *unit, "--level", level, *cfg, *deps, *vflags, "--json")},
165
+ {"step": "done", "purpose": "record the unit as done if the required rungs pass",
166
+ "command": done_command(u["id"], a)},
167
+ ] # fmt: skip
168
+
169
+
170
+ def acceptance(u: dict[str, Any], a: dict[str, Any]) -> list[str]:
171
+ tier, out = a["output_tier"], ["every function has Rust output and no `todo!()` is left"]
172
+ out.append(
173
+ "`cargo check` passes for the unit's files (compiled together with the units it depends on)"
174
+ )
175
+ if tier == "production":
176
+ out += [
177
+ "`cargo clippy` reports no warnings",
178
+ "`cargo test` passes and at least one Rust test exists"
179
+ if u["tests"]
180
+ else "`cargo test` passes",
181
+ ]
182
+ if tier != "draft":
183
+ if a["run_python"] == "yes":
184
+ how = {"strict": "byte for byte", "functional": "functionally (canonical JSON, [equivalence] rules)",
185
+ "functional-judge": "functionally; leftovers judged by the model and queued for review"}[a["equivalence"]] # fmt: skip
186
+ out.append(
187
+ f"the equivalence rung passes: Rust and Python outputs match {how}; it only runs "
188
+ "when `done` gets --run-python (otherwise the unit is recorded as compiled/tested, "
189
+ "never verified)"
190
+ )
191
+ else:
192
+ out.append("equivalence is NOT run (run_python=no): `done` records it as not verified")
193
+ if u["tests"]:
194
+ out.append(
195
+ "port " + ", ".join(u["tests"]) + " together with the code; never weaken an assertion"
196
+ )
197
+ if u["coverage"]["needs_review_todos"] or u["risk"]["areas"]:
198
+ out.append(
199
+ "needs_review work is handed to a human; they confirm with `python2rust done UNIT --reviewed`"
200
+ )
201
+ return out
202
+
203
+
204
+ def build(u: dict[str, Any], a: dict[str, Any], root: Path, remaining: int) -> dict[str, Any]:
205
+ brief = {
206
+ "unit": {
207
+ k: u[k]
208
+ for k in (
209
+ "id",
210
+ "order",
211
+ "modules",
212
+ "files",
213
+ "depends_on",
214
+ "depends_on_python",
215
+ "tests",
216
+ "difficulty",
217
+ "risk",
218
+ "size",
219
+ "coverage",
220
+ )
221
+ },
222
+ "remaining": remaining,
223
+ "decisions": unit_decisions(u, a),
224
+ "mapping_notes": mapping_notes(u, a),
225
+ "open_questions": open_questions(u, a),
226
+ "commands": commands(u, a, root),
227
+ "acceptance": acceptance(u, a),
228
+ "porting_md": PORTING,
229
+ }
230
+ brief["markdown"] = markdown(u, brief)
231
+ return brief
232
+
233
+
234
+ def _unit_section(u: dict[str, Any], b: dict[str, Any]) -> list[str]:
235
+ n = b["mapping_notes"]
236
+ lines = [f"## Unit: {u['id']}", ""]
237
+ lines += [f"- files: {', '.join(f'`{f}`' for f in u['files'])}"]
238
+ lines += [f"- depends on: {', '.join(u['depends_on']) or 'nothing (a leaf)'}"]
239
+ lines += [f"- tests found: {', '.join(u['tests']) or 'none'}"]
240
+ d = u["difficulty"]
241
+ lines += [
242
+ f"- difficulty: {d['level']} ({d['score']}): {'; '.join(d['reasons']) or 'small and plain'}",
243
+ "",
244
+ ]
245
+ lines += ["### Decisions", *(f"- {x['decision']} (`{x['id']}`)" for x in b["decisions"]), ""]
246
+ lines += ["### Mapping notes"]
247
+ lines += [f"- `{c['python']}` -> {c['rust']}" for c in n["crates"]] or [
248
+ "- no library imports to map"
249
+ ]
250
+ lines += [
251
+ "",
252
+ "### Open questions",
253
+ *([f"- {q}" for q in b["open_questions"]] or ["- none"]),
254
+ "",
255
+ ]
256
+ return lines
257
+
258
+
259
+ def longest_backticks(text: str) -> int:
260
+ return max((len(m) for m in re.findall(r"`+", text)), default=0)
261
+
262
+
263
+ def markdown(u: dict[str, Any], b: dict[str, Any]) -> str:
264
+ lines = [f"# Next unit: {u['id']} ({b['remaining']} unit(s) left including this one)", ""]
265
+ lines += _unit_section(u, b)[2:]
266
+ lines += ["### Commands (run from the project root)", ""]
267
+ for i, c in enumerate(b["commands"], 1):
268
+ fence = "`" * max(3, longest_backticks(c["command"]) + 1)
269
+ lines += [f"{i}. {c['purpose']}:", "", f"{fence}sh", c["command"], fence, ""]
270
+ lines += ["", "### Acceptance", *(f"- {x}" for x in b["acceptance"]), ""]
271
+ return "\n".join(lines)
272
+
273
+
274
+ # --- PORTING.md ---------------------------------------------------------------------------------
275
+
276
+
277
+ def _block(key: str, body: str) -> str:
278
+ return f"<!-- python2rust:begin {key} -->\n{body.rstrip()}\n<!-- python2rust:end {key} -->"
279
+
280
+
281
+ def refresh_porting(root: Path, plan: dict[str, Any], a: dict[str, Any]) -> Path:
282
+ """Create or refresh PORTING.md: generated blocks are replaced, anything else is kept."""
283
+ path = root / PORTING
284
+ text = path.read_text(encoding="utf-8") if path.is_file() else "# PORTING\n\n"
285
+ blocks = {"global": "## Decisions for the whole port\n\n"
286
+ + "\n".join(f"- {line}" for line in _global_lines(a)) + "\n\n### Type mapping\n\n"
287
+ + "\n".join(f"- {t}" for t in _type_notes(a))} # fmt: skip
288
+ for u in plan["units"]:
289
+ blocks[f"unit {u['id']}"] = "\n".join(_unit_section(u, build(u, a, root, 0)))
290
+ for key, body in blocks.items():
291
+ block = _block(key, body)
292
+ pat = re.compile(
293
+ rf"<!-- python2rust:begin {re.escape(key)} -->.*?<!-- python2rust:end {re.escape(key)} -->",
294
+ re.S,
295
+ )
296
+ text = (
297
+ pat.sub(lambda _m, b=block: b, text)
298
+ if pat.search(text)
299
+ else text.rstrip() + "\n\n" + block + "\n"
300
+ )
301
+ path.write_text(text, encoding="utf-8")
302
+ return path
303
+
304
+
305
+ def _global_lines(a: dict[str, Any]) -> list[str]:
306
+ return [
307
+ f"goal: {a['goal']}; scope: {', '.join(a['scope'])}; stays Python: {', '.join(a['keep_python']) or 'nothing'}",
308
+ f"equivalence: {a['equivalence']}; oracles: {', '.join(a['oracles']) or 'none'}; run Python: {a['run_python']}",
309
+ f"model backend: {a['backend']} (nothing is sent unless this is not `none`)",
310
+ f"crate: rust/{a['crate_name']} ({a['crate_layout']}); async/HTTP: {a['async_http']}",
311
+ f"human review areas: {', '.join(a['review_areas']) or 'none'}; commits: {a['commit_policy']}; tier: {a['output_tier']}",
312
+ ]