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,1135 @@
|
|
|
1
|
+
"""`check`: compile the generated Rust in a scratch crate and report errors by category.
|
|
2
|
+
|
|
3
|
+
The scratch crate is a throwaway workspace of its own, so it never touches the user's project.
|
|
4
|
+
Each translated file becomes one module (`m000`, `m001`, ...). rustc keeps going past a broken
|
|
5
|
+
module, so a single `cargo check` covers a whole corpus. The same scratch crate runs `cargo clippy`
|
|
6
|
+
and `cargo test` for `verify`.
|
|
7
|
+
|
|
8
|
+
Rust lines map to Python lines through the core's `source_map` (exact). Only when a module has no
|
|
9
|
+
source map does a regex/window heuristic run, and its results are labelled `mapped_by: "approximate"`.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import ast
|
|
15
|
+
import bisect
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import shutil
|
|
21
|
+
import subprocess
|
|
22
|
+
import tempfile
|
|
23
|
+
import tomllib
|
|
24
|
+
from collections import Counter
|
|
25
|
+
from collections.abc import Iterable, Sequence
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
from importlib import resources
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from python2rust.errors import UsageError
|
|
32
|
+
from python2rust.verify import sandbox as sandbox_mod
|
|
33
|
+
|
|
34
|
+
# rustc error code -> stable category name. Anything else is "other"; parse errors are "syntax".
|
|
35
|
+
CATEGORIES: dict[str, str] = {
|
|
36
|
+
"E0308": "type-mismatch",
|
|
37
|
+
"E0277": "trait-bound",
|
|
38
|
+
"E0599": "no-such-method",
|
|
39
|
+
"E0425": "unresolved-name",
|
|
40
|
+
"E0412": "unresolved-type",
|
|
41
|
+
"E0432": "unresolved-import",
|
|
42
|
+
"E0433": "unresolved-import",
|
|
43
|
+
"E0382": "use-after-move",
|
|
44
|
+
"E0499": "borrow",
|
|
45
|
+
"E0502": "borrow",
|
|
46
|
+
"E0505": "borrow",
|
|
47
|
+
"E0506": "borrow",
|
|
48
|
+
"E0507": "borrow",
|
|
49
|
+
"E0596": "mutability",
|
|
50
|
+
"E0384": "mutability",
|
|
51
|
+
"E0282": "type-annotations-needed",
|
|
52
|
+
"E0283": "type-annotations-needed",
|
|
53
|
+
"E0106": "lifetime",
|
|
54
|
+
"E0373": "lifetime",
|
|
55
|
+
"E0061": "wrong-arg-count",
|
|
56
|
+
"E0060": "wrong-arg-count",
|
|
57
|
+
"E0423": "unresolved-name",
|
|
58
|
+
"E0560": "no-such-field",
|
|
59
|
+
"E0609": "no-such-field",
|
|
60
|
+
"E0614": "type-mismatch",
|
|
61
|
+
"E0369": "trait-bound",
|
|
62
|
+
"E0728": "async",
|
|
63
|
+
"E0752": "async",
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
_ITEM = re.compile(
|
|
67
|
+
r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:(?:async|unsafe|const)\s+)*"
|
|
68
|
+
r"(?:fn|struct|enum|trait|static|type|const)\s+(\w+)"
|
|
69
|
+
r"|^\s*impl(?:<[^>]*>)?\s+(?:[\w:<>]+\s+for\s+)?(\w+)"
|
|
70
|
+
)
|
|
71
|
+
_TODO_WINDOW = (-1, 3) # rust lines around a todo!() that still count as "inside" it
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass
|
|
75
|
+
class CheckModule:
|
|
76
|
+
"""One Rust file to compile, with what is needed to map errors back to Python."""
|
|
77
|
+
|
|
78
|
+
name: str # the file's display name (Python path, or the .rs path)
|
|
79
|
+
rust: str
|
|
80
|
+
todos: list[dict[str, Any]] = field(default_factory=list)
|
|
81
|
+
python: str | None = None
|
|
82
|
+
# core source map: [{"rust_line", "py_file", "py_line", "py_end_line", "item"}]
|
|
83
|
+
source_map: list[dict[str, Any]] | None = None
|
|
84
|
+
# crates (version + features) the translation reported it needs, python2rust-rt included
|
|
85
|
+
required_crates: dict[str, Any] | None = None
|
|
86
|
+
# path below the crate's src/ in project mode ("shop/pricing.rs", "shop/mod.rs"); None: flat
|
|
87
|
+
rust_path: str | None = None
|
|
88
|
+
# translated tests of this file: [{"py_id", "rust_name", "status", ...}] (TranslateResult.tests)
|
|
89
|
+
tests: list[dict[str, Any]] = field(default_factory=list)
|
|
90
|
+
|
|
91
|
+
def __post_init__(self) -> None:
|
|
92
|
+
if self.source_map is not None:
|
|
93
|
+
self.source_map = sorted(self.source_map, key=lambda e: e["rust_line"])
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def categorize(code: str | None) -> str:
|
|
97
|
+
return "syntax" if code is None else CATEGORIES.get(code, "other")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _toml_value(v: Any) -> str:
|
|
101
|
+
if isinstance(v, bool):
|
|
102
|
+
return "true" if v else "false"
|
|
103
|
+
if isinstance(v, str | int | float):
|
|
104
|
+
return json.dumps(v)
|
|
105
|
+
if isinstance(v, list):
|
|
106
|
+
return "[" + ", ".join(_toml_value(x) for x in v) + "]"
|
|
107
|
+
if isinstance(v, dict):
|
|
108
|
+
return "{ " + ", ".join(f"{_toml_key(k)} = {_toml_value(x)}" for k, x in v.items()) + " }"
|
|
109
|
+
raise UsageError(f"cannot write a value of type {type(v).__name__} to Cargo.toml")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _toml_key(k: str) -> str:
|
|
113
|
+
return k if re.fullmatch(r"[A-Za-z0-9_-]+", k) else json.dumps(k)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# Crates a dependency table may name without --allow-unvetted-deps, besides the ones the translation
|
|
117
|
+
# itself reports (CheckModule.required_crates) and the ones listed under `[deps] allow` of
|
|
118
|
+
# python2rust.toml. Registry crates run build scripts and proc-macros when compiled, so the
|
|
119
|
+
# default is a short list of widely used, audited crates rather than "anything on crates.io".
|
|
120
|
+
VETTED_CRATES = frozenset(
|
|
121
|
+
{
|
|
122
|
+
"serde", "serde_json", "indexmap", "chrono", "uuid", "utoipa", "tokio", "tracing", "regex",
|
|
123
|
+
"sha2", "md-5", "base64", "thiserror", "anyhow", "once_cell", "itertools", "smallvec",
|
|
124
|
+
"rand", "async-trait", "futures", "axum", "hyper", "reqwest", "sqlx", "python2rust-rt",
|
|
125
|
+
}
|
|
126
|
+
) # fmt: skip
|
|
127
|
+
ALLOW_UNVETTED_DEFAULT: bool = (
|
|
128
|
+
False # the CLI sets it from --allow-unvetted-deps (module-wide opt-in)
|
|
129
|
+
)
|
|
130
|
+
_OPT_IN = "pass --allow-unvetted-deps to accept it, or list the crate under [deps] allow in python2rust.toml"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def configured_deps_allow(base: str | Path) -> set[str]:
|
|
134
|
+
"""`[deps] allow = [...]` of `<base>/python2rust.toml` (the project config; none: empty)."""
|
|
135
|
+
path = Path(base) / "python2rust.toml"
|
|
136
|
+
if not path.is_file():
|
|
137
|
+
return set()
|
|
138
|
+
try:
|
|
139
|
+
allow = tomllib.loads(path.read_text(encoding="utf-8")).get("deps", {}).get("allow", [])
|
|
140
|
+
except (OSError, tomllib.TOMLDecodeError) as exc:
|
|
141
|
+
raise UsageError(f"cannot read {path}: {exc}") from exc
|
|
142
|
+
if not isinstance(allow, list) or not all(isinstance(a, str) for a in allow):
|
|
143
|
+
raise UsageError(f"[deps] allow in {path} must be a list of crate names")
|
|
144
|
+
return set(allow)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@dataclass
|
|
148
|
+
class _Vet:
|
|
149
|
+
allowed: set[str]
|
|
150
|
+
root: Path | None
|
|
151
|
+
allow_build_scripts: bool
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _vet_manifest_tables(data: dict[str, Any], where: str, relaxed: bool) -> None:
|
|
155
|
+
"""Tables that make cargo run or fetch code the dependency list does not show."""
|
|
156
|
+
for key in ("patch", "replace"):
|
|
157
|
+
if data.get(key):
|
|
158
|
+
raise UsageError(f"{where}: [{key}] redirects crates to other sources; {_OPT_IN}")
|
|
159
|
+
if relaxed:
|
|
160
|
+
return
|
|
161
|
+
if build := data.get("build-dependencies") or data.get("build_dependencies"):
|
|
162
|
+
raise UsageError(
|
|
163
|
+
f"{where}: [build-dependencies] ({', '.join(build)}) run on this machine; {_OPT_IN}"
|
|
164
|
+
)
|
|
165
|
+
for cfg, table in (data.get("target") or {}).items():
|
|
166
|
+
for kind in ("dependencies", "build-dependencies"):
|
|
167
|
+
if isinstance(table, dict) and table.get(kind):
|
|
168
|
+
raise UsageError(
|
|
169
|
+
f"{where}: [target.{cfg}.{kind}] ({', '.join(table[kind])}) is not vetted; {_OPT_IN}"
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _vet_table(table: dict[str, Any], where: str, vet: _Vet, base: Path, depth: int) -> None:
|
|
174
|
+
for name, spec in table.items():
|
|
175
|
+
if isinstance(spec, dict):
|
|
176
|
+
if "git" in spec:
|
|
177
|
+
raise UsageError(f"dependency {name!r} ({where}) is a git dependency; {_OPT_IN}")
|
|
178
|
+
if "registry" in spec or "registry-index" in spec:
|
|
179
|
+
raise UsageError(
|
|
180
|
+
f"dependency {name!r} ({where}) comes from an alternate registry; {_OPT_IN}"
|
|
181
|
+
)
|
|
182
|
+
if "path" in spec:
|
|
183
|
+
_vet_path_dependency(base / str(spec["path"]), vet, depth + 1)
|
|
184
|
+
continue
|
|
185
|
+
package = str(spec.get("package", name)) if isinstance(spec, dict) else name
|
|
186
|
+
if package not in vet.allowed:
|
|
187
|
+
raise UsageError(
|
|
188
|
+
f"dependency {package!r} ({where}) is not on the allow-list of vetted crates; {_OPT_IN}"
|
|
189
|
+
)
|
|
190
|
+
version = spec.get("version") if isinstance(spec, dict) else spec
|
|
191
|
+
if not isinstance(version, str) or version.strip() in ("", "*"):
|
|
192
|
+
# a registry crate without a version requirement resolves to whatever is newest
|
|
193
|
+
raise UsageError(
|
|
194
|
+
f"dependency {package!r} ({where}) has no pinned version requirement "
|
|
195
|
+
f'(`version = "1"` or tighter); {_OPT_IN}'
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _vet_path_dependency(crate: Path, vet: _Vet, depth: int = 0) -> None:
|
|
200
|
+
"""A path dependency: below the confinement root (MCP), no build script and not a proc-macro
|
|
201
|
+
unless allowed, no hidden dependency tables, and its own dependencies vetted the same way.
|
|
202
|
+
Cargo executes build scripts and proc-macros on the host, so an unvetted one is code execution."""
|
|
203
|
+
crate = crate.resolve()
|
|
204
|
+
if vet.root is not None and not crate.is_relative_to(vet.root):
|
|
205
|
+
raise UsageError(f"path dependency {crate} is outside the allowed root {vet.root}")
|
|
206
|
+
try:
|
|
207
|
+
data = tomllib.loads((crate / "Cargo.toml").read_text(encoding="utf-8"))
|
|
208
|
+
except (OSError, tomllib.TOMLDecodeError) as exc:
|
|
209
|
+
raise UsageError(f"cannot read the manifest of path dependency {crate}: {exc}") from exc
|
|
210
|
+
lib = data.get("lib", {})
|
|
211
|
+
proc_macro = lib.get("proc-macro") is True or lib.get("proc_macro") is True
|
|
212
|
+
builds = (crate / "build.rs").exists() or data.get("package", {}).get("build") not in (
|
|
213
|
+
None,
|
|
214
|
+
False,
|
|
215
|
+
)
|
|
216
|
+
# a proc-macro runs on the host at compile time: only a registry crate on the allow-list is
|
|
217
|
+
# accepted, never one that merely lives at a path, whatever its name (`async-trait` at a path
|
|
218
|
+
# is not async-trait)
|
|
219
|
+
if (builds or proc_macro) and not vet.allow_build_scripts:
|
|
220
|
+
raise UsageError(
|
|
221
|
+
f"path dependency {crate.name} has a build script or is a proc-macro: cargo would run "
|
|
222
|
+
f"code on this machine. Only registry proc-macros of vetted crates are accepted, never a "
|
|
223
|
+
f"path crate, whatever its name; --allow-build-scripts permits this one, or "
|
|
224
|
+
f"--allow-unvetted-deps"
|
|
225
|
+
)
|
|
226
|
+
_vet_manifest_tables(data, f"path dependency {crate.name}", vet.allow_build_scripts)
|
|
227
|
+
if depth < 5:
|
|
228
|
+
_vet_table(
|
|
229
|
+
data.get("dependencies") or {}, f"path dependency {crate.name}", vet, crate, depth
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def read_dependencies(
|
|
234
|
+
cargo_toml: str,
|
|
235
|
+
*,
|
|
236
|
+
root: str | Path | None = None,
|
|
237
|
+
allow_build_scripts: bool = False,
|
|
238
|
+
allow_unvetted_deps: bool | None = None,
|
|
239
|
+
extra_allowed: Iterable[str] = (),
|
|
240
|
+
) -> dict[str, Any]:
|
|
241
|
+
"""Return the `[dependencies]` table of a Cargo.toml (or `[workspace.dependencies]` for a root).
|
|
242
|
+
|
|
243
|
+
`workspace = true` entries are resolved against the workspace table, and relative `path`
|
|
244
|
+
dependencies are made absolute so they still resolve from the scratch crate. The table comes
|
|
245
|
+
from a file this tool did not write, so it is vetted unless `allow_unvetted_deps` (default: the
|
|
246
|
+
CLI's `--allow-unvetted-deps`): registry crates must be on the allow-list (`VETTED_CRATES`, the
|
|
247
|
+
crates the translation reports in `extra_allowed`, `[deps] allow` of python2rust.toml in `root`
|
|
248
|
+
or the working directory); git dependencies, alternate registries, `[build-dependencies]`,
|
|
249
|
+
`[target.*.dependencies]`, `[patch]`/`[replace]`, and path dependencies with a build script or
|
|
250
|
+
that are proc-macros (unless `allow_build_scripts`) are refused, naming the crate. With `root`
|
|
251
|
+
(confined mode, used by the MCP server) path dependencies must also live below `root`.
|
|
252
|
+
"""
|
|
253
|
+
path = Path(cargo_toml)
|
|
254
|
+
try:
|
|
255
|
+
data = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
256
|
+
except FileNotFoundError:
|
|
257
|
+
raise UsageError(f"--deps-from file does not exist: {cargo_toml}") from None
|
|
258
|
+
except (OSError, tomllib.TOMLDecodeError) as exc:
|
|
259
|
+
raise UsageError(f"cannot read {cargo_toml}: {exc}") from exc
|
|
260
|
+
ws = data.get("workspace", {}).get("dependencies", {})
|
|
261
|
+
deps = dict(data.get("dependencies") or ws)
|
|
262
|
+
for name, spec in list(deps.items()):
|
|
263
|
+
if isinstance(spec, dict) and spec.get("workspace"):
|
|
264
|
+
base = ws.get(name)
|
|
265
|
+
if base is None:
|
|
266
|
+
raise UsageError(f"{name} uses workspace = true but {cargo_toml} has no such entry")
|
|
267
|
+
base = {"version": base} if isinstance(base, str) else dict(base)
|
|
268
|
+
extra = {k: v for k, v in spec.items() if k != "workspace"}
|
|
269
|
+
feats = [*base.get("features", []), *extra.pop("features", [])]
|
|
270
|
+
spec = {**base, **extra, **({"features": feats} if feats else {})}
|
|
271
|
+
if isinstance(spec, dict) and "path" in spec and not os.path.isabs(str(spec["path"])):
|
|
272
|
+
spec = {**spec, "path": str((path.parent / str(spec["path"])).resolve())}
|
|
273
|
+
deps[name] = spec
|
|
274
|
+
if allow_unvetted_deps is None:
|
|
275
|
+
allow_unvetted_deps = ALLOW_UNVETTED_DEFAULT
|
|
276
|
+
if root is not None:
|
|
277
|
+
for spec in deps.values(): # confinement is not an "unvetted" matter: it always applies
|
|
278
|
+
if isinstance(spec, dict) and "path" in spec:
|
|
279
|
+
resolved = Path(str(spec["path"])).resolve()
|
|
280
|
+
if not resolved.is_relative_to(Path(root).resolve()):
|
|
281
|
+
raise UsageError(
|
|
282
|
+
f"path dependency {resolved} is outside the allowed root {Path(root).resolve()}"
|
|
283
|
+
)
|
|
284
|
+
if not allow_unvetted_deps:
|
|
285
|
+
resolved_root = Path(root).resolve() if root is not None else None
|
|
286
|
+
vet = _Vet(
|
|
287
|
+
{*VETTED_CRATES, *extra_allowed, *configured_deps_allow(resolved_root or Path.cwd())},
|
|
288
|
+
resolved_root,
|
|
289
|
+
allow_build_scripts,
|
|
290
|
+
)
|
|
291
|
+
_vet_manifest_tables(data, str(cargo_toml), relaxed=False)
|
|
292
|
+
_vet_table(deps, str(cargo_toml), vet, path.parent, 0)
|
|
293
|
+
return deps
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
RUST_KEYWORDS = frozenset(
|
|
297
|
+
[
|
|
298
|
+
"as",
|
|
299
|
+
"async",
|
|
300
|
+
"await",
|
|
301
|
+
"break",
|
|
302
|
+
"const",
|
|
303
|
+
"continue",
|
|
304
|
+
"else",
|
|
305
|
+
"enum",
|
|
306
|
+
"extern",
|
|
307
|
+
"false",
|
|
308
|
+
"fn",
|
|
309
|
+
"for",
|
|
310
|
+
"if",
|
|
311
|
+
"impl",
|
|
312
|
+
"in",
|
|
313
|
+
"let",
|
|
314
|
+
"loop",
|
|
315
|
+
"match",
|
|
316
|
+
"mod",
|
|
317
|
+
"move",
|
|
318
|
+
"mut",
|
|
319
|
+
"pub",
|
|
320
|
+
"ref",
|
|
321
|
+
"return",
|
|
322
|
+
"static",
|
|
323
|
+
"struct",
|
|
324
|
+
"trait",
|
|
325
|
+
"true",
|
|
326
|
+
"type",
|
|
327
|
+
"unsafe",
|
|
328
|
+
"use",
|
|
329
|
+
"where",
|
|
330
|
+
"while",
|
|
331
|
+
"dyn",
|
|
332
|
+
"abstract",
|
|
333
|
+
"become",
|
|
334
|
+
"box",
|
|
335
|
+
"do",
|
|
336
|
+
"final",
|
|
337
|
+
"macro",
|
|
338
|
+
"override",
|
|
339
|
+
"priv",
|
|
340
|
+
"typeof",
|
|
341
|
+
"unsized",
|
|
342
|
+
"virtual",
|
|
343
|
+
"yield",
|
|
344
|
+
"try",
|
|
345
|
+
"gen",
|
|
346
|
+
]
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def rust_ident(name: str) -> str:
|
|
351
|
+
"""A module name as Rust code must spell it (`dyn` -> `r#dyn`; the file stays `dyn.rs`)."""
|
|
352
|
+
return f"r#{name}" if name in RUST_KEYWORDS else name
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
LIB_ALLOW = "#![allow(unused, dead_code, unreachable_code, non_snake_case, non_camel_case_types)]"
|
|
356
|
+
TREE_MARKER = "// python2rust: generated module tree (do not edit)"
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def module_tree(rel_paths: list[str]) -> tuple[str, dict[str, str]]:
|
|
360
|
+
"""`lib.rs` text and the `pub mod` footers of package `mod.rs` files for a project layout.
|
|
361
|
+
|
|
362
|
+
`pkg/__init__.py` is `pkg/mod.rs`; a directory without a `mod.rs` becomes an inline module in
|
|
363
|
+
`lib.rs` (or in its parent), so every path in `rel_paths` is reachable from the crate root.
|
|
364
|
+
"""
|
|
365
|
+
rels = set(rel_paths)
|
|
366
|
+
footers: dict[str, list[str]] = {}
|
|
367
|
+
for rel in rels:
|
|
368
|
+
p = Path(rel)
|
|
369
|
+
mod_dir, name = (
|
|
370
|
+
(p.parent.parent, p.parent.name) if p.name == "mod.rs" else (p.parent, p.stem)
|
|
371
|
+
)
|
|
372
|
+
if mod_dir == Path("."):
|
|
373
|
+
continue
|
|
374
|
+
host = (mod_dir / "mod.rs").as_posix()
|
|
375
|
+
if host in rels:
|
|
376
|
+
footers.setdefault(host, []).append(f"pub mod {rust_ident(name)};")
|
|
377
|
+
tree: dict[str, Any] = {}
|
|
378
|
+
for rel in sorted(rels):
|
|
379
|
+
node = tree
|
|
380
|
+
for d in Path(rel).parts[:-1]:
|
|
381
|
+
node = node.setdefault(d, {})
|
|
382
|
+
node[Path(rel).parts[-1]] = None
|
|
383
|
+
|
|
384
|
+
def emit(node: dict[str, Any], depth: int) -> list[str]:
|
|
385
|
+
pad = " " * depth
|
|
386
|
+
out: list[str] = []
|
|
387
|
+
for name, child in sorted(node.items()):
|
|
388
|
+
if child is None:
|
|
389
|
+
if name not in ("mod.rs", "lib.rs"):
|
|
390
|
+
out.append(f"{pad}pub mod {rust_ident(Path(name).stem)};")
|
|
391
|
+
elif "mod.rs" in child:
|
|
392
|
+
out.append(f"{pad}pub mod {rust_ident(name)};")
|
|
393
|
+
else:
|
|
394
|
+
out += [f"{pad}pub mod {rust_ident(name)} {{", *emit(child, depth + 1), f"{pad}}}"]
|
|
395
|
+
return out
|
|
396
|
+
|
|
397
|
+
lib = "\n".join([TREE_MARKER, LIB_ALLOW, *emit(tree, 0)]) + "\n"
|
|
398
|
+
return lib, {k: "\n" + "\n".join(sorted(v)) + "\n" for k, v in footers.items()}
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def layout_mode(modules: list[CheckModule]) -> bool:
|
|
402
|
+
"""True when every module knows its place in the crate (project mode)."""
|
|
403
|
+
return bool(modules) and all(m.rust_path for m in modules)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def rust_module_path(rust_path: str) -> str:
|
|
407
|
+
"""`shop/pricing.rs` -> `shop::pricing`, `shop/mod.rs` -> `shop`."""
|
|
408
|
+
parts = rust_path.removesuffix(".rs").split("/")
|
|
409
|
+
if parts[-1] == "mod":
|
|
410
|
+
parts.pop()
|
|
411
|
+
return "::".join(rust_ident(p) for p in parts)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def crate_module_name(modules: list[CheckModule], i: int) -> str:
|
|
415
|
+
"""How Rust code in the scratch crate names module `i`: `m000`, or its path in project mode."""
|
|
416
|
+
rust_path = modules[i].rust_path
|
|
417
|
+
return rust_module_path(rust_path) if layout_mode(modules) and rust_path else f"m{i:03d}"
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def write_scratch_crate(root: Path, modules: list[CheckModule], deps: dict[str, Any]) -> list[str]:
|
|
421
|
+
"""Create the scratch crate under `root`; returns the module names in order."""
|
|
422
|
+
(root / "src").mkdir(parents=True)
|
|
423
|
+
dep_lines = [f"{_toml_key(k)} = {_toml_value(v)}" for k, v in sorted(deps.items())]
|
|
424
|
+
manifest = [
|
|
425
|
+
"[package]",
|
|
426
|
+
'name = "python2rust_check"',
|
|
427
|
+
'version = "0.0.0"',
|
|
428
|
+
'edition = "2024"',
|
|
429
|
+
"publish = false",
|
|
430
|
+
"",
|
|
431
|
+
"[workspace]",
|
|
432
|
+
"",
|
|
433
|
+
"[dependencies]",
|
|
434
|
+
*dep_lines,
|
|
435
|
+
"",
|
|
436
|
+
]
|
|
437
|
+
(root / "Cargo.toml").write_text("\n".join(manifest), encoding="utf-8")
|
|
438
|
+
if layout_mode(modules): # project mode: the files sit where `use crate::a::b` expects them
|
|
439
|
+
paths = [str(m.rust_path) for m in modules]
|
|
440
|
+
lib, footers = module_tree(paths)
|
|
441
|
+
(root / "src" / "lib.rs").write_text(lib, encoding="utf-8")
|
|
442
|
+
for rel, m in zip(paths, modules, strict=True):
|
|
443
|
+
dest = root / "src" / rel
|
|
444
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
445
|
+
dest.write_text(m.rust.rstrip("\n") + "\n" + footers.get(rel, ""), encoding="utf-8")
|
|
446
|
+
return [p.removesuffix(".rs") for p in paths]
|
|
447
|
+
names = [f"m{i:03d}" for i in range(len(modules))]
|
|
448
|
+
lib = [LIB_ALLOW]
|
|
449
|
+
lib += [f"pub mod {n};" for n in names]
|
|
450
|
+
(root / "src" / "lib.rs").write_text("\n".join(lib) + "\n", encoding="utf-8")
|
|
451
|
+
for n, m in zip(names, modules, strict=True):
|
|
452
|
+
(root / "src" / f"{n}.rs").write_text(m.rust, encoding="utf-8")
|
|
453
|
+
return names
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def _python_defs(source: str | None) -> dict[str, int]:
|
|
457
|
+
if not source:
|
|
458
|
+
return {}
|
|
459
|
+
try:
|
|
460
|
+
tree = ast.parse(source)
|
|
461
|
+
except SyntaxError:
|
|
462
|
+
return {}
|
|
463
|
+
defs: dict[str, int] = {}
|
|
464
|
+
for node in ast.walk(tree):
|
|
465
|
+
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
|
|
466
|
+
defs.setdefault(node.name, node.lineno)
|
|
467
|
+
return defs
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def map_line(source_map: list[dict[str, Any]], rust_line: int) -> dict[str, Any] | None:
|
|
471
|
+
"""The source-map entry covering `rust_line`: the one with the largest rust_line <= it."""
|
|
472
|
+
keys = [e["rust_line"] for e in source_map]
|
|
473
|
+
i = bisect.bisect_right(keys, rust_line) - 1
|
|
474
|
+
return source_map[i] if i >= 0 else None
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def locate(module: CheckModule, rust_line: int, defs: dict[str, int]) -> dict[str, Any]:
|
|
478
|
+
"""Map a Rust line to Python: exactly via the source map, else approximately (labelled)."""
|
|
479
|
+
todo_id = next((t["id"] for t in module.todos if t["rust_line"] == rust_line), None)
|
|
480
|
+
if module.source_map:
|
|
481
|
+
if e := map_line(module.source_map, rust_line):
|
|
482
|
+
return {
|
|
483
|
+
"python_line": e["py_line"],
|
|
484
|
+
"mapped_by": "source_map",
|
|
485
|
+
"item": e.get("item"),
|
|
486
|
+
"todo_id": todo_id,
|
|
487
|
+
}
|
|
488
|
+
return {"python_line": None, "mapped_by": None, "item": None, "todo_id": todo_id}
|
|
489
|
+
lo, hi = _TODO_WINDOW
|
|
490
|
+
for t in module.todos:
|
|
491
|
+
if t["rust_line"] + lo <= rust_line <= t["rust_line"] + hi:
|
|
492
|
+
return {
|
|
493
|
+
"python_line": t["line"],
|
|
494
|
+
"mapped_by": "approximate",
|
|
495
|
+
"item": None,
|
|
496
|
+
"todo_id": t["id"],
|
|
497
|
+
}
|
|
498
|
+
lines = module.rust.splitlines()
|
|
499
|
+
for i in range(min(rust_line, len(lines)) - 1, -1, -1):
|
|
500
|
+
m = _ITEM.match(lines[i])
|
|
501
|
+
if m and (name := m.group(1) or m.group(2)) in defs:
|
|
502
|
+
return {
|
|
503
|
+
"python_line": defs[name],
|
|
504
|
+
"mapped_by": "approximate",
|
|
505
|
+
"item": name,
|
|
506
|
+
"todo_id": todo_id,
|
|
507
|
+
}
|
|
508
|
+
return {"python_line": None, "mapped_by": None, "item": None, "todo_id": todo_id}
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def _suggestions(d: dict[str, Any]) -> list[dict[str, Any]]:
|
|
512
|
+
out = []
|
|
513
|
+
for node in (d, *d.get("children", [])):
|
|
514
|
+
for sp in node.get("spans", []):
|
|
515
|
+
if sp.get("suggested_replacement") is not None:
|
|
516
|
+
out.append(
|
|
517
|
+
{
|
|
518
|
+
"byte_start": sp["byte_start"],
|
|
519
|
+
"byte_end": sp["byte_end"],
|
|
520
|
+
"replacement": sp["suggested_replacement"],
|
|
521
|
+
"applicability": sp.get("suggestion_applicability"),
|
|
522
|
+
"code": (d.get("code") or {}).get("code"),
|
|
523
|
+
}
|
|
524
|
+
)
|
|
525
|
+
return out
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def diagnostics_from(
|
|
529
|
+
messages: list[dict[str, Any]],
|
|
530
|
+
modules: list[CheckModule],
|
|
531
|
+
names: list[str],
|
|
532
|
+
*,
|
|
533
|
+
levels: tuple[str, ...] = ("error",),
|
|
534
|
+
suggestions: bool = False,
|
|
535
|
+
) -> list[dict[str, Any]]:
|
|
536
|
+
"""Turn rustc/clippy `compiler-message`s into diagnostics with category and Python line.
|
|
537
|
+
|
|
538
|
+
With `suggestions`, each diagnostic also lists the compiler's own suggested edits (byte spans in
|
|
539
|
+
the module file plus applicability), the raw material of the deterministic autofixer.
|
|
540
|
+
"""
|
|
541
|
+
by_file = {f"src/{n}.rs": (n, m) for n, m in zip(names, modules, strict=True)}
|
|
542
|
+
defs = {n: _python_defs(m.python) for n, m in zip(names, modules, strict=True)}
|
|
543
|
+
out: list[dict[str, Any]] = []
|
|
544
|
+
for msg in messages:
|
|
545
|
+
d = msg["message"]
|
|
546
|
+
level = "error" if str(d.get("level", "")).startswith("error") else d.get("level")
|
|
547
|
+
if level not in levels:
|
|
548
|
+
continue
|
|
549
|
+
if d["message"].startswith(("aborting due to", "could not compile")) or (
|
|
550
|
+
level == "warning" and "generated" in d["message"] and "warning" in d["message"]
|
|
551
|
+
):
|
|
552
|
+
continue
|
|
553
|
+
code = (d.get("code") or {}).get("code")
|
|
554
|
+
span = next((s for s in d.get("spans", []) if s.get("is_primary")), None)
|
|
555
|
+
mod_name, module = by_file.get(span["file_name"] if span else "", (None, None))
|
|
556
|
+
where: dict[str, Any] = {
|
|
557
|
+
"python_line": None,
|
|
558
|
+
"mapped_by": None,
|
|
559
|
+
"item": None,
|
|
560
|
+
"todo_id": None,
|
|
561
|
+
}
|
|
562
|
+
if module and span and mod_name:
|
|
563
|
+
where = locate(module, span["line_start"], defs[mod_name])
|
|
564
|
+
out.append(
|
|
565
|
+
{
|
|
566
|
+
"file": module.name if module else None,
|
|
567
|
+
"rust_file": span["file_name"] if span else None,
|
|
568
|
+
"rust_line": span["line_start"] if span else None,
|
|
569
|
+
"rust_col": span["column_start"] if span else None,
|
|
570
|
+
"level": level,
|
|
571
|
+
"code": code,
|
|
572
|
+
"category": categorize(code) if level == "error" else "lint",
|
|
573
|
+
"message": d["message"],
|
|
574
|
+
**where,
|
|
575
|
+
**({"suggestions": _suggestions(d)} if suggestions else {}),
|
|
576
|
+
}
|
|
577
|
+
)
|
|
578
|
+
out.sort(
|
|
579
|
+
key=lambda e: (e["file"] or "", e["rust_line"] or 0, e["rust_col"] or 0, e["code"] or "")
|
|
580
|
+
)
|
|
581
|
+
return out
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
class ToolError(Exception):
|
|
585
|
+
"""A tool that exists on PATH could not be run (timeout, OS error); not the same as missing."""
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def tool_version(tool: str) -> str | None:
|
|
589
|
+
"""The tool's `--version`; None only when the binary is not on PATH. Raises ToolError otherwise."""
|
|
590
|
+
exe = shutil.which(tool)
|
|
591
|
+
if exe is None:
|
|
592
|
+
return None
|
|
593
|
+
try:
|
|
594
|
+
out = subprocess.run([exe, "--version"], capture_output=True, text=True, timeout=20)
|
|
595
|
+
except subprocess.TimeoutExpired:
|
|
596
|
+
raise ToolError(f"{tool} --version timed out after 20s") from None
|
|
597
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
598
|
+
raise ToolError(f"{tool} could not be run: {exc}") from exc
|
|
599
|
+
return out.stdout.strip() or None
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def clippy_version() -> str | None:
|
|
603
|
+
"""`cargo clippy --version`; None when clippy is not installed. Raises ToolError on a failure to run."""
|
|
604
|
+
cargo = shutil.which("cargo")
|
|
605
|
+
if cargo is None:
|
|
606
|
+
return None
|
|
607
|
+
try:
|
|
608
|
+
out = subprocess.run(
|
|
609
|
+
[cargo, "clippy", "--version"], capture_output=True, text=True, timeout=30
|
|
610
|
+
)
|
|
611
|
+
except subprocess.TimeoutExpired:
|
|
612
|
+
raise ToolError("cargo clippy --version timed out after 30s") from None
|
|
613
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
614
|
+
raise ToolError(f"cargo clippy could not be run: {exc}") from exc
|
|
615
|
+
return out.stdout.strip() if out.returncode == 0 and out.stdout.strip() else None
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
TARGET_DIR_ENV = "PYTHON2RUST_TARGET_DIR"
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
def _cache_root() -> Path:
|
|
622
|
+
return Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "python2rust"
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def _cache_dir(deps: dict[str, Any] | None = None, sandboxed: bool = False) -> Path:
|
|
626
|
+
"""The cargo target dir: PYTHON2RUST_TARGET_DIR, else one per dependency table.
|
|
627
|
+
|
|
628
|
+
Keeping tables apart avoids rebuilding everything when the dependency set changes and avoids
|
|
629
|
+
two different tables fighting over one build directory lock; the same table reuses its build.
|
|
630
|
+
Sandboxed runs get their own (`-sandbox` suffix): the compile there is hostile code that can
|
|
631
|
+
write the dir, so an unsandboxed cargo must never reuse what it left behind, and the sandbox's
|
|
632
|
+
private cargo home gives registry sources another path, which cargo fingerprints.
|
|
633
|
+
"""
|
|
634
|
+
suffix = "-sandbox" if sandboxed else ""
|
|
635
|
+
if override := os.environ.get(TARGET_DIR_ENV):
|
|
636
|
+
return Path(override + suffix)
|
|
637
|
+
key = hashlib.sha256(json.dumps(deps or {}, sort_keys=True, default=str).encode()).hexdigest()[
|
|
638
|
+
:12
|
|
639
|
+
]
|
|
640
|
+
return _cache_root() / "check-target" / (key + suffix)
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
@dataclass
|
|
644
|
+
class CargoRun:
|
|
645
|
+
"""Raw outcome of one cargo invocation in the scratch crate."""
|
|
646
|
+
|
|
647
|
+
status: str # "ran" | "skipped" | "failed"
|
|
648
|
+
reason: str | None = None
|
|
649
|
+
version: str | None = None
|
|
650
|
+
available: bool = False
|
|
651
|
+
returncode: int | None = None
|
|
652
|
+
messages: list[dict[str, Any]] = field(default_factory=list) # compiler-message records
|
|
653
|
+
executables: list[str] = field(default_factory=list)
|
|
654
|
+
text: str = "" # non-JSON stdout (test output)
|
|
655
|
+
stderr: str = ""
|
|
656
|
+
names: list[str] = field(default_factory=list)
|
|
657
|
+
scratch_dir: str | None = None
|
|
658
|
+
deps_source: str = "none" # custom (--deps-from) | default | none (std only)
|
|
659
|
+
notes: list[str] = field(default_factory=list)
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
NO_DEFAULT_DEPS_ENV = "PYTHON2RUST_NO_DEFAULT_DEPS"
|
|
663
|
+
|
|
664
|
+
# The crates generated code is expected to use. `--deps-from` replaces this table entirely.
|
|
665
|
+
DEFAULT_DEPS: dict[str, Any] = {
|
|
666
|
+
"serde": {"version": "1", "features": ["derive"]},
|
|
667
|
+
"serde_json": "1",
|
|
668
|
+
"indexmap": {"version": "2", "features": ["serde"]},
|
|
669
|
+
"chrono": {"version": "0.4", "features": ["serde"]},
|
|
670
|
+
"uuid": {"version": "1", "features": ["serde", "v4"]},
|
|
671
|
+
"utoipa": {"version": "5", "features": ["uuid", "chrono", "indexmap", "axum_extras"]},
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
# Same features as the repository's rt/Cargo.toml (rt_lib.rs gates its helpers on them); the check
|
|
676
|
+
# crate enables exactly the ones the translation reports in `required_features`.
|
|
677
|
+
_RT_MANIFEST = """[package]
|
|
678
|
+
name = "python2rust-rt"
|
|
679
|
+
version = "0.1.0"
|
|
680
|
+
edition = "2024"
|
|
681
|
+
publish = false
|
|
682
|
+
|
|
683
|
+
[dependencies]
|
|
684
|
+
serde_json = { version = "1", features = ["preserve_order"] }
|
|
685
|
+
regex = { version = "1", optional = true }
|
|
686
|
+
sha2 = { version = "0.10", optional = true }
|
|
687
|
+
md-5 = { version = "0.10", optional = true }
|
|
688
|
+
base64 = { version = "0.22", optional = true }
|
|
689
|
+
serde = { version = "1", features = ["derive"] }
|
|
690
|
+
|
|
691
|
+
[features]
|
|
692
|
+
default = []
|
|
693
|
+
regex = ["dep:regex"]
|
|
694
|
+
hash = ["dep:sha2", "dep:md-5"]
|
|
695
|
+
base64 = ["dep:base64"]
|
|
696
|
+
pydantic = []
|
|
697
|
+
arc = []
|
|
698
|
+
all = ["regex", "hash", "base64", "pydantic"]
|
|
699
|
+
"""
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def _bundled_runtime_crate() -> Path | None:
|
|
703
|
+
"""The `python2rust-rt` crate written from the `rt_lib.rs` that ships inside the package.
|
|
704
|
+
|
|
705
|
+
A wheel has no repo checkout, so the crate is materialised once per content hash under the
|
|
706
|
+
cache dir (single source of truth: `python2rust/core/rt_lib.rs`, also what `vendor_runtime`
|
|
707
|
+
inlines). None when the file is missing or the cache dir is not writable.
|
|
708
|
+
"""
|
|
709
|
+
try:
|
|
710
|
+
lib = resources.files("python2rust.core").joinpath("rt_lib.rs").read_text(encoding="utf-8")
|
|
711
|
+
crate = _cache_root() / f"rt-{hashlib.sha256(lib.encode()).hexdigest()[:12]}"
|
|
712
|
+
for rel, text in (("Cargo.toml", _RT_MANIFEST), ("src/lib.rs", lib)):
|
|
713
|
+
dest = crate / rel
|
|
714
|
+
if not dest.is_file() or dest.read_text(encoding="utf-8") != text:
|
|
715
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
716
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}")
|
|
717
|
+
tmp.write_text(text, encoding="utf-8")
|
|
718
|
+
tmp.replace(dest) # atomic: concurrent runs never see half a file
|
|
719
|
+
return crate
|
|
720
|
+
except ModuleNotFoundError, OSError:
|
|
721
|
+
return None
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
def runtime_crate_path() -> Path | None:
|
|
725
|
+
"""The `python2rust-rt` crate: `PYTHON2RUST_RT_PATH` if it holds one, else the bundled one."""
|
|
726
|
+
override = os.environ.get("PYTHON2RUST_RT_PATH")
|
|
727
|
+
if override and (Path(override) / "Cargo.toml").is_file():
|
|
728
|
+
return Path(override)
|
|
729
|
+
return _bundled_runtime_crate()
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def default_dependencies() -> tuple[dict[str, Any], list[str]]:
|
|
733
|
+
"""The default dependency table, plus notes about what could not be included."""
|
|
734
|
+
deps, notes = dict(DEFAULT_DEPS), []
|
|
735
|
+
if (rt := runtime_crate_path()) is not None:
|
|
736
|
+
deps["python2rust-rt"] = {"path": str(rt)}
|
|
737
|
+
else:
|
|
738
|
+
notes.append(
|
|
739
|
+
"python2rust-rt could not be written to the cache dir (set XDG_CACHE_HOME or "
|
|
740
|
+
"PYTHON2RUST_RT_PATH); code that uses it shows up as unresolved-import"
|
|
741
|
+
)
|
|
742
|
+
return deps, notes
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
def with_required_crates(deps: dict[str, Any], modules: list[CheckModule]) -> dict[str, Any]:
|
|
746
|
+
"""`deps` plus the crates and features the translations report they need (their union).
|
|
747
|
+
|
|
748
|
+
python2rust-rt keeps its local path and gets exactly the reported features; any other crate the
|
|
749
|
+
code uses (tokio, tracing, ...) is added when missing and its features are merged in.
|
|
750
|
+
"""
|
|
751
|
+
out = {k: (dict(v) if isinstance(v, dict) else v) for k, v in deps.items()}
|
|
752
|
+
for module in modules:
|
|
753
|
+
for name, spec in (module.required_crates or {}).items():
|
|
754
|
+
have = out.get(name)
|
|
755
|
+
local = name == "python2rust-rt" and runtime_crate_path()
|
|
756
|
+
if local and not (isinstance(have, dict) and "path" in have):
|
|
757
|
+
# the runtime ships with the tool; it is not on crates.io
|
|
758
|
+
have = {
|
|
759
|
+
"path": str(local),
|
|
760
|
+
**(
|
|
761
|
+
{"features": have["features"]}
|
|
762
|
+
if isinstance(have, dict) and "features" in have
|
|
763
|
+
else {}
|
|
764
|
+
),
|
|
765
|
+
}
|
|
766
|
+
if have is None:
|
|
767
|
+
out[name] = {"version": spec["version"], "features": sorted(spec["features"])}
|
|
768
|
+
continue
|
|
769
|
+
base = {"version": have} if isinstance(have, str) else dict(have)
|
|
770
|
+
base["features"] = sorted({*base.get("features", []), *spec["features"]})
|
|
771
|
+
out[name] = base
|
|
772
|
+
return out
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
TEST_LINE = re.compile(r"^test (\S+) \.\.\. (ok|FAILED|ignored)", re.M)
|
|
776
|
+
_TEST_RESULT = re.compile(r"^test result: ", re.M)
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
def has_test_output(run: CargoRun) -> bool:
|
|
780
|
+
"""The test harness ran and printed `test x ... ok` / `test result:` lines.
|
|
781
|
+
|
|
782
|
+
`cargo test` exits 101 when a test fails (or panics) without any rustc error; that is a test
|
|
783
|
+
failure, not a dependency or manifest failure. Only a run with no test output at all is one.
|
|
784
|
+
"""
|
|
785
|
+
return bool(TEST_LINE.search(run.text) or _TEST_RESULT.search(run.text))
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def _resolution_failed(run: CargoRun) -> bool:
|
|
789
|
+
"""cargo failed without a single rustc error: dependency resolution, manifest, network."""
|
|
790
|
+
errors = any(str(m["message"].get("level", "")).startswith("error") for m in run.messages)
|
|
791
|
+
return run.status == "ran" and bool(run.returncode) and not errors and not has_test_output(run)
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
def run_cargo(
|
|
795
|
+
modules: list[CheckModule],
|
|
796
|
+
sub: str = "check",
|
|
797
|
+
*,
|
|
798
|
+
deps_from: str | None = None,
|
|
799
|
+
offline: bool = False,
|
|
800
|
+
timeout: float = 300,
|
|
801
|
+
target_dir: str | None = None,
|
|
802
|
+
keep: bool = False,
|
|
803
|
+
default_deps: bool = True,
|
|
804
|
+
deps_root: str | Path | None = None,
|
|
805
|
+
allow_build_scripts: bool = False,
|
|
806
|
+
test_args: Sequence[str] = (),
|
|
807
|
+
sandbox: bool = False,
|
|
808
|
+
allow_unvetted_deps: bool | None = None,
|
|
809
|
+
) -> CargoRun:
|
|
810
|
+
"""Run `cargo <sub>` (check | clippy | test) over `modules`; never raises for a missing cargo.
|
|
811
|
+
|
|
812
|
+
With `sandbox` (or inside `sandbox.confine()`, which the MCP server uses) the compile runs under
|
|
813
|
+
the OS sandbox of `verify/sandbox.py`: no network, reads confined; a missing sandbox tool raises
|
|
814
|
+
UsageError instead of compiling unconfined.
|
|
815
|
+
|
|
816
|
+
`test` runs the library's unit tests only (`--lib`: a `///` block that rustdoc would compile as
|
|
817
|
+
a doctest is documentation, not a test) and passes `test_args` to the test harness, e.g.
|
|
818
|
+
`["--exact", "--skip", "m000::tests::t"]`.
|
|
819
|
+
|
|
820
|
+
Dependencies: `--deps-from` if given, else the default table (serde, serde_json, indexmap,
|
|
821
|
+
chrono, uuid, utoipa with its features, python2rust-rt when found). If the default table cannot
|
|
822
|
+
be resolved (offline, no cache) the run is retried with std only, and a note says so.
|
|
823
|
+
"""
|
|
824
|
+
attempts: list[tuple[str, dict[str, Any], list[str]]]
|
|
825
|
+
if deps_from:
|
|
826
|
+
attempts = [
|
|
827
|
+
(
|
|
828
|
+
"custom",
|
|
829
|
+
read_dependencies(
|
|
830
|
+
deps_from,
|
|
831
|
+
root=deps_root,
|
|
832
|
+
allow_build_scripts=allow_build_scripts,
|
|
833
|
+
allow_unvetted_deps=allow_unvetted_deps,
|
|
834
|
+
extra_allowed={n for m in modules for n in (m.required_crates or {})},
|
|
835
|
+
),
|
|
836
|
+
[],
|
|
837
|
+
)
|
|
838
|
+
]
|
|
839
|
+
elif default_deps and os.environ.get(NO_DEFAULT_DEPS_ENV) != "1":
|
|
840
|
+
deps, notes = default_dependencies()
|
|
841
|
+
attempts = [("default", with_required_crates(deps, modules), notes), ("none", {}, [])]
|
|
842
|
+
else:
|
|
843
|
+
attempts = [("none", with_required_crates({}, modules), [])]
|
|
844
|
+
run = CargoRun("skipped")
|
|
845
|
+
previous = ""
|
|
846
|
+
for source, deps, notes in attempts:
|
|
847
|
+
run = _cargo_once(
|
|
848
|
+
modules, sub, deps, offline, timeout, target_dir, keep, test_args,
|
|
849
|
+
sandbox=sandbox, deps_root=deps_root,
|
|
850
|
+
) # fmt: skip
|
|
851
|
+
run.deps_source, run.notes = source, [*notes, *run.notes]
|
|
852
|
+
if previous:
|
|
853
|
+
run.notes.append(previous)
|
|
854
|
+
if not _resolution_failed(run) or source != "default":
|
|
855
|
+
break
|
|
856
|
+
tail = " ".join(run.stderr.strip().splitlines()[-2:])
|
|
857
|
+
previous = (
|
|
858
|
+
f"the default dependency table could not be resolved ({tail}); retried with std only, "
|
|
859
|
+
"so crate imports show up as unresolved-import. Use --deps-from or fix the network"
|
|
860
|
+
)
|
|
861
|
+
return run
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
def _exec(cmd: list[str], sub: str, timeout: float, run: CargoRun, cwd: str | None = None) -> None:
|
|
865
|
+
"""Run a cargo command, filling `run` with its compiler messages and test text."""
|
|
866
|
+
try:
|
|
867
|
+
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, cwd=cwd)
|
|
868
|
+
except subprocess.TimeoutExpired:
|
|
869
|
+
run.status, run.reason = "failed", f"cargo {sub} timed out after {timeout:g}s"
|
|
870
|
+
return
|
|
871
|
+
run.status, run.returncode, run.stderr = "ran", proc.returncode, proc.stderr
|
|
872
|
+
text: list[str] = []
|
|
873
|
+
for raw in proc.stdout.splitlines():
|
|
874
|
+
try:
|
|
875
|
+
msg = json.loads(raw)
|
|
876
|
+
except ValueError:
|
|
877
|
+
text.append(raw)
|
|
878
|
+
continue
|
|
879
|
+
if isinstance(msg, dict):
|
|
880
|
+
if msg.get("reason") == "compiler-message":
|
|
881
|
+
run.messages.append(msg)
|
|
882
|
+
elif msg.get("reason") == "compiler-artifact" and isinstance(
|
|
883
|
+
msg.get("executable"), str
|
|
884
|
+
):
|
|
885
|
+
run.executables.append(msg["executable"])
|
|
886
|
+
run.text = "\n".join(text)
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
def run_in_crate(
|
|
890
|
+
crate_dir: str | Path,
|
|
891
|
+
sub: str = "check",
|
|
892
|
+
*,
|
|
893
|
+
offline: bool = False,
|
|
894
|
+
timeout: float = 300,
|
|
895
|
+
target_dir: str | None = None,
|
|
896
|
+
sandbox: bool = False,
|
|
897
|
+
) -> CargoRun:
|
|
898
|
+
"""Run `cargo <sub>` in an existing crate (used by `port`); never raises for a missing cargo.
|
|
899
|
+
|
|
900
|
+
Sandboxed like `run_cargo` (`sandbox`, `sandbox.confine()` or the CLI policy): the crate is
|
|
901
|
+
readable, only the target dir is writable, and dependencies are fetched first (no network)."""
|
|
902
|
+
run = CargoRun("skipped")
|
|
903
|
+
cargo = shutil.which("cargo")
|
|
904
|
+
if cargo is None:
|
|
905
|
+
run.reason = (
|
|
906
|
+
"cargo was not found on PATH; install Rust (https://rustup.rs) to compile-check"
|
|
907
|
+
)
|
|
908
|
+
return run
|
|
909
|
+
run.available = True
|
|
910
|
+
sandbox = sandbox_mod.resolve(sandbox)
|
|
911
|
+
try:
|
|
912
|
+
run.version = tool_version("cargo")
|
|
913
|
+
except ToolError as exc:
|
|
914
|
+
run.status, run.reason = "failed", str(exc)
|
|
915
|
+
return run
|
|
916
|
+
crate = Path(crate_dir).resolve()
|
|
917
|
+
manifest = crate / "Cargo.toml"
|
|
918
|
+
tdir = Path(target_dir) if target_dir else crate / "target"
|
|
919
|
+
cmd = [cargo, sub, "--message-format=json", "--color=never", "--manifest-path", str(manifest)]
|
|
920
|
+
cmd += ["--target-dir", str(tdir)] if target_dir or sandbox else []
|
|
921
|
+
cmd += ["--offline"] if offline or sandbox else []
|
|
922
|
+
if not sandbox:
|
|
923
|
+
_exec(cmd, sub, timeout, run)
|
|
924
|
+
return run
|
|
925
|
+
# the sandbox has no network and cannot write the lockfile: resolve and download first (cargo
|
|
926
|
+
# fetch compiles and runs nothing)
|
|
927
|
+
fetch = [cargo, "fetch", "--manifest-path", str(manifest), *(["--offline"] if offline else [])]
|
|
928
|
+
try:
|
|
929
|
+
got = subprocess.run(fetch, capture_output=True, text=True, timeout=timeout)
|
|
930
|
+
except subprocess.TimeoutExpired:
|
|
931
|
+
run.status, run.reason = "failed", f"cargo fetch timed out after {timeout:g}s"
|
|
932
|
+
return run
|
|
933
|
+
if got.returncode:
|
|
934
|
+
run.status, run.returncode, run.stderr = "ran", got.returncode, got.stderr
|
|
935
|
+
return run
|
|
936
|
+
try:
|
|
937
|
+
deps = tomllib.loads(manifest.read_text(encoding="utf-8")).get("dependencies") or {}
|
|
938
|
+
except OSError, tomllib.TOMLDecodeError:
|
|
939
|
+
deps = {}
|
|
940
|
+
absolute = {
|
|
941
|
+
n: {**d, "path": str((crate / str(d["path"])).resolve())} if "path" in d else d
|
|
942
|
+
for n, d in deps.items()
|
|
943
|
+
if isinstance(d, dict)
|
|
944
|
+
}
|
|
945
|
+
tdir.mkdir(parents=True, exist_ok=True)
|
|
946
|
+
tmp = Path(tempfile.mkdtemp(prefix="python2rust-box-"))
|
|
947
|
+
try:
|
|
948
|
+
reads = [crate, *_sandbox_reads(absolute, None)]
|
|
949
|
+
cmd = sandbox_mod.wrap(cmd, tmp, allow_read=reads, allow_write=[tdir])
|
|
950
|
+
_exec(cmd, sub, timeout, run, cwd=str(tmp))
|
|
951
|
+
finally:
|
|
952
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
953
|
+
return run
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
def _path_dependency_dirs(deps: dict[str, Any], depth: int = 0) -> list[Path]:
|
|
957
|
+
"""Directories of the path dependencies in `deps` and, recursively, of theirs (read access)."""
|
|
958
|
+
out: list[Path] = []
|
|
959
|
+
for spec in deps.values():
|
|
960
|
+
if not isinstance(spec, dict) or "path" not in spec:
|
|
961
|
+
continue
|
|
962
|
+
crate = Path(str(spec["path"]))
|
|
963
|
+
out.append(crate)
|
|
964
|
+
try:
|
|
965
|
+
sub = tomllib.loads((crate / "Cargo.toml").read_text(encoding="utf-8"))
|
|
966
|
+
except OSError, tomllib.TOMLDecodeError:
|
|
967
|
+
continue
|
|
968
|
+
if depth < 5:
|
|
969
|
+
nested = {
|
|
970
|
+
k: {**v, "path": str((crate / str(v["path"])).resolve())}
|
|
971
|
+
for k, v in (sub.get("dependencies") or {}).items()
|
|
972
|
+
if isinstance(v, dict) and "path" in v
|
|
973
|
+
}
|
|
974
|
+
out += _path_dependency_dirs(nested, depth + 1)
|
|
975
|
+
return out
|
|
976
|
+
|
|
977
|
+
|
|
978
|
+
def _sandbox_reads(deps: dict[str, Any], deps_root: str | Path | None) -> list[Path]:
|
|
979
|
+
"""What a sandboxed compile may read besides the scratch crate: the vetted path dependencies
|
|
980
|
+
and the `Cargo.toml` of each directory above them up to `deps_root` (a workspace manifest the
|
|
981
|
+
dependency inherits from), never `deps_root` itself, which holds the user's other files."""
|
|
982
|
+
dirs = [d.resolve() for d in _path_dependency_dirs(deps)]
|
|
983
|
+
reads = list(dirs)
|
|
984
|
+
if deps_root is not None:
|
|
985
|
+
top = Path(deps_root).resolve()
|
|
986
|
+
for d in dirs:
|
|
987
|
+
if d.is_relative_to(top):
|
|
988
|
+
reads += [a / "Cargo.toml" for a in d.parents if a.is_relative_to(top)]
|
|
989
|
+
return reads
|
|
990
|
+
|
|
991
|
+
|
|
992
|
+
def _cargo_once(
|
|
993
|
+
modules: list[CheckModule],
|
|
994
|
+
sub: str,
|
|
995
|
+
deps: dict[str, Any],
|
|
996
|
+
offline: bool,
|
|
997
|
+
timeout: float,
|
|
998
|
+
target_dir: str | None,
|
|
999
|
+
keep: bool,
|
|
1000
|
+
test_args: Sequence[str] = (),
|
|
1001
|
+
*,
|
|
1002
|
+
sandbox: bool = False,
|
|
1003
|
+
deps_root: str | Path | None = None,
|
|
1004
|
+
) -> CargoRun:
|
|
1005
|
+
run = CargoRun("skipped")
|
|
1006
|
+
cargo = shutil.which("cargo")
|
|
1007
|
+
if cargo is None:
|
|
1008
|
+
run.reason = (
|
|
1009
|
+
"cargo was not found on PATH; install Rust (https://rustup.rs) to compile-check"
|
|
1010
|
+
)
|
|
1011
|
+
return run
|
|
1012
|
+
run.available = True
|
|
1013
|
+
sandbox = sandbox_mod.resolve(sandbox) # refuses here when a sandbox is required but missing
|
|
1014
|
+
try:
|
|
1015
|
+
run.version = tool_version("cargo")
|
|
1016
|
+
if sub == "clippy" and clippy_version() is None:
|
|
1017
|
+
run.reason = "clippy is not installed (rustup component add clippy)"
|
|
1018
|
+
return run
|
|
1019
|
+
except ToolError as exc:
|
|
1020
|
+
run.status, run.reason = "failed", str(exc)
|
|
1021
|
+
return run
|
|
1022
|
+
tmp = Path(tempfile.mkdtemp(prefix="python2rust-check-"))
|
|
1023
|
+
try:
|
|
1024
|
+
crate = tmp / "crate"
|
|
1025
|
+
run.names = write_scratch_crate(crate, modules, deps)
|
|
1026
|
+
tdir = Path(target_dir) if target_dir else _cache_dir(deps, sandbox)
|
|
1027
|
+
tdir.mkdir(parents=True, exist_ok=True)
|
|
1028
|
+
cmd = [cargo, sub, "--message-format=json", "--color=never", "--target-dir", str(tdir)]
|
|
1029
|
+
cmd += ["--manifest-path", str(crate / "Cargo.toml")] + (
|
|
1030
|
+
["--offline"] if offline or sandbox else []
|
|
1031
|
+
)
|
|
1032
|
+
if sub == "test":
|
|
1033
|
+
cmd += ["--lib", "--no-fail-fast", *(["--", *test_args] if test_args else [])]
|
|
1034
|
+
cwd = None
|
|
1035
|
+
if sandbox:
|
|
1036
|
+
# the sandbox has no network: resolve and download first, compile nothing
|
|
1037
|
+
if not offline:
|
|
1038
|
+
fetch = [cargo, "fetch", "--manifest-path", str(crate / "Cargo.toml")]
|
|
1039
|
+
try:
|
|
1040
|
+
got = subprocess.run(fetch, capture_output=True, text=True, timeout=timeout)
|
|
1041
|
+
except subprocess.TimeoutExpired:
|
|
1042
|
+
run.status, run.reason = "failed", f"cargo fetch timed out after {timeout:g}s"
|
|
1043
|
+
return run
|
|
1044
|
+
if got.returncode:
|
|
1045
|
+
run.status, run.returncode, run.stderr = "ran", got.returncode, got.stderr
|
|
1046
|
+
return run
|
|
1047
|
+
reads = _sandbox_reads(deps, deps_root)
|
|
1048
|
+
cmd = sandbox_mod.wrap(cmd, tmp, allow_read=reads, allow_write=[tdir])
|
|
1049
|
+
cwd = str(tmp)
|
|
1050
|
+
_exec(cmd, sub, timeout, run, cwd=cwd)
|
|
1051
|
+
return run
|
|
1052
|
+
finally:
|
|
1053
|
+
if keep:
|
|
1054
|
+
run.scratch_dir = str(tmp)
|
|
1055
|
+
else:
|
|
1056
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
1057
|
+
|
|
1058
|
+
|
|
1059
|
+
def cargo_failure(run: CargoRun, errors: list[dict[str, Any]]) -> str | None:
|
|
1060
|
+
"""Reason when cargo failed without a rustc error (dependency resolution, manifest, offline)."""
|
|
1061
|
+
if run.returncode and not errors and not has_test_output(run):
|
|
1062
|
+
tail = "\n".join(run.stderr.strip().splitlines()[-8:])
|
|
1063
|
+
return f"cargo exited {run.returncode}: {tail}"
|
|
1064
|
+
return None
|
|
1065
|
+
|
|
1066
|
+
|
|
1067
|
+
def run_check(
|
|
1068
|
+
modules: list[CheckModule],
|
|
1069
|
+
*,
|
|
1070
|
+
deps_from: str | None = None,
|
|
1071
|
+
offline: bool = False,
|
|
1072
|
+
timeout: float = 300,
|
|
1073
|
+
target_dir: str | None = None,
|
|
1074
|
+
keep: bool = False,
|
|
1075
|
+
deps_root: str | Path | None = None,
|
|
1076
|
+
allow_build_scripts: bool = False,
|
|
1077
|
+
sandbox: bool = False,
|
|
1078
|
+
allow_unvetted_deps: bool | None = None,
|
|
1079
|
+
) -> dict[str, Any]:
|
|
1080
|
+
"""Run `cargo check` over `modules`; a missing cargo is status "skipped", never success.
|
|
1081
|
+
|
|
1082
|
+
`deps_root` confines `--deps-from` path dependencies (see `read_dependencies`); the MCP server
|
|
1083
|
+
sets it.
|
|
1084
|
+
"""
|
|
1085
|
+
result: dict[str, Any] = {
|
|
1086
|
+
"available": False,
|
|
1087
|
+
"version": None,
|
|
1088
|
+
"status": "skipped",
|
|
1089
|
+
"reason": None,
|
|
1090
|
+
"offline": offline,
|
|
1091
|
+
"errors": 0,
|
|
1092
|
+
"warnings": 0,
|
|
1093
|
+
"errors_by_category": {},
|
|
1094
|
+
"diagnostics": [],
|
|
1095
|
+
"scratch_dir": None,
|
|
1096
|
+
"dependencies": "none",
|
|
1097
|
+
"notes": [],
|
|
1098
|
+
}
|
|
1099
|
+
if modules:
|
|
1100
|
+
run = run_cargo(
|
|
1101
|
+
modules, "check", deps_from=deps_from, offline=offline, timeout=timeout,
|
|
1102
|
+
target_dir=target_dir, keep=keep, deps_root=deps_root,
|
|
1103
|
+
allow_build_scripts=allow_build_scripts, sandbox=sandbox,
|
|
1104
|
+
allow_unvetted_deps=allow_unvetted_deps,
|
|
1105
|
+
) # fmt: skip
|
|
1106
|
+
else:
|
|
1107
|
+
run = CargoRun(
|
|
1108
|
+
"ran", "nothing to compile", tool_version("cargo"), shutil.which("cargo") is not None, 0
|
|
1109
|
+
)
|
|
1110
|
+
result.update(
|
|
1111
|
+
available=run.available,
|
|
1112
|
+
version=run.version,
|
|
1113
|
+
reason=run.reason,
|
|
1114
|
+
scratch_dir=run.scratch_dir,
|
|
1115
|
+
dependencies=run.deps_source,
|
|
1116
|
+
notes=run.notes,
|
|
1117
|
+
)
|
|
1118
|
+
if run.status != "ran":
|
|
1119
|
+
result["status"] = run.status
|
|
1120
|
+
return result
|
|
1121
|
+
errors = diagnostics_from(run.messages, modules, run.names)
|
|
1122
|
+
warnings = sum(1 for m in run.messages if m["message"].get("level") == "warning")
|
|
1123
|
+
result.update(
|
|
1124
|
+
errors=len(errors),
|
|
1125
|
+
warnings=warnings,
|
|
1126
|
+
diagnostics=errors,
|
|
1127
|
+
errors_by_category=dict(sorted(Counter(e["category"] for e in errors).items())),
|
|
1128
|
+
)
|
|
1129
|
+
if errors:
|
|
1130
|
+
result["status"] = "errors"
|
|
1131
|
+
elif (failure := cargo_failure(run, errors)) is not None:
|
|
1132
|
+
result.update(status="failed", reason=failure)
|
|
1133
|
+
else:
|
|
1134
|
+
result["status"] = "ok"
|
|
1135
|
+
return result
|