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,209 @@
1
+ """Static facts about one Python module, from its `ast` only. Nothing here imports or runs the code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import re
7
+ import sys
8
+ from collections.abc import Iterator
9
+ from dataclasses import dataclass, field
10
+ from typing import Any
11
+
12
+ DYNAMIC_CALLS = frozenset(
13
+ {"eval", "exec", "compile", "getattr", "setattr", "delattr", "hasattr", "__import__",
14
+ "globals", "locals", "vars"}
15
+ ) # fmt: skip
16
+ IO_ROOTS = frozenset(
17
+ {"os", "subprocess", "socket", "requests", "httpx", "urllib", "urllib3", "shutil", "pathlib",
18
+ "sqlite3", "http", "smtplib", "ftplib", "tempfile", "aiohttp", "websockets", "io"}
19
+ ) # fmt: skip
20
+
21
+ _AREA_ROOTS: dict[str, frozenset[str]] = {
22
+ "auth": frozenset({"jwt", "oauthlib", "authlib", "passlib", "bcrypt", "flask_login"}),
23
+ "crypto": frozenset({"hashlib", "hmac", "secrets", "ssl", "cryptography", "Crypto", "nacl"}),
24
+ "network": frozenset(
25
+ {
26
+ "socket",
27
+ "requests",
28
+ "httpx",
29
+ "urllib",
30
+ "urllib3",
31
+ "aiohttp",
32
+ "http",
33
+ "smtplib",
34
+ "ftplib",
35
+ "websockets",
36
+ }
37
+ ),
38
+ "subprocess": frozenset({"subprocess"}),
39
+ }
40
+ _AUTH_NAME = re.compile(r"password|passwd|api_?key|secret|bearer|jwt|oauth", re.I)
41
+ _SQL_WRITE = re.compile(
42
+ r"\b(INSERT\s+INTO|UPDATE\s+\w+\s+SET|DELETE\s+FROM|DROP\s+TABLE|CREATE\s+TABLE)\b", re.I
43
+ )
44
+ _FILE_WRITE_ATTRS = frozenset({"write_text", "write_bytes", "unlink", "rmtree", "remove", "rename"})
45
+ _OS_SHELL = re.compile(r"^(system|popen|exec\w*|spawn\w*)$")
46
+
47
+
48
+ @dataclass
49
+ class ModuleFacts:
50
+ lines: int = 0
51
+ functions: int = 0
52
+ classes: int = 0
53
+ async_functions: int = 0
54
+ try_blocks: int = 0
55
+ except_handlers: int = 0
56
+ raises: int = 0
57
+ exception_classes: list[str] = field(default_factory=list)
58
+ dynamic: list[str] = field(default_factory=list)
59
+ io: list[str] = field(default_factory=list)
60
+ areas: list[str] = field(default_factory=list)
61
+ third_party: list[str] = field(default_factory=list)
62
+ stdlib: list[str] = field(default_factory=list)
63
+ imports: list[tuple[str, int, tuple[str, ...]]] = field(
64
+ default_factory=list
65
+ ) # (module, level, names)
66
+
67
+
68
+ def walk_code(tree: ast.AST) -> Iterator[ast.AST]:
69
+ """Like ast.walk, but skips `if TYPE_CHECKING:` bodies (they create no runtime dependency)."""
70
+ todo = [tree]
71
+ while todo:
72
+ node = todo.pop()
73
+ yield node
74
+ if isinstance(node, ast.If) and _is_type_checking(node.test):
75
+ todo.extend(node.orelse)
76
+ continue
77
+ todo.extend(ast.iter_child_nodes(node))
78
+
79
+
80
+ def _is_type_checking(test: ast.expr) -> bool:
81
+ return (isinstance(test, ast.Name) and test.id == "TYPE_CHECKING") or (
82
+ isinstance(test, ast.Attribute) and test.attr == "TYPE_CHECKING"
83
+ )
84
+
85
+
86
+ def _base_name(base: ast.expr) -> str | None:
87
+ if isinstance(base, ast.Name):
88
+ return base.id
89
+ return base.attr if isinstance(base, ast.Attribute) else None
90
+
91
+
92
+ def _exception_classes(classes: list[ast.ClassDef]) -> list[str]:
93
+ """Classes deriving (transitively, within the module) from a name ending in Error/Exception."""
94
+ found: set[str] = set()
95
+ changed = True
96
+ while changed:
97
+ changed = False
98
+ for c in classes:
99
+ bases = {_base_name(b) for b in c.bases} - {None}
100
+ hit = any(
101
+ str(b).endswith(("Error", "Exception", "Warning")) or b in found for b in bases
102
+ )
103
+ if hit and c.name not in found:
104
+ found.add(c.name)
105
+ changed = True
106
+ return sorted(found)
107
+
108
+
109
+ def _open_writes(node: ast.Call) -> bool:
110
+ if not (isinstance(node.func, ast.Name) and node.func.id == "open"):
111
+ return False
112
+ mode = node.args[1] if len(node.args) > 1 else next(
113
+ (k.value for k in node.keywords if k.arg == "mode"), None
114
+ ) # fmt: skip
115
+ return (
116
+ isinstance(mode, ast.Constant)
117
+ and isinstance(mode.value, str)
118
+ and any(ch in mode.value for ch in "wax+")
119
+ )
120
+
121
+
122
+ def scan(tree: ast.Module, text: str, local_roots: frozenset[str] = frozenset()) -> ModuleFacts:
123
+ f = ModuleFacts(lines=len(text.splitlines()))
124
+ dynamic: set[str] = set()
125
+ io: set[str] = set()
126
+ areas: set[str] = set()
127
+ third: set[str] = set()
128
+ std: set[str] = set()
129
+ classes: list[ast.ClassDef] = []
130
+ stdlib = sys.stdlib_module_names
131
+
132
+ def root_seen(name: str) -> None:
133
+ root = name.partition(".")[0]
134
+ if root in IO_ROOTS:
135
+ io.add(root)
136
+ for area, roots in _AREA_ROOTS.items():
137
+ if root in roots:
138
+ areas.add(area)
139
+ if root in stdlib:
140
+ std.add(root)
141
+ elif root not in local_roots:
142
+ third.add(root)
143
+
144
+ for node in walk_code(tree):
145
+ if isinstance(node, ast.Import):
146
+ for a in node.names:
147
+ f.imports.append((a.name, 0, ()))
148
+ root_seen(a.name)
149
+ elif isinstance(node, ast.ImportFrom):
150
+ f.imports.append((node.module or "", node.level, tuple(a.name for a in node.names)))
151
+ if node.level == 0 and node.module:
152
+ root_seen(node.module)
153
+ elif isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
154
+ f.functions += 1
155
+ f.async_functions += isinstance(node, ast.AsyncFunctionDef)
156
+ if node.args.kwarg is not None:
157
+ dynamic.add("**kwargs")
158
+ if node.name in ("__getattr__", "__setattr__", "__getattribute__"):
159
+ dynamic.add(node.name)
160
+ elif isinstance(node, ast.ClassDef):
161
+ f.classes += 1
162
+ classes.append(node)
163
+ if any(k.arg == "metaclass" for k in node.keywords):
164
+ dynamic.add("metaclass")
165
+ elif isinstance(node, ast.Try | ast.TryStar):
166
+ f.try_blocks += 1
167
+ f.except_handlers += len(node.handlers)
168
+ elif isinstance(node, ast.Raise):
169
+ f.raises += 1
170
+ elif isinstance(node, ast.Call):
171
+ fn = node.func
172
+ if isinstance(fn, ast.Name) and fn.id in DYNAMIC_CALLS:
173
+ dynamic.add(fn.id)
174
+ if isinstance(fn, ast.Name) and fn.id == "open":
175
+ io.add("open")
176
+ if _open_writes(node):
177
+ areas.add("file-writes")
178
+ if isinstance(fn, ast.Attribute):
179
+ if fn.attr in _FILE_WRITE_ATTRS:
180
+ areas.add("file-writes")
181
+ if (
182
+ isinstance(fn.value, ast.Name)
183
+ and fn.value.id == "os"
184
+ and _OS_SHELL.match(fn.attr)
185
+ ):
186
+ areas.add("subprocess")
187
+ elif (
188
+ isinstance(node, ast.Constant)
189
+ and isinstance(node.value, str)
190
+ and _SQL_WRITE.search(node.value)
191
+ ):
192
+ areas.add("sql-writes")
193
+ name = node.id if isinstance(node, ast.Name) else getattr(node, "arg", None)
194
+ if isinstance(name, str) and _AUTH_NAME.search(name):
195
+ areas.add("auth")
196
+ f.exception_classes = _exception_classes(classes)
197
+ f.dynamic, f.io = sorted(dynamic), sorted(io)
198
+ f.areas, f.third_party, f.stdlib = sorted(areas), sorted(third), sorted(std - {"__future__"})
199
+ return f
200
+
201
+
202
+ def facts_dict(f: ModuleFacts) -> dict[str, Any]:
203
+ return {
204
+ "lines": f.lines, "functions": f.functions, "classes": f.classes,
205
+ "async_functions": f.async_functions, "try_blocks": f.try_blocks,
206
+ "except_handlers": f.except_handlers, "raises": f.raises,
207
+ "exception_classes": f.exception_classes, "dynamic": f.dynamic, "io": f.io,
208
+ "areas": f.areas, "third_party": f.third_party, "stdlib": f.stdlib,
209
+ } # fmt: skip
@@ -0,0 +1,395 @@
1
+ Metadata-Version: 2.4
2
+ Name: python2rust
3
+ Version: 0.1.0
4
+ Summary: Typed-Python to Rust transpiler built to be driven by AI agents: machine-readable diagnostics, loud TODOs, a validation loop.
5
+ Keywords: python,rust,transpiler,ai-agents,mcp,code-migration
6
+ Author: BMS Suisse
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ License-File: NOTICE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Programming Language :: Rust
15
+ Classifier: Topic :: Software Development :: Code Generators
16
+ Classifier: Typing :: Typed
17
+ Requires-Dist: pytest>=8 ; extra == 'dev'
18
+ Requires-Dist: ruff>=0.8 ; extra == 'dev'
19
+ Requires-Dist: ty ; extra == 'dev'
20
+ Requires-Dist: jsonschema>=4 ; extra == 'dev'
21
+ Requires-Dist: twine>=5 ; extra == 'dev'
22
+ Requires-Dist: mcp>=1.2 ; extra == 'dev'
23
+ Requires-Dist: hypothesis>=6 ; extra == 'dev'
24
+ Requires-Dist: pydantic>=2 ; extra == 'dev'
25
+ Requires-Dist: hypothesis>=6 ; extra == 'equiv'
26
+ Requires-Dist: mcp>=1.2 ; extra == 'mcp'
27
+ Requires-Python: >=3.14
28
+ Project-URL: Homepage, https://github.com/bmsuisse/python2rust
29
+ Project-URL: Repository, https://github.com/bmsuisse/python2rust
30
+ Project-URL: Issues, https://github.com/bmsuisse/python2rust/issues
31
+ Provides-Extra: dev
32
+ Provides-Extra: equiv
33
+ Provides-Extra: mcp
34
+ Description-Content-Type: text/markdown
35
+
36
+ <div align="center">
37
+
38
+ <img src="docs/assets/logo.svg" alt="python2rust logo" width="128" height="128">
39
+
40
+ # python2rust
41
+
42
+ **Typed Python in, Rust out, built for AI agents.**
43
+
44
+ Translates the typed subset of Python to Rust, never silently, and hands everything it cannot do
45
+ to an agent as a precise, machine-readable task.
46
+
47
+ [![CI](https://github.com/bmsuisse/python2rust/actions/workflows/ci.yml/badge.svg)](https://github.com/bmsuisse/python2rust/actions/workflows/ci.yml)
48
+ ![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)
49
+ ![Python 3.14+](https://img.shields.io/badge/python-3.14%2B-blue.svg)
50
+ ![Status: alpha](https://img.shields.io/badge/status-alpha-orange.svg)
51
+
52
+ </div>
53
+
54
+ > **Alpha, work in progress, not yet on PyPI.** Pydantic models, dataclasses, enums, typed functions, exceptions
55
+ > (`try`/`except`/`raise`), basic `async`/`await` and multi-module projects (a directory becomes one crate)
56
+ > translate, with `utoipa` schemas, source maps and a checked-output runtime crate. Classes, generators, decorators,
57
+ > most of the async library (`gather`, tasks, locks) and most third-party libraries are still explicit `todo!()`s
58
+ > (`python2rust constructs` lists exactly what is covered; the status table below is generated from it).
59
+ > `verify --level equiv`, the `port` repair loop and the `init`/`plan`/`next` agent flow exist; mining existing
60
+ > tests, end-to-end runs and capture/replay are not built yet.
61
+
62
+ ## Start here: tell your agent
63
+
64
+ Point any coding agent (Claude Code, Codex, ...) at this page and give it one line:
65
+
66
+ ````text
67
+ Port <path/to/python/src> to Rust with python2rust (https://github.com/bmsuisse/python2rust). Read its README and
68
+ AGENTS.md, run `uvx python2rust init --questions --json`, ask me those questions in a single message, then follow
69
+ `uvx python2rust status --json` until it says done. Report what needs my review.
70
+ ````
71
+
72
+ The tool carries the process, so the agent does not have to guess it. Every command takes `--json` (one JSON
73
+ document on stdout; exit `0` ok, `1` something is missing, `2` usage error, `3` internal error, `4` does not
74
+ verify), nothing is interactive:
75
+
76
+ ```bash
77
+ uvx python2rust init --questions --json # 1. the interview, as JSON
78
+ # the agent asks the human ALL questions in ONE message: options, consequences and defaults
79
+ uvx python2rust init --answers answers.json # 2. writes python2rust.toml and .python2rust/state.json
80
+ uvx python2rust plan --json # 3. units in dependency order, with difficulty and tests found
81
+ uvx python2rust next --json # 4. one unit as a brief: files, decisions, commands, acceptance
82
+ # port the unit with the commands from the brief (port, todos, apply, verify)
83
+ uvx python2rust done UNIT --json # 5. recorded only if the checks of your output tier pass
84
+ uvx python2rust status --json # any time: phase, blockers, the exact next command, review queue
85
+ ```
86
+
87
+ Repeat 4 and 5 until `status` says `complete`.
88
+
89
+ - **`init --questions`** asks about the goal of the port, the scope, how strict output equality must be (byte for
90
+ byte, functionally the same, or functionally the same with an AI judge for the leftovers; floats are compared
91
+ exactly unless you pick a tolerance), where trusted
92
+ examples come from, whether your code may be **run** (equivalence executes it) or **sent to a model** (nothing
93
+ leaves the machine unless you choose a backend), and a few style choices. Questions marked `ask_human` need
94
+ your decision: the agent must never answer them for you. `init --answers FILE`, repeated `--answer id=value`
95
+ or `--defaults` validate the answers (a bad id or value is exit 2 naming the allowed values) and write the
96
+ config. Re-running `init` refuses to overwrite unless you pass `--force`.
97
+ - **`plan`** reads the code with `ast` only (your code is never imported or run): import cycles become one unit,
98
+ units are ordered leaves first, easy first. Per unit it reports size, async code, exception classes, tests
99
+ found, an estimate of what translates mechanically, risk flags and a difficulty score with reasons.
100
+ - **`next`** hands over the next unit as a self-contained brief (JSON, or markdown without `--json`) and keeps
101
+ `PORTING.md` current: decisions from your answers, type and crate mapping notes, open questions. The brief's
102
+ commands (`port`, `todos`, `verify`, `apply`, `done`) all work on the whole planned project and narrow to the
103
+ unit with `--unit UNIT`: imports between units resolve, every unit stays in the one crate (`lib.rs` lists
104
+ them all, modules named from the project root: `shop/__init__.py` is `mod shop`) and the tests that import
105
+ the unit run.
106
+ - **`done UNIT`** runs the checks your output tier needs (`draft`: compiles; `verified`: plus the same output as
107
+ the Python, which executes your code and so needs `done UNIT --run-python` on that run, after you answered
108
+ `run_python: yes`; `production`: plus clippy and tests) and records the unit only if they pass. The recorded
109
+ tier says what actually ran (`compiled`, `tested`, `verified`, `production`): without `--run-python` a
110
+ `verified` unit is recorded as `compiled`, and `done` says equivalence was not verified and prints the
111
+ command to run. Otherwise it exits 1 with the exact list of what is missing (every `todo!()` left, wherever
112
+ it is).
113
+ Work flagged for human review stays in the review queue until a human runs `done UNIT --reviewed`.
114
+ - **`status`** always answers: phase (`init needed`, `plan needed`, `porting`, `verifying`, `complete`), current
115
+ unit, blockers, the exact next command, open questions and the review queue.
116
+
117
+ The same operations are MCP tools (`init_questions`, `init_apply`, `plan`, `next_unit`, `mark_done`, `status`).
118
+
119
+ ## Why
120
+
121
+ Porting a large Python codebase to Rust is mostly mechanical work with a few hard parts. The usual tools
122
+ either approximate silently or give up on the file. python2rust is built around three rules:
123
+
124
+ - **Never silent.** Whatever it cannot translate becomes a loud `todo!()` in the output, a diagnostic with a
125
+ stable `PY2RS<NNN>` code, and a self-contained hand-off task. Nothing is dropped quietly.
126
+ - **Agent-first.** Every command speaks JSON, nothing is interactive, exit codes are documented, and it ships an
127
+ MCP server and a bundled agent skill. An agent can drive the whole loop without a human reading output.
128
+ - **Proven, not claimed.** Output is verified by a ladder (parse, format, `cargo check`, clippy, tests) and every
129
+ Rust line maps back to the Python line it came from.
130
+
131
+ ## How it works
132
+
133
+ ```mermaid
134
+ flowchart LR
135
+ A[Typed Python] --> B[translate]
136
+ B --> C[Rust + .todo.json + diagnostics]
137
+ C --> D{cargo check}
138
+ D -- errors --> E[fix each todo!: stored fix, compiler suggestion, or agent]
139
+ E --> D
140
+ D -- clean --> F[verified Rust]
141
+ ```
142
+
143
+ 1. `translate` produces Rust, a source map back to the Python, and one task per `todo!()`.
144
+ 2. `check` and `verify` compile the result and map every error to a Python line.
145
+ 3. An agent (or a person) fixes only what failed. Accepted fixes are stored under `.python2rust/patches/` and
146
+ re-applied on the next translate, so a fix is only ever paid for once.
147
+ 4. Repeat until it compiles. `python2rust port` runs this loop for you.
148
+
149
+ **One command.** `python2rust port` translates, compiles the whole crate once per round, groups the errors per
150
+ function through the source map, and repairs only what fails, cheapest fixer first: a stored fix, the compiler's own
151
+ suggested edits, then a model, with a stronger one after a few failed rounds. Every candidate passes the anti-cheat
152
+ gate and a re-check before it is kept, and stops are explicit (converged, budget, no progress). It prints a JSON round
153
+ log (errors before and after, functions fixed per tier, tokens, seconds).
154
+
155
+ ```bash
156
+ uvx python2rust port src/ -o rust/ # dry run: prints the tasks it WOULD send
157
+ uvx python2rust port src/ -o rust/ --agent cmd --agent-cmd "claude -p" # any CLI agent: task JSON in, patch JSON out
158
+ uvx python2rust port src/ -o rust/ --agent anthropic --model <model> # or openai / azure, keys from the environment
159
+ ```
160
+
161
+ **Privacy.** Nothing leaves your machine unless you choose an `--agent`. Without one, `port` is a dry run that lists the
162
+ exact tasks (the Python function, the generated Rust, the compiler errors, signatures of the items it uses) and sends
163
+ nothing. With one, the same text is sent and a notice says so; prompts are only printed with `--verbose`.
164
+
165
+ ## Status
166
+
167
+ **Alpha. Expect TODOs.** Trust `python2rust constructs` (what is covered) and `python2rust coverage src/` (how much
168
+ of *your* code translates) over this README.
169
+
170
+ - Typed Python only. Unannotated code produces placeholders and diagnostics, not guesses.
171
+ - Dynamic Python (`getattr` with computed names, `**kwargs` forwarding, `eval`, metaclasses, shared mutable state)
172
+ has no static Rust form. It is a TODO by design, always.
173
+ - A file that compiles is not a proven-equivalent file. `check` proves the Rust type-checks; behaviour needs tests
174
+ on both sides (`verify --level equiv` compares outputs, see [docs/EQUIVALENCE.md](docs/EQUIVALENCE.md)).
175
+ - **Security.** `translate`, `todos`, `check`, `coverage`, `eval`, `explain`, `contract` and `port` never import,
176
+ execute or `eval` your code: they only parse it with `ast`. Only `verify --level equiv --run-python` and `done UNIT --run-python` run your
177
+ Python, in a child process with best-effort limits (network calls stubbed, memory and time capped; not an OS
178
+ sandbox, so only run it on code you trust), and only when you pass that flag. `cargo` does execute code (build scripts,
179
+ proc-macros), so the MCP server's compiling tools are off unless started with `--allow-compile`.
180
+
181
+ ## What it is for
182
+
183
+ python2rust targets real application Python: typed functions, services, tools and worker jobs, with the
184
+ async code, `try`/`except` and library calls that go with them. It was built to port a production backend of
185
+ roughly 100k lines, and the mapping rules come from that port, not from guesses. FastAPI routes are one
186
+ supported profile, not the centre of the tool.
187
+
188
+ <!-- constructs:begin (generated by tools/readme_constructs.py; checked by a test) -->
189
+ 180 constructs: **123 supported**, **39 partial** (a subset; the rest is an explicit TODO), **18 explicit TODO** today.
190
+
191
+ | Area | supported | partial | explicit TODO |
192
+ |---|---:|---:|---:|
193
+ | Expressions | 12 | 10 | 2 |
194
+ | Statements | 8 | 11 | 8 |
195
+ | Builtin functions | 27 | 0 | 0 |
196
+ | str / list / dict / set methods | 66 | 0 | 0 |
197
+ | Types | 3 | 0 | 0 |
198
+ | Models (pydantic, dataclass, enum, TypedDict) | 6 | 0 | 1 |
199
+ | Functions | 0 | 3 | 2 |
200
+ | Classes | 0 | 0 | 1 |
201
+ | Exceptions | 0 | 1 | 0 |
202
+ | Async | 1 | 0 | 4 |
203
+ | Modules | 0 | 2 | 0 |
204
+ | Projects (a directory as one crate) | 0 | 1 | 0 |
205
+ | Tests (pytest, unittest, doctest) | 0 | 1 | 0 |
206
+ | Libraries (mapped calls only) | 0 | 10 | 0 |
207
+
208
+ **Explicit TODO today** (stable codes, never silently dropped): `Yield expression`, `YieldFrom expression`, `async for`, `async with`, `asyncio.Lock / Semaphore / Queue`, `asyncio.create_task`, `asyncio.gather`, `asyncio.wait_for / timeout`, `decorators`, `generator function`, `global`, `nested async function`, `nested class`, `nested function`, `nonlocal`, `plain class / methods`, `try/except*`, `validators and computed fields`.
209
+
210
+ **Partial** (the common shapes are translated, the rest is a TODO): `*args / **kwargs parameters`, `Assign statement`, `Attribute expression`, `AugAssign statement`, `Await expression`, `BoolOp expression`, `Call expression`, `Compare expression`, `Delete statement`, `For statement`, `Import statement`, `ImportFrom statement`, `JoinedStr expression`, `Lambda expression`, `Match statement`, `Name expression`, `NamedExpr expression`, `Raise statement`, `Subscript expression`, `Try statement`, `While statement`, `With statement`, `async def / await of coroutines`, `default arguments`, `exception classes (kind tree)`, `import (typing/pydantic/mapped/library)`, `module-level constant`, `multi-module projects`, `pytest / unittest / doctest -> #[test]`; mapped library calls: asyncio, base64, hashlib, html, json, math, re, time, urllib, uuid.
211
+
212
+ Run `python2rust constructs` for the full list with codes. The test suite fails if this block drifts.
213
+ <!-- constructs:end -->
214
+
215
+ Do not expect a large codebase to port with one command. Models and plain logic come out mechanically and are
216
+ checked for compiling **and** producing the same output; the rest is closed task by task by an agent. The status above is
217
+ generated from the translator's own construct list, and `python2rust coverage` reports what your own code gets.
218
+
219
+ ## Quickstart
220
+
221
+ ```bash
222
+ # once published to PyPI; until then: uvx --from git+https://github.com/bmsuisse/python2rust python2rust ...
223
+ uvx python2rust translate shop.py # Rust on stdout, summary on stderr
224
+ uvx python2rust translate src/ -o rust/ # a directory: rust/**.rs + .todo.json + .diagnostics.json
225
+ uvx python2rust todos src/ -o rust/ --json # the agent work list
226
+ uvx python2rust check rust/ --deps-from Cargo.toml # cargo check in a scratch crate, errors by category
227
+ uvx python2rust explain PY2RS001 # what a diagnostic means and how to fix it
228
+ uvx python2rust coverage src/ # corpus metrics as a markdown table
229
+ ```
230
+
231
+ | Command | What it does |
232
+ |---|---|
233
+ | `translate` | Python to Rust, plus diagnostics, source map and tasks |
234
+ | `todos` | the agent hand-off list, one task per `todo!()` |
235
+ | `check` / `verify` | compile the output and map errors to Python lines; `verify` climbs a ladder of checks |
236
+ | `apply` | store an agent's fix for a task, behind an anti-cheat gate |
237
+ | `port` | the one-command loop: translate, compile, repair (dry run unless `--agent` is set) |
238
+ | `contract` | diff a Python OpenAPI document against the Rust one (experimental) |
239
+ | `eval` / `coverage` | metrics over a corpus |
240
+ | `explain` / `constructs` / `schema` | documentation for diagnostics, supported constructs and JSON output |
241
+ | `mcp` / `skill` / `doctor` | MCP server, the bundled agent skill, environment check |
242
+
243
+ `python2rust` and `py2rust` are the same program. It needs Python 3.14 or newer; `rustfmt` and `cargo` are needed
244
+ only for formatting and `check` (`python2rust doctor` reports what is available).
245
+
246
+ ## Use it with an agent
247
+
248
+ `python2rust skill` prints a ready-to-use agent skill with the exact JSON contracts, and [AGENTS.md](AGENTS.md)
249
+ holds the rules (never edit generated files blindly, always verify, escalate review items). For MCP clients:
250
+ `pip install 'python2rust[mcp]'`, then register `python2rust mcp` (stdio). The tools are `translate_source`,
251
+ `list_todos`, `explain_diagnostic`, `check_rust`, `coverage`, `apply_patch` and the workflow tools, each returning the
252
+ same JSON as the CLI. Files the tools read are limited to `--root` (default: the working directory). The tools that
253
+ run cargo (`check_rust`, `apply_patch`, coverage levels check and above) are off unless the server is started with
254
+ `--allow-compile`: cargo executes code, and these tools compile Rust that a model supplied. That compile runs in an OS
255
+ sandbox (no network, file reads confined to the scratch crate, the cargo/rustup homes and the toolchain): `sandbox-exec`
256
+ on macOS, `bwrap` on Linux. Without one the server refuses to compile unless it is started with
257
+ `--allow-unsandboxed-compile`.
258
+
259
+ <details>
260
+ <summary><b>Start a port: a prompt to give your agent</b></summary>
261
+
262
+ Paste this into Claude Code, Codex or any coding agent that can run shell commands. Replace the three values in
263
+ angle brackets first.
264
+
265
+ ````text
266
+ You are porting a typed Python codebase to Rust with python2rust. Work in small, checked steps.
267
+
268
+ Setup
269
+ - Python source: <path/to/python/src>. Rust target crate: <path/to/rust/crate> (create it with
270
+ `cargo new --lib` if missing; add the dependencies python2rust reports as unresolved).
271
+ - Run `uvx python2rust doctor --json` and `uvx python2rust skill` first. Read the skill: it has the exact
272
+ JSON contracts. Never guess a command; `uvx python2rust --help` lists them.
273
+
274
+ Plan
275
+ 1. Measure: `uvx python2rust coverage <python src> --json`. Pick the smallest module with the highest share
276
+ of clean functions. Port in this order: models and enums, pure functions, async services, HTTP routes.
277
+ 2. Translate one module: `uvx python2rust translate <module.py> -o <rust crate>/src/ --json`.
278
+ 3. List the work: `uvx python2rust todos <module.py> -o <rust crate>/src/ --json`. Each item has the Python
279
+ snippet, the Rust context and an instruction.
280
+ 4. Fix every `todo!()` from its snippet and submit the fix with `uvx python2rust apply <TODO_ID> --patch FILE`
281
+ (or `-` for stdin). NEVER edit the generated files: `apply` stores the fix and every re-translate puts it back, so
282
+ re-translating is always safe. Keep behaviour identical to the Python (error cases, defaults, order of checks).
283
+ `apply` accepts a fix only if it compiles, every translated test that uses the module passes (tests are never
284
+ fixed: a TODO inside a test is refused) and, for a pure function with a JSON-able signature, the output equals
285
+ the Python's: that needs `--run-python` (the Python runs in a best-effort-limited child process, not an OS sandbox: ask your human first); without it the
286
+ fix is stored as `unverified`. `--no-equiv` opts out and is recorded as "check+tests, not equivalence".
287
+ Or let `uvx python2rust port <python src> -o <rust crate>` do the loop (add `--agent` to let it call a model).
288
+ 5. Verify: `uvx python2rust check <rust crate>/src/ --deps-from <rust crate>/Cargo.toml --json`, then
289
+ `cargo test`. Fix by category until both pass. `apply` rejects `todo!`, `unwrap`, `expect`, `panic!`,
290
+ `#[allow]`, `Default::default()` stand-ins and `unsafe`: do not try to get around that, and never edit or delete a
291
+ test to make the Rust pass.
292
+ 6. Port the Python tests for the module and make them pass against the Rust code.
293
+ 7. Commit one module at a time, then repeat from step 1.
294
+
295
+ Rules
296
+ - Items marked `needs_review: true` (auth, tokens, SQL writes, outbound HTTP, crypto, permissions) must be
297
+ listed in your final report for a human to review. Do not mark them done yourself.
298
+ - If python2rust emits a wrong translation (not just a TODO), do not hand-patch it quietly: write the
299
+ Python snippet, the wrong Rust and the correct Rust into `PYTHON2RUST_FEEDBACK.md` so the tool can be
300
+ fixed.
301
+ - Never delete the Python original until the Rust version passes the ported tests.
302
+ - Stop and ask when the Python behaviour is unclear or relies on dynamic features (`getattr`, `**kwargs`
303
+ forwarding, monkeypatching).
304
+
305
+ Report at the end: modules ported, tests passing, the review list, the feedback file, and what is left.
306
+ ````
307
+
308
+ For a web framework port (FastAPI to Axum), add: "Port routes after their models, keep every status code, path
309
+ and response model, and compare the generated OpenAPI with the original."
310
+
311
+ </details>
312
+
313
+ <details>
314
+ <summary><b>Exit codes and JSON output</b></summary>
315
+
316
+ Every command takes `--json`: stdout is then exactly one JSON document and human text goes to stderr (`--quiet`
317
+ silences it). Nothing is ever interactive; `-` reads stdin; output order is stable.
318
+
319
+ | code | meaning |
320
+ |---|---|
321
+ | 0 | ok: no TODOs, no error diagnostics (`check`: it compiles) |
322
+ | 1 | translated, but TODOs or error diagnostics remain, or the result could not be verified (for example no cargo) |
323
+ | 2 | usage error (bad flag, missing path, invalid config) |
324
+ | 3 | internal error, or a missing core or optional dependency |
325
+ | 4 | the Rust does not compile or verify: compile errors, a failing rung (clippy, test, equiv), a rejected fix |
326
+
327
+ `python2rust schema [translate|todos|coverage|check|...]` prints the JSON Schema of each output.
328
+
329
+ ```jsonc
330
+ // python2rust translate shop.py --json (abridged)
331
+ {"schema_version": 1, "command": "translate", "ok": false,
332
+ "summary": {"files": 1, "files_clean": 0, "files_with_todos": 1, "todo_count": 1, "...": "..."},
333
+ "files": [{"file": "shop.py", "status": "todo", "rust_path": null, "rust": "pub fn add(...) ...",
334
+ "stats": {"functions_total": 2, "functions_clean": 1, "models_total": 0, "models_clean": 0, "todo_count": 1},
335
+ "diagnostics": [{"code": "PY2RS005", "severity": "warning", "file": "shop.py", "line": 6, "col": 0,
336
+ "construct": "function-body", "message": "...", "hint": "..."}],
337
+ "todos": ["..."]}]}
338
+
339
+ // python2rust todos shop.py -o out --json (the agent hand-off contract, abridged)
340
+ {"count": 1, "todos": [{
341
+ "id": "t3f9a1c2e", "code": "PY2RS005", "kind": "function-body", "file": "shop.py", "line": 6,
342
+ "python_snippet": "def get(o, name: str):\n return getattr(o, name)",
343
+ "rust_context": "pub fn get(o: (), name: String) -> () {", "rust_line": 8, "rust_file": "out/shop.rs",
344
+ "needs_review": false, "review_reason": null,
345
+ "instruction": "Replace the todo!() for t3f9a1c2e ... at out/shop.rs:8 with Rust that does what the Python at shop.py:6 does. ..."}]}
346
+ ```
347
+
348
+ Task ids are stable content hashes (`t` plus eight hex digits, like `t3f9a1c2e`); `python2rust schema` is the
349
+ contract to rely on for the exact fields.
350
+
351
+ </details>
352
+
353
+ ## Configuration
354
+
355
+ `--config project.toml` carries what the translator cannot guess about your project: `import_map` (Python module to
356
+ Rust path), `library_map` (third-party call to crate API), `type_map` and `review_patterns` (what to flag for
357
+ review). Keep it outside the generated output and re-translate after changing it.
358
+
359
+ ## python2rust and py2many
360
+
361
+ [py2many](https://github.com/py2many/py2many) (MIT) is the established Python transpiler and a major influence
362
+ here. Choose it when you want **many target languages** (C++, Go, Kotlin, Julia, Dart, Nim, V, Zig, Rust and more)
363
+ from one tool, when your Python is small, self-contained and often **unannotated** (it infers types), or when you
364
+ want a mature project with years of testing. Its Rust backend is its most developed one.
365
+
366
+ python2rust makes different trade-offs, aimed at porting large, *typed* application code with an agent in the loop:
367
+
368
+ | | py2many | python2rust |
369
+ |---|---|---|
370
+ | Targets | many languages | Rust only |
371
+ | Input | Python with type inference, wide version range | annotated Python, 3.14 syntax |
372
+ | Middle layer | rewrites and inference on the Python AST, code emitted per language | a typed IR between Python and a Rust emitter |
373
+ | Unsupported code | may raise, or be approximated depending on the node | always a `todo!()` plus a diagnostic |
374
+ | Output for tools | formatted source | source, diagnostics JSON, per-file task list, stable codes, JSON Schemas |
375
+ | Validation | none built in | compiles the output and maps errors back to Python lines |
376
+ | Interface | CLI | CLI with `--json` everywhere, MCP server, bundled agent skill |
377
+
378
+ The difference we care about most is a policy. In our own experiments on an annotated, async-heavy codebase,
379
+ `async`/`await`, `try`/`except`, dict comprehensions and walrus assignments were unsupported in py2many 0.9 (or
380
+ produced Rust that did not parse), and some constructs such as `**kwargs` were dropped without a diagnostic.
381
+ python2rust treats an untranslated construct as data an agent can act on. That is a design choice for this use
382
+ case, not a verdict on py2many; versions change, so measure on your own code. [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
383
+ describes what we took from it.
384
+
385
+ ## Development
386
+
387
+ ```bash
388
+ uv sync # installs the dev tools
389
+ uv run pytest # CLI contract tests, MCP in-memory tests, cargo tests (skipped without cargo)
390
+ uv run ruff check && uv run ruff format --check && uv run ty check
391
+ uv build
392
+ ```
393
+
394
+ Contributions are welcome. Read [AGENTS.md](AGENTS.md) first; this is a public project, so examples and tests use
395
+ only synthetic code. Licensed under the [MIT License](LICENSE).