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.
- python2rust/__init__.py +8 -0
- python2rust/__main__.py +5 -0
- python2rust/_core.py +44 -0
- python2rust/agent/__init__.py +0 -0
- python2rust/agent/agents.py +333 -0
- python2rust/agent/apply.py +516 -0
- python2rust/agent/finish.py +295 -0
- python2rust/agent/fixers.py +229 -0
- python2rust/agent/loop.py +441 -0
- python2rust/agent/patches.py +1165 -0
- python2rust/agent/port.py +579 -0
- python2rust/agent/prompts/judge_v2.md +96 -0
- python2rust/agent/review.py +34 -0
- python2rust/agent/rustlex.py +232 -0
- python2rust/cli/__init__.py +0 -0
- python2rust/cli/doctor.py +62 -0
- python2rust/cli/inputs.py +105 -0
- python2rust/cli/main.py +1162 -0
- python2rust/cli/ops.py +642 -0
- python2rust/cli/workflow.py +178 -0
- python2rust/core/__init__.py +38 -0
- python2rust/core/config.py +263 -0
- python2rust/core/constructs.py +124 -0
- python2rust/core/diagnostics.py +280 -0
- python2rust/core/emit/__init__.py +5 -0
- python2rust/core/emit/crates.py +51 -0
- python2rust/core/emit/render.py +561 -0
- python2rust/core/emit/schema.py +168 -0
- python2rust/core/emit/translate.py +304 -0
- python2rust/core/frontend/__init__.py +1 -0
- python2rust/core/frontend/module.py +896 -0
- python2rust/core/frontend/names.py +129 -0
- python2rust/core/frontend/project.py +277 -0
- python2rust/core/frontend/project_imports.py +173 -0
- python2rust/core/frontend/symbols.py +132 -0
- python2rust/core/frontend/walrus.py +59 -0
- python2rust/core/ir/__init__.py +1 -0
- python2rust/core/ir/nodes.py +675 -0
- python2rust/core/ir/rtypes.py +122 -0
- python2rust/core/ir/types.py +326 -0
- python2rust/core/lower/__init__.py +1 -0
- python2rust/core/lower/calls.py +1125 -0
- python2rust/core/lower/context.py +223 -0
- python2rust/core/lower/exceptions.py +317 -0
- python2rust/core/lower/exprs.py +845 -0
- python2rust/core/lower/fstrings.py +141 -0
- python2rust/core/lower/funcs.py +276 -0
- python2rust/core/lower/lowerer.py +366 -0
- python2rust/core/lower/modelcalls.py +195 -0
- python2rust/core/lower/models.py +645 -0
- python2rust/core/lower/stmts.py +722 -0
- python2rust/core/lower/testing.py +601 -0
- python2rust/core/lower/validation.py +253 -0
- python2rust/core/passes/__init__.py +1 -0
- python2rust/core/passes/aliasing.py +311 -0
- python2rust/core/passes/analysis.py +207 -0
- python2rust/core/passes/devirt.py +329 -0
- python2rust/core/passes/ownership.py +259 -0
- python2rust/core/passes/raises.py +275 -0
- python2rust/core/rt_lib.rs +2071 -0
- python2rust/data/README.md +81 -0
- python2rust/data/py2many_builtins.toml +4744 -0
- python2rust/errors.py +28 -0
- python2rust/py.typed +0 -0
- python2rust/report/__init__.py +0 -0
- python2rust/report/constructs.py +31 -0
- python2rust/report/contract.py +688 -0
- python2rust/report/corpus.py +323 -0
- python2rust/report/explain.py +168 -0
- python2rust/report/schemas.py +914 -0
- python2rust/server/__init__.py +0 -0
- python2rust/server/mcp_server.py +289 -0
- python2rust/server/mcp_workflow.py +100 -0
- python2rust/skill/SKILL.md +214 -0
- python2rust/verify/__init__.py +0 -0
- python2rust/verify/check.py +1135 -0
- python2rust/verify/equiv/__init__.py +1264 -0
- python2rust/verify/equiv/compare.py +455 -0
- python2rust/verify/equiv/harness.py +505 -0
- python2rust/verify/equiv/judge.py +358 -0
- python2rust/verify/equiv/procs.py +255 -0
- python2rust/verify/equiv/runner.py +248 -0
- python2rust/verify/equiv/types.py +543 -0
- python2rust/verify/keystore.py +76 -0
- python2rust/verify/ladder.py +396 -0
- python2rust/verify/sandbox.py +370 -0
- python2rust/verify/testrun.py +280 -0
- python2rust/workflow/__init__.py +0 -0
- python2rust/workflow/brief.py +312 -0
- python2rust/workflow/interview.py +366 -0
- python2rust/workflow/layout.py +103 -0
- python2rust/workflow/planner.py +409 -0
- python2rust/workflow/project.py +134 -0
- python2rust/workflow/schemas.py +265 -0
- python2rust/workflow/state.py +392 -0
- python2rust/workflow/staticscan.py +209 -0
- python2rust-0.1.0.dist-info/METADATA +395 -0
- python2rust-0.1.0.dist-info/RECORD +102 -0
- python2rust-0.1.0.dist-info/WHEEL +4 -0
- python2rust-0.1.0.dist-info/entry_points.txt +4 -0
- python2rust-0.1.0.dist-info/licenses/LICENSE +21 -0
- python2rust-0.1.0.dist-info/licenses/NOTICE +65 -0
|
@@ -0,0 +1,645 @@
|
|
|
1
|
+
"""Classes -> Rust items: Pydantic models, dataclasses, TypedDict, NamedTuple, Enums, NewType.
|
|
2
|
+
|
|
3
|
+
Everything a class does beyond data (methods, validators, plain classes) becomes a TODO.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import ast
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
from ..emit.schema import ANNOTATED_TYPES, field_items
|
|
13
|
+
from ..frontend.names import camel, const_name, snake, wire_name
|
|
14
|
+
from ..ir import nodes as ir
|
|
15
|
+
from ..ir.rtypes import MAP, SET, STR, RType, T, option
|
|
16
|
+
from ..ir.types import ENUM_DERIVES, TypeMapper, dotted
|
|
17
|
+
from ..passes import ownership
|
|
18
|
+
from ..passes.raises import BUILTIN_PARENTS, kind_ref
|
|
19
|
+
from .calls import CallLowerer
|
|
20
|
+
from .context import Ctx, EnumInfo, FieldInfo, ModelInfo
|
|
21
|
+
from .funcs import docstring, todo_item
|
|
22
|
+
from .lowerer import Unsupported
|
|
23
|
+
from .validation import FieldPlan, ModelFlags, plan_field, read_config
|
|
24
|
+
|
|
25
|
+
ENUM_BASES = {"Enum", "StrEnum", "IntEnum", "IntFlag", "Flag", "ReprEnum"}
|
|
26
|
+
CONSTRAINTS = (
|
|
27
|
+
"ge",
|
|
28
|
+
"le",
|
|
29
|
+
"gt",
|
|
30
|
+
"lt",
|
|
31
|
+
"min_length",
|
|
32
|
+
"max_length",
|
|
33
|
+
"pattern",
|
|
34
|
+
"multiple_of",
|
|
35
|
+
"min_items",
|
|
36
|
+
"max_items",
|
|
37
|
+
)
|
|
38
|
+
VALIDATORS = {
|
|
39
|
+
"field_validator",
|
|
40
|
+
"model_validator",
|
|
41
|
+
"validator",
|
|
42
|
+
"root_validator",
|
|
43
|
+
"computed_field",
|
|
44
|
+
"property",
|
|
45
|
+
}
|
|
46
|
+
DEFAULT_TYPES = {"String", "i64", "f64", "bool", "Vec", MAP, SET}
|
|
47
|
+
FACTORIES = {"list", "dict", "set"}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class ClassResult:
|
|
52
|
+
items: list[ir.Item] = field(default_factory=list)
|
|
53
|
+
is_model: bool = False
|
|
54
|
+
methods: int = 0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _tail(node: ast.expr) -> str:
|
|
58
|
+
return dotted(node.func if isinstance(node, ast.Call) else node).split(".")[-1]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _bases(node: ast.ClassDef) -> list[str]:
|
|
62
|
+
return [dotted(b).split(".")[-1] for b in node.bases]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _frozen_config(node: ast.ClassDef) -> bool:
|
|
66
|
+
"""`model_config = ConfigDict(frozen=True)` in the class body (inheritance is not followed)."""
|
|
67
|
+
for stmt in node.body:
|
|
68
|
+
if isinstance(stmt, ast.Assign) and any(
|
|
69
|
+
isinstance(t, ast.Name) and t.id == "model_config" for t in stmt.targets
|
|
70
|
+
):
|
|
71
|
+
value = stmt.value
|
|
72
|
+
if isinstance(value, ast.Call):
|
|
73
|
+
return any(k.arg == "frozen" and _const(k.value) is True for k in value.keywords)
|
|
74
|
+
return False
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _frozen_dataclass(node: ast.ClassDef) -> bool:
|
|
78
|
+
return any(
|
|
79
|
+
isinstance(d, ast.Call)
|
|
80
|
+
and _tail(d) == "dataclass"
|
|
81
|
+
and any(k.arg == "frozen" and _const(k.value) is True for k in d.keywords)
|
|
82
|
+
for d in node.decorator_list
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _is_dataclass(node: ast.ClassDef) -> bool:
|
|
87
|
+
return any(_tail(d) == "dataclass" for d in node.decorator_list)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def classify(ctx: Ctx, node: ast.ClassDef) -> str:
|
|
91
|
+
bases = _bases(node)
|
|
92
|
+
if ENUM_BASES & set(bases):
|
|
93
|
+
return "enum"
|
|
94
|
+
if "TypedDict" in bases:
|
|
95
|
+
return "typeddict"
|
|
96
|
+
if "NamedTuple" in bases:
|
|
97
|
+
return "namedtuple"
|
|
98
|
+
if "BaseModel" in bases or any(b in ctx.models for b in bases):
|
|
99
|
+
return "model"
|
|
100
|
+
if any(b in BUILTIN_PARENTS or b in ctx.exceptions for b in bases):
|
|
101
|
+
return "exception"
|
|
102
|
+
return "dataclass" if _is_dataclass(node) else "plain"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def register_class(ctx: Ctx, node: ast.ClassDef) -> None:
|
|
106
|
+
"""Pre-pass: make the Rust name visible to annotations that appear before the class."""
|
|
107
|
+
kind = classify(ctx, node)
|
|
108
|
+
if kind == "enum":
|
|
109
|
+
ctx.enums[node.name] = EnumInfo(camel(node.name))
|
|
110
|
+
elif kind == "exception":
|
|
111
|
+
ctx.exceptions[node.name] = _bases(node)[0]
|
|
112
|
+
elif kind != "plain":
|
|
113
|
+
info = ModelInfo(camel(node.name))
|
|
114
|
+
info.frozen = kind == "namedtuple" or _frozen_dataclass(node) or _frozen_config(node)
|
|
115
|
+
ctx.models[node.name] = info
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def lower_class(ctx: Ctx, mapper: TypeMapper, node: ast.ClassDef) -> ClassResult:
|
|
119
|
+
kind = classify(ctx, node)
|
|
120
|
+
out = ClassResult()
|
|
121
|
+
for d in node.decorator_list:
|
|
122
|
+
if _tail(d) != "dataclass":
|
|
123
|
+
out.items.append(
|
|
124
|
+
todo_item(ctx, "PY2RS014", d, f"decorator @{ast.unparse(d)}", "decorator")
|
|
125
|
+
)
|
|
126
|
+
methods = [s for s in node.body if isinstance(s, (ast.FunctionDef, ast.AsyncFunctionDef))]
|
|
127
|
+
out.methods = len(methods)
|
|
128
|
+
if kind == "exception" and not methods and _only_docstring(node):
|
|
129
|
+
out.is_model = True
|
|
130
|
+
out.items.append(_exception_kind(ctx, node))
|
|
131
|
+
return out
|
|
132
|
+
if kind in ("plain", "exception"):
|
|
133
|
+
out.items.append(todo_item(ctx, "PY2RS013", node, f"class {node.name}", "class"))
|
|
134
|
+
return out
|
|
135
|
+
out.is_model = True
|
|
136
|
+
out.items += _enum(ctx, node) if kind == "enum" else _struct(ctx, mapper, node, kind)
|
|
137
|
+
for m in methods:
|
|
138
|
+
code = "PY2RS018" if any(_tail(d) in VALIDATORS for d in m.decorator_list) else "PY2RS013"
|
|
139
|
+
out.items.append(todo_item(ctx, code, m, f"method {node.name}.{m.name}", "method"))
|
|
140
|
+
return out
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _only_docstring(node: ast.ClassDef) -> bool:
|
|
144
|
+
return all(
|
|
145
|
+
isinstance(s, ast.Pass) or (isinstance(s, ast.Expr) and isinstance(s.value, ast.Constant))
|
|
146
|
+
for s in node.body
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _exception_kind(ctx: Ctx, node: ast.ClassDef) -> ir.Item:
|
|
151
|
+
"""`class E(Base): pass` -> a node of the static exception-kind tree (see python2rust-rt)."""
|
|
152
|
+
parent = kind_ref(ctx, _bases(node)[0])
|
|
153
|
+
parent_ref = ir.Ref(operand=ir.Path(path=str(parent)))
|
|
154
|
+
value = ir.StructLit(
|
|
155
|
+
name="rt::ExcKind",
|
|
156
|
+
fields=[
|
|
157
|
+
("name", ir.lit("str", node.name, STR)),
|
|
158
|
+
("parent", ir.Call(func=ir.Path(path="Some"), args=[parent_ref])),
|
|
159
|
+
],
|
|
160
|
+
)
|
|
161
|
+
return ir.Const(
|
|
162
|
+
const_name(node.name), T("rt::ExcKind"), value, "static_plain", "pub ",
|
|
163
|
+
docstring(node.body)[0], span=ir.span_of(node, ctx.col.file),
|
|
164
|
+
) # fmt: skip
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def lower_newtype(ctx: Ctx, mapper: TypeMapper, node: ast.Assign) -> list[ir.Item]:
|
|
168
|
+
"""`UserId = NewType("UserId", int)` -> `#[serde(transparent)] struct UserId(pub i64);`"""
|
|
169
|
+
call = node.value
|
|
170
|
+
assert isinstance(call, ast.Call) and isinstance(node.targets[0], ast.Name)
|
|
171
|
+
py = node.targets[0].id
|
|
172
|
+
inner = mapper.map(call.args[1], camel(py)) if len(call.args) == 2 else None
|
|
173
|
+
if inner is None:
|
|
174
|
+
return [todo_item(ctx, "PY2RS004", node, f"NewType {py}")]
|
|
175
|
+
info = ctx.models[py] = ModelInfo(camel(py), newtype=inner)
|
|
176
|
+
derives = ctx.derives("Debug", "Clone", "PartialEq", "Serialize", "Deserialize")
|
|
177
|
+
_register(ctx, info.rust)
|
|
178
|
+
struct = ir.Struct(
|
|
179
|
+
info.rust,
|
|
180
|
+
[],
|
|
181
|
+
derives,
|
|
182
|
+
[],
|
|
183
|
+
[ir.Attribute("serde", [("transparent", None)])],
|
|
184
|
+
"pub ",
|
|
185
|
+
inner,
|
|
186
|
+
span=ir.span_of(node, ctx.col.file),
|
|
187
|
+
)
|
|
188
|
+
return [struct, *mapper.flush()]
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _register(ctx: Ctx, rust: str) -> None:
|
|
192
|
+
if ctx.cfg.schema_enabled:
|
|
193
|
+
ctx.schemas.append(rust)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
# -- enums --------------------------------------------------------------------------------
|
|
197
|
+
def _enum(ctx: Ctx, node: ast.ClassDef) -> list[ir.Item]:
|
|
198
|
+
info = ctx.enums[node.name]
|
|
199
|
+
is_str = bool({"StrEnum", "str"} & set(_bases(node)))
|
|
200
|
+
variants: list[ir.Variant] = []
|
|
201
|
+
extra: list[ir.Item] = []
|
|
202
|
+
counter, taken = 0, set()
|
|
203
|
+
for stmt in node.body:
|
|
204
|
+
if not (
|
|
205
|
+
isinstance(stmt, ast.Assign)
|
|
206
|
+
and len(stmt.targets) == 1
|
|
207
|
+
and isinstance(stmt.targets[0], ast.Name)
|
|
208
|
+
):
|
|
209
|
+
continue
|
|
210
|
+
member = stmt.targets[0].id
|
|
211
|
+
if member.startswith("_"):
|
|
212
|
+
continue
|
|
213
|
+
value = _enum_value(stmt.value, member, is_str, counter)
|
|
214
|
+
if value is None:
|
|
215
|
+
extra.append(
|
|
216
|
+
todo_item(ctx, "PY2RS037", stmt, f"enum member {node.name}.{member}", "enum")
|
|
217
|
+
)
|
|
218
|
+
continue
|
|
219
|
+
vname = camel(member)
|
|
220
|
+
while vname in taken:
|
|
221
|
+
vname += "_"
|
|
222
|
+
taken.add(vname)
|
|
223
|
+
info.members[member] = vname
|
|
224
|
+
if isinstance(value, int):
|
|
225
|
+
counter = value + 1
|
|
226
|
+
variants.append(ir.Variant(vname, discriminant=str(value)))
|
|
227
|
+
ctx.col.diag(
|
|
228
|
+
"PY2RS009",
|
|
229
|
+
stmt,
|
|
230
|
+
f"{node.name}.{member} serialises by variant name, not by value {value}",
|
|
231
|
+
severity="info",
|
|
232
|
+
)
|
|
233
|
+
else:
|
|
234
|
+
attrs = [ir.Attribute("serde", [("rename", value)])] if value != vname else []
|
|
235
|
+
variants.append(ir.Variant(vname, attrs=attrs))
|
|
236
|
+
doc = docstring(node.body)[0]
|
|
237
|
+
_register(ctx, info.rust)
|
|
238
|
+
return [
|
|
239
|
+
ir.EnumDef(
|
|
240
|
+
info.rust,
|
|
241
|
+
variants,
|
|
242
|
+
ctx.derives(*ENUM_DERIVES),
|
|
243
|
+
doc,
|
|
244
|
+
span=ir.span_of(node, ctx.col.file),
|
|
245
|
+
),
|
|
246
|
+
*extra,
|
|
247
|
+
]
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _esc(text: str) -> str:
|
|
251
|
+
return text.replace("\\", "\\\\").replace('"', '\\"')
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _enum_value(node: ast.expr, member: str, is_str: bool, counter: int) -> str | int | None:
|
|
255
|
+
if isinstance(node, ast.Call) and dotted(node.func).split(".")[-1] == "auto":
|
|
256
|
+
return member.lower() if is_str else counter + 1
|
|
257
|
+
if (
|
|
258
|
+
isinstance(node, ast.Constant)
|
|
259
|
+
and isinstance(node.value, (str, int))
|
|
260
|
+
and not isinstance(node.value, bool)
|
|
261
|
+
):
|
|
262
|
+
return node.value
|
|
263
|
+
return None
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
# -- structs ------------------------------------------------------------------------------
|
|
267
|
+
def _struct(ctx: Ctx, mapper: TypeMapper, node: ast.ClassDef, kind: str) -> list[ir.Item]:
|
|
268
|
+
if node.name not in ctx.models: # a base class imported from another module made it a model
|
|
269
|
+
register = ModelInfo(camel(node.name))
|
|
270
|
+
register.frozen = _frozen_dataclass(node) or _frozen_config(node)
|
|
271
|
+
ctx.models[node.name] = register
|
|
272
|
+
info = ctx.models[node.name]
|
|
273
|
+
parents = [ctx.models[b] for b in _bases(node) if b in ctx.models and ctx.models[b] is not info]
|
|
274
|
+
inherited = next((p.config for p in parents if isinstance(p.config, ModelFlags)), None)
|
|
275
|
+
flags = info.config = read_config(node, inherited)
|
|
276
|
+
fields: list[ir.FieldDef] = []
|
|
277
|
+
extra: list[ir.Item] = []
|
|
278
|
+
for base in _bases(node): # inherited fields come first, like in Python
|
|
279
|
+
parent = ctx.models.get(base)
|
|
280
|
+
if parent and parent is not info:
|
|
281
|
+
info.fields.update(parent.fields)
|
|
282
|
+
fields += parent.ir_fields
|
|
283
|
+
for stmt in node.body:
|
|
284
|
+
if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):
|
|
285
|
+
built = _field(
|
|
286
|
+
ctx,
|
|
287
|
+
mapper,
|
|
288
|
+
info,
|
|
289
|
+
node.name,
|
|
290
|
+
stmt,
|
|
291
|
+
flags,
|
|
292
|
+
kind,
|
|
293
|
+
"param" if node.name in ctx.cfg.query_models else "schema",
|
|
294
|
+
)
|
|
295
|
+
if built:
|
|
296
|
+
fields.append(built[0])
|
|
297
|
+
extra += built[1]
|
|
298
|
+
elif isinstance(stmt, ast.ClassDef):
|
|
299
|
+
extra.append(
|
|
300
|
+
todo_item(ctx, "PY2RS018", stmt, f"nested class {node.name}.{stmt.name}", "class")
|
|
301
|
+
)
|
|
302
|
+
elif isinstance(stmt, ast.Assign) and not any(
|
|
303
|
+
isinstance(t, ast.Name) and t.id == "model_config" for t in stmt.targets
|
|
304
|
+
):
|
|
305
|
+
extra.append(
|
|
306
|
+
todo_item(ctx, "PY2RS013", stmt, f"class attribute in {node.name}", "class")
|
|
307
|
+
)
|
|
308
|
+
info.ir_fields = list(fields)
|
|
309
|
+
info.source = kind
|
|
310
|
+
info.frozen = (
|
|
311
|
+
info.frozen or flags.frozen or any(p.frozen for p in parents) or _frozen_dataclass(node)
|
|
312
|
+
)
|
|
313
|
+
if flags.problems:
|
|
314
|
+
info.unchecked = True
|
|
315
|
+
extra += [
|
|
316
|
+
todo_item(ctx, "PY2RS018", node, f"{node.name}: {p}", "config") for p in flags.problems
|
|
317
|
+
]
|
|
318
|
+
for p in parents: # what a base class does not do, the subclass does not do either
|
|
319
|
+
if p.dirty or p.unchecked:
|
|
320
|
+
ctx.col.diag(
|
|
321
|
+
"PY2RS018",
|
|
322
|
+
node,
|
|
323
|
+
f"{node.name} inherits untranslated or unenforced behaviour from {p.rust}",
|
|
324
|
+
construct=node.name,
|
|
325
|
+
)
|
|
326
|
+
info.unchecked = info.unchecked or any(p.unchecked for p in parents)
|
|
327
|
+
info.validated = info.validated or any(p.validated for p in parents)
|
|
328
|
+
info.inexact = info.inexact or any(p.inexact for p in parents)
|
|
329
|
+
info.unchecked = info.unchecked or any(
|
|
330
|
+
isinstance(s, ast.FunctionDef | ast.AsyncFunctionDef)
|
|
331
|
+
and any(_tail(d) in VALIDATORS - {"property"} for d in s.decorator_list)
|
|
332
|
+
for s in node.body
|
|
333
|
+
)
|
|
334
|
+
info.binary = any("Vec<u8>" in f.ty.rust() for f in fields)
|
|
335
|
+
info.aliased = info.aliased or any(p.aliased for p in parents)
|
|
336
|
+
attrs = [ir.Attribute("serde", [("deny_unknown_fields", None)])] if flags.forbid else []
|
|
337
|
+
derives = ["Debug", "Clone", "PartialEq", "Serialize", "Deserialize"] # == compares fields
|
|
338
|
+
if ctx.cfg.schema_enabled and node.name in ctx.cfg.query_models:
|
|
339
|
+
derives.append("IntoParams")
|
|
340
|
+
attrs.append(ir.Attribute("into_params", [("parameter_in", ir.Ident("Query"))]))
|
|
341
|
+
else:
|
|
342
|
+
derives = ctx.derives(*derives)
|
|
343
|
+
_register(ctx, info.rust)
|
|
344
|
+
if _is_generic(node) or any(re.search(rf"\b{info.rust}\b", f.ty.rust()) for f in fields):
|
|
345
|
+
extra.append(
|
|
346
|
+
todo_item(ctx, "PY2RS048", node, f"recursive or generic model {node.name}", "class")
|
|
347
|
+
)
|
|
348
|
+
wire = kind == "model" and node.name not in ctx.cfg.query_models
|
|
349
|
+
if wire and ctx.cfg.vendor_runtime: # the vendored runtime has no optional features
|
|
350
|
+
ctx.col.diag(
|
|
351
|
+
"PY2RS043",
|
|
352
|
+
node,
|
|
353
|
+
f"{node.name} accepts JSON arrays and duplicate keys, unlike Pydantic",
|
|
354
|
+
severity="info",
|
|
355
|
+
construct=node.name,
|
|
356
|
+
)
|
|
357
|
+
wire = False
|
|
358
|
+
struct = ir.Struct(
|
|
359
|
+
info.rust,
|
|
360
|
+
fields,
|
|
361
|
+
derives,
|
|
362
|
+
docstring(node.body)[0],
|
|
363
|
+
attrs,
|
|
364
|
+
"pub ",
|
|
365
|
+
span=ir.span_of(node, ctx.col.file),
|
|
366
|
+
)
|
|
367
|
+
if not wire:
|
|
368
|
+
return [struct, *mapper.flush(), *extra]
|
|
369
|
+
# Pydantic only accepts a JSON object, and the last of duplicate keys wins. serde's derive
|
|
370
|
+
# accepts arrays and rejects duplicates, so the public struct reads through `Object<Wire>`.
|
|
371
|
+
ctx.features.add("pydantic")
|
|
372
|
+
taken = {m.rust for m in ctx.models.values()} | set(ctx.enums) | set(ctx.exceptions)
|
|
373
|
+
wname = f"__{info.rust}Wire" # module-private; a user class cannot be called that
|
|
374
|
+
while wname in taken:
|
|
375
|
+
wname += "_"
|
|
376
|
+
wire_fields = [
|
|
377
|
+
ir.FieldDef(f.name, f.ty, [], [a for a in f.attrs if a.name == "serde"]) for f in fields
|
|
378
|
+
]
|
|
379
|
+
wire_struct = ir.Struct(wname, wire_fields, ["Deserialize"], [], attrs, "")
|
|
380
|
+
struct.attrs = [ir.Attribute("serde", [("from", f"rt::pydantic::Object<{wname}>")])]
|
|
381
|
+
impl = ir.WireImpl(info.rust, wname, [f.name for f in fields])
|
|
382
|
+
return [struct, wire_struct, impl, *mapper.flush(), *extra]
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _is_generic(node: ast.ClassDef) -> bool:
|
|
386
|
+
return bool(getattr(node, "type_params", None)) or any(
|
|
387
|
+
dotted(b.value if isinstance(b, ast.Subscript) else b).split(".")[-1] == "Generic"
|
|
388
|
+
for b in node.bases
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _const(node: ast.expr | None) -> object:
|
|
393
|
+
"""The value of a literal keyword argument, else None."""
|
|
394
|
+
return node.value if isinstance(node, ast.Constant) else None
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _constraint_call(node: ast.expr) -> ast.Call | None:
|
|
398
|
+
"""`StringConstraints(...)`, `annotated_types.Ge(1)` and friends inside Annotated[...]."""
|
|
399
|
+
if isinstance(node, ast.Call) and (
|
|
400
|
+
_tail(node) in ANNOTATED_TYPES or _tail(node) == "StringConstraints"
|
|
401
|
+
):
|
|
402
|
+
return node
|
|
403
|
+
return None
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _field_call(node: ast.expr | None) -> ast.Call | None:
|
|
407
|
+
if isinstance(node, ast.Call) and dotted(node.func).split(".")[-1] in ("Field", "field"):
|
|
408
|
+
return node
|
|
409
|
+
return None
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _field(
|
|
413
|
+
ctx: Ctx,
|
|
414
|
+
mapper: TypeMapper,
|
|
415
|
+
info: ModelInfo,
|
|
416
|
+
struct: str,
|
|
417
|
+
stmt: ast.AnnAssign,
|
|
418
|
+
flags: ModelFlags,
|
|
419
|
+
kind: str,
|
|
420
|
+
attr: str = "schema",
|
|
421
|
+
) -> tuple[ir.FieldDef, list[ir.Item]] | None:
|
|
422
|
+
assert isinstance(stmt.target, ast.Name)
|
|
423
|
+
py = stmt.target.id
|
|
424
|
+
head = dotted(
|
|
425
|
+
stmt.annotation.value if isinstance(stmt.annotation, ast.Subscript) else stmt.annotation
|
|
426
|
+
).split(".")[-1]
|
|
427
|
+
if head == "ClassVar":
|
|
428
|
+
return None
|
|
429
|
+
ty, meta = mapper.map_meta(stmt.annotation, f"{struct}_{py}")
|
|
430
|
+
if "impl Fn" in ty.rust(): # a stored callable needs a design decision (Box<dyn Fn>)
|
|
431
|
+
marker = ctx.col.todo("PY2RS005", stmt, f"{struct}.{py}: a callable field", kind="type")
|
|
432
|
+
ty = T(f"Py2rsUnmapped_Callable /* {marker} */")
|
|
433
|
+
kw: dict[str, ast.expr] = {}
|
|
434
|
+
for name in (
|
|
435
|
+
n.id
|
|
436
|
+
for n in ast.walk(stmt.annotation)
|
|
437
|
+
if isinstance(n, ast.Name) and n.id in ctx.alias_meta
|
|
438
|
+
):
|
|
439
|
+
meta = [*ctx.alias_meta[name], *meta]
|
|
440
|
+
break
|
|
441
|
+
unknown: list[str] = []
|
|
442
|
+
for m in meta:
|
|
443
|
+
call = _field_call(m) or _constraint_call(m)
|
|
444
|
+
if call:
|
|
445
|
+
kw.update({k.arg: k.value for k in call.keywords if k.arg})
|
|
446
|
+
if _tail(call) in ANNOTATED_TYPES and call.args:
|
|
447
|
+
kw[ANNOTATED_TYPES[_tail(call)]] = call.args[0]
|
|
448
|
+
elif not (isinstance(m, ast.Constant) and isinstance(m.value, str)):
|
|
449
|
+
unknown.append(ast.unparse(m))
|
|
450
|
+
call = _field_call(stmt.value)
|
|
451
|
+
if call:
|
|
452
|
+
kw.update({k.arg: k.value for k in call.keywords if k.arg})
|
|
453
|
+
if call.args and not (
|
|
454
|
+
isinstance(call.args[0], ast.Constant) and call.args[0].value is Ellipsis
|
|
455
|
+
):
|
|
456
|
+
kw.setdefault("default", call.args[0])
|
|
457
|
+
default = kw.get("default") if (call or meta) else None
|
|
458
|
+
if stmt.value is not None and not call:
|
|
459
|
+
default = stmt.value
|
|
460
|
+
factory = kw.get("default_factory")
|
|
461
|
+
optional_by_absence = head == "NotRequired" or (kind == "typeddict" and not flags.total)
|
|
462
|
+
attrs: list[ir.Arg] = []
|
|
463
|
+
extra: list[ir.Item] = []
|
|
464
|
+
default_expr: ir.RExpr | None = None
|
|
465
|
+
is_none = isinstance(default, ast.Constant) and default.value is None
|
|
466
|
+
if optional_by_absence or is_none:
|
|
467
|
+
if ty.name != "Option":
|
|
468
|
+
ctx.col.diag(
|
|
469
|
+
"PY2RS009",
|
|
470
|
+
stmt,
|
|
471
|
+
f"{struct}.{py} becomes Option (default None / not required)",
|
|
472
|
+
severity="info",
|
|
473
|
+
)
|
|
474
|
+
ty = option(ty)
|
|
475
|
+
attrs.append(("default", None))
|
|
476
|
+
if optional_by_absence or ctx.cfg.omit_none: # Pydantic dumps None fields as null
|
|
477
|
+
attrs.append(("skip_serializing_if", "Option::is_none"))
|
|
478
|
+
default_expr = ir.Lit(kind="none", ty=ty)
|
|
479
|
+
elif default is not None or factory is not None:
|
|
480
|
+
serde_default, default_expr, extra = _default(ctx, mapper, struct, py, default, factory, ty)
|
|
481
|
+
attrs.append(serde_default)
|
|
482
|
+
docs: list[str] = []
|
|
483
|
+
schema_attr: list[ir.Attribute] = []
|
|
484
|
+
if isinstance(kw.get("description"), ast.Constant):
|
|
485
|
+
docs.append(str(_const(kw["description"])))
|
|
486
|
+
if ctx.cfg.schema_enabled:
|
|
487
|
+
items, _ = field_items(ty, kw, default)
|
|
488
|
+
if items:
|
|
489
|
+
schema_attr.append(ir.Attribute(attr, items))
|
|
490
|
+
if _const(kw.get("exclude")):
|
|
491
|
+
attrs.append(("skip_serializing", None))
|
|
492
|
+
rust = snake(py)
|
|
493
|
+
if kind == "model":
|
|
494
|
+
has_default = default is not None or factory is not None or optional_by_absence
|
|
495
|
+
plan = plan_field(ty, stmt.annotation, kw, unknown, flags, has_default, ctx.cfg.i64_models)
|
|
496
|
+
extra += _enforce(ctx, info, struct, py, rust, ty, stmt, plan, attrs)
|
|
497
|
+
elif unknown or any(k in kw for k in NOT_ENFORCED_OUTSIDE_PYDANTIC):
|
|
498
|
+
ctx.col.diag(
|
|
499
|
+
"PY2RS017",
|
|
500
|
+
stmt,
|
|
501
|
+
f"{struct}.{py}: constraints are not enforced for a {kind}",
|
|
502
|
+
construct=py,
|
|
503
|
+
)
|
|
504
|
+
_aliases(ctx, info, py, rust, kw, flags, attrs)
|
|
505
|
+
info.fields[py] = FieldInfo(py, rust, ty, default_expr)
|
|
506
|
+
serde = [ir.Attribute("serde", attrs)] if attrs else []
|
|
507
|
+
return ir.FieldDef(
|
|
508
|
+
rust, ty, docs, serde + schema_attr, span=ir.span_of(stmt, ctx.col.file)
|
|
509
|
+
), extra
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
NOT_ENFORCED_OUTSIDE_PYDANTIC = ("ge", "gt", "le", "lt", "min_length", "max_length", "pattern")
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def _enforce(
|
|
516
|
+
ctx: Ctx,
|
|
517
|
+
info: ModelInfo,
|
|
518
|
+
struct: str,
|
|
519
|
+
py: str,
|
|
520
|
+
rust: str,
|
|
521
|
+
ty: RType,
|
|
522
|
+
stmt: ast.AnnAssign,
|
|
523
|
+
plan: FieldPlan,
|
|
524
|
+
attrs: list[ir.Arg],
|
|
525
|
+
) -> list[ir.Item]:
|
|
526
|
+
"""Turn a field plan into `deserialize_with`, TODOs and drift entries."""
|
|
527
|
+
items: list[ir.Item] = []
|
|
528
|
+
problems = list(plan.problems)
|
|
529
|
+
needs_runtime = plan.validator or plan.required_option
|
|
530
|
+
if needs_runtime and ctx.cfg.vendor_runtime:
|
|
531
|
+
problems.append("field validation needs the python2rust-rt feature pydantic (not vendored)")
|
|
532
|
+
needs_runtime = False
|
|
533
|
+
if needs_runtime:
|
|
534
|
+
ctx.features.add("pydantic")
|
|
535
|
+
if plan.validator:
|
|
536
|
+
name = f"check_{wire_name(snake(struct))}_{wire_name(rust)}"
|
|
537
|
+
attrs.append(("deserialize_with", name))
|
|
538
|
+
items.append(ir.Validator(name, ty, plan.rules, span=ir.span_of(stmt, ctx.col.file)))
|
|
539
|
+
else:
|
|
540
|
+
attrs.append(("deserialize_with", "rt::pydantic::required"))
|
|
541
|
+
for problem in problems:
|
|
542
|
+
info.unchecked = True
|
|
543
|
+
items.append(todo_item(ctx, "PY2RS017", stmt, f"{struct}.{py}: {problem}", "constraint"))
|
|
544
|
+
info.inexact = info.inexact or bool(plan.drift)
|
|
545
|
+
for code, text in plan.drift:
|
|
546
|
+
ctx.col.diag(code, stmt, f"{struct}.{py}: {text}", severity="info", construct=py)
|
|
547
|
+
info.validated = info.validated or plan.constrained
|
|
548
|
+
return items
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _aliases(
|
|
552
|
+
ctx: Ctx,
|
|
553
|
+
info: ModelInfo,
|
|
554
|
+
py: str,
|
|
555
|
+
rust: str,
|
|
556
|
+
kw: dict[str, ast.expr],
|
|
557
|
+
flags: ModelFlags,
|
|
558
|
+
attrs: list[ir.Arg],
|
|
559
|
+
) -> None:
|
|
560
|
+
"""Pydantic validates by alias but dumps by field name (unless `by_alias`, the FastAPI way)."""
|
|
561
|
+
|
|
562
|
+
def text(key: str) -> str | None:
|
|
563
|
+
value = _const(kw.get(key))
|
|
564
|
+
return value if isinstance(value, str) else None
|
|
565
|
+
|
|
566
|
+
alias = text("alias")
|
|
567
|
+
read = text("validation_alias") or alias
|
|
568
|
+
by_alias = ctx.cfg.profile == "fastapi"
|
|
569
|
+
deserialize = read or py
|
|
570
|
+
serialize = (text("serialization_alias") or alias or py) if by_alias else py
|
|
571
|
+
plain = wire_name(rust)
|
|
572
|
+
if deserialize == serialize:
|
|
573
|
+
if deserialize != plain:
|
|
574
|
+
attrs.insert(0, ("rename", deserialize))
|
|
575
|
+
else:
|
|
576
|
+
pair = tuple(
|
|
577
|
+
(k, v)
|
|
578
|
+
for k, v in (("deserialize", deserialize), ("serialize", serialize))
|
|
579
|
+
if v != plain
|
|
580
|
+
)
|
|
581
|
+
attrs.insert(0, ("rename", pair))
|
|
582
|
+
if read and read != py and flags.populate_by_name:
|
|
583
|
+
attrs.insert(1, ("alias", py))
|
|
584
|
+
info.aliased = info.aliased or any(a != py for a in (read, text("serialization_alias")) if a)
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def _emptyish(node: ast.expr | None, ty: RType) -> bool:
|
|
588
|
+
"""A default equal to Rust's `Default::default()` for the field type."""
|
|
589
|
+
if node is None or ty.name not in DEFAULT_TYPES:
|
|
590
|
+
return False
|
|
591
|
+
if isinstance(node, ast.Constant):
|
|
592
|
+
return node.value is not None and not isinstance(node.value, bytes) and not node.value
|
|
593
|
+
if isinstance(node, (ast.List, ast.Set, ast.Tuple)):
|
|
594
|
+
return not node.elts
|
|
595
|
+
return isinstance(node, ast.Dict) and not node.keys
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def _default(
|
|
599
|
+
ctx: Ctx,
|
|
600
|
+
mapper: TypeMapper,
|
|
601
|
+
struct: str,
|
|
602
|
+
py: str,
|
|
603
|
+
default: ast.expr | None,
|
|
604
|
+
factory: ast.expr | None,
|
|
605
|
+
ty: RType,
|
|
606
|
+
) -> tuple[ir.Arg, ir.RExpr, list[ir.Item]]:
|
|
607
|
+
"""(serde attribute arg, Rust default expression, helper items) for a field default."""
|
|
608
|
+
std = ir.Call(func=ir.Path(path="Default::default"), ty=ty)
|
|
609
|
+
if (
|
|
610
|
+
factory is not None
|
|
611
|
+
and isinstance(factory, ast.Name)
|
|
612
|
+
and factory.id in FACTORIES
|
|
613
|
+
and ty.name in DEFAULT_TYPES
|
|
614
|
+
):
|
|
615
|
+
return ("default", None), std, []
|
|
616
|
+
if _emptyish(default, ty):
|
|
617
|
+
return ("default", None), std, []
|
|
618
|
+
source: ast.expr | None = default
|
|
619
|
+
if factory is not None:
|
|
620
|
+
source = (
|
|
621
|
+
factory.body
|
|
622
|
+
if isinstance(factory, ast.Lambda)
|
|
623
|
+
else ast.Call(func=factory, args=[], keywords=[])
|
|
624
|
+
)
|
|
625
|
+
ast.copy_location(source, factory)
|
|
626
|
+
ast.fix_missing_locations(source)
|
|
627
|
+
fn = f"default_{wire_name(snake(struct))}_{wire_name(snake(py))}"
|
|
628
|
+
lw = CallLowerer(ctx, mapper)
|
|
629
|
+
try:
|
|
630
|
+
assert source is not None
|
|
631
|
+
value = lw.coerce(lw.expr(source), ty)
|
|
632
|
+
except Unsupported as exc:
|
|
633
|
+
value = ir.TodoX(
|
|
634
|
+
marker=ctx.col.todo(
|
|
635
|
+
exc.code,
|
|
636
|
+
exc.node or source,
|
|
637
|
+
f"default of {struct}.{py}: {exc.construct}",
|
|
638
|
+
kind="expr",
|
|
639
|
+
)
|
|
640
|
+
)
|
|
641
|
+
helper = ir.Function(
|
|
642
|
+
fn, [], ty, [ir.Return(value, True)], vis="pub ", span=ir.span_of(source, ctx.col.file)
|
|
643
|
+
)
|
|
644
|
+
ownership.apply(helper)
|
|
645
|
+
return ("default", fn), ir.Call(func=ir.Path(path=fn), ty=ty), [helper]
|