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,561 @@
1
+ """The only place Rust text is produced: IR -> source, plus source-map marker handling.
2
+
3
+ Each statement/item with a Python span is preceded by a `//@py <line> <end> <item>` marker line.
4
+ Markers survive rustfmt, then `extract_markers` strips them and records the final line numbers.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import re
11
+ from typing import TypedDict
12
+
13
+ from ..diagnostics import rust_escape
14
+ from ..ir import nodes as ir
15
+ from .schema import operation_attr
16
+
17
+ MARK = "//@py "
18
+ HEADER = "// Generated by python2rust from {path}. Review every todo!() before use."
19
+ ALLOW = "#![allow(unused, unreachable_code, non_camel_case_types)]"
20
+ PREC = {
21
+ "||": 15, "&&": 20, "==": 30, "!=": 30, "<": 30, "<=": 30, ">": 30, ">=": 30,
22
+ "|": 40, "^": 45, "&": 50, "<<": 55, ">>": 55, "+": 60, "-": 60, "*": 70, "/": 70, "%": 70,
23
+ } # fmt: skip
24
+ UNARY, CAST, POSTFIX, LOOSE = 90, 80, 100, 5
25
+ AUTO_USES = (
26
+ (r"\brt::", "use python2rust_rt as rt;"),
27
+ (r"\bIndex(?:Map|Set)\b", None),
28
+ (r"\bLazyLock\b", "use std::sync::LazyLock;"),
29
+ (r"\b(?:Serialize|Deserialize)\b", "use serde::{Deserialize, Serialize};"),
30
+ (r"\b(?:ToSchema|IntoParams)\b", None),
31
+ )
32
+
33
+
34
+ def indent(lines: list[str], n: int = 1) -> list[str]:
35
+ return [(" " * n + line) if line else line for line in lines]
36
+
37
+
38
+ # -- expressions ------------------------------------------------------------------------
39
+ def _prec(e: ir.RExpr) -> int:
40
+ match e:
41
+ case ir.Bin():
42
+ return PREC[e.op]
43
+ case ir.Ref() if e.elide:
44
+ return _prec(e.operand)
45
+ case ir.Borrow() if not e.deref:
46
+ return POSTFIX
47
+ case ir.Un() | ir.Ref() | ir.Deref() | ir.Borrow():
48
+ return UNARY
49
+ case ir.Lit() if (
50
+ isinstance(e.value, int | float)
51
+ and not isinstance(e.value, bool)
52
+ and math.copysign(1, e.value) < 0 # also -0.0, which `-0.0_f64.abs()` would negate
53
+ ):
54
+ return UNARY
55
+ case ir.Path() if e.path.startswith("&"):
56
+ return UNARY
57
+ case ir.Cast():
58
+ return CAST
59
+ case ir.RangeX():
60
+ return 10
61
+ case ir.Question() if e.label is None:
62
+ return POSTFIX
63
+ case ir.Closure() | ir.IfX() | ir.BlockX() | ir.Question():
64
+ return LOOSE
65
+ case _:
66
+ return POSTFIX
67
+
68
+
69
+ def expr(e: ir.RExpr, need: int = 0) -> str:
70
+ text = _expr(e)
71
+ return f"({text})" if _prec(e) < need else text
72
+
73
+
74
+ def _lit(e: ir.Lit, suffix: bool = False) -> str:
75
+ v = e.value
76
+ suffix = suffix or e.suffixed
77
+ match e.kind:
78
+ case "int":
79
+ return f"{v}_i64" if suffix else str(v)
80
+ case "float" if isinstance(v, float | int):
81
+ if v != v:
82
+ return "f64::NAN"
83
+ if v in (float("inf"), float("-inf")):
84
+ return "f64::INFINITY" if v > 0 else "f64::NEG_INFINITY"
85
+ text = repr(v)
86
+ text = text if any(c in text for c in ".e") else text + ".0"
87
+ return f"{text}_f64" if suffix else text
88
+ case "bool":
89
+ return "true" if v else "false"
90
+ case "str":
91
+ return f'"{rust_escape(str(v))}"'
92
+ case "bytes":
93
+ return 'b"' + "".join(f"\\x{b:02x}" for b in (v if isinstance(v, bytes) else b"")) + '"'
94
+ case "none":
95
+ return "None"
96
+ case _:
97
+ return "()"
98
+
99
+
100
+ def _operand(e: ir.RExpr, need: int) -> str:
101
+ """Operands of binary operators: casts are always parenthesised (`a as f64 < b` is a parse error)."""
102
+ return f"({_expr(e)})" if isinstance(e, ir.Cast) or _prec(e) < need else _expr(e)
103
+
104
+
105
+ def _recv(e: ir.RExpr) -> str:
106
+ if isinstance(e, ir.Lit) and e.kind in ("int", "float"):
107
+ return _lit(e, suffix=True) if _prec(e) == POSTFIX else f"({_lit(e, True)})"
108
+ return expr(e, POSTFIX)
109
+
110
+
111
+ def _expr(e: ir.RExpr) -> str:
112
+ match e:
113
+ case ir.Lit():
114
+ return _lit(e)
115
+ case ir.Var():
116
+ return e.name
117
+ case ir.Path():
118
+ return e.path
119
+ case ir.Attr():
120
+ return f"{_recv(e.base)}.{e.name}"
121
+ case ir.Index():
122
+ return f"{expr(e.base, POSTFIX)}[{expr(e.index)}]"
123
+ case ir.Call():
124
+ return f"{expr(e.func, POSTFIX)}({', '.join(expr(a) for a in e.args)})"
125
+ case ir.Method():
126
+ fish = f"::<{e.turbofish.rust()}>" if e.turbofish else ""
127
+ return f"{_recv(e.recv)}.{e.name}{fish}({', '.join(expr(a) for a in e.args)})"
128
+ case ir.Macro():
129
+ return _macro(e)
130
+ case ir.Un():
131
+ return f"{e.op}{expr(e.operand, UNARY)}"
132
+ case ir.Bin():
133
+ p = PREC[e.op]
134
+ non_assoc = p == 30
135
+ return f"{_operand(e.left, p + non_assoc)} {e.op} {_operand(e.right, p + 1)}"
136
+ case ir.Cast():
137
+ return f"{expr(e.operand, CAST)} as {e.ty.rust()}"
138
+ case ir.Ref():
139
+ if e.elide:
140
+ return _expr(e.operand)
141
+ return f"&{'mut ' if e.mut else ''}{expr(e.operand, UNARY)}"
142
+ case ir.Deref():
143
+ return f"*{expr(e.operand, UNARY)}"
144
+ case ir.Borrow():
145
+ call = f"{expr(e.operand, POSTFIX)}.{'borrow_mut' if e.mut else 'borrow'}()"
146
+ return f"*{call}" if e.deref else call
147
+ case ir.Closure():
148
+ body = _expr(e.body) if not isinstance(e.body, ir.StructLit) else f"({_expr(e.body)})"
149
+ return f"{'move ' if e.move else ''}|{', '.join(pat(p) for p in e.params)}| {body}"
150
+ case ir.IfX():
151
+ return f"if {head(e.cond)} {{ {expr(e.then)} }} else {{ {expr(e.other)} }}"
152
+ case ir.BlockX():
153
+ lines = block_lines(e.stmts, "") + ([expr(e.tail)] if e.tail else [])
154
+ lbl = f"'{e.label}: " if e.label else ""
155
+ return lbl + "{\n" + "\n".join(indent(lines)) + "\n}"
156
+ case ir.Question():
157
+ if e.label is None:
158
+ return f"{expr(e.operand, POSTFIX)}?"
159
+ return f"match {head(e.operand)} {{ Ok(v) => v, Err(e) => break '{e.label} Err(e) }}"
160
+ case ir.TupleX():
161
+ inner = ", ".join(expr(x) for x in e.elems)
162
+ return f"({inner},)" if len(e.elems) == 1 else f"({inner})"
163
+ case ir.ArrayX():
164
+ return f"[{', '.join(expr(x) for x in e.elems)}]"
165
+ case ir.StructLit():
166
+ parts = [f"{n}: {expr(v)}" for n, v in e.fields]
167
+ if e.base is not None:
168
+ parts.append(f"..{expr(e.base)}")
169
+ return f"{e.name} {{ {', '.join(parts)} }}"
170
+ case ir.RangeX():
171
+ return f"{expr(e.lo, 11)}..{'=' if e.inclusive else ''}{expr(e.hi, 11)}"
172
+ case ir.CloneX():
173
+ return f"{_recv(e.operand)}.clone()"
174
+ case ir.Template():
175
+ return re.sub(
176
+ r"\{(\d+)\}",
177
+ lambda m: expr(e.args[int(m[1])], POSTFIX) if int(m[1]) < len(e.args) else "",
178
+ e.template,
179
+ )
180
+ case ir.TodoX():
181
+ return f'todo!("{rust_escape(e.marker)}")'
182
+ case ir.AwaitX():
183
+ return f"{expr(e.operand, POSTFIX)}.await"
184
+ case ir.YieldX():
185
+ return _unlowered("PY2RS027", "yield")
186
+ raise TypeError(f"cannot emit {type(e).__name__}")
187
+
188
+
189
+ def _unlowered(code: str, what: str) -> str:
190
+ """A 0.2 node nobody lowered into yet: an explicit TODO, never silently dropped."""
191
+ return f'todo!("python2rust {code}: {what} is not lowered yet")'
192
+
193
+
194
+ def _macro(e: ir.Macro) -> str:
195
+ args = [expr(a) for a in e.args]
196
+ match e.name:
197
+ case name if name.startswith("tracing::"):
198
+ tail = "".join(", " + a for a in args)
199
+ return f'{name}!("{rust_escape(e.template or "")}"{tail})'
200
+ case "format" | "println" | "panic" | "unreachable":
201
+ tail = "".join(", " + a for a in args)
202
+ return f'{e.name}!("{rust_escape(e.template or "")}"{tail})'
203
+ case "vec":
204
+ return f"vec![{', '.join(args)}]"
205
+ case "vec_repeat":
206
+ return f"vec![{args[0]}; {args[1]}]"
207
+ case "assert" | "assert_eq" | "assert_ne":
208
+ need = 1 if e.name == "assert" else 2
209
+ if e.template is not None: # a static message (test lowering)
210
+ text = rust_escape(e.template.replace("{", "{{").replace("}", "}}"))
211
+ msg = f', "{text}"'
212
+ else:
213
+ msg = f', "{{}}", {args[need]}' if len(args) > need else ""
214
+ return f"{e.name}!({', '.join(args[:need])}{msg})"
215
+ case "matches":
216
+ assert e.pat is not None
217
+ return f"matches!({args[0]}, {pat(e.pat)})"
218
+ case "json":
219
+ return f"serde_json::json!({args[0]})"
220
+ raise ValueError(e.name)
221
+
222
+
223
+ def _has_struct_lit(e: object) -> bool:
224
+ if isinstance(e, ir.StructLit):
225
+ return True
226
+ if isinstance(e, list):
227
+ return any(_has_struct_lit(x) for x in e)
228
+ if isinstance(e, ir.Expr):
229
+ return any(_has_struct_lit(v) for v in vars(e).values() if isinstance(v, (ir.Expr, list)))
230
+ return False
231
+
232
+
233
+ def head(e: ir.RExpr) -> str:
234
+ """An expression in an `if`/`while`/`for`/`match` head: struct literals need parentheses."""
235
+ text = expr(e)
236
+ return f"({text})" if _has_struct_lit(e) else text
237
+
238
+
239
+ def pat(p: ir.Pat) -> str:
240
+ match p:
241
+ case ir.PVar():
242
+ return f"{'mut ' if p.mut else ''}{p.name}"
243
+ case ir.PTuple():
244
+ inner = ", ".join(pat(x) for x in p.elems)
245
+ return f"({inner},)" if len(p.elems) == 1 else f"({inner})"
246
+ case ir.PWild():
247
+ return "_"
248
+ case ir.PExpr():
249
+ return expr(p.expr)
250
+ case ir.POr():
251
+ return " | ".join(pat(x) for x in p.alts)
252
+ case ir.PBind():
253
+ return f"{p.name} @ {pat(p.pat)}"
254
+ raise TypeError(type(p).__name__)
255
+
256
+
257
+ # -- statements -------------------------------------------------------------------------
258
+ def _marker(node: ir.Node, item: str) -> list[str]:
259
+ s = node.span
260
+ return [f"{MARK}{s.line} {s.end_line} {item}"] if s and item else []
261
+
262
+
263
+ def block_lines(stmts: list[ir.RStmt], item: str) -> list[str]:
264
+ out: list[str] = []
265
+ for s in stmts:
266
+ out += _marker(s, item) + stmt_lines(s, item)
267
+ return out
268
+
269
+
270
+ def _body(stmts: list[ir.RStmt], item: str) -> list[str]:
271
+ return indent(block_lines(stmts, item))
272
+
273
+
274
+ def stmt_lines(s: ir.RStmt, item: str) -> list[str]:
275
+ match s:
276
+ case ir.Let():
277
+ ty = f": {s.ty.rust()}" if s.ty and s.ty.name != "?" else ""
278
+ init = f" = {expr(s.init)}" if s.init is not None else ""
279
+ return [f"let {pat(s.pat)}{ty}{init};"]
280
+ case ir.Assign():
281
+ return [f"{expr(s.lhs)} {s.op} {expr(s.rhs)};"]
282
+ case ir.ExprS():
283
+ return [f"{expr(s.expr)};"]
284
+ case ir.Return():
285
+ if s.tail:
286
+ return [expr(s.value)] if s.value is not None else []
287
+ return [f"return {expr(s.value)};" if s.value is not None else "return;"]
288
+ case ir.Break():
289
+ label = f" '{s.label}" if s.label else ""
290
+ value = f" {expr(s.value)}" if s.value is not None else ""
291
+ return [f"break{label}{value};"]
292
+ case ir.Continue():
293
+ return ["continue;"]
294
+ case ir.IfS():
295
+ return _if(s, item)
296
+ case ir.WhileS():
297
+ return [f"while {head(s.cond)} {{", *_body(s.body, item), "}"]
298
+ case ir.LoopS():
299
+ return ["loop {", *_body(s.body, item), "}"]
300
+ case ir.ForS():
301
+ return [f"for {pat(s.pat)} in {head(s.iter)} {{", *_body(s.body, item), "}"]
302
+ case ir.MatchS():
303
+ arms: list[str] = []
304
+ for a in s.arms:
305
+ guard = f" if {expr(a.guard)}" if a.guard is not None else ""
306
+ arms += [f"{pat(a.pat)}{guard} => {{", *_body(a.body, item), "}"]
307
+ return [f"match {head(s.subject)} {{", *indent(arms), "}"]
308
+ case ir.TodoS():
309
+ return [f'todo!("{rust_escape(s.marker)}");']
310
+ case ir.CommentS():
311
+ return [f"// {s.text}".rstrip()]
312
+ case ir.TryS():
313
+ return [f"{_unlowered('PY2RS012', 'try/except')};"]
314
+ case ir.RaiseS():
315
+ return [f"{_unlowered('PY2RS024', 'raise')};"]
316
+ case ir.WithS():
317
+ return [f"{_unlowered('PY2RS025', 'with')};"]
318
+ raise TypeError(type(s).__name__)
319
+
320
+
321
+ def _if(s: ir.IfS, item: str) -> list[str]:
322
+ lines = [f"if {head(s.cond)} {{", *_body(s.then, item), "}"]
323
+ if s.other is None:
324
+ return lines
325
+ if len(s.other) == 1 and isinstance(s.other[0], ir.IfS):
326
+ rest = _if(s.other[0], item)
327
+ lines[-1] += " else " + rest[0]
328
+ return lines + rest[1:]
329
+ lines[-1] = "} else {"
330
+ return [*lines, *_body(s.other, item), "}"]
331
+
332
+
333
+ # -- items ------------------------------------------------------------------------------
334
+ def _value(v: ir.AttrValue) -> str:
335
+ if isinstance(v, bool):
336
+ return "true" if v else "false"
337
+ if isinstance(v, str):
338
+ return f'"{rust_escape(v)}"'
339
+ if isinstance(v, ir.Ident):
340
+ return v.name
341
+ if isinstance(v, tuple):
342
+ return "(" + ", ".join(f"{k} = {_value(x)}" for k, x in v) + ")"
343
+ if isinstance(v, int | float):
344
+ return repr(v)
345
+ return v.rust()
346
+
347
+
348
+ def attr_line(a: ir.Attribute) -> str:
349
+ args = ", ".join(
350
+ k if v is None else f"{k}{_value(v)}" if isinstance(v, tuple) else f"{k} = {_value(v)}"
351
+ for k, v in a.args
352
+ )
353
+ return f"#[{a.name}({args})]" if a.args else f"#[{a.name}]"
354
+
355
+
356
+ def _attrs(attrs: list[ir.Attribute]) -> list[str]:
357
+ return [attr_line(a) for a in attrs]
358
+
359
+
360
+ def _docs(doc: list[str], pad: str = "") -> list[str]:
361
+ return [f"{pad}/// {line}".rstrip() for line in doc]
362
+
363
+
364
+ def _struct(s: ir.Struct) -> list[str]:
365
+ out = [*_docs(s.doc), f"#[derive({', '.join(s.derives)})]", *_attrs(s.attrs)]
366
+ if s.tuple_inner is not None:
367
+ return [*out, f"{s.vis}struct {s.name}(pub {s.tuple_inner.rust()});"]
368
+ out.append(f"{s.vis}struct {s.name} {{")
369
+ for f in s.fields:
370
+ out += [
371
+ *indent(_marker(f, s.name) + _docs(f.doc) + _attrs(f.attrs)),
372
+ f" pub {f.name}: {f.ty.rust()},",
373
+ ]
374
+ return [*out, "}"]
375
+
376
+
377
+ def _enum(e: ir.EnumDef) -> list[str]:
378
+ out = [
379
+ *_docs(e.doc),
380
+ f"#[derive({', '.join(e.derives)})]",
381
+ *_attrs(e.attrs),
382
+ f"{e.vis}enum {e.name} {{",
383
+ ]
384
+ for v in e.variants:
385
+ out += indent(_docs(v.doc) + _attrs(v.attrs))
386
+ text = v.name + (f"({v.payload.rust()})" if v.payload else "")
387
+ out.append(f" {text}{f' = {v.discriminant}' if v.discriminant else ''},")
388
+ return [*out, "}"]
389
+
390
+
391
+ def _mod(m: ir.ModItem) -> list[str]:
392
+ body: list[str] = []
393
+ for item in m.items:
394
+ body += ([""] if body else []) + item_lines(item)
395
+ return [
396
+ *_attrs(m.attrs),
397
+ f"mod {m.name} {{",
398
+ *indent([*m.uses, *([""] if m.uses else []), *body]),
399
+ "}",
400
+ ]
401
+
402
+
403
+ def _rule(name: str, value: int | float | str | None) -> str:
404
+ if value is None:
405
+ return f"rt::pydantic::Rule::{name}"
406
+ if isinstance(value, str):
407
+ return f'rt::pydantic::Rule::{name}("{rust_escape(value)}")'
408
+ text = repr(float(value)) if name not in ("MinLength", "MaxLength") else str(int(value))
409
+ return f"rt::pydantic::Rule::{name}({text})"
410
+
411
+
412
+ def _validator(v: ir.Validator) -> list[str]:
413
+ head_line = f"pub fn {v.name}<'de, D: serde::Deserializer<'de>>(d: D) -> Result<{v.ty.rust()}, D::Error> {{"
414
+ rules = ", ".join(_rule(n, x) for n, x in v.rules)
415
+ return [head_line, f" rt::pydantic::field(d, &[{rules}])", "}"]
416
+
417
+
418
+ def _function(f: ir.Function) -> list[str]:
419
+ params = ", ".join(f"{'mut ' if p.mut else ''}{p.name}: {p.ty.rust()}" for p in f.params)
420
+ ret = f" -> {f.ret.rust()}" if f.ret.name != "()" else ""
421
+ head_line = f"{f.vis}{'async ' if f.is_async else ''}fn {f.name}({params}){ret} {{"
422
+ attr = [operation_attr(f.operation)] if f.operation is not None else []
423
+ return _docs(f.doc) + _attrs(f.attrs) + attr + [head_line, *_body(f.body, f.name), "}"]
424
+
425
+
426
+ def _const(c: ir.Const) -> list[str]:
427
+ out = _docs(c.doc)
428
+ if c.kind == "cell":
429
+ return [
430
+ *out,
431
+ f"{c.vis}static {c.name}: std::sync::OnceLock<{c.ty.rust()}> = {expr(c.value)};",
432
+ ]
433
+ if c.kind == "thread_static":
434
+ return [
435
+ *out,
436
+ f"thread_local! {{ {c.vis}static {c.name}: {c.ty.rust()} = {expr(c.value)}; }}",
437
+ ]
438
+ if c.kind == "static_plain":
439
+ return [*out, f"{c.vis}static {c.name}: {c.ty.rust()} = {expr(c.value)};"]
440
+ if c.kind == "static":
441
+ return [
442
+ *out,
443
+ f"{c.vis}static {c.name}: LazyLock<{c.ty.rust()}> = LazyLock::new(|| {expr(c.value)});",
444
+ ]
445
+ return [*out, f"{c.vis}const {c.name}: {c.ty.rust()} = {expr(c.value)};"]
446
+
447
+
448
+ def item_lines(item: ir.Item) -> list[str]:
449
+ name = getattr(item, "name", "")
450
+ body: list[str]
451
+ match item:
452
+ case ir.Struct():
453
+ body = _struct(item)
454
+ case ir.EnumDef():
455
+ body = _enum(item)
456
+ case ir.Function():
457
+ body = _function(item)
458
+ case ir.Const():
459
+ body = _const(item)
460
+ case ir.TypeAlias():
461
+ body = [f"{item.vis}type {item.name} = {item.target.rust()};"]
462
+ case ir.TodoItem():
463
+ ident = "".join(c if c.isalnum() else "_" for c in item.marker.split()[1])
464
+ body = [f'fn py2rs_todo_{ident}() {{ todo!("{rust_escape(item.marker)}") }}']
465
+ case ir.CommentItem():
466
+ body = list(item.lines)
467
+ case ir.Validator():
468
+ body = _validator(item)
469
+ case ir.WireImpl():
470
+ names = ", ".join(item.fields)
471
+ body = [
472
+ f"impl From<rt::pydantic::Object<{item.wire}>> for {item.target} {{",
473
+ f" fn from(w: rt::pydantic::Object<{item.wire}>) -> Self {{",
474
+ f" let {item.wire} {{ {names} }} = w.0;",
475
+ f" {item.target} {{ {names} }}",
476
+ " }",
477
+ "}",
478
+ ]
479
+ case ir.ModItem():
480
+ body = _mod(item)
481
+ case ir.ClassDef():
482
+ body = [f"fn py2rs_todo_class_{item.name}() {{ {_unlowered('PY2RS013', 'class')} }}"]
483
+ case _:
484
+ raise TypeError(type(item).__name__)
485
+ return _marker(item, name or "<module>") + body
486
+
487
+
488
+ def _auto_uses(body: str) -> list[str]:
489
+ uses: list[str] = []
490
+ for pattern, text in AUTO_USES:
491
+ found = sorted(set(re.findall(pattern, body)))
492
+ if found:
493
+ crate = "utoipa" if found[0] in ("IntoParams", "ToSchema") else "indexmap"
494
+ uses.append(text or f"use {crate}::{{{', '.join(found)}}};")
495
+ std = sorted(set(re.findall(r"\b(?:BTreeSet|HashSet)\b", body)))
496
+ if std:
497
+ uses.append(f"use std::collections::{{{', '.join(std)}}};")
498
+ return uses
499
+
500
+
501
+ SET_TYPES = {"indexset": "IndexSet", "btreeset": "BTreeSet", "hashset": "HashSet"}
502
+
503
+
504
+ def render_module(
505
+ module: ir.Module, path: str, runtime: str | None = None, set_type: str = "indexset"
506
+ ) -> str:
507
+ """Render `module` (with source-map markers); `use` lines come from the names the body mentions."""
508
+ body: list[str] = []
509
+ for item in module.items:
510
+ if body:
511
+ body.append("")
512
+ body += item_lines(item)
513
+ text = "\n".join(body)
514
+ chosen = SET_TYPES.get(set_type, "IndexSet")
515
+ if chosen != "IndexSet": # lowering always speaks IndexSet; the configured type is a spelling
516
+ text = re.sub(r"\bIndexSet\b", chosen, text)
517
+ head_lines = [HEADER.format(path=path), ALLOW, *[f"//! {d}".rstrip() for d in module.doc]]
518
+ uses = module.uses + _auto_uses(text)
519
+ if runtime is not None:
520
+ uses = [u for u in uses if "python2rust_rt" not in u] + ["use python2rust_rt as rt;"]
521
+ parts = ["\n".join(head_lines)]
522
+ if uses:
523
+ parts.append("\n".join(uses))
524
+ if text:
525
+ parts.append(text)
526
+ if runtime is not None:
527
+ parts.append("mod python2rust_rt {\n" + runtime + "\n}")
528
+ return "\n\n".join(parts) + "\n"
529
+
530
+
531
+ class SourceMapEntry(TypedDict):
532
+ """One row of `TranslateResult.source_map`: a Rust line and the Python lines it came from."""
533
+
534
+ rust_line: int
535
+ py_file: str
536
+ py_line: int
537
+ py_end_line: int
538
+ item: str
539
+
540
+
541
+ def extract_markers(text: str, py_file: str) -> tuple[str, list[SourceMapEntry]]:
542
+ """Strip `//@py` marker lines; return clean text and the source map for its final lines."""
543
+ out: list[str] = []
544
+ pending: list[tuple[int, int, str]] = []
545
+ smap: list[SourceMapEntry] = []
546
+ for line in text.splitlines():
547
+ stripped = line.strip()
548
+ if stripped.startswith(MARK):
549
+ a, b, item = stripped[len(MARK) :].split(" ", 2)
550
+ pending.append((int(a), int(b), item))
551
+ continue
552
+ out.append(line)
553
+ if pending and stripped:
554
+ smap += [
555
+ SourceMapEntry(
556
+ rust_line=len(out), py_file=py_file, py_line=a, py_end_line=b, item=item
557
+ )
558
+ for a, b, item in pending
559
+ ]
560
+ pending = []
561
+ return "\n".join(out) + "\n", smap