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,366 @@
1
+ """Lowering base: scopes, spans and the value-conversion helpers used by every lowering module.
2
+
3
+ Lowering never decides clone-or-borrow: it emits plain places and the ownership pass adds
4
+ `.clone()` where a place is moved. Types on IR nodes are Rust types (`&mut Vec<T>` for a
5
+ mutably borrowed parameter); `peel` strips references when a rule only cares about the value.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import re
12
+ from dataclasses import dataclass
13
+
14
+ from ..frontend.names import mangle, snake
15
+ from ..ir import nodes as ir
16
+ from ..ir.rtypes import (
17
+ BOOL,
18
+ BYTES,
19
+ FLOAT,
20
+ INT,
21
+ MAP,
22
+ SET,
23
+ SHARED,
24
+ STR,
25
+ UNIT,
26
+ UNKNOWN,
27
+ VALUE,
28
+ RType,
29
+ T,
30
+ arg,
31
+ peel,
32
+ ) # fmt: skip
33
+ from ..ir.types import TypeMapper
34
+ from ..passes.raises import is_a, parents
35
+ from .context import Ctx
36
+
37
+ SIMPLE_LOCAL = re.compile(r"[a-z_][a-z0-9_]*")
38
+
39
+
40
+ class NotFresh(Exception):
41
+ """A local chosen to be a plain value is assigned something that may be shared: keep its handle."""
42
+
43
+ def __init__(self, name: str) -> None:
44
+ super().__init__(name)
45
+ self.name = name
46
+
47
+
48
+ class Unsupported(Exception):
49
+ """Raised by lowering code; the nearest statement (or item) becomes a todo!()."""
50
+
51
+ def __init__(
52
+ self, code: str, construct: str, node: ast.AST | None = None, hint: str | None = None
53
+ ):
54
+ super().__init__(construct)
55
+ self.code, self.construct, self.node, self.hint = code, construct, node, hint
56
+
57
+
58
+ @dataclass
59
+ class Var:
60
+ rust: str
61
+ ty: RType
62
+
63
+
64
+ def local_name(py_name: str) -> str:
65
+ return mangle(py_name) if SIMPLE_LOCAL.fullmatch(py_name) else snake(py_name)
66
+
67
+
68
+ def int_lit(value: int) -> ir.Lit:
69
+ return ir.lit("int", value, INT)
70
+
71
+
72
+ def true_lit() -> ir.Lit:
73
+ return ir.lit("bool", True, BOOL)
74
+
75
+
76
+ def not_(e: ir.RExpr) -> ir.Un:
77
+ return ir.Un(op="!", operand=e, ty=BOOL)
78
+
79
+
80
+ def bin_(op: str, a: ir.RExpr, b: ir.RExpr, ty: RType) -> ir.Bin:
81
+ return ir.Bin(op=op, left=a, right=b, ty=ty)
82
+
83
+
84
+ def _is_ref_item(e: ir.RExpr) -> bool:
85
+ """Literals and const/static items are already `&T` in Rust."""
86
+ return (isinstance(e, ir.Lit) and e.kind in ("str", "bytes")) or (
87
+ isinstance(e, ir.Path) and e.borrowed
88
+ )
89
+
90
+
91
+ def is_none(e: ir.RExpr) -> bool:
92
+ return isinstance(e, ir.Lit) and e.kind == "none"
93
+
94
+
95
+ class Lowerer:
96
+ def __init__(self, ctx: Ctx, mapper: TypeMapper, ret: RType = UNIT) -> None:
97
+ self.ctx = ctx
98
+ self.mapper = mapper
99
+ self.ret = ret
100
+ self.frames: list[dict[str, Var]] = [{}]
101
+ self.mutated: set[str] = set()
102
+ self.hoist: set[str] = set()
103
+ self.container_mut: set[str] = set()
104
+ # exception lowering state (see exceptions.py)
105
+ self.fallible = False # the function returns Result<T, rt::PyError>
106
+ self.try_labels: list[str] = [] # labeled blocks that an error currently breaks out of
107
+ self.catch_stack: list[set[str]] = [] # exception classes caught by enclosing handlers
108
+ self.handlers: list[tuple[str, set[str]]] = [] # (variable, kinds) of the enclosing except
109
+ self.closure_depth = (
110
+ 0 # inside a closure (lambda/comprehension): `?` and labels cannot cross
111
+ )
112
+ self.plain_py: set[str] = set() # Python names that may become plain values (devirt)
113
+ self.plain: set[str] = set() # Rust names of locals lowered to plain owned values
114
+ self.comp_vars: list[set[str]] = [] # variables of the comprehensions being lowered
115
+ self.loop_inplace: set[str] = set() # loop variables that the body changes in place
116
+ self.alias_hazards: dict[
117
+ int, tuple[str, bool]
118
+ ] = {} # id(Name) -> why a stored value may be shared
119
+ self.late_bound: set[str] = set() # names a lambda would read at call time, not creation
120
+ self._labels = 0
121
+
122
+ def catches(self, kind: str) -> bool:
123
+ """Is `kind` caught by an enclosing `except` (so the operation may be a Result here)?"""
124
+ table = parents(self.ctx)
125
+ return not self.closure_depth and any(
126
+ is_a(kind, c, table) for caught in self.catch_stack for c in caught
127
+ )
128
+
129
+ def question(self, call: ir.RExpr, ty: RType, node: ast.AST) -> ir.RExpr:
130
+ """Propagate the error of a Result-valued `call`: `?`, or a break to the enclosing try."""
131
+ if self.closure_depth:
132
+ raise Unsupported(
133
+ "PY2RS012", "fallible operation inside a closure or comprehension", node
134
+ )
135
+ label = self.try_labels[-1] if self.try_labels else None
136
+ if label is None and not self.fallible:
137
+ raise Unsupported(
138
+ "PY2RS012", "fallible call in a function that cannot return Result", node
139
+ )
140
+ return ir.Question(operand=call, label=label, ty=ty, span=call.span)
141
+
142
+ def sp(self, node: ast.AST | None) -> ir.Span | None:
143
+ return ir.span_of(node, self.ctx.col.file)
144
+
145
+ # -- scopes ---------------------------------------------------------------------------
146
+ def push(self) -> None:
147
+ self.frames.append({})
148
+
149
+ def pop(self) -> None:
150
+ self.frames.pop()
151
+
152
+ def lookup(self, name: str) -> Var | None:
153
+ for frame in reversed(self.frames):
154
+ if name in frame:
155
+ return frame[name]
156
+ return None
157
+
158
+ # -- Python objects are handles ------------------------------------------------------------
159
+ @property
160
+ def shared(self) -> bool:
161
+ return self.ctx.cfg.shared != "off"
162
+
163
+ def mutable_ty(self, ty: RType) -> bool:
164
+ """Is a value of this (value) type a shared, mutable Python object?"""
165
+ ty = peel(ty)
166
+ if ty.name in ("Vec", MAP, SET):
167
+ return ty != BYTES
168
+ model = self.ctx.model_by_rust(ty.name) if ty.args == () else None
169
+ return model is not None and not model.frozen
170
+
171
+ def elem_ty(self, ty: RType) -> RType:
172
+ """Storage form of a type held inside a container, tuple or Option: objects are handles."""
173
+ if ty.name == SHARED:
174
+ return T(SHARED, self.inner_ty(ty.args[0]))
175
+ if self.mutable_ty(ty) and ty.name not in ("&", "&mut"):
176
+ return T(SHARED, self.inner_ty(ty))
177
+ if ty.name in ("tuple", "Option", "Result") and ty.args:
178
+ return T(ty.name, *(self.elem_ty(a) for a in ty.args))
179
+ return ty
180
+
181
+ def inner_ty(self, ty: RType) -> RType:
182
+ """A container type with the storage form of its elements."""
183
+ if ty.name in ("Vec", MAP, SET) and ty != BYTES:
184
+ return T(ty.name, *(self.elem_ty(a) for a in ty.args))
185
+ return ty
186
+
187
+ def store_ty(self, ty: RType) -> RType:
188
+ """The type of a variable or field holding a value of type `ty`."""
189
+ if not self.shared or ty.name in ("&", "&mut", "Iter", "Fn", "?"):
190
+ return ty
191
+ if ty.name == SHARED:
192
+ return self.elem_ty(ty)
193
+ return self.elem_ty(ty)
194
+
195
+ def declare(self, name: str, ty: RType, plain: bool = False) -> Var:
196
+ ty = ty if plain else self.store_ty(ty)
197
+ var = Var(local_name(name), ty)
198
+ self.frames[-1][name] = var
199
+ return var
200
+
201
+ def expr(self, node: ast.expr) -> ir.RExpr:
202
+ raise NotImplementedError
203
+
204
+ def var(self, v: Var) -> ir.Var:
205
+ return ir.Var(name=v.rust, ty=v.ty)
206
+
207
+ # -- conversions ----------------------------------------------------------------------
208
+ def coerce(self, e: ir.RExpr, target: RType, *, promote: bool = False) -> ir.RExpr:
209
+ """`e` converted to `target`: Some(..), int -> f64, Literal variant, untagged union, Value.
210
+
211
+ `promote=True` is arithmetic promotion (the result is a float in Python too); otherwise an
212
+ int that becomes a float is a stored value that Python would keep as an int (PY2RS057)."""
213
+ if target.name == SHARED and isinstance(e, ir.Var) and e.name in self.plain:
214
+ # a devirtualised local leaves the function (or is stored): wrap it into a handle
215
+ return ir.Call(func=ir.Path(path="rt::Shared::new"), args=[e], ty=target, span=e.span)
216
+ if target.name == SHARED: # the dispatcher makes the handles; coerce the value
217
+ target = target.args[0]
218
+ if (
219
+ target.name in ("Vec", MAP, SET)
220
+ and isinstance(e, ir.Borrow)
221
+ and isinstance(e.operand, ir.Call)
222
+ and isinstance(e.operand.func, ir.Path)
223
+ and e.operand.func.path == "rt::Shared::new"
224
+ ): # a fresh list/dict/instance: coerce what it holds (`xs: list[float] = [1, 2]`)
225
+ fresh = e.operand
226
+ fresh.args = [self.coerce(fresh.args[0], target, promote=promote)]
227
+ return e
228
+ if target.unknown:
229
+ return e
230
+ if target == VALUE and is_none(e):
231
+ return ir.Path(path="serde_json::Value::Null", ty=VALUE, span=e.span)
232
+ if target.name == "Option":
233
+ if is_none(e):
234
+ return ir.Lit(kind="none", ty=target, span=e.span)
235
+ if peel(e.ty).name == "Option":
236
+ return e
237
+ return ir.Call(
238
+ func=ir.Path(path="Some"),
239
+ args=[self.coerce(e, arg(target))],
240
+ ty=target,
241
+ span=e.span,
242
+ )
243
+ ty = peel(e.ty)
244
+ if target.name == "Vec" and isinstance(e, ir.Macro) and e.name == "vec" and e.args:
245
+ return ir.Macro(
246
+ name="vec",
247
+ args=[self.coerce(i, arg(target)) for i in e.args],
248
+ ty=target,
249
+ span=e.span,
250
+ )
251
+ if target == FLOAT and ty == INT:
252
+ if not promote:
253
+ self.ctx.col.drift("PY2RS057", e.span, "an int where a float is annotated")
254
+ if (n := ir.lit_int(e)) is not None:
255
+ return ir.lit("float", float(n), FLOAT, e.span)
256
+ return ir.Cast(operand=e, ty=FLOAT, span=e.span)
257
+ if target.name in self.ctx.lit_enums and isinstance(e, ir.Lit) and e.kind == "str":
258
+ variant = self.ctx.lit_enums[target.name].get(e.value)
259
+ if variant:
260
+ return ir.Path(path=f"{target.name}::{variant}", ty=target, span=e.span)
261
+ if target.name in self.ctx.unions and ty != target:
262
+ for vname, vty in self.ctx.unions[target.name]:
263
+ if vty == ty:
264
+ return ir.Call(
265
+ func=ir.Path(path=f"{target.name}::{vname}"),
266
+ args=[e],
267
+ ty=target,
268
+ span=e.span,
269
+ )
270
+ if target.name.startswith(VALUE.name) and not ty.name.startswith(VALUE.name) and ty.known:
271
+ return ir.Macro(name="json", args=[e], ty=VALUE, span=e.span)
272
+ return e
273
+
274
+ def as_str(self, e: ir.RExpr) -> ir.RExpr:
275
+ """`e` (a str) in a `&str` position."""
276
+ if _is_ref_item(e):
277
+ return ir.Ref(operand=e, elide=True, ty=e.ty, span=e.span)
278
+ return ir.method(e, "as_str", ty=STR)
279
+
280
+ def ref_of(self, e: ir.RExpr) -> ir.RExpr:
281
+ return ir.Ref(operand=e, elide=_is_ref_item(e), ty=T("&", e.ty), span=e.span)
282
+
283
+ def mut_ref(self, e: ir.RExpr) -> ir.RExpr:
284
+ """`&mut e`; an existing `&mut` binding is reborrowed instead of moved."""
285
+ inner = ir.Deref(operand=e, ty=peel(e.ty)) if e.ty.name == "&mut" else e
286
+ return ir.Ref(operand=inner, mut=True, ty=T("&mut", peel(e.ty)), span=e.span)
287
+
288
+ def truthy(self, e: ir.RExpr, node: ast.AST | None = None) -> ir.RExpr:
289
+ """Python truthiness of `e` as a Rust bool expression."""
290
+ ty = peel(e.ty)
291
+ if e.ty.name in ("&", "&mut") and ty in (INT, FLOAT, BOOL):
292
+ e = ir.Deref(operand=e, ty=ty)
293
+ if ty == BOOL:
294
+ return e
295
+ if ty == INT:
296
+ return bin_("!=", e, int_lit(0), BOOL)
297
+ if ty == FLOAT:
298
+ return bin_("!=", e, ir.lit("float", 0.0, FLOAT), BOOL)
299
+ if ty.name in ("String", "Vec", MAP, SET):
300
+ return not_(ir.method(e, "is_empty", ty=BOOL))
301
+ if ty.name == "Option":
302
+ return self._opt_truthy(e, arg(ty))
303
+ if ty.name.startswith(VALUE.name):
304
+ return ir.rt("truthy", self.ref_of(e), ty=BOOL)
305
+ if ty == UNIT:
306
+ return ir.lit("bool", False, BOOL)
307
+ if ty.known and ty.name not in ("Iter", "Fn"):
308
+ return true_lit()
309
+ raise Unsupported("PY2RS036", "truthiness of a value with unknown type", node)
310
+
311
+ def _opt_truthy(self, e: ir.RExpr, inner: RType) -> ir.RExpr:
312
+ v = ir.Var(name="v", ty=T("&", inner))
313
+ if inner == STR:
314
+ ref = ir.method(e, "as_deref", ty=T("Option", STR))
315
+ test = not_(ir.method(ir.Var(name="s", ty=T("&", STR)), "is_empty", ty=BOOL))
316
+ return ir.method(
317
+ ref, "is_some_and", ir.Closure(params=[ir.PVar("s")], body=test), ty=BOOL
318
+ )
319
+ if inner in (INT, FLOAT, BOOL):
320
+ zero = {INT: int_lit(0), FLOAT: ir.lit("float", 0.0, FLOAT)}.get(inner)
321
+ by_value = ir.Var(
322
+ name="v", ty=inner
323
+ ) # is_some_and consumes the Option: the closure gets T
324
+ body = bin_("!=", by_value, zero, BOOL) if zero else by_value
325
+ return ir.method(
326
+ e, "is_some_and", ir.Closure(params=[ir.PVar("v")], body=body), ty=BOOL
327
+ )
328
+ if inner.name in ("Vec", MAP, SET):
329
+ test = not_(ir.method(v, "is_empty", ty=BOOL))
330
+ as_ref = ir.method(e, "as_ref", ty=T("Option", T("&", inner)))
331
+ return ir.method(
332
+ as_ref, "is_some_and", ir.Closure(params=[ir.PVar("v")], body=test), ty=BOOL
333
+ )
334
+ return ir.method(e, "is_some", ty=BOOL)
335
+
336
+ def _owned_iterator(self, it: ir.RExpr) -> ir.BlockX:
337
+ """Drop temporary borrow guards before entering Rust's for loop."""
338
+ name = "py2rs_iter"
339
+ bind = ir.Let(ir.PVar(name), None, it)
340
+ return ir.BlockX(stmts=[bind], tail=ir.Var(name=name, ty=it.ty), ty=it.ty)
341
+
342
+ def _snapshot(self, source: ir.RExpr, it: ir.RExpr, item: RType) -> ir.RExpr:
343
+ """Iterating a shared object must not hold its borrow: the body may change it (Python lets
344
+ a list grow and a dict value change while it is iterated)."""
345
+ if not isinstance(source, ir.Borrow):
346
+ return it
347
+ owned = ir.method(it, "collect", ty=T("Vec", arg(item)), turbofish=T("Vec", UNKNOWN))
348
+ return ir.method(owned, "into_iter", ty=item)
349
+
350
+ def as_iter(self, e: ir.RExpr, node: ast.AST | None = None) -> ir.RExpr:
351
+ """`e` as a Rust iterator yielding owned items."""
352
+ ty = peel(e.ty)
353
+ if ty.name in ("Iter", "Range"):
354
+ return e
355
+ item = T("Iter", arg(ty))
356
+ if ty.name in ("Vec", SET):
357
+ if ir.is_place(e) or e.ty.name in ("&", "&mut") or _is_ref_item(e):
358
+ return self._snapshot(e, ir.method(ir.method(e, "iter"), "cloned", ty=item), item)
359
+ return ir.method(e, "into_iter", ty=item)
360
+ if ty.name == MAP:
361
+ return self._snapshot(e, ir.method(ir.method(e, "keys"), "cloned", ty=item), item)
362
+ if ty == STR:
363
+ c = ir.Var(name="c", ty=T("char"))
364
+ to_s = ir.Closure(params=[ir.PVar("c")], body=ir.method(c, "to_string", ty=STR))
365
+ return ir.method(ir.method(e, "chars"), "map", to_s, ty=T("Iter", STR))
366
+ raise Unsupported("PY2RS004", f"iteration over a value of type {ty.rust()}", node)
@@ -0,0 +1,195 @@
1
+ """Pydantic helpers (model_dump / model_dump_json / model_validate / model_copy) and extra str methods."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+
7
+ from ..ir import nodes as ir
8
+ from ..ir.rtypes import INT, STR, VALUE, RType, T, peel
9
+ from .calls import CallLowerer, KwBag, expect, lit_str
10
+ from .context import ModelInfo
11
+ from .lowerer import Unsupported
12
+
13
+ DUMPS = ("model_dump", "model_dump_json", "model_copy")
14
+ VALIDATES = ("model_validate", "model_validate_json")
15
+ SERIALISABLE = "serialisable"
16
+
17
+
18
+ def _flag(node: ast.expr | None) -> bool | None:
19
+ if node is None:
20
+ return None
21
+ if isinstance(node, ast.Constant) and isinstance(node.value, bool):
22
+ return node.value
23
+ raise Unsupported("PY2RS019", "a computed flag argument", node)
24
+
25
+
26
+ class ModelCalls(CallLowerer):
27
+ def _call_attr(self, node: ast.Call, f: ast.Attribute) -> ir.RExpr:
28
+ owner = f.value
29
+ if (
30
+ f.attr in VALIDATES
31
+ and isinstance(owner, ast.Name)
32
+ and owner.id in self.ctx.models
33
+ and not self.lookup(owner.id)
34
+ ):
35
+ return self._validate(node, self.ctx.models[owner.id], f.attr)
36
+ if f.attr in DUMPS:
37
+ recv = self.expr(owner)
38
+ model = self.ctx.model_by_rust(peel(recv.ty).name)
39
+ if model is not None:
40
+ return self._model_method(node, recv, model, f.attr)
41
+ return super()._call_attr(node, f)
42
+
43
+ def _validate(self, node: ast.Call, model: ModelInfo, attr: str) -> ir.RExpr:
44
+ if model.unchecked: # accepting what Pydantic rejects would be silently wrong
45
+ raise Unsupported(
46
+ "PY2RS017",
47
+ f"{model.rust}.{attr}(): constraints/validators are not enforced by serde",
48
+ node,
49
+ )
50
+ if len(node.args) != 1 or node.keywords:
51
+ raise Unsupported("PY2RS019", f"{attr}() with options", node)
52
+ if model.inexact: # some field of the model is not validated exactly like Pydantic
53
+ self.drift(
54
+ "PY2RS043", node, f"{model.rust}.{attr}() differs from Pydantic for some inputs"
55
+ )
56
+ arg = self.expr(node.args[0])
57
+ if attr == "model_validate_json":
58
+ fn, source = "serde_json::from_str", self.as_str(arg)
59
+ else:
60
+ fn, source = "serde_json::from_value", self.coerce(arg, VALUE)
61
+ ty = T(model.rust)
62
+ parsed = ir.Call(func=ir.Path(path=f"{fn}::<{model.rust}>"), args=[source])
63
+ to_error = ir.Closure(
64
+ params=[ir.PVar("e")],
65
+ body=ir.rt("validation_error", ir.Ref(operand=ir.Var(name="e"))),
66
+ )
67
+ result = ir.method(parsed, "map_err", to_error)
68
+ if self.catches("ValidationError"):
69
+ return self.question(result, ty, node)
70
+ self.drift("PY2RS045", node, "ValidationError becomes a panic outside a try")
71
+ return ir.rt("or_panic", result, ty=ty)
72
+
73
+ def _model_method(
74
+ self, node: ast.Call, recv: ir.RExpr, model: ModelInfo, attr: str
75
+ ) -> ir.RExpr:
76
+ if node.args:
77
+ raise Unsupported("PY2RS019", f"{attr}() with positional arguments", node)
78
+ kw = KwBag(node)
79
+ if attr == "model_copy":
80
+ out = self._copy(node, recv, model, kw.get("update"), kw.get("deep"))
81
+ else:
82
+ out = self._dump(node, recv, model, attr, kw)
83
+ kw.finish(node)
84
+ return out
85
+
86
+ def _copy(
87
+ self,
88
+ node: ast.Call,
89
+ recv: ir.RExpr,
90
+ model: ModelInfo,
91
+ update: ast.expr | None,
92
+ deep: ast.expr | None,
93
+ ) -> ir.RExpr:
94
+ ty = T(model.rust)
95
+ base = ir.CloneX(operand=recv, ty=ty)
96
+ if update is None:
97
+ return base
98
+ if not isinstance(update, ast.Dict) or not all(
99
+ isinstance(k, ast.Constant) and k.value in model.fields for k in update.keys
100
+ ):
101
+ raise Unsupported(
102
+ "PY2RS019", "model_copy(update=) needs a literal dict of fields", node
103
+ )
104
+ parts = []
105
+ for key, value in zip(update.keys, update.values, strict=True):
106
+ assert isinstance(key, ast.Constant)
107
+ info = model.fields[str(key.value)]
108
+ parts.append((info.rust, self.coerce(self.expr(value), info.ty)))
109
+ return ir.StructLit(name=model.rust, fields=parts, base=base, ty=ty)
110
+
111
+ def _dump(
112
+ self, node: ast.Call, recv: ir.RExpr, model: ModelInfo, attr: str, kw: KwBag
113
+ ) -> ir.RExpr:
114
+ mode, by_alias = kw.get("mode"), _flag(kw.get("by_alias"))
115
+ exclude_none = _flag(kw.get("exclude_none"))
116
+ if mode is not None and not (
117
+ isinstance(mode, ast.Constant) and mode.value in ("json", "python")
118
+ ):
119
+ raise Unsupported("PY2RS019", f"{attr}() with a computed mode", node)
120
+ wants_alias = self.ctx.cfg.profile == "fastapi" # how the struct serialises
121
+ if model.aliased and bool(by_alias) != wants_alias:
122
+ raise Unsupported(
123
+ "PY2RS019", f"{attr}(by_alias={bool(by_alias)}) on this aliased model", node
124
+ )
125
+ if model.binary:
126
+ raise Unsupported("PY2RS019", f"{attr}() of bytes fields (base64 vs array)", node)
127
+ message = f"{SERIALISABLE} model"
128
+ source = self.ref_of(recv)
129
+ if attr == "model_dump_json" and not exclude_none:
130
+ text = ir.Call(func=ir.Path(path="serde_json::to_string"), args=[source])
131
+ return expect(text, message, STR)
132
+ value = expect(
133
+ ir.Call(func=ir.Path(path="serde_json::to_value"), args=[source]), message, VALUE
134
+ )
135
+ if exclude_none:
136
+ value = ir.rt("strip_none", value, ty=VALUE)
137
+ if attr == "model_dump_json":
138
+ return ir.method(value, "to_string", ty=STR)
139
+ return value
140
+
141
+ # -- str methods beyond the basics ----------------------------------------------------
142
+ def _rt_str(
143
+ self, name: str, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], ty: RType
144
+ ) -> ir.RExpr:
145
+ return ir.rt(name, self.as_str(s), *[self.as_str(a) for a in args], ty=ty)
146
+
147
+ def m_str_casefold(
148
+ self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
149
+ ) -> ir.RExpr:
150
+ self.drift("PY2RS044", node, "casefold()")
151
+ return self._rt_str("casefold", node, s, self._argc(node, args, 0), STR)
152
+
153
+ def m_str_partition(
154
+ self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
155
+ ) -> ir.RExpr:
156
+ triple = T("tuple", STR, STR, STR)
157
+ return self._rt_str("partition", node, s, self._argc(node, args, 1), triple)
158
+
159
+ def m_str_rpartition(
160
+ self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
161
+ ) -> ir.RExpr:
162
+ triple = T("tuple", STR, STR, STR)
163
+ return self._rt_str("rpartition", node, s, self._argc(node, args, 1), triple)
164
+
165
+ def m_str_index(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
166
+ call = self._rt_str("try_str_index", node, s, self._argc(node, args, 1), INT)
167
+ if self.catches("ValueError"):
168
+ return self.question(call, INT, node)
169
+ self.drift("PY2RS045", node, "index() panics instead of raising ValueError")
170
+ return ir.rt("or_panic", call, ty=INT)
171
+
172
+ def m_str_zfill(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
173
+ (width,) = self._argc(node, args, 1)
174
+ return ir.rt("zfill", self.as_str(s), width, ty=STR)
175
+
176
+ def _justify(self, name: str, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr]) -> ir.RExpr:
177
+ args = self._argc(node, args, 1, 2)
178
+ fill = self.as_str(args[1]) if len(args) == 2 else ir.Ref(operand=lit_str(" "), elide=True)
179
+ return ir.rt(name, self.as_str(s), args[0], fill, ty=STR)
180
+
181
+ def m_str_ljust(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
182
+ return self._justify("ljust", node, s, args)
183
+
184
+ def m_str_rjust(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
185
+ return self._justify("rjust", node, s, args)
186
+
187
+ def m_str_title(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
188
+ self.drift("PY2RS044", node, "title()")
189
+ return self._rt_str("title", node, s, self._argc(node, args, 0), STR)
190
+
191
+ def m_str_capitalize(
192
+ self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
193
+ ) -> ir.RExpr:
194
+ self.drift("PY2RS044", node, "capitalize()")
195
+ return self._rt_str("capitalize", node, s, self._argc(node, args, 0), STR)