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,370 @@
1
+ """Confine the cargo run that compiles Rust a model submitted (MCP): no network, reads limited.
2
+
3
+ Scanning submitted Rust for `include_str!` and friends (`agent.patches.host_access_violations`) is a
4
+ deny-list and keeps leaking: aliases, macros and attributes find ways around it. This module is the
5
+ boundary that does not depend on what the Rust says. The compile (rustc, and the build scripts and
6
+ proc-macros of vetted dependencies) runs under an OS sandbox that
7
+
8
+ * has no network,
9
+ * may read only the scratch crate, cargo's download caches (`registry/`, `git/`), the toolchain
10
+ (rustup `toolchains/`, the rustc sysroot), the target dir, vetted path dependencies and system
11
+ libraries; never the rest of the cargo home (`credentials.toml`, `config.toml`), host
12
+ configuration (`/etc`) or the server root,
13
+ * may write only the scratch crate and the target dir (and the temp dirs the linker needs),
14
+ * sees a scrubbed environment and a private, empty CARGO_HOME.
15
+
16
+ macOS uses `sandbox-exec` with a generated profile; Linux uses `bwrap` (bubblewrap). `unshare -n`
17
+ alone is not enough (it has no file confinement), so it does not count. Without a tool nothing
18
+ runs unless the caller opts out explicitly (`--allow-unsandboxed-compile`).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import contextlib
24
+ import contextvars
25
+ import functools
26
+ import hashlib
27
+ import os
28
+ import re
29
+ import shutil
30
+ import subprocess
31
+ import sys
32
+ from collections.abc import Generator, Iterable
33
+ from pathlib import Path
34
+
35
+ from python2rust.errors import UsageError
36
+
37
+ MISSING = (
38
+ "no compile sandbox is available on this machine (needs `sandbox-exec` on macOS or `bwrap` on "
39
+ "Linux), so Rust submitted through MCP is NOT compiled: cargo would run it unconfined, and a "
40
+ "compile can read host files. Install bubblewrap, or start the server with "
41
+ "--allow-unsandboxed-compile to accept that risk"
42
+ )
43
+
44
+ MISSING_CLI = (
45
+ "no compile sandbox is available on this machine (needs `sandbox-exec` on macOS or `bwrap` on "
46
+ "Linux), so the Rust this command compiles would run unconfined: cargo, build scripts and "
47
+ "proc-macros can read host files and use the network. Install bubblewrap, or pass "
48
+ "--allow-unsandboxed-compile (or set PYTHON2RUST_ALLOW_UNSANDBOXED_COMPILE=1) to accept that risk"
49
+ )
50
+ UNSANDBOXED_ENV = "PYTHON2RUST_ALLOW_UNSANDBOXED_COMPILE"
51
+
52
+ _ENV_KEEP = re.compile(
53
+ r"(?:PATH|HOME|USER|LOGNAME|LANG|LC_[A-Z]+|TMPDIR|TEMP|TMP|SDKROOT|DEVELOPER_DIR|"
54
+ r"MACOSX_DEPLOYMENT_TARGET|CC|CXX|AR|CFLAGS|LDFLAGS|XDG_CACHE_HOME|XDG_CONFIG_HOME|"
55
+ r"CARGO_[A-Z_]+|RUST[A-Z_]*)"
56
+ )
57
+ # never forward a credential even when its name matches a keep rule
58
+ _ENV_DROP = re.compile(r"TOKEN|SECRET|PASSWORD|CREDENTIAL|_KEY|REGISTRY|PROXY|_AUTH", re.I)
59
+
60
+ _active: contextvars.ContextVar[bool] = contextvars.ContextVar("p2r_compile_sandbox", default=False)
61
+ # The CLI's switch: None = not configured (library use), False = every compile is sandboxed,
62
+ # True = sandbox when a tool exists, otherwise compile unconfined after a loud warning.
63
+ _cli_unsandboxed_ok: bool | None = None
64
+ _warned = False
65
+
66
+
67
+ @functools.lru_cache(maxsize=8)
68
+ def _works(tool: str) -> bool:
69
+ """Whether `tool` can actually confine a process here. Present is not enough: bwrap fails
70
+ where unprivileged user namespaces are off (some CI images, containers), and sandbox-exec
71
+ fails when already running inside a sandbox. One probe per process."""
72
+ true = shutil.which("true") or "/usr/bin/true"
73
+ if sys.platform == "darwin":
74
+ argv = [tool, "-p", "(version 1)(allow default)", true]
75
+ else:
76
+ argv = [tool, "--unshare-net", "--ro-bind", "/", "/", "--dev", "/dev", true]
77
+ try:
78
+ return subprocess.run(argv, capture_output=True, timeout=30).returncode == 0
79
+ except OSError, subprocess.SubprocessError:
80
+ return False
81
+
82
+
83
+ def find() -> str | None:
84
+ """Path of the sandbox tool for this OS if it exists and works, else None."""
85
+ if sys.platform == "darwin":
86
+ tool = shutil.which("sandbox-exec")
87
+ else:
88
+ tool = shutil.which("bwrap") if sys.platform.startswith("linux") else None
89
+ return tool if tool and _works(tool) else None
90
+
91
+
92
+ def confined() -> bool:
93
+ """True inside `confine()`: cargo runs started by this thread must be sandboxed."""
94
+ return _active.get()
95
+
96
+
97
+ def configure_cli(allow_unsandboxed: bool = False) -> None:
98
+ """Make every cargo run of this process sandboxed (`check.run_cargo`, `run_in_crate`, and so
99
+ the ladder, apply, port and done which call them). Without a sandbox tool a run refuses, unless
100
+ `allow_unsandboxed` (`--allow-unsandboxed-compile`, or PYTHON2RUST_ALLOW_UNSANDBOXED_COMPILE=1),
101
+ which warns loudly and compiles unconfined. Nothing is checked until cargo is about to start,
102
+ so commands that do not compile are unaffected."""
103
+ global _cli_unsandboxed_ok, _warned
104
+ _cli_unsandboxed_ok = allow_unsandboxed or os.environ.get(UNSANDBOXED_ENV) == "1"
105
+ _warned = False
106
+
107
+
108
+ def reset_cli() -> None:
109
+ """Forget `configure_cli` (tests)."""
110
+ global _cli_unsandboxed_ok
111
+ _cli_unsandboxed_ok = None
112
+
113
+
114
+ def resolve(explicit: bool = False) -> bool:
115
+ """True when the cargo run about to start must run in the sandbox (the caller wraps it).
116
+
117
+ `explicit` or `confine()` demand it and refuse without a tool (UsageError); the CLI policy
118
+ (`configure_cli`) demands it too but may be told to compile unconfined, with a warning."""
119
+ global _warned
120
+ demanded = explicit or confined()
121
+ if not demanded and _cli_unsandboxed_ok is None:
122
+ return False
123
+ if find() is not None:
124
+ return True
125
+ if demanded:
126
+ raise UsageError(MISSING)
127
+ if not _cli_unsandboxed_ok:
128
+ raise UsageError(MISSING_CLI)
129
+ if not _warned:
130
+ _warned = True
131
+ print(
132
+ "WARNING: compiling WITHOUT an OS sandbox (--allow-unsandboxed-compile): the Rust, its "
133
+ "build scripts and proc-macros run with your full file and network access.",
134
+ file=sys.stderr,
135
+ )
136
+ return False
137
+
138
+
139
+ @contextlib.contextmanager
140
+ def confine() -> Generator[None]:
141
+ """Make every `check.run_cargo` in this context run sandboxed (or refuse when it cannot)."""
142
+ token = _active.set(True)
143
+ try:
144
+ yield
145
+ finally:
146
+ _active.reset(token)
147
+
148
+
149
+ def cargo_home() -> Path:
150
+ return Path(os.environ.get("CARGO_HOME") or Path.home() / ".cargo")
151
+
152
+
153
+ def rustup_home() -> Path:
154
+ return Path(os.environ.get("RUSTUP_HOME") or Path.home() / ".rustup")
155
+
156
+
157
+ def scrubbed_env(
158
+ tmpdir: str | Path | None = None, cargo_home_dir: str | Path | None = None
159
+ ) -> list[str]:
160
+ """`NAME=value` pairs of the environment the sandboxed cargo may see (no credentials).
161
+
162
+ `tmpdir` replaces TMPDIR so temp files land in the scratch dir, the only writable place;
163
+ `cargo_home_dir` replaces CARGO_HOME (see `private_cargo_home`)."""
164
+ env = {
165
+ k: v for k, v in os.environ.items() if _ENV_KEEP.fullmatch(k) and not _ENV_DROP.search(k)
166
+ }
167
+ if tmpdir is not None:
168
+ env["TMPDIR"] = str(tmpdir)
169
+ if cargo_home_dir is not None:
170
+ env["CARGO_HOME"] = str(cargo_home_dir)
171
+ return [f"{k}={v}" for k, v in env.items()]
172
+
173
+
174
+ def _sbpl(s: str | Path) -> str:
175
+ return '"' + os.path.realpath(s).replace("\\", "\\\\").replace('"', '\\"') + '"'
176
+
177
+
178
+ def _darwin_dirs() -> list[str]:
179
+ """The per-user cache dir the Apple toolchain shims (xcrun) use."""
180
+ try:
181
+ out = subprocess.run(
182
+ ["/usr/bin/getconf", "DARWIN_USER_CACHE_DIR"], capture_output=True, text=True, timeout=5
183
+ ).stdout.strip()
184
+ except OSError, subprocess.SubprocessError:
185
+ return []
186
+ return [out] if out else []
187
+
188
+
189
+ # What a compile needs to read, as narrowly as it can be listed: system libraries and linkers, the
190
+ # dynamic loader cache, the C toolchain (Command Line Tools / Xcode, Homebrew prefixes). Not the
191
+ # whole of /Library, /private/etc, /opt/homebrew or /private/var/db, which hold keychains, host
192
+ # configuration and credentials.
193
+ _SYSTEM_READ = (
194
+ "/usr", "/System", "/bin", "/sbin", "/dev",
195
+ "/Library/Developer", "/Library/Frameworks", "/Library/Apple",
196
+ "/private/var/db/dyld", "/private/var/db/timezone", "/private/var/db/xcode_select_link",
197
+ "/private/etc/ssl",
198
+ "/opt/homebrew/bin", "/opt/homebrew/sbin", "/opt/homebrew/lib", "/opt/homebrew/opt",
199
+ "/opt/homebrew/Cellar", "/opt/homebrew/include", "/opt/homebrew/share",
200
+ ) # fmt: skip
201
+ _XCODE_APPS = r"^/Applications/Xcode[^/]*\.app(/|$)"
202
+
203
+
204
+ @functools.lru_cache(maxsize=4)
205
+ def _sysroot(rustc: str) -> str | None:
206
+ try:
207
+ out = subprocess.run(
208
+ [rustc, "--print", "sysroot"], capture_output=True, text=True, timeout=30
209
+ ).stdout.strip()
210
+ except OSError, subprocess.SubprocessError:
211
+ return None
212
+ return out or None
213
+
214
+
215
+ def toolchain_dirs() -> list[Path]:
216
+ """Directories holding the Rust toolchain: rustup's `toolchains/` and the active rustc's sysroot
217
+ (which is elsewhere for a distro or Homebrew install)."""
218
+ dirs = [rustup_home() / "toolchains"]
219
+ if (rustc := shutil.which("rustc")) and (root := _sysroot(rustc)):
220
+ dirs.append(Path(root))
221
+ return dirs
222
+
223
+
224
+ def cargo_reads() -> list[Path]:
225
+ """What the sandbox may read of the real cargo home: downloaded sources (`registry/`, `git/`)
226
+ and the rustup proxies in `bin/`. Not `credentials.toml`, `config.toml`, tokens or the rest."""
227
+ home = cargo_home()
228
+ return [home / "registry", home / "git", home / "bin"]
229
+
230
+
231
+ _LOCK_FILES = (".package-cache", ".package-cache-mutate", ".global-cache")
232
+
233
+
234
+ def private_cargo_home() -> Path:
235
+ """The CARGO_HOME the sandboxed cargo sees: a small per-user directory (so no host
236
+ `config.toml` or `credentials.toml` is loaded) whose `registry` and `git` are links to the real,
237
+ read-only download caches, plus cargo's three lock/cache files (the only writable things in it).
238
+
239
+ The path is stable on purpose: cargo hashes the path of registry sources into its fingerprints,
240
+ so a fresh directory per run would recompile every dependency every time. Created and repaired
241
+ here, outside the sandbox, which cannot change the links."""
242
+ real = cargo_home()
243
+ root = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "python2rust"
244
+ home = root / "sandbox-cargo-home" / hashlib.sha256(str(real).encode()).hexdigest()[:12]
245
+ home.mkdir(parents=True, exist_ok=True)
246
+ for name in ("registry", "git"):
247
+ link = home / name
248
+ if link.is_symlink() and Path(os.readlink(link)) != real / name:
249
+ link.unlink()
250
+ if not link.is_symlink() and (real / name).is_dir():
251
+ link.symlink_to(real / name, target_is_directory=True)
252
+ for name in _LOCK_FILES:
253
+ (home / name).touch(exist_ok=True)
254
+ return home
255
+
256
+
257
+ def _read_files() -> list[Path]:
258
+ """Single files that are readable although their directory is not: the rustup proxy's
259
+ settings (which toolchain is the default)."""
260
+ return [rustup_home() / "settings.toml"]
261
+
262
+
263
+ def _write_files(home: Path) -> list[Path]:
264
+ return [home / name for name in _LOCK_FILES]
265
+
266
+
267
+ def darwin_profile(scratch: Path, allow_read: Iterable[Path], allow_write: Iterable[Path]) -> str:
268
+ """The sandbox-exec profile: everything allowed, then network, reads and writes taken away.
269
+
270
+ Later rules win in SBPL, so each `deny` is followed by the few `allow`s that restore access.
271
+ Metadata (stat) stays readable so path lookups work; file contents and directory listings do not.
272
+ """
273
+ home = private_cargo_home()
274
+ reads = [*_SYSTEM_READ, scratch, home, *cargo_reads(), *toolchain_dirs()]
275
+ reads += [*allow_read, *allow_write, *_darwin_dirs()]
276
+ writes = [scratch, *allow_write, *_darwin_dirs()]
277
+ lines = [
278
+ "(version 1)",
279
+ "(allow default)",
280
+ "(deny network*)",
281
+ '(deny file-read-data (subpath "/"))',
282
+ *(f"(allow file-read-data (subpath {_sbpl(p)}))" for p in reads),
283
+ f'(allow file-read-data (regex #"{_XCODE_APPS}"))',
284
+ *(f"(allow file-read-data (literal {_sbpl(p)}))" for p in _read_files()),
285
+ '(allow file-read-data (literal "/"))',
286
+ '(deny file-write* (subpath "/"))',
287
+ *(f"(allow file-write* (subpath {_sbpl(p)}))" for p in writes),
288
+ '(allow file-write* (subpath "/dev"))',
289
+ *(f"(allow file-write* (literal {_sbpl(p)}))" for p in _write_files(home)),
290
+ ]
291
+ return "\n".join(lines) + "\n"
292
+
293
+
294
+ def _bwrap_args(
295
+ scratch: Path, allow_read: Iterable[Path], allow_write: Iterable[Path], env: Iterable[str]
296
+ ) -> list[str]:
297
+ """bubblewrap arguments: no network, own pid/ipc/uts namespaces and session (no TIOCSTI into
298
+ the caller's terminal), an empty environment plus `env`, and read-only binds of only the
299
+ system libraries, the toolchain and the cargo download caches."""
300
+ args = ["--die-with-parent", "--new-session", "--unshare-net", "--unshare-pid"]
301
+ args += ["--unshare-ipc", "--unshare-uts", "--clearenv"]
302
+ for pair in env:
303
+ name, _, value = pair.partition("=")
304
+ args += ["--setenv", name, value]
305
+ for p in ("/usr", "/lib", "/lib64", "/bin", "/sbin", "/etc/alternatives", "/etc/ld.so.cache"):
306
+ args += ["--ro-bind-try", p, p]
307
+ args += ["--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp"]
308
+ home = private_cargo_home()
309
+ for p in (home, *cargo_reads(), *toolchain_dirs(), *_read_files(), *allow_read):
310
+ args += ["--ro-bind-try", str(p), str(p)]
311
+ for p in (scratch, *allow_write, *_write_files(home)):
312
+ args += ["--bind", str(p), str(p)]
313
+ # The namespace root and /tmp provide mount points, while the explicit child binds remain writable.
314
+ return [*args, "--remount-ro", "/tmp", "--remount-ro", "/", "--chdir", str(scratch)]
315
+
316
+
317
+ def wrap(
318
+ argv: list[str],
319
+ scratch: str | Path,
320
+ *,
321
+ allow_read: Iterable[str | Path] = (),
322
+ allow_write: Iterable[str | Path] = (),
323
+ tool: str | None = None,
324
+ ) -> list[str]:
325
+ """`argv` run inside the sandbox. `scratch` is the throwaway crate dir (read + write);
326
+ `allow_read` are extra read-only paths, `allow_write` extra writable ones (the target dir).
327
+ Raises RuntimeError when no sandbox tool exists (callers check `find()` first)."""
328
+ tool = tool or find()
329
+ if tool is None:
330
+ raise RuntimeError(MISSING)
331
+ scratch_p = Path(scratch)
332
+ read = [Path(p) for p in allow_read]
333
+ write = [Path(p) for p in allow_write]
334
+ tmpdir = scratch_p / ".tmp"
335
+ tmpdir.mkdir(parents=True, exist_ok=True)
336
+ env = scrubbed_env(tmpdir, private_cargo_home())
337
+ if sys.platform == "darwin":
338
+ return [
339
+ "/usr/bin/env",
340
+ "-i",
341
+ *env,
342
+ tool,
343
+ "-p",
344
+ darwin_profile(scratch_p, read, write),
345
+ *argv,
346
+ ]
347
+ # The rustup shim may initialize state even when the toolchain is already installed.
348
+ # Enter through that toolchain's real binaries, keeping rustup's host state read-only.
349
+ if (
350
+ Path(argv[0]).name == "cargo"
351
+ and (rustc := shutil.which("rustc"))
352
+ and (root := _sysroot(rustc))
353
+ ):
354
+ bin_dir = Path(root) / "bin"
355
+ cargo = bin_dir / "cargo"
356
+ if cargo.is_file():
357
+ argv = [str(cargo), *argv[1:]]
358
+ read.append(bin_dir.parent)
359
+ path = os.defpath
360
+ for entry in env:
361
+ if entry.startswith("PATH="):
362
+ path = entry.removeprefix("PATH=")
363
+ break
364
+ env = [entry for entry in env if not entry.startswith("PATH=")]
365
+ env.append(f"PATH={bin_dir}{os.pathsep}{path}")
366
+ # The tool executables can live outside the cargo home used for registry storage.
367
+ for name in (argv[0], "rustc", "rustdoc", "cargo-clippy", "clippy-driver"):
368
+ if executable := shutil.which(name):
369
+ read.append(Path(executable))
370
+ return ["/usr/bin/env", "-i", tool, *_bwrap_args(scratch_p, read, write, env), *argv]
@@ -0,0 +1,280 @@
1
+ """The `test` rung of `apply`: which translated tests may run while other TODOs are still open.
2
+
3
+ A module with two TODOs would make every single fix fail if all its tests ran: the second
4
+ `todo!()` panics inside whatever test reaches it. So each test is classified before the run, from
5
+ the Rust text alone (conservative: names, not types):
6
+
7
+ * **runs** and must pass: it reaches no open TODO;
8
+ * **skipped-todo**: it contains an open `todo!()` or mentions a function that (transitively) does.
9
+ It is listed in the verification document, counted neither as passed nor as failed;
10
+ * **out of scope**: it neither lives in the patched module nor reaches one of its functions.
11
+
12
+ A test that panics with a `todo!()` message anyway (the static reach missed it) is `skipped-todo`
13
+ too, never `failed`.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ from collections.abc import Iterable
20
+ from dataclasses import dataclass, field
21
+ from typing import Any
22
+
23
+ from python2rust.agent.patches import strip_noise
24
+ from python2rust.verify import check as chk
25
+ from python2rust.verify.check import CheckModule
26
+
27
+ _TOKEN = re.compile(r"\bmod\s+(?:r#)?(\w+)\s*\{|\bfn\s+(?:r#)?(\w+)|[{}()\[\];]")
28
+ _IDENT = re.compile(r"(?:r#)?([A-Za-z_]\w*)")
29
+ _STUB = re.compile(r"\b(?:todo|unimplemented)\s*!")
30
+ _TEST_ATTR = re.compile(r"#\s*\[\s*test\s*\](?:\s*#\s*\[[^\]]*\])*\s*(?:pub\s+)?(?:async\s+)?$")
31
+ _CFG_TEST = re.compile(r"#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\](?:\s*#\s*\[[^\]]*\])*\s*(?:pub\s+)?$")
32
+ _TODO_PANIC = re.compile(r"python2rust [0-9A-Za-z]+ PY2RS\d+")
33
+ _BLOCK = re.compile(r"^---- (\S+) stdout ----\n(.*?)(?=^---- |^failures:|\Z)", re.M | re.S)
34
+
35
+
36
+ @dataclass
37
+ class RustFn:
38
+ name: str
39
+ mods: tuple[str, ...]
40
+ start_line: int
41
+ end_line: int
42
+ idents: frozenset[str]
43
+ stub: bool # contains todo!() / unimplemented!() or an open core TODO
44
+ is_test: bool # a #[test] function
45
+ in_test_mod: bool # inside `#[cfg(test)] mod ...` or a module named `tests`
46
+
47
+ @property
48
+ def path(self) -> str:
49
+ return "::".join([*self.mods, self.name])
50
+
51
+
52
+ @dataclass
53
+ class Scan:
54
+ fns: list[RustFn] = field(default_factory=list)
55
+ test_spans: list[tuple[int, int]] = field(default_factory=list) # lines of test modules/fns
56
+
57
+
58
+ def scan_rust(rust: str, open_todo_lines: Iterable[int] = ()) -> Scan:
59
+ """Functions of `rust` with their module path, identifiers and test/stub flags."""
60
+ clean = strip_noise(rust)
61
+ todo_lines = sorted(open_todo_lines)
62
+ out = Scan()
63
+ # frames: ("mod", name, is_test_mod, start_off) | ("fn", name, body_start, fn_start) | ("other",)
64
+ stack: list[tuple[Any, ...]] = []
65
+ pending: tuple[str, int] | None = None
66
+ pdepth = 0
67
+
68
+ def line_of(off: int) -> int:
69
+ return clean.count("\n", 0, off) + 1
70
+
71
+ for m in _TOKEN.finditer(clean):
72
+ tok = m.group()
73
+ if m.group(1) is not None: # `mod name {`
74
+ before = clean[max(0, m.start() - 200) : m.start()]
75
+ before = re.sub(r"(?:pub(?:\([^)]*\))?\s+)$", "", before)
76
+ test_mod = bool(_CFG_TEST.search(before)) or m.group(1) == "tests"
77
+ stack.append(("mod", m.group(1), test_mod, m.start()))
78
+ elif m.group(2) is not None: # `fn name`
79
+ pending, pdepth = (m.group(2), m.start()), 0
80
+ elif tok in "([":
81
+ pdepth += pending is not None
82
+ elif tok in ")]":
83
+ pdepth -= pending is not None
84
+ elif tok == ";":
85
+ if pending is not None and pdepth <= 0:
86
+ pending = None
87
+ elif tok == "{":
88
+ if pending is not None and pdepth <= 0:
89
+ stack.append(("fn", pending[0], m.end(), pending[1]))
90
+ pending = None
91
+ else:
92
+ stack.append(("other",))
93
+ elif tok == "}" and stack:
94
+ frame = stack.pop()
95
+ if frame[0] == "mod" and frame[2]:
96
+ out.test_spans.append((line_of(frame[3]), line_of(m.start())))
97
+ elif frame[0] == "fn":
98
+ body = clean[frame[2] : m.start()]
99
+ start, end = line_of(frame[3]), line_of(m.start())
100
+ prefix = clean[max(0, frame[3] - 200) : frame[3]]
101
+ prefix = re.sub(r"(?:pub(?:\([^)]*\))?\s+)$", "", prefix)
102
+ is_test = bool(_TEST_ATTR.search(prefix))
103
+ in_test = any(f[0] == "mod" and f[2] for f in stack)
104
+ if is_test:
105
+ out.test_spans.append((start, end))
106
+ out.fns.append(
107
+ RustFn(
108
+ frame[1],
109
+ tuple(f[1] for f in stack if f[0] == "mod"),
110
+ start,
111
+ end,
112
+ frozenset(i.group(1) for i in _IDENT.finditer(body)),
113
+ bool(_STUB.search(body)) or any(start <= n <= end for n in todo_lines),
114
+ is_test,
115
+ in_test,
116
+ )
117
+ )
118
+ return out
119
+
120
+
121
+ def todo_in_tests(rust: str, rust_line: int) -> bool:
122
+ """The TODO's line is inside translated test code (a `#[test]` or a test module)."""
123
+ return any(a <= rust_line <= b for a, b in scan_rust(rust).test_spans)
124
+
125
+
126
+ def is_test_file(display: str) -> bool:
127
+ """A Python file that only holds tests (pytest/unittest naming)."""
128
+ name = display.replace("\\", "/").rsplit("/", 1)[-1]
129
+ return (
130
+ name == "conftest.py"
131
+ or (name.startswith("test_") and name.endswith(".py"))
132
+ or (name.endswith("_test.py"))
133
+ )
134
+
135
+
136
+ def _tainted(fns: list[RustFn]) -> set[str]:
137
+ """Names of functions that still contain an open TODO, directly or through what they call."""
138
+ tainted = {f.name for f in fns if f.stub}
139
+ grew = True
140
+ while grew:
141
+ grew = False
142
+ for f in fns:
143
+ if f.name not in tainted and f.idents & tainted:
144
+ tainted.add(f.name)
145
+ grew = True
146
+ return tainted
147
+
148
+
149
+ def _reaching(fns: list[RustFn], seeds: set[str]) -> set[str]:
150
+ """Names of functions that (transitively, by name) use one of `seeds`, seeds included."""
151
+ names = set(seeds)
152
+ grew = True
153
+ while grew:
154
+ grew = False
155
+ for f in fns:
156
+ if f.name not in names and f.idents & names:
157
+ names.add(f.name)
158
+ grew = True
159
+ return names
160
+
161
+
162
+ def _norm(path: str) -> str:
163
+ return path.replace("r#", "")
164
+
165
+
166
+ def _message(block: str) -> str:
167
+ lines = [ln.strip() for ln in block.splitlines() if ln.strip() and "RUST_BACKTRACE" not in ln]
168
+ return " | ".join(lines[:3])[:300]
169
+
170
+
171
+ def run_tests(
172
+ modules: list[CheckModule],
173
+ patched: int,
174
+ *,
175
+ deps_from: str | None = None,
176
+ offline: bool = False,
177
+ timeout: float = 300,
178
+ target_dir: str | None = None,
179
+ ) -> dict[str, Any]:
180
+ """Run the tests that must hold for the patched module `modules[patched]`.
181
+
182
+ Returns `{status, detail, passed, failed, skipped_todo, out_of_scope, scope}` where status is
183
+ `pass` (at least one test ran and none failed), `fail`, `unverified` (the run did not happen or
184
+ the tests do not compile) or `none` (nothing was left to run). Tests are reported by Rust path
185
+ and, when the translation knows it, by Python test id.
186
+ """
187
+ scans = [
188
+ scan_rust(m.rust, (t["rust_line"] for t in m.todos if t.get("state") != "patched"))
189
+ for m in modules
190
+ ]
191
+ every = [f for s in scans for f in s.fns]
192
+ tainted = _tainted(every)
193
+ own = {f.name for f in scans[patched].fns if not f.is_test and not f.in_test_mod}
194
+ uses_patched = _reaching([f for f in every if not f.is_test], own)
195
+ names = [chk.crate_module_name(modules, i) for i in range(len(modules))]
196
+ planned: list[dict[str, Any]] = []
197
+ for i, (m, scan) in enumerate(zip(modules, scans, strict=True)):
198
+ known = {e["rust_name"]: e for e in m.tests}
199
+ for f in scan.fns:
200
+ if not f.is_test:
201
+ continue
202
+ full = f"{names[i]}::{f.path}"
203
+ entry: dict[str, Any] = {
204
+ "test": full,
205
+ "py_id": (known.get(f.path) or {}).get("py_id"),
206
+ "file": m.name,
207
+ }
208
+ if f.stub or f.idents & tainted:
209
+ via = sorted(f.idents & tainted)[:3]
210
+ entry["why"] = (
211
+ "contains an open TODO"
212
+ if f.stub
213
+ else f"reaches an open TODO ({', '.join(via)})"
214
+ )
215
+ entry["state"] = "skipped-todo"
216
+ elif i != patched and not f.idents & uses_patched:
217
+ entry["state"] = "out-of-scope"
218
+ else:
219
+ entry["state"] = "run"
220
+ planned.append(entry)
221
+ doc: dict[str, Any] = {
222
+ "status": "none",
223
+ "detail": None,
224
+ "scope": [m.name for m in modules],
225
+ "passed": [],
226
+ "failed": [],
227
+ "skipped_todo": [
228
+ {k: v for k, v in p.items() if k != "state"}
229
+ for p in planned
230
+ if p["state"] == "skipped-todo"
231
+ ],
232
+ "out_of_scope": sum(p["state"] == "out-of-scope" for p in planned),
233
+ }
234
+ if not planned:
235
+ doc["detail"] = "no #[test] functions in the generated Rust"
236
+ return doc
237
+ skip = [p["test"] for p in planned if p["state"] != "run"]
238
+ args = ["--exact"] if skip else []
239
+ for name in skip:
240
+ args += ["--skip", name]
241
+ run = chk.run_cargo(
242
+ modules, "test", deps_from=deps_from, offline=offline, timeout=timeout,
243
+ target_dir=target_dir, test_args=args,
244
+ ) # fmt: skip
245
+ if run.status != "ran":
246
+ doc.update(status="unverified", detail=run.reason)
247
+ return doc
248
+ diags = chk.diagnostics_from(run.messages, modules, run.names)
249
+ if diags:
250
+ first = diags[0]
251
+ where = f"{first['rust_file']}:{first['rust_line']}"
252
+ doc.update(
253
+ status="unverified",
254
+ detail=f"the tests do not compile ({first['code'] or first['category']}: "
255
+ f"{first['message']} at {where})",
256
+ )
257
+ return doc
258
+ if failure := chk.cargo_failure(run, diags):
259
+ doc.update(status="unverified", detail=failure)
260
+ return doc
261
+ by_name = {_norm(p["test"]): p for p in planned}
262
+ blocks = {_norm(n): b for n, b in _BLOCK.findall(run.text)}
263
+ for path, outcome in chk.TEST_LINE.findall(run.text):
264
+ if outcome == "ignored":
265
+ continue
266
+ base = by_name.get(_norm(path), {"test": path, "py_id": None, "file": None})
267
+ item = {k: base[k] for k in ("test", "py_id", "file")}
268
+ block = blocks.get(_norm(path), "")
269
+ if outcome == "ok":
270
+ doc["passed"].append(item)
271
+ elif _TODO_PANIC.search(block):
272
+ doc["skipped_todo"].append({**item, "why": "panicked at an open todo!()"})
273
+ else:
274
+ doc["failed"].append({**item, "message": _message(block)})
275
+ p, f, s = len(doc["passed"]), len(doc["failed"]), len(doc["skipped_todo"])
276
+ doc["detail"] = f"{p} passed, {f} failed, {s} skipped (reach an open TODO)" + (
277
+ f", {doc['out_of_scope']} out of scope" if doc["out_of_scope"] else ""
278
+ )
279
+ doc["status"] = "fail" if f else ("pass" if p else "none")
280
+ return doc
File without changes