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,168 @@
1
+ """Pydantic/dataclass metadata -> utoipa attributes, and the `api_docs.rs` registry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ from collections.abc import Mapping, Sequence
7
+
8
+ from ..diagnostics import rust_escape
9
+ from ..ir import nodes as ir
10
+ from ..ir.rtypes import MAP, SET, SHARED, STR, RType, option, peel
11
+
12
+ # Python constraint keyword -> utoipa attribute (min/max_length become *_items on collections).
13
+ CONSTRAINT_ATTRS = {
14
+ "ge": "minimum", "le": "maximum", "gt": "exclusive_minimum", "lt": "exclusive_maximum",
15
+ "multiple_of": "multiple_of", "pattern": "pattern", "min_length": "min_length",
16
+ "max_length": "max_length", "min_items": "min_items", "max_items": "max_items",
17
+ } # fmt: skip
18
+ ANNOTATED_TYPES = {
19
+ "Ge": "ge",
20
+ "Gt": "gt",
21
+ "Le": "le",
22
+ "Lt": "lt",
23
+ "MinLen": "min_length",
24
+ "MaxLen": "max_length",
25
+ "MultipleOf": "multiple_of",
26
+ }
27
+ NATIVE = ("chrono::", "uuid::") # utoipa knows these through its `chrono`/`uuid` features
28
+
29
+
30
+ def literal_text(node: ast.expr | None) -> str | None:
31
+ """Rust text of a scalar literal (numbers, strings, bools), else None."""
32
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
33
+ inner = literal_text(node.operand)
34
+ return f"-{inner}" if inner and inner[0].isdigit() else None
35
+ if isinstance(node, ast.Constant):
36
+ v = node.value
37
+ if isinstance(v, bool):
38
+ return "true" if v else "false"
39
+ if isinstance(v, (int, float)):
40
+ return repr(v)
41
+ if isinstance(v, str):
42
+ return f'"{rust_escape(v)}"'
43
+ return None
44
+
45
+
46
+ def _first_example(kw: Mapping[str, ast.expr]) -> ast.expr | None:
47
+ if "example" in kw:
48
+ return kw["example"]
49
+ examples = kw.get("examples")
50
+ if isinstance(examples, (ast.List, ast.Tuple)) and examples.elts:
51
+ return examples.elts[0]
52
+ extra = kw.get("json_schema_extra")
53
+ if isinstance(extra, ast.Dict):
54
+ for k, v in zip(extra.keys, extra.values, strict=False):
55
+ if isinstance(k, ast.Constant) and k.value == "example":
56
+ return v
57
+ return None
58
+
59
+
60
+ def _object(ty: RType) -> RType:
61
+ """`ty` with serde_json::Value spelled `Object`, the name utoipa's `value_type` understands."""
62
+ if ty.name == "serde_json::Value":
63
+ return RType("Object")
64
+ return RType(ty.name, tuple(_object(a) for a in ty.args))
65
+
66
+
67
+ def _unshared(ty: RType) -> RType:
68
+ while ty.name == SHARED:
69
+ ty = ty.args[0]
70
+ return RType(ty.name, tuple(_unshared(a) for a in ty.args))
71
+
72
+
73
+ def value_type(ty: RType) -> list[ir.Arg]:
74
+ """`value_type`/`format` attributes for types utoipa cannot derive (Value, bytes)."""
75
+ if "rt::Shared<" in ty.rust(): # utoipa knows the value, not the handle around it
76
+ plain = _unshared(ty)
77
+ extra = value_type(plain)
78
+ return extra or [("value_type", plain)]
79
+ if "serde_json::Value" in ty.rust():
80
+ return [("value_type", _object(ty))]
81
+ inner = peel(ty.args[0]) if ty.name == "Option" else ty
82
+ if inner.name == "Vec" and inner.args and inner.args[0].name == "u8":
83
+ wire = RType("Option", (STR,)) if ty.name == "Option" else STR
84
+ return [("value_type", wire), ("format", ir.Ident("Binary"))]
85
+ return []
86
+
87
+
88
+ def literal_value(node: ast.expr | None) -> int | float | str | bool | None:
89
+ """The value of a scalar literal (numbers, strings, bools, negated numbers), else None."""
90
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
91
+ inner = literal_value(node.operand)
92
+ return -inner if isinstance(inner, int | float) and not isinstance(inner, bool) else None
93
+ if isinstance(node, ast.Constant) and isinstance(node.value, int | float | str | bool):
94
+ return node.value
95
+ return None
96
+
97
+
98
+ def field_items(
99
+ ty: RType, kw: Mapping[str, ast.expr], default: ast.expr | None
100
+ ) -> tuple[list[ir.Arg], list[str]]:
101
+ """(attribute args, constraints that serde will not enforce) for one field."""
102
+ inner = ty.args[0] if ty.name == "Option" else ty
103
+ on_collection = peel(inner).name in ("Vec", SET, MAP)
104
+ items: list[ir.Arg] = []
105
+ constraints: list[str] = []
106
+ for py, attr in CONSTRAINT_ATTRS.items():
107
+ value = literal_value(kw.get(py))
108
+ if value is None:
109
+ continue
110
+ constraints.append(f"{py}={value!r}")
111
+ if on_collection and py in ("min_length", "max_length"):
112
+ attr = attr.replace("length", "items")
113
+ items.append((attr, value))
114
+ scalar = peel(inner) == STR or peel(inner).name in ("i64", "f64", "bool")
115
+ shown = literal_value(default)
116
+ if shown is not None and scalar:
117
+ items.append(("default", shown))
118
+ example = literal_value(_first_example(kw))
119
+ if example is not None:
120
+ items.append(("example", example))
121
+ deprecated = kw.get("deprecated")
122
+ if isinstance(deprecated, ast.Constant) and deprecated.value:
123
+ items.append(("deprecated", None))
124
+ return items + value_type(ty), constraints
125
+
126
+
127
+ def operation_attr(op: object) -> str:
128
+ """`#[utoipa::path(...)]` for an `ir.Operation` (the 0.2 route frontend fills these in)."""
129
+ assert isinstance(op, ir.Operation)
130
+ parts = [op.method.lower(), f'path = "{rust_escape(op.path)}"']
131
+ if op.operation_id:
132
+ parts.append(f'operation_id = "{rust_escape(op.operation_id)}"')
133
+ if op.tag:
134
+ parts.append(f'tag = "{rust_escape(op.tag)}"')
135
+ if op.params:
136
+ rendered = []
137
+ for p in op.params:
138
+ ty = p.ty if p.required or p.ty.name == "Option" else option(p.ty)
139
+ desc = f', description = "{rust_escape(p.description)}"' if p.description else ""
140
+ rendered.append(f'("{p.name}" = {ty.rust()}, {p.location.capitalize()}{desc})')
141
+ parts.append(f"params({', '.join(rendered)})")
142
+ if op.request_body is not None:
143
+ parts.append(f"request_body = {op.request_body.rust()}")
144
+ rows = []
145
+ for r in op.responses:
146
+ body = f", body = {r.body.rust()}" if r.body is not None else ""
147
+ rows.append(f'(status = {r.status}, description = "{rust_escape(r.description)}"{body})')
148
+ if rows:
149
+ parts.append(f"responses({', '.join(rows)})")
150
+ if op.security:
151
+ parts.append(f"security({', '.join(f'("{s}" = [])' for s in op.security)})")
152
+ return f"#[utoipa::path({', '.join(parts)})]"
153
+
154
+
155
+ def render_api_docs(
156
+ modules: Mapping[str, Sequence[str]], root: str = "crate", name: str = "ApiDoc"
157
+ ) -> str:
158
+ """The `api_docs.rs` registry: an OpenApi derive listing every generated schema."""
159
+ paths = [
160
+ f"{root}::{mod}::{schema}" for mod, schemas in sorted(modules.items()) for schema in schemas
161
+ ]
162
+ listing = ",\n ".join(paths)
163
+ return (
164
+ "use utoipa::OpenApi;\n\n"
165
+ "#[derive(OpenApi)]\n"
166
+ f"#[openapi(components(schemas(\n {listing}\n)))]\n"
167
+ f"pub struct {name};\n"
168
+ )
@@ -0,0 +1,304 @@
1
+ """translate_source: parse, lower to IR, run passes, emit, format, and assemble the result."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import subprocess
7
+ import sys
8
+ from collections.abc import Generator
9
+ from contextlib import contextmanager
10
+ from dataclasses import dataclass, field
11
+ from importlib import resources
12
+ from typing import TypedDict
13
+
14
+ from ..config import Config
15
+ from ..diagnostics import DIAGNOSTIC_CODES, DRIFT_CODES, Collector, Diagnostic, Todo
16
+ from ..frontend.module import _rust_name, build_module
17
+ from ..frontend.symbols import ProjectContext, export_symbols
18
+ from ..ir.types import TypeMapper
19
+ from ..lower.context import Ctx
20
+ from ..lower.testing import TestEntry
21
+ from .crates import CrateSpec, required_crates
22
+ from .render import SourceMapEntry, extract_markers, render_module
23
+
24
+
25
+ class DriftEntry(TypedDict):
26
+ """One drift-ledger row (info diagnostics with a PY2RS041..PY2RS049 drift code)."""
27
+
28
+ code: str
29
+ file: str
30
+ line: int
31
+ message: str
32
+ construct: str | None
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class TranslateResult:
37
+ rust: str
38
+ diagnostics: tuple[Diagnostic, ...]
39
+ todos: tuple[Todo, ...]
40
+ stats: dict[str, int]
41
+ source_map: list[SourceMapEntry] = field(default_factory=list)
42
+ schemas: tuple[str, ...] = () # Rust names deriving ToSchema, for `render_api_docs`
43
+ tests: tuple[TestEntry, ...] = () # translated/dropped tests with their stable ids
44
+ drift: tuple[DriftEntry, ...] = () # the drift ledger: where Rust may differ from Python
45
+ required_features: tuple[str, ...] = () # python2rust-rt features the output calls into
46
+ required_crates: dict[str, CrateSpec] = field(
47
+ default_factory=dict
48
+ ) # crate -> version + features
49
+ not_clean: tuple[str, ...] = () # Rust names of the items counted not clean
50
+
51
+
52
+ def runtime_source() -> str:
53
+ """The python2rust-rt crate source (for `vendor_runtime` and for writing a standalone file)."""
54
+ return resources.files("python2rust.core").joinpath("rt_lib.rs").read_text(encoding="utf-8")
55
+
56
+
57
+ MAX_FORMAT_CLOSURE_DEPTH = 12
58
+
59
+
60
+ def _closure_depth(tree: ast.AST, depth: int = 0) -> int:
61
+ """The deepest nesting of lambdas below `tree`."""
62
+ deepest = depth
63
+ for child in ast.iter_child_nodes(tree):
64
+ here = depth + isinstance(child, ast.Lambda)
65
+ deepest = max(deepest, _closure_depth(child, here))
66
+ return deepest
67
+
68
+
69
+ def format_rust(text: str, timeout: float = 30.0) -> tuple[str, str | None]:
70
+ """Run `rustfmt --edition 2024`; returns (text, error). On any failure the input is returned."""
71
+ try:
72
+ done = subprocess.run(
73
+ ["rustfmt", "--edition", "2024"],
74
+ input=text,
75
+ capture_output=True,
76
+ text=True,
77
+ timeout=timeout,
78
+ check=False,
79
+ )
80
+ except FileNotFoundError:
81
+ return text, "rustfmt is not installed"
82
+ except subprocess.TimeoutExpired:
83
+ return text, "rustfmt timed out"
84
+ if done.returncode != 0:
85
+ return text, (done.stderr.strip().splitlines() or ["rustfmt failed"])[0]
86
+ return done.stdout, None
87
+
88
+
89
+ def _syntax_error(exc: Exception, path: str) -> TranslateResult:
90
+ if isinstance(
91
+ exc, (RecursionError, MemoryError)
92
+ ): # not a syntax problem: the input is too big or too nested
93
+ hint = "split the file or flatten the deeply nested expression"
94
+ return _failure(
95
+ path, "PY2RS050", f"input too complex to parse ({type(exc).__name__})", hint=hint
96
+ )
97
+ line = getattr(exc, "lineno", 0) or 0
98
+ msg = getattr(exc, "msg", None) or str(exc) or type(exc).__name__
99
+ return _failure(
100
+ path, "PY2RS001", f"syntax error: {msg}", line, (getattr(exc, "offset", 0) or 0) - 1
101
+ )
102
+
103
+
104
+ def _locate(todo_id: str, lines: list[str]) -> int:
105
+ """Index of the line holding the TODO's `todo!(` token (its comment for types); -1 if absent."""
106
+ needle = f"python2rust {todo_id} "
107
+ for i, line in enumerate(lines):
108
+ if needle in line:
109
+ for j in range(i, max(i - 4, -1), -1): # rustfmt may wrap `todo!(` onto its own line
110
+ if "todo!(" in lines[j]:
111
+ return j
112
+ return i
113
+ return -1
114
+
115
+
116
+ def _context(lines: list[str], i: int) -> str:
117
+ """The item that holds line `i` (rustfmt separates items by blank lines) plus 3 lines each side."""
118
+ start, end = i, i
119
+ while start > 0 and lines[start - 1].strip():
120
+ start -= 1
121
+ while end + 1 < len(lines) and lines[end + 1].strip():
122
+ end += 1
123
+ return "\n".join(lines[max(0, start - 3) : end + 4])
124
+
125
+
126
+ def _finish_todos(col: Collector, text: str) -> tuple[Todo, ...]:
127
+ lines = text.splitlines()
128
+ out: list[Todo] = []
129
+ for p in col.todos:
130
+ i = _locate(p.id, lines)
131
+ context = _context(lines, i) if i >= 0 else ""
132
+ out.append(
133
+ Todo(
134
+ p.id,
135
+ p.code,
136
+ col.file,
137
+ p.line,
138
+ p.snippet,
139
+ context,
140
+ i + 1 if i >= 0 else 0,
141
+ p.kind,
142
+ bool(p.review_reason),
143
+ p.review_reason,
144
+ )
145
+ )
146
+ return tuple(out)
147
+
148
+
149
+ @contextmanager
150
+ def _deep_recursion(limit: int = 10_000) -> Generator[None]:
151
+ """Pure-Python recursion is cheap in 3.12+; give hostile-but-bounded input room before it is a TODO."""
152
+ old = sys.getrecursionlimit()
153
+ sys.setrecursionlimit(max(old, limit))
154
+ try:
155
+ yield
156
+ finally:
157
+ sys.setrecursionlimit(old)
158
+
159
+
160
+ def _failure(
161
+ path: str, code: str, message: str, line: int = 0, col: int = 0, hint: str | None = None
162
+ ) -> TranslateResult:
163
+ diag = Diagnostic(code, "error", message, path, line, max(col, 0), None, hint)
164
+ text = " ".join(f"{code}: {message}".split())
165
+ stats = {
166
+ "functions_total": 0,
167
+ "functions_clean": 0,
168
+ "models_total": 0,
169
+ "models_clean": 0,
170
+ "models_clean_modulo_int_range": 0,
171
+ "module_init_effects": 0,
172
+ "functions_clean_if_init_run": 0,
173
+ "models_clean_if_init_run": 0,
174
+ "todo_count": 0,
175
+ }
176
+ return TranslateResult(f"// python2rust {text} ({path})\n", (diag,), (), stats)
177
+
178
+
179
+ def translate_source(
180
+ source: str,
181
+ path: str = "<string>",
182
+ config: Config | None = None,
183
+ *,
184
+ project: ProjectContext | None = None,
185
+ ) -> TranslateResult:
186
+ """Translate Python `source` to Rust. Never raises, never runs the source (`ast.parse` only).
187
+
188
+ `project` is set by `translate_project`: imports of other project modules then resolve, and
189
+ this module's exports are recorded in the project's symbol table.
190
+ """
191
+ cfg = config or Config()
192
+ source = source.removeprefix("\ufeff") # CPython accepts a UTF-8 byte order mark
193
+ if len(source.encode("utf-8", errors="replace")) > cfg.max_source_bytes:
194
+ return _failure(
195
+ path, "PY2RS050", f"input is larger than the {cfg.max_source_bytes} byte limit"
196
+ )
197
+ with _deep_recursion():
198
+ try:
199
+ return _translate(source, path, cfg, project)
200
+ except Exception as exc:
201
+ return _failure(path, "PY2RS002", f"internal error: {type(exc).__name__}: {exc}"[:200])
202
+
203
+
204
+ def _translate(
205
+ source: str, path: str, cfg: Config, project: ProjectContext | None
206
+ ) -> TranslateResult:
207
+ try:
208
+ tree = ast.parse(source, filename=path)
209
+ except (SyntaxError, ValueError, RecursionError, MemoryError) as exc:
210
+ return _syntax_error(exc, path)
211
+ for node in ast.walk(tree):
212
+ if (
213
+ isinstance(node, ast.Constant)
214
+ and isinstance(node.value, str)
215
+ and any("\ud800" <= ch <= "\udfff" for ch in node.value)
216
+ ):
217
+ return _failure(
218
+ path, "PY2RS062", DIAGNOSTIC_CODES["PY2RS062"], node.lineno, node.col_offset
219
+ )
220
+ col = Collector(path, source)
221
+ ctx = Ctx(cfg, col)
222
+ if cfg.int_overflow not in ("checked", "wrapping", "native"):
223
+ col.diag(
224
+ "PY2RS041",
225
+ None,
226
+ f"int_overflow={cfg.int_overflow!r} is not implemented (no bigint yet): behaves as 'checked'",
227
+ severity="info",
228
+ construct="int_overflow",
229
+ )
230
+ ctx.load_comments()
231
+ ctx.project = project
232
+ if cfg.shared == "arc":
233
+ ctx.features.add("arc") # the runtime's Shared<T> is an Arc<RwLock<T>>
234
+ build = build_module(tree, ctx, TypeMapper(ctx))
235
+ if project is not None:
236
+ project.index.modules[project.module] = export_symbols(ctx, build.module, project)
237
+ runtime = runtime_source() if cfg.vendor_runtime else None
238
+ text = render_module(build.module, path, runtime, cfg.set_type)
239
+ unformatted = False
240
+ if cfg.format:
241
+ depth = _closure_depth(tree)
242
+ if depth > MAX_FORMAT_CLOSURE_DEPTH: # rustfmt needs minutes for deeply nested closures
243
+ error = f"skipped: {depth} nested lambdas make rustfmt too slow"
244
+ else:
245
+ text, error = format_rust(text)
246
+ if error:
247
+ unformatted = True
248
+ col.diag("PY2RS031", None, f"rustfmt: {error}")
249
+ text, source_map = extract_markers(text, path)
250
+ todos = _finish_todos(col, text)
251
+ stats = {
252
+ k: build.stats.get(k, 0)
253
+ for k in (
254
+ "functions_total",
255
+ "functions_clean",
256
+ "models_total",
257
+ "models_clean",
258
+ "models_clean_modulo_int_range",
259
+ "module_init_effects",
260
+ "functions_clean_if_init_run",
261
+ "models_clean_if_init_run",
262
+ )
263
+ }
264
+ if unformatted: # the marker lines may not be where `todos` says: never count it clean
265
+ for key in ("functions_clean", "models_clean", "models_clean_modulo_int_range"):
266
+ stats[key] = 0
267
+ build.not_clean = tuple(sorted({_rust_name(ctx, n) for n in ctx.status}))
268
+ stats["todo_count"] = len(todos)
269
+ for t in todos:
270
+ stats[f"todo.{t.code}"] = stats.get(f"todo.{t.code}", 0) + 1
271
+ for d in col.diagnostics:
272
+ if d.severity == "info" and d.code in DRIFT_CODES:
273
+ stats[f"drift.{d.code}"] = stats.get(f"drift.{d.code}", 0) + 1
274
+ for (
275
+ root,
276
+ count,
277
+ ) in ctx.imports_unmapped.items(): # the histogram that drives the import/library map
278
+ stats[f"import.{root}"] = count
279
+ for missing, n in ctx.unresolved.items(): # project imports that did not resolve
280
+ stats[f"unresolved.{missing}"] = n
281
+ stats["escape_hatch.template"] = ctx.templates # user-supplied Rust text in the IR
282
+ for status in ("translated", "partial", "dropped"):
283
+ count = sum(1 for t in ctx.tests if t["status"] == status)
284
+ if count:
285
+ stats[f"test.{status}"] = count
286
+ stats["needs_review"] = sum(1 for d in col.diagnostics if d.code == "PY2RS030")
287
+ drift = tuple(
288
+ DriftEntry(code=d.code, file=d.file, line=d.line, message=d.message, construct=d.construct)
289
+ for d in col.diagnostics
290
+ if d.severity == "info" and d.code in DRIFT_CODES
291
+ )
292
+ return TranslateResult(
293
+ text,
294
+ tuple(col.diagnostics),
295
+ todos,
296
+ stats,
297
+ source_map,
298
+ tuple(dict.fromkeys(ctx.schemas)),
299
+ tuple(ctx.tests),
300
+ drift,
301
+ tuple(sorted(ctx.features)),
302
+ required_crates(text, ctx.features),
303
+ build.not_clean,
304
+ )
@@ -0,0 +1 @@
1
+ """Python frontend: module and project analysis, names, symbols, walrus hoisting."""