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,409 @@
1
+ """`python2rust plan`: porting units in dependency order. Static analysis only (`ast`, never import).
2
+
3
+ Modules become nodes of the import graph; strongly connected components (import cycles) become one
4
+ unit; units are ordered leaves first and, within a level, easy first.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ast
10
+ import hashlib
11
+ import re
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from python2rust import __version__
17
+ from python2rust._core import core_name
18
+ from python2rust.cli import inputs, ops
19
+ from python2rust.errors import SCHEMA_VERSION, UsageError
20
+ from python2rust.workflow import layout
21
+ from python2rust.workflow.interview import review_patterns as default_patterns
22
+ from python2rust.workflow.staticscan import ModuleFacts, scan
23
+
24
+ _TEST_FILE = re.compile(r"^(test_.+|.+_test)\.py$")
25
+ _TEST_DIRS = {"tests", "test"}
26
+
27
+
28
+ @dataclass
29
+ class Mod:
30
+ name: str
31
+ rel: str # posix path below the project root
32
+ text: str
33
+ tree: ast.Module
34
+ is_pkg: bool
35
+ facts: ModuleFacts
36
+
37
+
38
+ @dataclass
39
+ class TestFile:
40
+ rel: str
41
+ names: set[str]
42
+
43
+
44
+ def _chain(base: Path) -> list[str]:
45
+ """Package names of `base` and its parents while they hold an __init__.py (outermost first)."""
46
+ out: list[str] = []
47
+ while (base / "__init__.py").exists() and base != base.parent:
48
+ out.append(base.name)
49
+ base = base.parent
50
+ return out[::-1]
51
+
52
+
53
+ def dotted_name(file: Path, base: Path) -> tuple[str, bool]:
54
+ parts = list(file.relative_to(base).with_suffix("").parts)
55
+ is_pkg = parts[-1] == "__init__"
56
+ if is_pkg:
57
+ parts.pop()
58
+ return ".".join([*_chain(base), *parts]), is_pkg
59
+
60
+
61
+ def _base_of(path: Path) -> Path:
62
+ return path if path.is_dir() else path.parent
63
+
64
+
65
+ def _import_targets(
66
+ imports: list[tuple[str, int, tuple[str, ...]]], name: str, is_pkg: bool, known: set[str]
67
+ ) -> set[str]:
68
+ """Known module names a module depends on. `from pkg import sub` depends on `pkg.sub` only."""
69
+ out: set[str] = set()
70
+ pkg = name if is_pkg else name.rpartition(".")[0]
71
+ for module, level, names in imports:
72
+ if level:
73
+ anchor = pkg
74
+ for _ in range(level - 1):
75
+ anchor = anchor.rpartition(".")[0]
76
+ module = f"{anchor}.{module}" if module and anchor else (module or anchor)
77
+ if not names: # `import a.b.c`: the deepest known prefix
78
+ parts = module.split(".")
79
+ hit = next(
80
+ (p for i in range(len(parts), 0, -1) if (p := ".".join(parts[:i])) in known), None
81
+ )
82
+ if hit:
83
+ out.add(hit)
84
+ continue
85
+ subs = {f"{module}.{n}" if module else n for n in names} & known
86
+ out |= subs
87
+ if module in known and len(subs) < len(names):
88
+ out.add(module)
89
+ out.discard(name)
90
+ return out
91
+
92
+
93
+ # --- discovery ----------------------------------------------------------------------------------
94
+
95
+
96
+ def _read_tree(src: inputs.Source) -> tuple[ast.Module | None, str | None]:
97
+ if src.text is None:
98
+ return None, src.read_error
99
+ try:
100
+ return ast.parse(src.text, filename=src.display), None
101
+ except (SyntaxError, ValueError) as exc:
102
+ return None, f"cannot parse: {exc}"
103
+
104
+
105
+ def discover(
106
+ root: Path, scope: list[Path], keep: list[str]
107
+ ) -> tuple[dict[str, Mod], list[TestFile], list[str], list[dict[str, str]], list[str]]:
108
+ """(modules in scope, test files, kept-Python module names, unparsable files, warnings)."""
109
+ mods: dict[str, Mod] = {}
110
+ unparsable: list[dict[str, str]] = []
111
+ roots, warnings = layout.source_roots(root)
112
+ for path in scope:
113
+ if not path.resolve().is_relative_to(root):
114
+ raise UsageError(f"{path} is outside the project root {root}")
115
+ scope_base = _base_of(path.resolve())
116
+ for src in inputs.collect([str(path)]):
117
+ file = Path(src.display).resolve()
118
+ base = layout.base_for(file, roots, scope_base)
119
+ rel = file.relative_to(root)
120
+ if (
121
+ _TEST_FILE.match(file.name)
122
+ or file.name == "conftest.py"
123
+ or _TEST_DIRS & set(rel.parts[:-1])
124
+ ):
125
+ continue
126
+ tree, err = _read_tree(src)
127
+ if tree is None or src.text is None:
128
+ unparsable.append({"file": rel.as_posix(), "error": err or "unreadable"})
129
+ continue
130
+ name, is_pkg = dotted_name(file, base)
131
+ if name in mods:
132
+ warnings.append(
133
+ f"module {name!r} found twice; keeping {mods[name].rel}, ignoring {rel.as_posix()}"
134
+ )
135
+ continue
136
+ mods[name] = Mod(name, rel.as_posix(), src.text, tree, is_pkg, ModuleFacts())
137
+ local = frozenset(n.partition(".")[0] for n in mods)
138
+ for m in mods.values():
139
+ m.facts = scan(m.tree, m.text, local)
140
+ kept = sorted(n for n, m in mods.items() if any(_keeps(k, n, m.rel) for k in keep))
141
+ tests = _find_tests(root, set(mods))
142
+ return mods, tests, kept, unparsable, warnings
143
+
144
+
145
+ def _keeps(entry: str, name: str, rel: str) -> bool:
146
+ e = entry.strip().strip("/")
147
+ return bool(e) and (
148
+ name == e
149
+ or name.startswith(e + ".")
150
+ or rel == e
151
+ or rel.startswith(e + "/")
152
+ or rel == e + ".py"
153
+ )
154
+
155
+
156
+ def _find_tests(root: Path, known: set[str]) -> list[TestFile]:
157
+ try:
158
+ sources = inputs.collect([str(root)])
159
+ except UsageError:
160
+ return []
161
+ out: list[TestFile] = []
162
+ for src in sources:
163
+ file = Path(src.display).resolve()
164
+ if not _TEST_FILE.match(file.name):
165
+ continue
166
+ tree, _ = _read_tree(src)
167
+ if tree is None:
168
+ continue
169
+ base = file.parent
170
+ while (base / "__init__.py").exists() and base != root:
171
+ base = base.parent
172
+ name, is_pkg = dotted_name(file, base)
173
+ imports = scan(tree, src.text or "").imports
174
+ out.append(
175
+ TestFile(
176
+ file.relative_to(root).as_posix(),
177
+ _import_targets(imports, name, is_pkg, known),
178
+ )
179
+ )
180
+ return sorted(out, key=lambda t: t.rel)
181
+
182
+
183
+ # --- graph --------------------------------------------------------------------------------------
184
+
185
+
186
+ def tarjan(graph: dict[str, set[str]]) -> list[list[str]]:
187
+ """Strongly connected components, dependencies first (iterative, so deep graphs are safe)."""
188
+ index: dict[str, int] = {}
189
+ low: dict[str, int] = {}
190
+ stack: list[str] = []
191
+ on: set[str] = set()
192
+ out: list[list[str]] = []
193
+ for start in sorted(graph):
194
+ if start in index:
195
+ continue
196
+ work = [(start, iter(sorted(graph[start])))]
197
+ index[start] = low[start] = len(index)
198
+ stack.append(start)
199
+ on.add(start)
200
+ while work:
201
+ node, it = work[-1]
202
+ for nxt in it:
203
+ if nxt not in index:
204
+ index[nxt] = low[nxt] = len(index)
205
+ stack.append(nxt)
206
+ on.add(nxt)
207
+ work.append((nxt, iter(sorted(graph[nxt]))))
208
+ break
209
+ if nxt in on:
210
+ low[node] = min(low[node], index[nxt])
211
+ else:
212
+ work.pop()
213
+ if work:
214
+ parent = work[-1][0]
215
+ low[parent] = min(low[parent], low[node])
216
+ if low[node] == index[node]:
217
+ comp = []
218
+ while True:
219
+ w = stack.pop()
220
+ on.discard(w)
221
+ comp.append(w)
222
+ if w == node:
223
+ break
224
+ out.append(sorted(comp))
225
+ return out
226
+
227
+
228
+ def unit_id(names: list[str]) -> str:
229
+ return (
230
+ names[0]
231
+ if len(names) == 1
232
+ else "+".join(names)
233
+ if len(names) <= 3
234
+ else f"{names[0]}+{len(names) - 1}more"
235
+ )
236
+
237
+
238
+ # --- scoring ------------------------------------------------------------------------------------
239
+
240
+
241
+ def difficulty(u: dict[str, Any]) -> dict[str, Any]:
242
+ cov, risk = u["coverage"], u["risk"]
243
+ parts: list[tuple[int, str]] = [
244
+ (min(20, u["size"]["lines"] // 40), f"{u['size']['lines']} lines")
245
+ ]
246
+ if cov["no_todo_pct"] is not None and cov["no_todo_pct"] < 100:
247
+ miss = round(100 - cov["no_todo_pct"])
248
+ parts.append((miss * 3 // 10, f"{miss}% of the estimated functions need hand work"))
249
+ if u["async_functions"]:
250
+ parts.append((8, f"{u['async_functions']} async function(s)"))
251
+ if u["try_blocks"] or u["exception_classes"]:
252
+ n = min(10, 2 * u["try_blocks"] + 2 * len(u["exception_classes"]))
253
+ parts.append(
254
+ (
255
+ n,
256
+ f"exceptions: {u['try_blocks']} try block(s), {len(u['exception_classes'])} exception class(es)",
257
+ )
258
+ )
259
+ if risk["dynamic"]:
260
+ parts.append(
261
+ (min(20, 7 * len(risk["dynamic"])), "dynamic features: " + ", ".join(risk["dynamic"]))
262
+ )
263
+ if risk["io"]:
264
+ parts.append((min(9, 3 * len(risk["io"])), "I/O: " + ", ".join(risk["io"])))
265
+ if risk["areas"]:
266
+ parts.append((min(12, 4 * len(risk["areas"])), "review areas: " + ", ".join(risk["areas"])))
267
+ if risk["cycle"]:
268
+ parts.append((10, f"import cycle of {len(u['modules'])} modules"))
269
+ if u["depends_on_python"]:
270
+ parts.append((6, "imports Python that stays Python: " + ", ".join(u["depends_on_python"])))
271
+ score = min(100, sum(n for n, _ in parts))
272
+ level = "easy" if score < 25 else "medium" if score < 55 else "hard"
273
+ return {"score": score, "level": level, "reasons": [r for n, r in parts if n > 0]}
274
+
275
+
276
+ # --- the plan -----------------------------------------------------------------------------------
277
+
278
+
279
+ def _patterns(config: Any, areas: list[str]) -> list[re.Pattern[str]]:
280
+ raw = getattr(config, "review_patterns", None) or default_patterns(areas)
281
+ out = []
282
+ for p in raw if isinstance(raw, list | tuple) else ():
283
+ if isinstance(p, str):
284
+ try:
285
+ out.append(re.compile(p))
286
+ except re.error:
287
+ continue
288
+ return out
289
+
290
+
291
+ def _coverage(
292
+ mods: list[Mod], entries: dict[str, dict[str, Any]], pats: list[re.Pattern[str]]
293
+ ) -> tuple[dict[str, Any], list[str]]:
294
+ keys = ("functions_total", "functions_clean", "models_total", "models_clean", "todo_count")
295
+ tot = dict.fromkeys(keys, 0)
296
+ review: list[dict[str, Any]] = []
297
+ errors: list[str] = []
298
+ for m in mods:
299
+ e = entries[m.rel]
300
+ for k in keys:
301
+ tot[k] += e["stats"].get(k, 0)
302
+ if e["status"] in ("error", "internal_error"):
303
+ errors.append(f"{m.rel}: {e['error'] or 'translation failed'}")
304
+ review += [
305
+ {
306
+ "id": t["id"],
307
+ "file": m.rel,
308
+ "line": t["line"],
309
+ "kind": t["kind"],
310
+ "reason": t["review_reason"],
311
+ }
312
+ for t in e["todos"]
313
+ if t["needs_review"]
314
+ ]
315
+ whole = tot["functions_total"] + tot["models_total"]
316
+ pct = (
317
+ round(100.0 * (tot["functions_clean"] + tot["models_clean"]) / whole, 1) if whole else None
318
+ )
319
+ cov = {
320
+ "functions_total": tot["functions_total"], "functions_no_todo": tot["functions_clean"],
321
+ "models_total": tot["models_total"], "models_no_todo": tot["models_clean"],
322
+ "todo_count": tot["todo_count"], "no_todo_pct": pct,
323
+ "needs_review_todos": sorted(review, key=lambda r: (r["file"], r["line"], r["id"])),
324
+ "translate_errors": errors,
325
+ } # fmt: skip
326
+ hits = sorted({p.pattern for m in mods for p in pats if p.search(m.text)})
327
+ return cov, hits
328
+
329
+
330
+ def build_plan(
331
+ root: Path, scope: list[Path], answers: dict[str, Any], config_path: str | None
332
+ ) -> dict[str, Any]:
333
+ """The plan document for `scope` (paths below `root`); writes nothing."""
334
+ mods, tests, kept, unparsable, warnings = discover(root, scope, answers.get("keep_python", []))
335
+ in_scope = {n: m for n, m in mods.items() if n not in kept}
336
+ known = set(mods)
337
+ deps = {n: _import_targets(m.facts.imports, n, m.is_pkg, known) for n, m in mods.items()}
338
+ graph = {n: deps[n] - set(kept) for n in in_scope}
339
+ comps = tarjan(graph)
340
+ comp_of = {n: i for i, c in enumerate(comps) for n in c}
341
+ entries = {
342
+ e["file"]: e
343
+ for e in ops.run_translate(
344
+ [inputs.Source(m.rel, Path(m.rel).name, m.text) for m in in_scope.values()],
345
+ config_path, fmt=False, project=None,
346
+ )
347
+ } # fmt: skip
348
+ config = ops.load_config(config_path, fmt=False)
349
+ pats = _patterns(config, answers.get("review_areas", []))
350
+ wanted_areas = set(answers.get("review_areas", [])) if "review_areas" in answers else None
351
+ levels: list[int] = []
352
+ units: list[dict[str, Any]] = []
353
+ for i, comp in enumerate(comps):
354
+ ms = [in_scope[n] for n in comp]
355
+ dep_idx = {comp_of[d] for n in comp for d in graph[n]} - {i}
356
+ levels.append(1 + max((levels[j] for j in dep_idx), default=-1))
357
+ cov, hits = _coverage(ms, entries, pats)
358
+ f = [m.facts for m in ms]
359
+ areas = sorted({a for x in f for a in x.areas if wanted_areas is None or a in wanted_areas})
360
+ names = set(comp)
361
+ u: dict[str, Any] = {
362
+ "id": unit_id(comp), "level": levels[i], "modules": comp,
363
+ "files": sorted(m.rel for m in ms),
364
+ "depends_on": sorted(unit_id(comps[j]) for j in dep_idx),
365
+ "depends_on_python": sorted({d for n in comp for d in deps[n] if d in kept}),
366
+ "size": {
367
+ "lines": sum(x.lines for x in f), "functions": sum(x.functions for x in f),
368
+ "classes": sum(x.classes for x in f),
369
+ },
370
+ "async_functions": sum(x.async_functions for x in f),
371
+ "try_blocks": sum(x.try_blocks for x in f),
372
+ "except_handlers": sum(x.except_handlers for x in f),
373
+ "exception_classes": sorted({c for x in f for c in x.exception_classes}),
374
+ "third_party": sorted({t for x in f for t in x.third_party}),
375
+ "stdlib": sorted({t for x in f for t in x.stdlib}),
376
+ "tests": sorted(t.rel for t in tests if t.names & names),
377
+ "coverage": cov,
378
+ "risk": {
379
+ "areas": areas, "dynamic": sorted({d for x in f for d in x.dynamic}),
380
+ "io": sorted({d for x in f for d in x.io}), "review_pattern_hits": hits,
381
+ "cycle": len(comp) > 1,
382
+ },
383
+ } # fmt: skip
384
+ u["difficulty"] = difficulty(u)
385
+ units.append(u)
386
+ units.sort(key=lambda u: (u["level"], u["difficulty"]["score"], u["id"]))
387
+ for n, u in enumerate(units, 1):
388
+ u["order"] = n
389
+ pct = [u["coverage"]["no_todo_pct"] for u in units if u["coverage"]["no_todo_pct"] is not None]
390
+ return {
391
+ "schema_version": SCHEMA_VERSION, "command": "plan", "version": __version__,
392
+ "ok": not unparsable,
393
+ "sources": sorted(p.resolve().relative_to(root).as_posix() or "." for p in scope),
394
+ "core": {"name": core_name()},
395
+ "summary": {
396
+ "modules": len(in_scope), "units": len(units),
397
+ "cycles": sum(len(c) > 1 for c in comps), "files_unparsable": len(unparsable),
398
+ "tests_found": sum(bool(u["tests"]) for u in units), "kept_python": len(kept),
399
+ "estimated_no_todo_pct": round(sum(pct) / len(pct), 1) if pct else None,
400
+ },
401
+ "cycles": [c for c in comps if len(c) > 1],
402
+ "order": [u["id"] for u in units], "units": units,
403
+ "kept_python": kept, "unparsable": unparsable,
404
+ "third_party": sorted({t for u in units for t in u["third_party"]}),
405
+ "files_sha256": {
406
+ m.rel: hashlib.sha256(m.text.encode()).hexdigest() for m in sorted(in_scope.values(), key=lambda m: m.rel)
407
+ },
408
+ "warnings": warnings,
409
+ } # fmt: skip
@@ -0,0 +1,134 @@
1
+ """The project a workflow unit belongs to: every module of the plan (and its tests) as one translation.
2
+
3
+ A unit is never ported, fixed or judged alone. Translated alone, `shop/pricing.py` becomes `src/pricing.rs`
4
+ and `from shop.pricing import net` in a sibling is an unknown function; translated with its project it
5
+ is `crate::shop::pricing::net`. So `port`, `todos`, `verify`, `apply` and `done` all translate the whole
6
+ plan together (`--unit UNIT` on the CLI) and only narrow what they repair or report to the unit's files.
7
+
8
+ The core names a module from its path below the directory it is given. A source tree such as
9
+ `src/shop/cart.py` (named `shop.cart` by the plan) and its tests (`tests/test_cart.py`, which import
10
+ `shop.cart`) do not sit under one directory, so the sources are laid out in a scratch directory under
11
+ their module names for the core to read. Nothing but the core's input lives there: every result is
12
+ named after the real project-relative file.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import ast
18
+ import tempfile
19
+ from collections.abc import Generator
20
+ from contextlib import contextmanager
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ from python2rust.cli.inputs import Source
26
+ from python2rust.errors import UsageError
27
+ from python2rust.verify import testrun
28
+ from python2rust.workflow import layout, planner
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class UnitScope:
33
+ """All sources of the plan (modules and tests, sorted by display name) and the unit's own files."""
34
+
35
+ root: Path
36
+ unit: dict[str, Any]
37
+ sources: list[Source]
38
+ own: frozenset[str]
39
+
40
+
41
+ def is_blank(text: str) -> bool:
42
+ """True for a module with no code: empty, comments only, or just a docstring."""
43
+ try:
44
+ body = ast.parse(text).body
45
+ except SyntaxError:
46
+ return False
47
+ return all(isinstance(n, ast.Expr) and isinstance(n.value, ast.Constant) for n in body)
48
+
49
+
50
+ def unit_of(plan: dict[str, Any], unit_id: str) -> dict[str, Any]:
51
+ unit = next((u for u in plan["units"] if u["id"] == unit_id), None)
52
+ if unit is None:
53
+ known = ", ".join(plan["order"][:8]) + (" ..." if len(plan["order"]) > 8 else "")
54
+ raise UsageError(f"unknown unit {unit_id!r}; units in the plan: {known or 'none'}")
55
+ return unit
56
+
57
+
58
+ def module_files(root: Path, plan: dict[str, Any]) -> dict[str, str | None]:
59
+ """Every file of the plan -> where the core sees it (the module's own path, e.g. `shop/cart.py`).
60
+
61
+ None for a file with no module name (a top-level `__init__.py` outside any package): it is
62
+ translated on its own.
63
+ """
64
+ roots, _ = layout.source_roots(root)
65
+ scopes = sorted(
66
+ ((root / s).resolve() for s in plan["sources"]), key=lambda p: len(p.parts), reverse=True
67
+ )
68
+ out: dict[str, str | None] = {}
69
+ for unit in plan["units"]:
70
+ for rel in unit["files"]:
71
+ file = (root / rel).resolve()
72
+ scope = next((s for s in scopes if file.is_relative_to(s)), root)
73
+ base = layout.base_for(file, roots, scope if scope.is_dir() else scope.parent)
74
+ name, is_pkg = planner.dotted_name(file, base)
75
+ parts = name.split(".") if name else []
76
+ out[rel] = "/".join(parts) + ("/__init__.py" if is_pkg else ".py") if parts else None
77
+ return out
78
+
79
+
80
+ def _read(root: Path, rel: str) -> str:
81
+ try:
82
+ return (root / rel).read_text(encoding="utf-8")
83
+ except (OSError, UnicodeDecodeError) as exc:
84
+ raise UsageError(f"{rel} cannot be read ({exc}); re-run `python2rust plan`") from exc
85
+
86
+
87
+ @contextmanager
88
+ def open_unit(root: Path, plan: dict[str, Any], unit: dict[str, Any]) -> Generator[UnitScope]:
89
+ """The scope of `unit`, valid inside the `with` (the scratch layout is removed afterwards)."""
90
+ files = module_files(root, plan)
91
+ tests = sorted({t for u in plan["units"] for t in u["tests"]})
92
+ with tempfile.TemporaryDirectory(prefix="python2rust-project-") as tmp:
93
+ layout_dir = Path(tmp)
94
+ sources: list[Source] = []
95
+ for rel, mrel in [*files.items(), *((t, t) for t in tests)]:
96
+ text = _read(root, rel)
97
+ if mrel is None: # no module name: translated on its own
98
+ sources.append(Source(rel, Path(rel).name, text))
99
+ continue
100
+ dest = layout_dir / mrel
101
+ if dest.exists(): # a test path a module already took: it cannot join the project
102
+ continue
103
+ dest.parent.mkdir(parents=True, exist_ok=True)
104
+ dest.write_text(text, encoding="utf-8")
105
+ sources.append(Source(rel, mrel, text, root=str(layout_dir)))
106
+ sources.sort(key=lambda s: s.display)
107
+ yield UnitScope(root, unit, sources, frozenset(unit["files"]))
108
+
109
+
110
+ def compile_scope(
111
+ sources: list[Source], entries: list[dict[str, Any]], own: frozenset[str]
112
+ ) -> list[int]:
113
+ """Indices (into `sources`/`entries`) of what must compile and run together to judge `own`.
114
+
115
+ The unit's files, the units they import (and what those import), and every test file that imports
116
+ the unit, with what that test imports. Units that merely use the unit are left out: they are not
117
+ ported yet and their own errors must not decide this unit's verdict.
118
+ """
119
+ by_name = {e["module"]["name"]: i for i, e in enumerate(entries) if e.get("module")}
120
+
121
+ def deps(i: int) -> set[int]:
122
+ mod = entries[i].get("module")
123
+ return {by_name[d] for d in mod["depends_on"] if d in by_name} if mod else set()
124
+
125
+ seed = {i for i, s in enumerate(sources) if s.display in own}
126
+ need = seed | {
127
+ i for i, s in enumerate(sources) if testrun.is_test_file(s.display) and deps(i) & seed
128
+ }
129
+ todo = list(need)
130
+ while todo:
131
+ for j in deps(todo.pop()) - need:
132
+ need.add(j)
133
+ todo.append(j)
134
+ return [i for i in sorted(need) if entries[i]["rust"]]