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
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""The ONLY module that imports and runs the user's Python (`verify --level equiv --run-python`).
|
|
2
|
+
|
|
3
|
+
It is a standalone script started as `python -I runner.py` in a child process, never imported
|
|
4
|
+
by the CLI. The parent talks to it in JSON lines (prefix `@@P2R `) over stdin/stdout:
|
|
5
|
+
|
|
6
|
+
{"op": "init", "path", "extra_path", "memory_mb", "sig": {fn: {"params": [Ty], "ret": Ty}}}
|
|
7
|
+
{"op": "call", "fn", "args"} -> {"ok": value} | {"err": ClassName, "mro", "msg"}
|
|
8
|
+
{"op": "model", "name", "payload"} -> {"ok": dumped} | {"err": "reject"}
|
|
9
|
+
|
|
10
|
+
Containment (best effort, documented in docs/EQUIVALENCE.md): `-I` isolation, a scrubbed
|
|
11
|
+
environment (set by the parent), cwd = scratch directory, `RLIMIT_AS` where the platform honours
|
|
12
|
+
it, no network (socket is patched), stdin replaced by /dev/null and stdout redirected to stderr so
|
|
13
|
+
user prints cannot corrupt the protocol. The parent enforces the per-call timeout and kills us.
|
|
14
|
+
Standard library only; it must not import python2rust.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import dataclasses
|
|
20
|
+
import importlib.util
|
|
21
|
+
import json
|
|
22
|
+
import math
|
|
23
|
+
import os
|
|
24
|
+
import sys
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
PREFIX = "@@P2R "
|
|
28
|
+
_USER = "__python2rust_user__"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _deny(*_a: object, **_k: object) -> None:
|
|
32
|
+
raise OSError("network access is disabled during python2rust equivalence runs")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _block_network() -> None:
|
|
36
|
+
import socket
|
|
37
|
+
|
|
38
|
+
for name in ("connect", "connect_ex", "sendto"):
|
|
39
|
+
setattr(socket.socket, name, _deny)
|
|
40
|
+
for name in ("create_connection", "getaddrinfo", "gethostbyname", "gethostbyname_ex"):
|
|
41
|
+
setattr(socket, name, _deny)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _limit_memory(megabytes: int) -> bool:
|
|
45
|
+
try:
|
|
46
|
+
import resource
|
|
47
|
+
|
|
48
|
+
limit = megabytes * 1024 * 1024
|
|
49
|
+
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
|
|
50
|
+
return True
|
|
51
|
+
except ImportError, ValueError, OSError:
|
|
52
|
+
return False # macOS and others do not honour it; the parent watches our RSS instead
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# --- wire format --------------------------------------------------------------------------------
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class _Unencodable(Exception):
|
|
59
|
+
pass
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def enc(v: Any) -> Any:
|
|
63
|
+
if v is None or isinstance(v, bool | str):
|
|
64
|
+
return v
|
|
65
|
+
if isinstance(v, int):
|
|
66
|
+
return int(v)
|
|
67
|
+
if isinstance(v, float):
|
|
68
|
+
if math.isnan(v):
|
|
69
|
+
return {"$f": "nan"}
|
|
70
|
+
if math.isinf(v):
|
|
71
|
+
return {"$f": "inf" if v > 0 else "-inf"}
|
|
72
|
+
return v
|
|
73
|
+
if isinstance(v, list | tuple):
|
|
74
|
+
return [enc(x) for x in v]
|
|
75
|
+
if isinstance(v, dict):
|
|
76
|
+
if not all(isinstance(k, str) for k in v):
|
|
77
|
+
raise _Unencodable("dict with non-str keys")
|
|
78
|
+
return {k: enc(x) for k, x in v.items()}
|
|
79
|
+
raise _Unencodable(type(v).__name__)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _float(w: Any) -> float:
|
|
83
|
+
if isinstance(w, dict):
|
|
84
|
+
return float(str(w["$f"]))
|
|
85
|
+
return float(w)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def dec(ty: list, w: Any) -> Any:
|
|
89
|
+
k = ty[0]
|
|
90
|
+
if k == "float":
|
|
91
|
+
return _float(w)
|
|
92
|
+
if k == "opt":
|
|
93
|
+
return None if w is None else dec(ty[1], w)
|
|
94
|
+
if k == "list":
|
|
95
|
+
return [dec(ty[1], x) for x in w]
|
|
96
|
+
if k == "tuplev":
|
|
97
|
+
return tuple(dec(ty[1], x) for x in w)
|
|
98
|
+
if k == "tuple":
|
|
99
|
+
return tuple(dec(t, x) for t, x in zip(ty[1], w, strict=True))
|
|
100
|
+
if k == "dict":
|
|
101
|
+
return {a: dec(ty[1], b) for a, b in w.items()}
|
|
102
|
+
return w
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _fits(ty: list, v: Any) -> bool:
|
|
106
|
+
k = ty[0]
|
|
107
|
+
if k == "int":
|
|
108
|
+
return type(v) is int
|
|
109
|
+
if k == "float":
|
|
110
|
+
return type(v) in (int, float)
|
|
111
|
+
if k == "str":
|
|
112
|
+
return isinstance(v, str)
|
|
113
|
+
if k == "bool":
|
|
114
|
+
return isinstance(v, bool)
|
|
115
|
+
if k == "none":
|
|
116
|
+
return v is None
|
|
117
|
+
if k == "opt":
|
|
118
|
+
return v is None or _fits(ty[1], v)
|
|
119
|
+
if k == "list":
|
|
120
|
+
return isinstance(v, list) and all(_fits(ty[1], x) for x in v)
|
|
121
|
+
if k == "tuplev":
|
|
122
|
+
return isinstance(v, list) and all(_fits(ty[1], x) for x in v)
|
|
123
|
+
if k == "tuple":
|
|
124
|
+
return isinstance(v, list) and len(v) == len(ty[1]) and all(
|
|
125
|
+
_fits(t, x) for t, x in zip(ty[1], v, strict=True)
|
|
126
|
+
) # fmt: skip
|
|
127
|
+
if k == "dict":
|
|
128
|
+
return isinstance(v, dict) and all(_fits(ty[1], x) for x in v.values())
|
|
129
|
+
return True
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# --- operations ---------------------------------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class Runner:
|
|
136
|
+
def __init__(self) -> None:
|
|
137
|
+
self.module: object = None
|
|
138
|
+
self.sig: dict[str, dict] = {}
|
|
139
|
+
self.models: dict[str, dict] = {}
|
|
140
|
+
self.pydantic = False
|
|
141
|
+
|
|
142
|
+
def init(self, req: dict) -> dict:
|
|
143
|
+
limited = _limit_memory(int(req["memory_mb"])) if req.get("memory_mb") else False
|
|
144
|
+
_block_network()
|
|
145
|
+
for p in reversed(req.get("extra_path", [])):
|
|
146
|
+
if p not in sys.path:
|
|
147
|
+
sys.path.insert(0, p)
|
|
148
|
+
self.sig = req.get("sig", {})
|
|
149
|
+
self.models = req.get("models", {})
|
|
150
|
+
try:
|
|
151
|
+
spec = importlib.util.spec_from_file_location(_USER, req["path"])
|
|
152
|
+
if spec is None or spec.loader is None:
|
|
153
|
+
return {"err": "import", "msg": f"cannot load {req['path']}"}
|
|
154
|
+
mod = importlib.util.module_from_spec(spec)
|
|
155
|
+
sys.modules[_USER] = mod
|
|
156
|
+
spec.loader.exec_module(mod)
|
|
157
|
+
except BaseException as exc:
|
|
158
|
+
return {"err": "import", "kind": type(exc).__name__, "msg": str(exc)[:300]}
|
|
159
|
+
self.module = mod
|
|
160
|
+
missing = [f for f in self.sig if not callable(getattr(mod, f, None))]
|
|
161
|
+
try:
|
|
162
|
+
import pydantic # noqa: F401
|
|
163
|
+
|
|
164
|
+
self.pydantic = True
|
|
165
|
+
except ImportError:
|
|
166
|
+
self.pydantic = False
|
|
167
|
+
return {
|
|
168
|
+
"ok": True,
|
|
169
|
+
"limits": {"as": limited},
|
|
170
|
+
"missing": missing,
|
|
171
|
+
"pydantic": self.pydantic,
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
def call(self, req: dict) -> dict:
|
|
175
|
+
fn = getattr(self.module, req["fn"])
|
|
176
|
+
sig = self.sig[req["fn"]]
|
|
177
|
+
args = []
|
|
178
|
+
try:
|
|
179
|
+
args = [dec(t, a) for t, a in zip(sig["params"], req["args"], strict=True)]
|
|
180
|
+
result = fn(*args)
|
|
181
|
+
except BaseException as exc:
|
|
182
|
+
mro = [c.__name__ for c in type(exc).__mro__ if c not in (object, BaseException)]
|
|
183
|
+
reply = {"err": type(exc).__name__, "mro": mro, "msg": str(exc)[:300]}
|
|
184
|
+
else:
|
|
185
|
+
try:
|
|
186
|
+
reply = {"ok": enc(result)}
|
|
187
|
+
except _Unencodable as exc:
|
|
188
|
+
return {"unencodable": str(exc)}
|
|
189
|
+
try:
|
|
190
|
+
if (observe := req.get("observe")) and args:
|
|
191
|
+
reply["args_after"] = [enc(args[i]) for i in observe]
|
|
192
|
+
return reply
|
|
193
|
+
except _Unencodable as exc:
|
|
194
|
+
return {"unencodable": str(exc)}
|
|
195
|
+
|
|
196
|
+
def model(self, req: dict) -> dict:
|
|
197
|
+
spec = self.models[req["name"]]
|
|
198
|
+
cls = getattr(self.module, req["name"], None)
|
|
199
|
+
payload = req["payload"]
|
|
200
|
+
if cls is None:
|
|
201
|
+
return {"err": "missing"}
|
|
202
|
+
try:
|
|
203
|
+
if spec["kind"] == "pydantic":
|
|
204
|
+
if not self.pydantic:
|
|
205
|
+
return {"err": "no-pydantic"}
|
|
206
|
+
return {"ok": enc(cls.model_validate(payload).model_dump(mode="json"))}
|
|
207
|
+
return self._dataclass(cls, spec, payload)
|
|
208
|
+
except _Unencodable as exc:
|
|
209
|
+
return {"unencodable": str(exc)}
|
|
210
|
+
except Exception:
|
|
211
|
+
return {"err": "reject"}
|
|
212
|
+
|
|
213
|
+
@staticmethod
|
|
214
|
+
def _dataclass(cls: type, spec: dict, payload: object) -> dict:
|
|
215
|
+
if not isinstance(payload, dict):
|
|
216
|
+
return {"err": "reject"}
|
|
217
|
+
kwargs = {}
|
|
218
|
+
for name, ty, has_default in spec["fields"]:
|
|
219
|
+
if name not in payload:
|
|
220
|
+
if not has_default:
|
|
221
|
+
return {"err": "reject"}
|
|
222
|
+
continue
|
|
223
|
+
if not _fits(ty, payload[name]):
|
|
224
|
+
return {"err": "reject"}
|
|
225
|
+
kwargs[name] = dec(ty, payload[name])
|
|
226
|
+
obj = cls(**kwargs)
|
|
227
|
+
return {"ok": {f.name: enc(getattr(obj, f.name)) for f in dataclasses.fields(obj)}}
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def main() -> None:
|
|
231
|
+
proto_in = os.fdopen(os.dup(0), "r", encoding="utf-8")
|
|
232
|
+
proto_out = os.fdopen(os.dup(1), "w", encoding="utf-8", buffering=1)
|
|
233
|
+
os.dup2(os.open(os.devnull, os.O_RDONLY), 0) # user code cannot read the protocol
|
|
234
|
+
os.dup2(2, 1) # user prints go to stderr
|
|
235
|
+
sys.setrecursionlimit(2000)
|
|
236
|
+
runner = Runner()
|
|
237
|
+
handlers = {"init": runner.init, "call": runner.call, "model": runner.model}
|
|
238
|
+
for line in proto_in:
|
|
239
|
+
try:
|
|
240
|
+
req = json.loads(line)
|
|
241
|
+
reply = handlers[req["op"]](req)
|
|
242
|
+
except BaseException as exc:
|
|
243
|
+
reply = {"err": "runner", "msg": f"{type(exc).__name__}: {exc}"[:300]}
|
|
244
|
+
proto_out.write(PREFIX + json.dumps(reply, allow_nan=False) + "\n")
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
if __name__ == "__main__":
|
|
248
|
+
main()
|