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.
- python2rust/__init__.py +8 -0
- python2rust/__main__.py +5 -0
- python2rust/_core.py +44 -0
- python2rust/agent/__init__.py +0 -0
- python2rust/agent/agents.py +333 -0
- python2rust/agent/apply.py +516 -0
- python2rust/agent/finish.py +295 -0
- python2rust/agent/fixers.py +229 -0
- python2rust/agent/loop.py +441 -0
- python2rust/agent/patches.py +1165 -0
- python2rust/agent/port.py +579 -0
- python2rust/agent/prompts/judge_v2.md +96 -0
- python2rust/agent/review.py +34 -0
- python2rust/agent/rustlex.py +232 -0
- python2rust/cli/__init__.py +0 -0
- python2rust/cli/doctor.py +62 -0
- python2rust/cli/inputs.py +105 -0
- python2rust/cli/main.py +1162 -0
- python2rust/cli/ops.py +642 -0
- python2rust/cli/workflow.py +178 -0
- python2rust/core/__init__.py +38 -0
- python2rust/core/config.py +263 -0
- python2rust/core/constructs.py +124 -0
- python2rust/core/diagnostics.py +280 -0
- python2rust/core/emit/__init__.py +5 -0
- python2rust/core/emit/crates.py +51 -0
- python2rust/core/emit/render.py +561 -0
- python2rust/core/emit/schema.py +168 -0
- python2rust/core/emit/translate.py +304 -0
- python2rust/core/frontend/__init__.py +1 -0
- python2rust/core/frontend/module.py +896 -0
- python2rust/core/frontend/names.py +129 -0
- python2rust/core/frontend/project.py +277 -0
- python2rust/core/frontend/project_imports.py +173 -0
- python2rust/core/frontend/symbols.py +132 -0
- python2rust/core/frontend/walrus.py +59 -0
- python2rust/core/ir/__init__.py +1 -0
- python2rust/core/ir/nodes.py +675 -0
- python2rust/core/ir/rtypes.py +122 -0
- python2rust/core/ir/types.py +326 -0
- python2rust/core/lower/__init__.py +1 -0
- python2rust/core/lower/calls.py +1125 -0
- python2rust/core/lower/context.py +223 -0
- python2rust/core/lower/exceptions.py +317 -0
- python2rust/core/lower/exprs.py +845 -0
- python2rust/core/lower/fstrings.py +141 -0
- python2rust/core/lower/funcs.py +276 -0
- python2rust/core/lower/lowerer.py +366 -0
- python2rust/core/lower/modelcalls.py +195 -0
- python2rust/core/lower/models.py +645 -0
- python2rust/core/lower/stmts.py +722 -0
- python2rust/core/lower/testing.py +601 -0
- python2rust/core/lower/validation.py +253 -0
- python2rust/core/passes/__init__.py +1 -0
- python2rust/core/passes/aliasing.py +311 -0
- python2rust/core/passes/analysis.py +207 -0
- python2rust/core/passes/devirt.py +329 -0
- python2rust/core/passes/ownership.py +259 -0
- python2rust/core/passes/raises.py +275 -0
- python2rust/core/rt_lib.rs +2071 -0
- python2rust/data/README.md +81 -0
- python2rust/data/py2many_builtins.toml +4744 -0
- python2rust/errors.py +28 -0
- python2rust/py.typed +0 -0
- python2rust/report/__init__.py +0 -0
- python2rust/report/constructs.py +31 -0
- python2rust/report/contract.py +688 -0
- python2rust/report/corpus.py +323 -0
- python2rust/report/explain.py +168 -0
- python2rust/report/schemas.py +914 -0
- python2rust/server/__init__.py +0 -0
- python2rust/server/mcp_server.py +289 -0
- python2rust/server/mcp_workflow.py +100 -0
- python2rust/skill/SKILL.md +214 -0
- python2rust/verify/__init__.py +0 -0
- python2rust/verify/check.py +1135 -0
- python2rust/verify/equiv/__init__.py +1264 -0
- python2rust/verify/equiv/compare.py +455 -0
- python2rust/verify/equiv/harness.py +505 -0
- python2rust/verify/equiv/judge.py +358 -0
- python2rust/verify/equiv/procs.py +255 -0
- python2rust/verify/equiv/runner.py +248 -0
- python2rust/verify/equiv/types.py +543 -0
- python2rust/verify/keystore.py +76 -0
- python2rust/verify/ladder.py +396 -0
- python2rust/verify/sandbox.py +370 -0
- python2rust/verify/testrun.py +280 -0
- python2rust/workflow/__init__.py +0 -0
- python2rust/workflow/brief.py +312 -0
- python2rust/workflow/interview.py +366 -0
- python2rust/workflow/layout.py +103 -0
- python2rust/workflow/planner.py +409 -0
- python2rust/workflow/project.py +134 -0
- python2rust/workflow/schemas.py +265 -0
- python2rust/workflow/state.py +392 -0
- python2rust/workflow/staticscan.py +209 -0
- python2rust-0.1.0.dist-info/METADATA +395 -0
- python2rust-0.1.0.dist-info/RECORD +102 -0
- python2rust-0.1.0.dist-info/WHEEL +4 -0
- python2rust-0.1.0.dist-info/entry_points.txt +4 -0
- python2rust-0.1.0.dist-info/licenses/LICENSE +21 -0
- python2rust-0.1.0.dist-info/licenses/NOTICE +65 -0
python2rust/cli/ops.py
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
"""The operations behind every command. Pure functions that return JSON-able dicts.
|
|
2
|
+
|
|
3
|
+
The CLI and the MCP server both call these, so they always return the same documents.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import dataclasses
|
|
9
|
+
import json
|
|
10
|
+
from collections import Counter
|
|
11
|
+
from collections.abc import Sequence
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from python2rust import __version__
|
|
16
|
+
from python2rust._core import get_core
|
|
17
|
+
from python2rust.agent.patches import PatchStore, apply_overlay, gate_allowlist, unhealed_not_clean
|
|
18
|
+
from python2rust.agent.review import apply_floor
|
|
19
|
+
from python2rust.cli.inputs import Source
|
|
20
|
+
from python2rust.errors import (
|
|
21
|
+
EXIT_COMPILE,
|
|
22
|
+
EXIT_FINDINGS,
|
|
23
|
+
EXIT_INTERNAL,
|
|
24
|
+
EXIT_OK,
|
|
25
|
+
SCHEMA_VERSION,
|
|
26
|
+
InternalError,
|
|
27
|
+
UsageError,
|
|
28
|
+
)
|
|
29
|
+
from python2rust.verify.check import CheckModule
|
|
30
|
+
|
|
31
|
+
# The workflow (port, apply, done) translates with every built-in error as a Result, so a fix and the
|
|
32
|
+
# Python it replaces can be compared by the kind of error they raise.
|
|
33
|
+
WORKFLOW_BUILTIN_ERRORS = "always"
|
|
34
|
+
|
|
35
|
+
STAT_KEYS = ("functions_total", "functions_clean", "models_total", "models_clean", "todo_count")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def envelope(command: str, **fields: Any) -> dict[str, Any]:
|
|
39
|
+
return {"schema_version": SCHEMA_VERSION, "command": command, "version": __version__, **fields}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def error_doc(kind: str, message: str, **extra: Any) -> dict[str, Any]:
|
|
43
|
+
return {
|
|
44
|
+
"schema_version": SCHEMA_VERSION,
|
|
45
|
+
"ok": False,
|
|
46
|
+
"error": {"kind": kind, "message": message, **extra},
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def load_config(
|
|
51
|
+
path: str | None,
|
|
52
|
+
*,
|
|
53
|
+
fmt: bool = True,
|
|
54
|
+
vendor_runtime: bool = False,
|
|
55
|
+
builtin_errors: str | None = None,
|
|
56
|
+
) -> Any:
|
|
57
|
+
"""The core's Config for `path` (None: the core's defaults, represented as None).
|
|
58
|
+
|
|
59
|
+
The CLI switches are Config fields: `--no-fmt` sets `format = False`, `--vendor-runtime` sets
|
|
60
|
+
`vendor_runtime = True` and `builtin_errors` (the workflow passes `"always"`, so a built-in error
|
|
61
|
+
is a `Result` a comparison can tell apart by kind) sets `builtin_errors`, with
|
|
62
|
+
`dataclasses.replace` on the loaded config or on `core.Config()`. A core whose Config lacks a
|
|
63
|
+
requested field is an error, never a silently ignored flag.
|
|
64
|
+
"""
|
|
65
|
+
core = get_core()
|
|
66
|
+
config = None
|
|
67
|
+
if path is not None:
|
|
68
|
+
try:
|
|
69
|
+
config = core.load_config(path)
|
|
70
|
+
except FileNotFoundError:
|
|
71
|
+
raise UsageError(f"config file does not exist: {path}") from None
|
|
72
|
+
except Exception as exc:
|
|
73
|
+
raise UsageError(f"invalid config {path}: {exc}") from exc
|
|
74
|
+
changes: dict[str, bool | str] = {}
|
|
75
|
+
if not fmt:
|
|
76
|
+
changes["format"] = False
|
|
77
|
+
if vendor_runtime:
|
|
78
|
+
changes["vendor_runtime"] = True
|
|
79
|
+
if builtin_errors is not None:
|
|
80
|
+
changes["builtin_errors"] = builtin_errors
|
|
81
|
+
if not changes:
|
|
82
|
+
return config
|
|
83
|
+
try:
|
|
84
|
+
return dataclasses.replace(config if config is not None else core.Config(), **changes)
|
|
85
|
+
except (AttributeError, TypeError) as exc:
|
|
86
|
+
raise InternalError(
|
|
87
|
+
f"the core's Config cannot honour {', '.join(changes)} (--no-fmt, --vendor-runtime, "
|
|
88
|
+
f"builtin_errors): {exc}"
|
|
89
|
+
) from exc
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def rust_path_for(rel: str) -> str:
|
|
93
|
+
p = Path(rel)
|
|
94
|
+
return (p.parent / ("mod.rs" if p.stem == "__init__" else p.stem + ".rs")).as_posix()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# --- translate ----------------------------------------------------------------------------------
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _handoff(todo: dict[str, Any], rust_file: str | None, hint: str | None) -> dict[str, Any]:
|
|
101
|
+
"""Extend a core Todo into the agent-handoff contract (adds `rust_file`, `hint`, `instruction`)."""
|
|
102
|
+
where = (
|
|
103
|
+
f"{rust_file}:{todo['rust_line']}"
|
|
104
|
+
if rust_file
|
|
105
|
+
else f"line {todo['rust_line']} of the generated Rust"
|
|
106
|
+
)
|
|
107
|
+
steps = [
|
|
108
|
+
f"Fix {todo['id']} ({todo['kind']}, {todo['code']}): write Rust that does what the Python at "
|
|
109
|
+
f"{todo['file']}:{todo['line']} does, to replace the todo!() at {where}.",
|
|
110
|
+
"Do not edit the generated file. Submit only the replacement for that todo!() with "
|
|
111
|
+
f"`python2rust apply {todo['id']} --patch FILE` (or `--patch -` for stdin); it is stored in "
|
|
112
|
+
".python2rust/patches/ and re-applied on every translate. Keep signatures; take types and "
|
|
113
|
+
"helper names from rust_context; do not invent crate APIs.",
|
|
114
|
+
"`apply` rejects patches containing todo!, unimplemented!, unwrap(, expect(, panic!, #[allow, "
|
|
115
|
+
"Default::default() stand-ins or unsafe, and accepts one only if it passes `cargo check`.",
|
|
116
|
+
]
|
|
117
|
+
if hint:
|
|
118
|
+
steps.insert(1, f"Hint from the translator: {hint.rstrip('.')}.")
|
|
119
|
+
if todo["needs_review"]:
|
|
120
|
+
steps.append(
|
|
121
|
+
"This TODO is flagged needs_review"
|
|
122
|
+
+ (f" ({todo['review_reason']})" if todo["review_reason"] else "")
|
|
123
|
+
+ ": do not treat it as finished; a human or a stronger model must review the result."
|
|
124
|
+
)
|
|
125
|
+
return {**todo, "rust_file": rust_file, "hint": hint, "instruction": " ".join(steps)}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _new_entry(src: Source) -> dict[str, Any]:
|
|
129
|
+
entry: dict[str, Any] = {
|
|
130
|
+
"file": src.display,
|
|
131
|
+
"status": "error",
|
|
132
|
+
"rust_path": None,
|
|
133
|
+
"rust": None,
|
|
134
|
+
}
|
|
135
|
+
entry.update(
|
|
136
|
+
stats=dict.fromkeys(STAT_KEYS, 0),
|
|
137
|
+
diagnostics=[],
|
|
138
|
+
todos=[],
|
|
139
|
+
patches=[],
|
|
140
|
+
drift=[],
|
|
141
|
+
notes=[],
|
|
142
|
+
required_crates={},
|
|
143
|
+
required_features=[],
|
|
144
|
+
tests=[],
|
|
145
|
+
not_clean=[],
|
|
146
|
+
error=None,
|
|
147
|
+
)
|
|
148
|
+
entry["source_map"] = None
|
|
149
|
+
return entry
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _failed(entry: dict[str, Any], exc: Exception) -> dict[str, Any]:
|
|
153
|
+
"""A core crash on one file must not lose the others."""
|
|
154
|
+
if isinstance(exc, SyntaxError):
|
|
155
|
+
entry["error"] = f"syntax error: {exc}"
|
|
156
|
+
else:
|
|
157
|
+
entry["status"] = "internal_error"
|
|
158
|
+
entry["error"] = f"{type(exc).__name__}: {exc}"
|
|
159
|
+
return entry
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _renamed(items: list[dict[str, Any]], key: str, old: str, new: str) -> list[dict[str, Any]]:
|
|
163
|
+
"""The core names a file as it was given to it; reports use the display name."""
|
|
164
|
+
return [{**i, key: new} if i.get(key) == old else i for i in items]
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _fill_entry(
|
|
168
|
+
entry: dict[str, Any],
|
|
169
|
+
src: Source,
|
|
170
|
+
result: Any,
|
|
171
|
+
*,
|
|
172
|
+
store: PatchStore | None,
|
|
173
|
+
skip: frozenset[str],
|
|
174
|
+
core_file: str,
|
|
175
|
+
extra_diagnostics: Sequence[Any] = (),
|
|
176
|
+
) -> dict[str, Any]:
|
|
177
|
+
diags = sorted(
|
|
178
|
+
_renamed(
|
|
179
|
+
[dataclasses.asdict(d) for d in (*result.diagnostics, *extra_diagnostics)],
|
|
180
|
+
"file",
|
|
181
|
+
core_file,
|
|
182
|
+
src.display,
|
|
183
|
+
),
|
|
184
|
+
key=lambda d: (d["line"], d["col"], d["code"], d["message"]),
|
|
185
|
+
)
|
|
186
|
+
hints = {(d["line"], d["code"]): d["hint"] for d in diags if d.get("hint")}
|
|
187
|
+
todos = sorted(
|
|
188
|
+
_renamed(
|
|
189
|
+
[apply_floor(dataclasses.asdict(t)) for t in result.todos],
|
|
190
|
+
"file",
|
|
191
|
+
core_file,
|
|
192
|
+
src.display,
|
|
193
|
+
),
|
|
194
|
+
key=lambda t: (t["line"], t["rust_line"], t["id"]),
|
|
195
|
+
)
|
|
196
|
+
todos = [
|
|
197
|
+
{**_handoff(t, None, hints.get((t["line"], t["code"]))), "state": "open"} for t in todos
|
|
198
|
+
]
|
|
199
|
+
rust = result.rust
|
|
200
|
+
smap = [dict(e) for e in (getattr(result, "source_map", None) or ())] or None
|
|
201
|
+
if smap:
|
|
202
|
+
smap = _renamed(smap, "py_file", core_file, src.display)
|
|
203
|
+
if store is not None and store.exists() and rust:
|
|
204
|
+
rust, smap, todos, entry["patches"] = apply_overlay(
|
|
205
|
+
rust, smap, todos, store, src.display, skip, src.text
|
|
206
|
+
)
|
|
207
|
+
entry["rust"], entry["source_map"] = rust, smap
|
|
208
|
+
entry["diagnostics"], entry["todos"] = diags, todos
|
|
209
|
+
# the drift ledger: where the Rust may behave differently from the Python (info diagnostics)
|
|
210
|
+
entry["drift"] = sorted(
|
|
211
|
+
_renamed([dict(d) for d in getattr(result, "drift", ())], "file", core_file, src.display),
|
|
212
|
+
key=lambda d: (d["line"], d["code"], d["message"]),
|
|
213
|
+
)
|
|
214
|
+
entry["required_crates"] = dict(getattr(result, "required_crates", {}) or {})
|
|
215
|
+
entry["required_features"] = list(getattr(result, "required_features", ()) or ())
|
|
216
|
+
entry["tests"] = [dict(t) for t in getattr(result, "tests", ()) or ()]
|
|
217
|
+
entry["not_clean"] = list(
|
|
218
|
+
getattr(result, "not_clean", ()) or ()
|
|
219
|
+
) # items the core counts not clean
|
|
220
|
+
open_todos = sum(t["state"] == "open" for t in todos)
|
|
221
|
+
entry["stats"] = {**dict.fromkeys(STAT_KEYS, 0), **result.stats, "todo_count": open_todos}
|
|
222
|
+
has_error = any(d["severity"] == "error" for d in diags)
|
|
223
|
+
if has_error:
|
|
224
|
+
entry["status"] = "error"
|
|
225
|
+
elif open_todos:
|
|
226
|
+
entry["status"] = "todo"
|
|
227
|
+
elif unhealed_not_clean(entry, src.text or ""):
|
|
228
|
+
entry["status"] = "not_clean"
|
|
229
|
+
else:
|
|
230
|
+
entry["status"] = "clean"
|
|
231
|
+
return entry
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def translate_one(
|
|
235
|
+
src: Source,
|
|
236
|
+
config: Any,
|
|
237
|
+
*,
|
|
238
|
+
store: PatchStore | None = None,
|
|
239
|
+
skip: frozenset[str] = frozenset(),
|
|
240
|
+
) -> dict[str, Any]:
|
|
241
|
+
"""Translate one source on its own (status: clean | not_clean | todo | error | internal_error).
|
|
242
|
+
|
|
243
|
+
With a patch `store` holding accepted patches, they are spliced into the generated Rust.
|
|
244
|
+
The entry also carries `source_map` (list or None); public documents drop it.
|
|
245
|
+
"""
|
|
246
|
+
entry = _new_entry(src)
|
|
247
|
+
if src.text is None:
|
|
248
|
+
entry["error"] = src.read_error
|
|
249
|
+
return entry
|
|
250
|
+
try:
|
|
251
|
+
result = get_core().translate_source(src.text, src.display, config)
|
|
252
|
+
except Exception as exc:
|
|
253
|
+
return _failed(entry, exc)
|
|
254
|
+
return _fill_entry(entry, src, result, store=store, skip=skip, core_file=src.display)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def translate_project_group(
|
|
258
|
+
root: str,
|
|
259
|
+
sources: list[Source],
|
|
260
|
+
config: Any,
|
|
261
|
+
*,
|
|
262
|
+
store: PatchStore | None,
|
|
263
|
+
skip: frozenset[str],
|
|
264
|
+
) -> list[dict[str, Any]]:
|
|
265
|
+
"""Translate the files of one directory together, so imports between them resolve.
|
|
266
|
+
|
|
267
|
+
If `root` is itself a package (it has an `__init__.py`), the project root is its parent, so the
|
|
268
|
+
modules are named `pkg.module` the way the code imports them. Each entry also gets `module`: its
|
|
269
|
+
Rust module path, crate-relative file and dependencies. A file the core has no result for is
|
|
270
|
+
translated on its own instead.
|
|
271
|
+
"""
|
|
272
|
+
entries = [_new_entry(s) for s in sources]
|
|
273
|
+
top = Path(root).resolve()
|
|
274
|
+
if (top / "__init__.py").is_file():
|
|
275
|
+
base, prefix = str(top.parent), f"{top.name}/"
|
|
276
|
+
else:
|
|
277
|
+
base, prefix = str(top), ""
|
|
278
|
+
core_rel = {s.display: prefix + s.rel for s in sources}
|
|
279
|
+
try:
|
|
280
|
+
res = get_core().translate_project(base, list(core_rel.values()), config)
|
|
281
|
+
except Exception as exc:
|
|
282
|
+
return [_failed(e, exc) for e in entries]
|
|
283
|
+
info = {m.path: m for m in res.modules}
|
|
284
|
+
cycles: dict[str, list[Any]] = {}
|
|
285
|
+
for d in res.diagnostics:
|
|
286
|
+
cycles.setdefault(d.file, []).append(d)
|
|
287
|
+
out = []
|
|
288
|
+
for src, entry in zip(sources, entries, strict=True):
|
|
289
|
+
key = core_rel[src.display]
|
|
290
|
+
result = res.files.get(key)
|
|
291
|
+
if result is None: # e.g. a top-level `__init__.py` of a directory that is not a package
|
|
292
|
+
out.append(translate_one(src, config, store=store, skip=skip))
|
|
293
|
+
continue
|
|
294
|
+
_fill_entry(
|
|
295
|
+
entry, src, result, store=store, skip=skip, core_file=key,
|
|
296
|
+
extra_diagnostics=cycles.get(key, ()),
|
|
297
|
+
) # fmt: skip
|
|
298
|
+
if (m := info.get(key)) is not None:
|
|
299
|
+
entry["module"] = {
|
|
300
|
+
"name": m.name,
|
|
301
|
+
"rust_module": m.rust_module,
|
|
302
|
+
"crate_path": m.rust_path,
|
|
303
|
+
"depends_on": list(m.depends_on),
|
|
304
|
+
"in_cycle": m.in_cycle,
|
|
305
|
+
}
|
|
306
|
+
out.append(entry)
|
|
307
|
+
return out
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def translate_sources(
|
|
311
|
+
sources: list[Source],
|
|
312
|
+
config: Any,
|
|
313
|
+
*,
|
|
314
|
+
store: PatchStore | None = None,
|
|
315
|
+
skip: frozenset[str] = frozenset(),
|
|
316
|
+
per_file: bool = False,
|
|
317
|
+
) -> list[dict[str, Any]]:
|
|
318
|
+
"""Translate `sources`: files found under one directory argument are translated as a project.
|
|
319
|
+
|
|
320
|
+
A project (several files under the same directory) resolves imports between its modules, so
|
|
321
|
+
`use crate::a::b::name` replaces an unresolved-import TODO. `per_file` (or a core without project
|
|
322
|
+
mode) translates every file alone.
|
|
323
|
+
"""
|
|
324
|
+
entries: list[dict[str, Any] | None] = [None] * len(sources)
|
|
325
|
+
groups: dict[str, list[int]] = {}
|
|
326
|
+
if not per_file and hasattr(get_core(), "translate_project"):
|
|
327
|
+
for i, s in enumerate(sources):
|
|
328
|
+
if s.root is not None and s.text is not None:
|
|
329
|
+
groups.setdefault(s.root, []).append(i)
|
|
330
|
+
for root, idx in groups.items():
|
|
331
|
+
if len(idx) < 2: # one lone file gains nothing from project mode
|
|
332
|
+
continue
|
|
333
|
+
got = translate_project_group(
|
|
334
|
+
root, [sources[i] for i in idx], config, store=store, skip=skip
|
|
335
|
+
)
|
|
336
|
+
for i, e in zip(idx, got, strict=True):
|
|
337
|
+
entries[i] = e
|
|
338
|
+
return [
|
|
339
|
+
e if e is not None else translate_one(s, config, store=store, skip=skip)
|
|
340
|
+
for s, e in zip(sources, entries, strict=True)
|
|
341
|
+
]
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def write_outputs(entry: dict[str, Any], rel: str, out_dir: Path) -> None:
|
|
345
|
+
"""Write `<name>.rs`, `.rs.map`, `.todo.json` and `.diagnostics.json`; drop the inline source."""
|
|
346
|
+
if not entry["rust"]:
|
|
347
|
+
entry["rust"] = None
|
|
348
|
+
return
|
|
349
|
+
rs = out_dir / (entry.get("module") or {}).get("crate_path", rust_path_for(rel))
|
|
350
|
+
rs.parent.mkdir(parents=True, exist_ok=True)
|
|
351
|
+
rs.write_text(entry["rust"], encoding="utf-8")
|
|
352
|
+
entry["rust_path"] = rs.as_posix()
|
|
353
|
+
entry["rust"] = None
|
|
354
|
+
entry["todos"] = [_rehandoff(t, entry["rust_path"]) for t in entry["todos"]]
|
|
355
|
+
sidecars = [(".todo.json", entry["todos"]), (".diagnostics.json", entry["diagnostics"])]
|
|
356
|
+
if entry["source_map"] is not None:
|
|
357
|
+
sidecars.append((".rs.map", entry["source_map"]))
|
|
358
|
+
for suffix, data in sidecars:
|
|
359
|
+
name = rs.name + ".map" if suffix == ".rs.map" else rs.stem + suffix
|
|
360
|
+
(rs.parent / name).write_text(
|
|
361
|
+
json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def write_crate_glue(entries: list[dict[str, Any]], out_dir: Path) -> None:
|
|
366
|
+
"""In project mode: `lib.rs` and the `pub mod` lines of package `mod.rs` files, so the output
|
|
367
|
+
directory is a crate source tree (`cargo check` it with a Cargo.toml next to src/)."""
|
|
368
|
+
from python2rust.verify.check import module_tree
|
|
369
|
+
|
|
370
|
+
placed = [e for e in entries if e.get("rust_path") and e.get("module")]
|
|
371
|
+
if not placed:
|
|
372
|
+
return
|
|
373
|
+
rels = [e["module"]["crate_path"] for e in placed]
|
|
374
|
+
lib, footers = module_tree(rels)
|
|
375
|
+
(out_dir / "lib.rs").write_text(lib, encoding="utf-8")
|
|
376
|
+
for rel, footer in footers.items():
|
|
377
|
+
path = out_dir / rel
|
|
378
|
+
if path.is_file():
|
|
379
|
+
path.write_text(
|
|
380
|
+
path.read_text(encoding="utf-8").rstrip("\n") + "\n" + footer, encoding="utf-8"
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _rehandoff(todo: dict[str, Any], rust_file: str) -> dict[str, Any]:
|
|
385
|
+
base = {k: v for k, v in todo.items() if k not in ("rust_file", "hint", "instruction")}
|
|
386
|
+
return {**_handoff(base, rust_file, todo.get("hint")), "state": todo.get("state", "open")}
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def public(entry: dict[str, Any]) -> dict[str, Any]:
|
|
390
|
+
"""The entry as it appears in JSON documents (no source map; that is a sidecar)."""
|
|
391
|
+
return {k: v for k, v in entry.items() if k != "source_map"}
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def modules_for(sources: list[Source], entries: list[dict[str, Any]]) -> list[CheckModule]:
|
|
395
|
+
"""The Rust modules to verify: one per translated file, with its source map and todos."""
|
|
396
|
+
return [
|
|
397
|
+
CheckModule(
|
|
398
|
+
s.display,
|
|
399
|
+
e["rust"],
|
|
400
|
+
e["todos"],
|
|
401
|
+
s.text,
|
|
402
|
+
e["source_map"],
|
|
403
|
+
e.get("required_crates"),
|
|
404
|
+
(e.get("module") or {}).get("crate_path"),
|
|
405
|
+
e.get("tests") or [],
|
|
406
|
+
)
|
|
407
|
+
for s, e in zip(sources, entries, strict=True)
|
|
408
|
+
if e["rust"]
|
|
409
|
+
]
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def summarize(entries: list[dict[str, Any]]) -> dict[str, Any]:
|
|
413
|
+
stats = Counter()
|
|
414
|
+
for e in entries:
|
|
415
|
+
stats.update(e["stats"])
|
|
416
|
+
sev = Counter(d["severity"] for e in entries for d in e["diagnostics"])
|
|
417
|
+
drift = Counter(d["code"] for e in entries for d in e["drift"])
|
|
418
|
+
status = Counter(e["status"] for e in entries)
|
|
419
|
+
return {
|
|
420
|
+
"files": len(entries),
|
|
421
|
+
"files_clean": status["clean"],
|
|
422
|
+
"files_with_todos": status["todo"],
|
|
423
|
+
"files_not_clean": status["not_clean"],
|
|
424
|
+
"files_failed": status["error"] + status["internal_error"],
|
|
425
|
+
# "no TODO" is not "translated and compiling": see functions_check_clean in verify/coverage
|
|
426
|
+
"functions_total": stats["functions_total"],
|
|
427
|
+
"functions_no_todo": stats["functions_clean"],
|
|
428
|
+
"models_total": stats["models_total"],
|
|
429
|
+
"models_no_todo": stats["models_clean"],
|
|
430
|
+
"todo_count": stats["todo_count"],
|
|
431
|
+
"todos_patched": sum(t.get("state") == "patched" for e in entries for t in e["todos"]),
|
|
432
|
+
"needs_review_count": sum(t["needs_review"] for e in entries for t in e["todos"]),
|
|
433
|
+
"error_count": sev["error"],
|
|
434
|
+
"warning_count": sev["warning"],
|
|
435
|
+
# where the Rust may differ from the Python even when it compiles (PY2RS041..PY2RS049)
|
|
436
|
+
"drift_count": sum(drift.values()),
|
|
437
|
+
"not_clean_count": sum(len(e.get("not_clean", ())) for e in entries),
|
|
438
|
+
"drift_by_code": dict(sorted(drift.items())),
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def exit_code(entries: list[dict[str, Any]]) -> int:
|
|
443
|
+
if any(e["status"] == "internal_error" for e in entries):
|
|
444
|
+
return EXIT_INTERNAL
|
|
445
|
+
return EXIT_OK if all(e["status"] == "clean" for e in entries) else EXIT_FINDINGS
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def translate_doc(
|
|
449
|
+
entries: list[dict[str, Any]], command: str = "translate"
|
|
450
|
+
) -> tuple[dict[str, Any], int]:
|
|
451
|
+
code = exit_code(entries)
|
|
452
|
+
files = [public(e) for e in entries]
|
|
453
|
+
return envelope(command, ok=code == EXIT_OK, summary=summarize(entries), files=files), code
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
# --- check / verify -----------------------------------------------------------------------------
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def check_doc(entries: list[dict[str, Any]], cargo: dict[str, Any]) -> tuple[dict[str, Any], int]:
|
|
460
|
+
"""Combine the translation results (may be empty for raw .rs input) with the cargo result."""
|
|
461
|
+
translation, code = None, EXIT_OK
|
|
462
|
+
if entries:
|
|
463
|
+
tdoc, code = translate_doc(entries)
|
|
464
|
+
translation = {"summary": tdoc["summary"], "files": tdoc["files"]}
|
|
465
|
+
if cargo["status"] == "errors":
|
|
466
|
+
code = EXIT_COMPILE if code != EXIT_INTERNAL else code
|
|
467
|
+
elif cargo["status"] != "ok":
|
|
468
|
+
code = max(code, EXIT_FINDINGS)
|
|
469
|
+
return envelope("check", ok=code == EXIT_OK, translation=translation, cargo=cargo), code
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def verify_doc(entries: list[dict[str, Any]], ladder: dict[str, Any]) -> tuple[dict[str, Any], int]:
|
|
473
|
+
"""The `verify` document: per-function verdicts plus a summary; exit 4 when a rung fails."""
|
|
474
|
+
from python2rust.verify.ladder import LEVELS, verify_summary
|
|
475
|
+
|
|
476
|
+
files = ladder["files"]
|
|
477
|
+
summary = {**summarize(entries), **verify_summary(files, ladder["level"])}
|
|
478
|
+
wanted = LEVELS[: LEVELS.index(ladder["level"]) + 1]
|
|
479
|
+
# parse/check/clippy/test failures are "does not compile" (exit 4); an unformatted file is exit 1
|
|
480
|
+
hard = [r for r in wanted if r != "fmt"]
|
|
481
|
+
failed = any(fl["rungs"][r]["status"] == "fail" for fl in files for r in hard)
|
|
482
|
+
failed = failed or any(
|
|
483
|
+
fn["rungs"].get(r) == "fail" for fl in files for fn in fl["functions"] for r in hard
|
|
484
|
+
)
|
|
485
|
+
soft = any(fl["rungs"][r]["status"] == "fail" for fl in files for r in wanted if r == "fmt")
|
|
486
|
+
unverified = any(r["status"] == "unverified" for fl in files for r in fl["rungs"].values())
|
|
487
|
+
code = exit_code(entries)
|
|
488
|
+
if failed and code != EXIT_INTERNAL:
|
|
489
|
+
code = EXIT_COMPILE
|
|
490
|
+
elif (unverified or soft) and code == EXIT_OK:
|
|
491
|
+
code = EXIT_FINDINGS
|
|
492
|
+
brief = {e["file"]: e["status"] for e in entries}
|
|
493
|
+
for fl in files:
|
|
494
|
+
fl["translation_status"] = brief.get(fl["file"], "n/a")
|
|
495
|
+
doc = envelope(
|
|
496
|
+
"verify",
|
|
497
|
+
ok=code == EXIT_OK,
|
|
498
|
+
level=ladder["level"],
|
|
499
|
+
rungs=list(wanted),
|
|
500
|
+
tools=ladder["tools"],
|
|
501
|
+
summary=summary,
|
|
502
|
+
files=files,
|
|
503
|
+
)
|
|
504
|
+
doc.update({k: ladder[k] for k in ("equiv", "judged", "spot_check") if k in ladder})
|
|
505
|
+
return doc, code
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
# --- todos --------------------------------------------------------------------------------------
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def todos_doc(
|
|
512
|
+
entries: list[dict[str, Any]], *, only_review: bool = False, include_patched: bool = False
|
|
513
|
+
) -> tuple[dict[str, Any], int]:
|
|
514
|
+
"""Open TODOs (plus patched ones with `include_patched`; patched needs_review ones with only_review)."""
|
|
515
|
+
|
|
516
|
+
def wanted(t: dict[str, Any]) -> bool:
|
|
517
|
+
if only_review and not t["needs_review"]:
|
|
518
|
+
return False
|
|
519
|
+
return t["state"] == "open" or include_patched or only_review
|
|
520
|
+
|
|
521
|
+
todos = [t for e in entries for t in e["todos"] if wanted(t)]
|
|
522
|
+
problems = [
|
|
523
|
+
{"file": e["file"], "status": e["status"], "error": e["error"]}
|
|
524
|
+
for e in entries
|
|
525
|
+
if e["status"] in ("error", "internal_error")
|
|
526
|
+
]
|
|
527
|
+
code = exit_code(entries)
|
|
528
|
+
return (
|
|
529
|
+
envelope("todos", ok=code == EXIT_OK, count=len(todos), todos=todos, failed_files=problems),
|
|
530
|
+
code,
|
|
531
|
+
)
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
# --- coverage -----------------------------------------------------------------------------------
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def coverage_doc(
|
|
538
|
+
entries: list[dict[str, Any]], ladder: dict[str, Any] | None = None
|
|
539
|
+
) -> tuple[dict[str, Any], int]:
|
|
540
|
+
"""Corpus metrics. With a `ladder` result the headline is `functions_check_clean`.
|
|
541
|
+
|
|
542
|
+
functions_check_clean = functions with Rust output, no todo!() left, passing `cargo check`.
|
|
543
|
+
Without a ladder (or without cargo) it is null: "no TODO" is reported separately and is never
|
|
544
|
+
presented as the headline.
|
|
545
|
+
"""
|
|
546
|
+
from python2rust.verify.ladder import verify_summary
|
|
547
|
+
|
|
548
|
+
totals = summarize(entries)
|
|
549
|
+
if ladder is not None:
|
|
550
|
+
totals.update(verify_summary(ladder["files"], ladder["level"]))
|
|
551
|
+
else:
|
|
552
|
+
totals.update(
|
|
553
|
+
functions_translated=None, functions_check_pass=None, functions_check_clean=None,
|
|
554
|
+
functions_unverified=None, functions_check_clean_pct=None,
|
|
555
|
+
) # fmt: skip
|
|
556
|
+
by_kind = Counter(t["kind"] for e in entries for t in e["todos"] if t["state"] == "open")
|
|
557
|
+
by_todo_code = Counter(t["code"] for e in entries for t in e["todos"] if t["state"] == "open")
|
|
558
|
+
by_diag_code = Counter(d["code"] for e in entries for d in e["diagnostics"])
|
|
559
|
+
files = [
|
|
560
|
+
{
|
|
561
|
+
"file": e["file"],
|
|
562
|
+
"status": e["status"],
|
|
563
|
+
**e["stats"],
|
|
564
|
+
"diagnostics": len(e["diagnostics"]),
|
|
565
|
+
}
|
|
566
|
+
for e in entries
|
|
567
|
+
]
|
|
568
|
+
doc = envelope(
|
|
569
|
+
"coverage",
|
|
570
|
+
level=ladder["level"] if ladder else None,
|
|
571
|
+
totals=totals,
|
|
572
|
+
todos_by_construct=dict(sorted(by_kind.items(), key=lambda kv: (-kv[1], kv[0]))),
|
|
573
|
+
todos_by_code=dict(sorted(by_todo_code.items())),
|
|
574
|
+
diagnostics_by_code=dict(sorted(by_diag_code.items())),
|
|
575
|
+
files=files,
|
|
576
|
+
)
|
|
577
|
+
doc["markdown"] = coverage_markdown(doc)
|
|
578
|
+
code = exit_code(entries)
|
|
579
|
+
doc["ok"] = code == EXIT_OK
|
|
580
|
+
return doc, code
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def _pct_text(part: int | None, whole: int, unverified: str = "n/a (not verified)") -> str:
|
|
584
|
+
if part is None:
|
|
585
|
+
return unverified
|
|
586
|
+
return f"{part} / {whole} ({round(100.0 * part / whole, 1) if whole else 100.0}%)"
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def coverage_markdown(doc: dict[str, Any]) -> str:
|
|
590
|
+
t = doc["totals"]
|
|
591
|
+
lines = [
|
|
592
|
+
"| metric | value |",
|
|
593
|
+
"|---|---:|",
|
|
594
|
+
f"| files | {t['files']} |",
|
|
595
|
+
f"| files with no remaining translation findings | {t['files_clean']} |",
|
|
596
|
+
f"| files with unchecked behavior and no open TODOs | {t['files_not_clean']} |",
|
|
597
|
+
f"| files with open TODOs | {t['files_with_todos']} |",
|
|
598
|
+
f"| files failed | {t['files_failed']} |",
|
|
599
|
+
f"| **functions check-clean** (Rust output, no todo!(), passes `cargo check`) | {_pct_text(t['functions_check_clean'], t['functions_total'])} |",
|
|
600
|
+
f"| functions with Rust output and no todo!() | {_pct_text(t['functions_translated'], t['functions_total'], str(t['functions_no_todo']) + ' (core count)')} |",
|
|
601
|
+
f"| models without a TODO | {t['models_no_todo']} / {t['models_total']} |",
|
|
602
|
+
f"| open TODOs | {t['todo_count']} |",
|
|
603
|
+
f"| TODOs patched | {t['todos_patched']} |",
|
|
604
|
+
f"| TODOs needing review | {t['needs_review_count']} |",
|
|
605
|
+
f"| drift notes (Rust may behave differently from Python, even if it compiles) | {t['drift_count']} |",
|
|
606
|
+
]
|
|
607
|
+
if doc["todos_by_construct"]:
|
|
608
|
+
lines += ["", "| construct | open TODOs |", "|---|---:|"]
|
|
609
|
+
lines += [f"| {k} | {v} |" for k, v in doc["todos_by_construct"].items()]
|
|
610
|
+
if t["drift_by_code"]:
|
|
611
|
+
codes = getattr(get_core(), "DIAGNOSTIC_CODES", {})
|
|
612
|
+
lines += ["", "| drift code | places | what may differ |", "|---|---:|---|"]
|
|
613
|
+
for code, n in t["drift_by_code"].items():
|
|
614
|
+
what = codes.get(code, "").removeprefix("Drift: ").replace("|", "\\|")
|
|
615
|
+
lines.append(f"| {code} | {n} | {what} |")
|
|
616
|
+
return "\n".join(lines) + "\n"
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def run_translate(
|
|
620
|
+
sources: list[Source],
|
|
621
|
+
config_path: str | None,
|
|
622
|
+
*,
|
|
623
|
+
fmt: bool = True,
|
|
624
|
+
vendor_runtime: bool = False,
|
|
625
|
+
project: str | None = None,
|
|
626
|
+
skip: frozenset[str] = frozenset(),
|
|
627
|
+
per_file: bool = False,
|
|
628
|
+
builtin_errors: str | None = None,
|
|
629
|
+
) -> list[dict[str, Any]]:
|
|
630
|
+
"""Translate every source with one shared config; raises UsageError for a bad config.
|
|
631
|
+
|
|
632
|
+
`project` is the directory whose `.python2rust/patches/` overlay is applied (None: no overlay).
|
|
633
|
+
"""
|
|
634
|
+
get_core() # a missing core is exit 3, not a per-file failure
|
|
635
|
+
config = load_config(
|
|
636
|
+
config_path, fmt=fmt, vendor_runtime=vendor_runtime, builtin_errors=builtin_errors
|
|
637
|
+
)
|
|
638
|
+
store = PatchStore(project, gate_allowlist(config_path)) if project is not None else None
|
|
639
|
+
try:
|
|
640
|
+
return translate_sources(sources, config, store=store, skip=skip, per_file=per_file)
|
|
641
|
+
except ImportError as exc: # the core itself is broken
|
|
642
|
+
raise InternalError(f"cannot load the translator core: {exc}") from exc
|