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,601 @@
1
+ """pytest / unittest / doctest -> Rust `#[test]` functions in `#[cfg(test)] mod tests`.
2
+
3
+ Stable test ids (the CLI maps a failing Rust test back to the Python test with these):
4
+
5
+ Python `<file>::<test>` `<file>::<Class>::<test>` `<file>::<fn> (doctest)`
6
+ Rust `tests::<test>` `tests::<class>_<test>` `tests::doctest_<fn>`
7
+
8
+ A `@pytest.mark.parametrize` row `i` becomes its own test: Python id `<file>::<test>[<i>]`, Rust
9
+ `tests::<test>_case_<i>` (the row index is the id; `pytest.param(..., id="x")` keeps `x` as a label
10
+ in `TestEntry.label`). Every translated test is a `TestEntry` in `TranslateResult.tests`, with
11
+ `status` `translated`, `partial` (contains a `todo!()`) or `dropped`. A dropped test is never
12
+ silent: it is an item TODO (PY2RS052) plus a `test.dropped` drift entry (PY2RS053), and a weakened
13
+ assertion (for example `pytest.raises(match=...)`) is a drift entry too.
14
+
15
+ Lowered shapes: `assert` -> `assert!`, `assert a == b` -> `assert_eq!` (`!=` -> `assert_ne!`),
16
+ `== pytest.approx(...)` -> `rt::approx_eq`, `with pytest.raises(E)` -> `rt::assert_raises("E", ..)`
17
+ (panics carry the Python exception class name), parametrize tables, simple fixtures (a single
18
+ `return <expr>`) inlined as `let`, `unittest.TestCase` assertion methods, and doctest examples with
19
+ literal expected values. Everything else (tmp_path, monkeypatch, capsys, mocks, async, marks such
20
+ as skip/xfail, setUp/tearDown) is dropped.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import ast
26
+ import doctest
27
+ import itertools
28
+ from collections.abc import Callable
29
+ from dataclasses import dataclass, field
30
+ from typing import TypedDict
31
+
32
+ from ..frontend.names import fn_name, snake
33
+ from ..ir import nodes as ir
34
+ from ..ir.rtypes import FLOAT, INT, UNIT, T
35
+ from ..ir.types import TypeMapper, dotted
36
+ from ..passes import ownership
37
+ from ..passes.analysis import analyze
38
+ from .context import Ctx
39
+ from .funcs import docstring, todo_item
40
+ from .lowerer import Unsupported
41
+ from .stmts import StmtLowerer
42
+
43
+ BUILTIN_FIXTURES = frozenset(
44
+ [
45
+ "tmp_path",
46
+ "tmp_path_factory",
47
+ "tmpdir",
48
+ "monkeypatch",
49
+ "capsys",
50
+ "capfd",
51
+ "caplog",
52
+ "request",
53
+ "mocker",
54
+ "pytestconfig",
55
+ "event_loop",
56
+ "anyio_backend",
57
+ ]
58
+ )
59
+ DROPPING_MARKS = frozenset({"skip", "skipif", "xfail", "asyncio", "anyio", "usefixtures"})
60
+ UNITTEST_ASSERTS = {
61
+ "assertEqual": "{0} == {1}", "assertEquals": "{0} == {1}", "assertNotEqual": "{0} != {1}",
62
+ "assertTrue": "{0}", "assertFalse": "not {0}", "assertIsNone": "{0} is None",
63
+ "assertIsNotNone": "{0} is not None", "assertIn": "{0} in {1}", "assertNotIn": "{0} not in {1}",
64
+ } # fmt: skip
65
+ SETUP_NAMES = frozenset({"setUp", "tearDown", "setUpClass", "tearDownClass", "asyncSetUp"})
66
+
67
+
68
+ class TestEntry(TypedDict):
69
+ py_id: str
70
+ py_file: str
71
+ py_line: int
72
+ rust_name: str
73
+ status: str # translated | partial | dropped
74
+ reason: str | None
75
+ label: str | None
76
+
77
+
78
+ @dataclass
79
+ class TestResult:
80
+ __test__ = False # not a pytest class
81
+
82
+ items: list[ir.Item] = field(default_factory=list)
83
+ entries: list[TestEntry] = field(default_factory=list)
84
+
85
+
86
+ def is_test_module(tree: ast.Module, path: str) -> bool:
87
+ stem = path.rsplit("/", 1)[-1].removesuffix(".py")
88
+ if stem.startswith("test_") or stem.endswith("_test"):
89
+ return True
90
+ for node in ast.walk(tree):
91
+ if isinstance(node, ast.Import | ast.ImportFrom):
92
+ names = [a.name for a in node.names] + [getattr(node, "module", "") or ""]
93
+ if any(n.split(".")[0] in ("pytest", "unittest") for n in names):
94
+ return True
95
+ return False
96
+
97
+
98
+ def _tail(node: ast.expr) -> str:
99
+ return dotted(node.func if isinstance(node, ast.Call) else node)
100
+
101
+
102
+ def is_fixture(node: ast.FunctionDef | ast.AsyncFunctionDef) -> bool:
103
+ return any(_tail(d).split(".")[-1] == "fixture" for d in node.decorator_list)
104
+
105
+
106
+ def is_test_function(node: ast.stmt) -> bool:
107
+ return isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef) and node.name.startswith("test")
108
+
109
+
110
+ def is_test_class(node: ast.stmt) -> bool:
111
+ if not isinstance(node, ast.ClassDef):
112
+ return False
113
+ bases = [dotted(b).split(".")[-1] for b in node.bases]
114
+ return node.name.startswith("Test") or "TestCase" in bases
115
+
116
+
117
+ def _ok_unit() -> ir.RExpr:
118
+ return ir.Call(func=ir.Path(path="Ok"), args=[ir.Lit(kind="unit")])
119
+
120
+
121
+ class TestLowerer(StmtLowerer):
122
+ """Statement lowering with test-shaped asserts, pytest.raises and unittest assertion methods."""
123
+
124
+ __test__ = False
125
+
126
+ def _approx(self, node: ast.expr) -> ast.Call | None:
127
+ if isinstance(node, ast.Call) and _tail(node).endswith("approx"):
128
+ return node
129
+ return None
130
+
131
+ def st_Assert(self, s: ast.Assert) -> list[ir.RStmt]:
132
+ test = s.test
133
+ msg = f"assert {ast.unparse(test)} ({self.ctx.col.file}:{s.lineno})"
134
+ if (
135
+ isinstance(test, ast.Compare)
136
+ and len(test.ops) == 1
137
+ and isinstance(test.ops[0], ast.Eq | ast.NotEq)
138
+ ):
139
+ left, right = test.left, test.comparators[0]
140
+ approx = self._approx(right) or self._approx(left)
141
+ if approx is not None:
142
+ actual = left if approx is right else right
143
+ return [
144
+ ir.ExprS(
145
+ self._approx_assert(
146
+ s, actual, approx, isinstance(test.ops[0], ast.NotEq), msg
147
+ )
148
+ )
149
+ ]
150
+ a, b = self.expr(left), self.expr(right)
151
+ none = [x for x in (a, b) if isinstance(x, ir.Lit) and x.kind == "none"]
152
+ if not none:
153
+ a, b = self._pair(a, b)
154
+ name = "assert_eq" if isinstance(test.ops[0], ast.Eq) else "assert_ne"
155
+ return [ir.ExprS(ir.Macro(name=name, args=[a, b], template=msg, ty=UNIT))]
156
+ return [ir.ExprS(ir.Macro(name="assert", args=[self.cond(test)], template=msg, ty=UNIT))]
157
+
158
+ def _approx_assert(
159
+ self, s: ast.Assert, actual: ast.expr, approx: ast.Call, negate: bool, msg: str
160
+ ) -> ir.RExpr:
161
+ kws = {k.arg: k.value for k in approx.keywords}
162
+ if len(approx.args) != 1 or set(kws) - {"rel", "abs"}:
163
+ raise Unsupported("PY2RS052", "pytest.approx with unsupported arguments", s)
164
+ a, e = self.expr(actual), self.expr(approx.args[0])
165
+ if {a.ty, e.ty} - {FLOAT, INT} or a.ty not in (FLOAT, INT):
166
+ raise Unsupported("PY2RS052", "pytest.approx of a non-scalar value", s)
167
+ rel = (
168
+ self.coerce(self.expr(kws["rel"]), FLOAT, promote=True)
169
+ if "rel" in kws
170
+ else ir.lit("float", 1e-6, FLOAT)
171
+ )
172
+ tol = (
173
+ self.coerce(self.expr(kws["abs"]), FLOAT, promote=True)
174
+ if "abs" in kws
175
+ else ir.lit("float", 1e-12, FLOAT)
176
+ )
177
+ ok = ir.rt(
178
+ "approx_eq",
179
+ self.coerce(a, FLOAT, promote=True),
180
+ self.coerce(e, FLOAT, promote=True),
181
+ rel,
182
+ tol,
183
+ ty=ir.UNKNOWN,
184
+ )
185
+ test = ir.Un(op="!", operand=ok, ty=ir.UNKNOWN) if negate else ok
186
+ return ir.Macro(name="assert", args=[test], template=msg, ty=UNIT)
187
+
188
+ # -- pytest.raises ---------------------------------------------------------------------
189
+ def stmt(self, s: ast.stmt, tail: bool) -> list[ir.RStmt]:
190
+ if (
191
+ isinstance(s, ast.With)
192
+ and len(s.items) == 1
193
+ and _tail(s.items[0].context_expr).endswith(("raises", "assertRaises"))
194
+ ):
195
+ return self._raises(s, s.items[0].context_expr)
196
+ return super().stmt(s, tail)
197
+
198
+ def _raises(self, s: ast.With, ctx_expr: ast.expr) -> list[ir.RStmt]:
199
+ assert isinstance(ctx_expr, ast.Call)
200
+ if s.items[0].optional_vars is not None or not ctx_expr.args:
201
+ raise Unsupported("PY2RS052", "pytest.raises(...) as excinfo / without an exception", s)
202
+ kind = dotted(ctx_expr.args[0]).split(".")[-1]
203
+ if any(k.arg == "match" for k in ctx_expr.keywords):
204
+ self.ctx.col.drift(
205
+ "PY2RS053", s, "pytest.raises(match=...): the message is not checked"
206
+ )
207
+ return [ir.ExprS(self._raises_call(kind, s, lambda: self.scoped(s.body, s.lineno)))]
208
+
209
+ def _raises_call(
210
+ self, kind: str, node: ast.AST, body: Callable[[], list[ir.RStmt]]
211
+ ) -> ir.RExpr:
212
+ """`rt::assert_raises(&KIND, || 'try: { body; Ok(()) })`: the body is lowered like a try body."""
213
+ kind_ref = self.kind_expr(kind, node)
214
+ label = f"try{self._next_label()}"
215
+ self.try_labels.append(label)
216
+ self.catch_stack.append({kind})
217
+ try:
218
+ stmts = body()
219
+ finally:
220
+ self.try_labels.pop()
221
+ self.catch_stack.pop()
222
+ done = ir.BlockX(stmts=stmts, tail=_ok_unit(), label=label)
223
+ return ir.rt("assert_raises", kind_ref, ir.Closure(params=[], body=done), ty=UNIT)
224
+
225
+ # -- unittest.TestCase methods -----------------------------------------------------------
226
+ def expr_Call(self, node: ast.Call) -> ir.RExpr:
227
+ f = node.func
228
+ if isinstance(f, ast.Attribute) and isinstance(f.value, ast.Name) and f.value.id == "self":
229
+ return self._unittest(node, f.attr)
230
+ if self._approx(node) is not None:
231
+ raise Unsupported("PY2RS052", "pytest.approx outside an assert", node)
232
+ return super().expr_Call(node)
233
+
234
+ def _unittest(self, node: ast.Call, name: str) -> ir.RExpr:
235
+ if name in UNITTEST_ASSERTS:
236
+ text = UNITTEST_ASSERTS[name].format(*[f"__a{i}" for i in range(len(node.args))])
237
+ return self._synth_assert(node, text, node.args)
238
+ if name == "assertAlmostEqual" and len(node.args) == 2:
239
+ places = next((k.value for k in node.keywords if k.arg == "places"), None)
240
+ delta = next((k.value for k in node.keywords if k.arg == "delta"), None)
241
+ if places is not None and not (
242
+ isinstance(places, ast.Constant) and isinstance(places.value, int)
243
+ ):
244
+ raise Unsupported("PY2RS052", "assertAlmostEqual with a computed places", node)
245
+ digits = 7
246
+ if isinstance(places, ast.Constant) and isinstance(places.value, int):
247
+ digits = places.value
248
+ tol = delta if delta is not None else ast.Constant(0.5 * 10.0**-digits)
249
+ approx = ast.Call(
250
+ func=ast.Name(id="approx"),
251
+ args=[node.args[1]],
252
+ keywords=[
253
+ ast.keyword(arg="abs", value=tol),
254
+ ast.keyword(arg="rel", value=ast.Constant(0.0)),
255
+ ],
256
+ )
257
+ cmp = ast.Compare(left=node.args[0], ops=[ast.Eq()], comparators=[approx])
258
+ return self._lower_assert(node, cmp)
259
+ if name in ("assertRaises", "assertRaisesRegex") and len(node.args) >= 2:
260
+ kind = dotted(node.args[0]).split(".")[-1]
261
+ call = ast.Call(func=node.args[1], args=node.args[2:], keywords=[])
262
+ ast.copy_location(call, node)
263
+ return self._raises_call(kind, node, lambda: [ir.ExprS(self.expr(call))])
264
+ raise Unsupported("PY2RS052", f"unittest method self.{name}()", node)
265
+
266
+ def _synth_assert(self, node: ast.Call, template: str, args: list[ast.expr]) -> ir.RExpr:
267
+ """Build `assert <template>` over the call's own argument expressions and lower it."""
268
+ names = {f"__a{i}": a for i, a in enumerate(args)}
269
+
270
+ class Fill(ast.NodeTransformer):
271
+ def visit_Name(self, node: ast.Name) -> ast.AST:
272
+ return names.get(node.id, node)
273
+
274
+ test = Fill().visit(ast.parse(template, mode="eval").body)
275
+ return self._lower_assert(node, test)
276
+
277
+ def _lower_assert(self, node: ast.Call, test: ast.expr) -> ir.RExpr:
278
+ assert_node = ast.Assert(test=test, msg=None)
279
+ ast.copy_location(assert_node, node)
280
+ ast.fix_missing_locations(assert_node)
281
+ stmt = self.st_Assert(assert_node)[0]
282
+ assert isinstance(stmt, ir.ExprS)
283
+ return stmt.expr
284
+
285
+
286
+ # -- driver ------------------------------------------------------------------------------
287
+ def _mark_names(fn: ast.FunctionDef | ast.AsyncFunctionDef) -> list[tuple[str, ast.expr]]:
288
+ out = []
289
+ for d in fn.decorator_list:
290
+ parts = _tail(d).split(".")
291
+ if "mark" in parts or parts[-1] in DROPPING_MARKS:
292
+ out.append((parts[-1], d))
293
+ return out
294
+
295
+
296
+ def _fixture_value(fn: ast.FunctionDef | ast.AsyncFunctionDef) -> ast.expr | None:
297
+ """The single expression a simple fixture returns (no parameters, no yield, no I/O)."""
298
+ if isinstance(fn, ast.AsyncFunctionDef) or fn.args.args or fn.args.kwonlyargs:
299
+ return None
300
+ _, body = docstring(fn.body)
301
+ if len(body) == 1 and isinstance(body[0], ast.Return) and body[0].value is not None:
302
+ return body[0].value
303
+ return None
304
+
305
+
306
+ class _Dropped(Exception):
307
+ pass
308
+
309
+
310
+ def _param_rows(
311
+ fn: ast.FunctionDef | ast.AsyncFunctionDef,
312
+ ) -> tuple[list[list[tuple[str, ast.expr]]], list[str | None]]:
313
+ """The parametrize rows (cartesian product over stacked decorators) as (name, value) lists."""
314
+ tables: list[list[tuple[list[tuple[str, ast.expr]], str | None]]] = []
315
+ for d in fn.decorator_list:
316
+ if not (isinstance(d, ast.Call) and _tail(d).endswith("parametrize") and len(d.args) >= 2):
317
+ continue
318
+ names_node, values = d.args[0], d.args[1]
319
+ if not (isinstance(names_node, ast.Constant) and isinstance(names_node.value, str)):
320
+ raise _Dropped("parametrize argnames are not a literal string")
321
+ names = [n.strip() for n in names_node.value.split(",") if n.strip()]
322
+ if not isinstance(values, ast.List | ast.Tuple):
323
+ raise _Dropped("parametrize values are not a literal list")
324
+ rows = []
325
+ for element in values.elts:
326
+ label = None
327
+ if isinstance(element, ast.Call) and _tail(element).endswith("param"):
328
+ label = next(
329
+ (
330
+ k.value.value
331
+ for k in element.keywords
332
+ if k.arg == "id" and isinstance(k.value, ast.Constant)
333
+ ),
334
+ None,
335
+ )
336
+ if any(k.arg == "marks" for k in element.keywords):
337
+ raise _Dropped("pytest.param with marks")
338
+ cells = list(element.args)
339
+ elif len(names) == 1:
340
+ cells = [element]
341
+ elif isinstance(element, ast.Tuple | ast.List) and len(element.elts) == len(names):
342
+ cells = list(element.elts)
343
+ else:
344
+ raise _Dropped("parametrize row does not match its argnames")
345
+ if len(cells) != len(names):
346
+ raise _Dropped("parametrize row does not match its argnames")
347
+ rows.append(
348
+ (list(zip(names, cells, strict=True)), str(label) if label is not None else None)
349
+ )
350
+ tables.append(rows)
351
+ if not tables:
352
+ return [[]], [None]
353
+ combos = list(itertools.product(*tables))
354
+ return [[cell for rows, _ in combo for cell in rows] for combo in combos], [
355
+ "-".join(lbl for _, lbl in combo if lbl) or None for combo in combos
356
+ ]
357
+
358
+
359
+ def lower_tests(
360
+ ctx: Ctx, mapper: TypeMapper, tree: ast.Module, path: str, test_module: bool
361
+ ) -> TestResult:
362
+ out = TestResult()
363
+ fixtures = {
364
+ n.name: n
365
+ for n in tree.body
366
+ if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef) and is_fixture(n)
367
+ }
368
+ for node in tree.body:
369
+ if test_module and is_test_function(node):
370
+ assert isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef)
371
+ _lower_one(ctx, mapper, node, fixtures, path, None, out)
372
+ elif test_module and is_test_class(node):
373
+ assert isinstance(node, ast.ClassDef)
374
+ _lower_class(ctx, mapper, node, fixtures, path, out)
375
+ elif isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef) and not is_fixture(node):
376
+ _lower_doctest(ctx, mapper, node, path, out)
377
+ return out
378
+
379
+
380
+ def _lower_class(
381
+ ctx: Ctx, mapper: TypeMapper, cls: ast.ClassDef, fixtures: dict, path: str, out: TestResult
382
+ ) -> None:
383
+ setup = [m.name for m in cls.body if isinstance(m, ast.FunctionDef) and m.name in SETUP_NAMES]
384
+ for m in cls.body:
385
+ if isinstance(m, ast.FunctionDef | ast.AsyncFunctionDef) and m.name.startswith("test"):
386
+ if setup:
387
+ _drop(
388
+ ctx,
389
+ m,
390
+ f"{snake(cls.name)}_{m.name}",
391
+ f"{path}::{cls.name}::{m.name}",
392
+ f"class defines {setup[0]}",
393
+ path,
394
+ out,
395
+ )
396
+ else:
397
+ _lower_one(ctx, mapper, m, fixtures, path, cls.name, out)
398
+
399
+
400
+ def _drop(
401
+ ctx: Ctx, node: ast.AST, rust: str, py_id: str, reason: str, path: str, out: TestResult
402
+ ) -> None:
403
+ out.items.append(todo_item(ctx, "PY2RS052", node, f"test {py_id} dropped: {reason}", "test"))
404
+ ctx.col.drift("PY2RS053", node, f"test.dropped {py_id}: {reason}")
405
+ out.entries.append(
406
+ TestEntry(
407
+ py_id=py_id,
408
+ py_file=path,
409
+ py_line=getattr(node, "lineno", 0),
410
+ rust_name=rust,
411
+ status="dropped",
412
+ reason=reason,
413
+ label=None,
414
+ )
415
+ )
416
+
417
+
418
+ def _lower_one(
419
+ ctx: Ctx,
420
+ mapper: TypeMapper,
421
+ fn: ast.FunctionDef | ast.AsyncFunctionDef,
422
+ fixtures: dict,
423
+ path: str,
424
+ cls: str | None,
425
+ out: TestResult,
426
+ ) -> None:
427
+ base = fn_name(fn.name) if cls is None else f"{snake(cls)}_{fn_name(fn.name)}"
428
+ py_base = f"{path}::{fn.name}" if cls is None else f"{path}::{cls}::{fn.name}"
429
+ try:
430
+ if isinstance(fn, ast.AsyncFunctionDef):
431
+ raise _Dropped("async test")
432
+ marks = [n for n, _ in _mark_names(fn) if n in DROPPING_MARKS]
433
+ if marks:
434
+ raise _Dropped(f"mark {marks[0]}")
435
+ rows, labels = _param_rows(fn)
436
+ params = [
437
+ a.arg
438
+ for a in fn.args.posonlyargs + fn.args.args + fn.args.kwonlyargs
439
+ if a.arg != "self"
440
+ ]
441
+ bound = {name for row in rows[:1] for name, _ in row}
442
+ needed = [p for p in params if p not in bound]
443
+ for p in needed:
444
+ if p in BUILTIN_FIXTURES:
445
+ raise _Dropped(f"fixture {p}")
446
+ if p not in fixtures or _fixture_value(fixtures[p]) is None:
447
+ raise _Dropped(f"fixture {p} is not a single-expression fixture")
448
+ extra = bound - set(params)
449
+ if extra:
450
+ raise _Dropped(f"parametrize names {sorted(extra)[0]} are not test parameters")
451
+ except _Dropped as why:
452
+ _drop(ctx, fn, base, py_base, str(why), path, out)
453
+ return
454
+ for i, (row, label) in enumerate(zip(rows, labels, strict=True)):
455
+ suffix = f"_case_{i}" if len(rows) > 1 or row else ""
456
+ py_id = f"{py_base}[{i}]" if suffix else py_base
457
+ lets = [(p, _fixture_value(fixtures[p])) for p in needed] + [(n, v) for n, v in row]
458
+ fn_ir, status = _build(ctx, mapper, fn, base + suffix, lets)
459
+ out.items.append(fn_ir)
460
+ out.entries.append(
461
+ TestEntry(
462
+ py_id=py_id,
463
+ py_file=path,
464
+ py_line=fn.lineno,
465
+ rust_name=fn_ir.name,
466
+ status=status,
467
+ reason=None,
468
+ label=label,
469
+ )
470
+ )
471
+
472
+
473
+ def _build(
474
+ ctx: Ctx,
475
+ mapper: TypeMapper,
476
+ fn: ast.FunctionDef | ast.AsyncFunctionDef,
477
+ rust: str,
478
+ lets: list[tuple[str, ast.expr | None]],
479
+ ) -> tuple[ir.Function, str]:
480
+ before = len(ctx.col.todos)
481
+ ana = analyze(fn, {p for p, _ in lets})
482
+ lw = TestLowerer(ctx, mapper, UNIT)
483
+ lw.fallible = True # a raising callee fails the test (`#[test]` fns may return Result)
484
+ lw.mutated, lw.hoist, lw.leaky = (
485
+ ana.mutated | {p for p, _ in lets if p in ana.reassigned},
486
+ ana.hoist,
487
+ ana.leaky_for,
488
+ )
489
+ lw.container_mut = ana.method_mut | ana.attr_mut
490
+ stmts: list[ir.RStmt] = []
491
+ with ctx.col.enclosing(rust):
492
+ for name, value in lets:
493
+ assert value is not None
494
+ try:
495
+ stmts += lw.bind(name, lw.expr(value))
496
+ except Unsupported as exc:
497
+ stmts += lw._failed(fn, exc.code, exc.construct, exc.node or fn, exc.hint)
498
+ doc, body = docstring(fn.body)
499
+ stmts += lw.block(body, after=body[0].lineno - 1 if body else fn.lineno)
500
+ decls = [
501
+ ir.Let(ir.PVar(v.rust, True), v.ty if v.ty.name != "?" else None, None)
502
+ for v in lw.hoisted.values()
503
+ ]
504
+ ok_unit = ir.Call(func=ir.Path(path="Ok"), args=[ir.Lit(kind="unit")])
505
+ func = ir.Function(
506
+ rust,
507
+ [],
508
+ T("Result", UNIT, T("rt::PyError")),
509
+ decls + stmts + [ir.Return(ok_unit, tail=True)],
510
+ doc,
511
+ "",
512
+ attrs=[ir.Attribute("test")],
513
+ span=ir.span_of(fn, ctx.col.file),
514
+ )
515
+ ownership.apply(func)
516
+ return func, "partial" if len(ctx.col.todos) > before else "translated"
517
+
518
+
519
+ def _literal_want(want: str) -> ast.expr | None:
520
+ try:
521
+ node = ast.parse(want.strip(), mode="eval").body
522
+ except SyntaxError:
523
+ return None
524
+ for n in ast.walk(node):
525
+ if not isinstance(
526
+ n,
527
+ ast.Constant
528
+ | ast.List
529
+ | ast.Tuple
530
+ | ast.Dict
531
+ | ast.Set
532
+ | ast.UnaryOp
533
+ | ast.USub
534
+ | ast.Load,
535
+ ):
536
+ return None
537
+ return node
538
+
539
+
540
+ def _lower_doctest(
541
+ ctx: Ctx,
542
+ mapper: TypeMapper,
543
+ fn: ast.FunctionDef | ast.AsyncFunctionDef,
544
+ path: str,
545
+ out: TestResult,
546
+ ) -> None:
547
+ doc = ast.get_docstring(fn) or ""
548
+ if ">>>" not in doc:
549
+ return
550
+ rust, py_id = f"doctest_{fn_name(fn.name)}", f"{path}::{fn.name} (doctest)"
551
+ body: list[ast.stmt] = []
552
+ try:
553
+ for ex in doctest.DocTestParser().get_examples(doc):
554
+ parsed = ast.parse(ex.source)
555
+ if ex.exc_msg is not None:
556
+ raise _Dropped("doctest expects an exception")
557
+ if len(parsed.body) == 1 and isinstance(parsed.body[0], ast.Expr) and ex.want.strip():
558
+ want = _literal_want(ex.want)
559
+ if want is None:
560
+ raise _Dropped(f"doctest output is not a literal: {ex.want.strip()[:30]}")
561
+ body.append(
562
+ ast.Assert(
563
+ test=ast.Compare(
564
+ left=parsed.body[0].value, ops=[ast.Eq()], comparators=[want]
565
+ ),
566
+ msg=None,
567
+ )
568
+ )
569
+ else:
570
+ body.extend(parsed.body)
571
+ except (_Dropped, SyntaxError) as why:
572
+ _drop(ctx, fn, rust, py_id, str(why), path, out)
573
+ return
574
+ for node in body:
575
+ ast.fix_missing_locations(node)
576
+ for n in ast.walk(node):
577
+ if isinstance(n, ast.stmt | ast.expr):
578
+ n.lineno, n.end_lineno, n.col_offset, n.end_col_offset = fn.lineno, fn.lineno, 0, 0
579
+ holder = ast.FunctionDef(
580
+ name=rust,
581
+ args=fn.args.__class__(posonlyargs=[], args=[], kwonlyargs=[], kw_defaults=[], defaults=[]),
582
+ body=body or [ast.Pass()],
583
+ decorator_list=[],
584
+ lineno=fn.lineno,
585
+ col_offset=0,
586
+ end_lineno=fn.lineno,
587
+ end_col_offset=0,
588
+ )
589
+ func, status = _build(ctx, mapper, holder, rust, [])
590
+ out.items.append(func)
591
+ out.entries.append(
592
+ TestEntry(
593
+ py_id=py_id,
594
+ py_file=path,
595
+ py_line=fn.lineno,
596
+ rust_name=rust,
597
+ status=status,
598
+ reason=None,
599
+ label=None,
600
+ )
601
+ )