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,122 @@
|
|
|
1
|
+
"""Rust types. `RType.name` is the Rust spelling; `tuple`, `Iter`, `Fn`, `&`, `&mut` and `?` are internal."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class RType:
|
|
10
|
+
name: str
|
|
11
|
+
args: tuple[RType, ...] = ()
|
|
12
|
+
|
|
13
|
+
def rust(self) -> str:
|
|
14
|
+
if self.name == "?":
|
|
15
|
+
return "_"
|
|
16
|
+
if self.name == "&":
|
|
17
|
+
return f"&{self.args[0].rust()}"
|
|
18
|
+
if self.name == "&mut":
|
|
19
|
+
return f"&mut {self.args[0].rust()}"
|
|
20
|
+
if self.name == "[]":
|
|
21
|
+
return f"[{self.args[0].rust()}]"
|
|
22
|
+
if self.name == "tuple":
|
|
23
|
+
inner = ", ".join(a.rust() for a in self.args)
|
|
24
|
+
return f"({inner},)" if len(self.args) == 1 else f"({inner})"
|
|
25
|
+
if self.args:
|
|
26
|
+
return f"{self.name}<{', '.join(a.rust() for a in self.args)}>"
|
|
27
|
+
return self.name
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def known(self) -> bool:
|
|
31
|
+
return self.name != "?" and all(a.known for a in self.args)
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def unknown(self) -> bool:
|
|
35
|
+
return self.name == "?"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def T(name: str, *args: RType) -> RType:
|
|
39
|
+
return RType(name, args)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
UNKNOWN = T("?")
|
|
43
|
+
STR, INT, FLOAT, BOOL, UNIT = T("String"), T("i64"), T("f64"), T("bool"), T("()")
|
|
44
|
+
VALUE = T("serde_json::Value")
|
|
45
|
+
BYTES = T("Vec", T("u8"))
|
|
46
|
+
COPY_NAMES = frozenset({"i64", "f64", "bool", "()", "usize", "u8", "char"})
|
|
47
|
+
NOT_CLONED = frozenset({"Iter", "Fn", "?"}) # moved as-is, never cloned
|
|
48
|
+
MAP, SET = "IndexMap", "IndexSet"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def option(inner: RType) -> RType:
|
|
52
|
+
return inner if inner.name == "Option" else T("Option", inner)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
SHARED = "rt::Shared" # a user class called Shared must not collide: the name carries the path
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def peel(ty: RType) -> RType:
|
|
59
|
+
"""The value type: references and Shared handles are looked through."""
|
|
60
|
+
while ty.name in ("&", "&mut", SHARED):
|
|
61
|
+
ty = ty.args[0]
|
|
62
|
+
return ty
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def is_ref(ty: RType) -> bool:
|
|
66
|
+
return ty.name in ("&", "&mut")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def is_copy(ty: RType) -> bool:
|
|
70
|
+
return ty.name in COPY_NAMES or (ty.name == "tuple" and all(is_copy(a) for a in ty.args))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def arg(ty: RType, i: int = 0) -> RType:
|
|
74
|
+
ty = peel(ty)
|
|
75
|
+
return ty.args[i] if len(ty.args) > i else UNKNOWN
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def elem_type(ty: RType) -> RType:
|
|
79
|
+
ty = peel(ty)
|
|
80
|
+
if ty.name == "String":
|
|
81
|
+
return STR
|
|
82
|
+
return arg(ty) if ty.name in ("Vec", SET, "Iter", MAP) else UNKNOWN
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _unshare(ty: RType) -> RType:
|
|
86
|
+
while ty.name == SHARED:
|
|
87
|
+
ty = ty.args[0]
|
|
88
|
+
return ty
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def compatible(a: RType, b: RType) -> bool:
|
|
92
|
+
"""Can a variable of type `a` be assigned a value of type `b` (after None/int->float coercion)?"""
|
|
93
|
+
a, b = _unshare(a), _unshare(b)
|
|
94
|
+
if a.unknown or b.unknown or a == b:
|
|
95
|
+
return True
|
|
96
|
+
if {a.name, b.name} <= {"i64", "f64"}:
|
|
97
|
+
return True
|
|
98
|
+
if a.name == "Option" and b.name != "Option":
|
|
99
|
+
return compatible(arg(a), b)
|
|
100
|
+
if a.name != b.name or len(a.args) != len(b.args):
|
|
101
|
+
return False
|
|
102
|
+
return all(compatible(x, y) for x, y in zip(a.args, b.args, strict=False))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def unify(a: RType, b: RType) -> RType:
|
|
106
|
+
"""Common type of two branches (None and T unify to Option<T>)."""
|
|
107
|
+
a, b = _unshare(a), _unshare(b)
|
|
108
|
+
if a.unknown:
|
|
109
|
+
return b
|
|
110
|
+
if b.unknown or a == b:
|
|
111
|
+
return a
|
|
112
|
+
if a.name == "Option" and arg(a).unknown:
|
|
113
|
+
return option(b)
|
|
114
|
+
if b.name == "Option" and arg(b).unknown:
|
|
115
|
+
return option(a)
|
|
116
|
+
if a.name == "Option" and arg(a) == b:
|
|
117
|
+
return a
|
|
118
|
+
if b.name == "Option" and arg(b) == a:
|
|
119
|
+
return b
|
|
120
|
+
if {a.name, b.name} == {"i64", "f64"}:
|
|
121
|
+
return FLOAT
|
|
122
|
+
return a
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"""Python annotation -> Rust type. Generated enums (Literal, Union) are collected on the mapper."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
|
|
8
|
+
from ..frontend.names import camel, variant_name
|
|
9
|
+
from ..lower.context import Ctx, ModelInfo
|
|
10
|
+
from . import nodes as ir
|
|
11
|
+
from .rtypes import (
|
|
12
|
+
BOOL,
|
|
13
|
+
BYTES,
|
|
14
|
+
FLOAT,
|
|
15
|
+
INT,
|
|
16
|
+
MAP,
|
|
17
|
+
SET,
|
|
18
|
+
SHARED,
|
|
19
|
+
STR,
|
|
20
|
+
UNIT,
|
|
21
|
+
UNKNOWN,
|
|
22
|
+
VALUE,
|
|
23
|
+
RType,
|
|
24
|
+
T,
|
|
25
|
+
arg,
|
|
26
|
+
option,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
SIMPLE = {"str": STR, "int": INT, "float": FLOAT, "bool": BOOL, "bytes": BYTES, "None": UNIT}
|
|
30
|
+
LISTS = {
|
|
31
|
+
"list",
|
|
32
|
+
"List",
|
|
33
|
+
"Sequence",
|
|
34
|
+
"MutableSequence",
|
|
35
|
+
"Iterable",
|
|
36
|
+
"Collection",
|
|
37
|
+
"deque",
|
|
38
|
+
"Iterator",
|
|
39
|
+
}
|
|
40
|
+
DICTS = {"dict", "Dict", "Mapping", "MutableMapping", "OrderedDict", "defaultdict"}
|
|
41
|
+
SETS = {"set", "Set", "frozenset", "FrozenSet", "AbstractSet", "MutableSet"}
|
|
42
|
+
ANYS = {"Any", "object", "JsonValue", "JSON"}
|
|
43
|
+
WRAPPERS = {"Final", "ClassVar", "Required", "NotRequired", "ReadOnly", "InitVar"}
|
|
44
|
+
ENUM_DERIVES = ["Debug", "Clone", "Copy", "PartialEq", "Eq", "Hash", "Serialize", "Deserialize"]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def dotted(node: ast.AST) -> str:
|
|
48
|
+
if isinstance(node, ast.Name):
|
|
49
|
+
return node.id
|
|
50
|
+
if isinstance(node, ast.Attribute):
|
|
51
|
+
return f"{dotted(node.value)}.{node.attr}"
|
|
52
|
+
return ""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class TypeMapper:
|
|
56
|
+
def __init__(self, ctx: Ctx) -> None:
|
|
57
|
+
self.ctx = ctx
|
|
58
|
+
self.generated: list[ir.Item] = []
|
|
59
|
+
self._enum_names: dict[tuple[str, ...], str] = {}
|
|
60
|
+
self._used: set[str] = set()
|
|
61
|
+
|
|
62
|
+
# -- public ---------------------------------------------------------------------------
|
|
63
|
+
def map(self, node: ast.expr | None, hint: str = "Kind") -> RType:
|
|
64
|
+
return self.map_meta(node, hint)[0]
|
|
65
|
+
|
|
66
|
+
def map_meta(self, node: ast.expr | None, hint: str = "Kind") -> tuple[RType, list[ast.expr]]:
|
|
67
|
+
"""Map an annotation; also return `Annotated[...]` metadata expressions."""
|
|
68
|
+
if node is None:
|
|
69
|
+
return UNKNOWN, []
|
|
70
|
+
if isinstance(node, ast.Subscript) and dotted(node.value).split(".")[-1] == "Annotated":
|
|
71
|
+
items = _elements(node.slice)
|
|
72
|
+
return self.map(items[0], hint), items[1:]
|
|
73
|
+
return self._map(node, hint), []
|
|
74
|
+
|
|
75
|
+
def _register(self, name: str) -> None:
|
|
76
|
+
if self.ctx.cfg.schema_enabled:
|
|
77
|
+
self.ctx.schemas.append(name)
|
|
78
|
+
|
|
79
|
+
def flush(self) -> list[ir.Item]:
|
|
80
|
+
items, self.generated = self.generated, []
|
|
81
|
+
return items
|
|
82
|
+
|
|
83
|
+
# -- dispatch -------------------------------------------------------------------------
|
|
84
|
+
def _map(self, node: ast.expr, hint: str) -> RType:
|
|
85
|
+
if isinstance(node, ast.Constant):
|
|
86
|
+
if node.value is None:
|
|
87
|
+
return UNIT
|
|
88
|
+
if isinstance(node.value, str):
|
|
89
|
+
return self._forward(node, hint)
|
|
90
|
+
return self._unknown(node)
|
|
91
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
|
|
92
|
+
return self._union(_flatten_or(node), node, hint)
|
|
93
|
+
if isinstance(node, ast.Subscript):
|
|
94
|
+
return self._subscript(node, hint)
|
|
95
|
+
if isinstance(node, (ast.Name, ast.Attribute)):
|
|
96
|
+
return self._named(node, hint)
|
|
97
|
+
return self._unknown(node)
|
|
98
|
+
|
|
99
|
+
def shared(self, ty: RType) -> RType:
|
|
100
|
+
"""A Python list/dict/set/instance is a handle (`Shared<T>`), unless shared = "off"."""
|
|
101
|
+
return T(SHARED, ty) if self.ctx.cfg.shared != "off" else ty
|
|
102
|
+
|
|
103
|
+
def shared_model(self, info: ModelInfo) -> RType:
|
|
104
|
+
ty = T(info.rust)
|
|
105
|
+
return ty if info.frozen else self.shared(ty)
|
|
106
|
+
|
|
107
|
+
def _forward(self, node: ast.Constant, hint: str) -> RType:
|
|
108
|
+
try:
|
|
109
|
+
inner = ast.parse(str(node.value), mode="eval").body
|
|
110
|
+
except SyntaxError:
|
|
111
|
+
return self._unknown(node)
|
|
112
|
+
ast.copy_location(inner, node)
|
|
113
|
+
for child in ast.walk(inner):
|
|
114
|
+
ast.copy_location(child, node)
|
|
115
|
+
return self._map(inner, hint)
|
|
116
|
+
|
|
117
|
+
def _named(self, node: ast.Name | ast.Attribute, hint: str) -> RType:
|
|
118
|
+
name = dotted(node)
|
|
119
|
+
last = name.split(".")[-1]
|
|
120
|
+
cfg = self.ctx.cfg.type_map
|
|
121
|
+
resolved = self.ctx.resolve(name)
|
|
122
|
+
for key in (name, resolved, last):
|
|
123
|
+
if key in cfg:
|
|
124
|
+
if last == "Decimal" and cfg[key] == "String":
|
|
125
|
+
self.ctx.col.diag(
|
|
126
|
+
"PY2RS009", node, "Decimal is kept as a String (JSON form)", severity="info"
|
|
127
|
+
)
|
|
128
|
+
return T(cfg[key])
|
|
129
|
+
if last in self.ctx.aliases and "." not in name:
|
|
130
|
+
return self.ctx.aliases[last]
|
|
131
|
+
if last in SIMPLE and "." not in name:
|
|
132
|
+
return SIMPLE[last]
|
|
133
|
+
if last in ANYS:
|
|
134
|
+
self.ctx.col.diag(
|
|
135
|
+
"PY2RS007", node, f"{last} maps to serde_json::Value", severity="info"
|
|
136
|
+
)
|
|
137
|
+
return VALUE
|
|
138
|
+
if last in LISTS | SETS | DICTS | {"tuple", "Tuple"}:
|
|
139
|
+
return self._subscript_args(last, [], node, hint)
|
|
140
|
+
member = self.ctx.project_member(name) if "." in name else None
|
|
141
|
+
if member and member[0].kind == "alias":
|
|
142
|
+
return member[0].obj
|
|
143
|
+
if member and member[0].kind in ("model", "enum"):
|
|
144
|
+
from ..frontend.project_imports import bring_in
|
|
145
|
+
|
|
146
|
+
bring_in(self.ctx, member[0], member[0].name)
|
|
147
|
+
obj = member[0].obj
|
|
148
|
+
return self.shared_model(obj) if member[0].kind == "model" else T(obj.rust)
|
|
149
|
+
if name in self.ctx.models:
|
|
150
|
+
return self.shared_model(self.ctx.models[name])
|
|
151
|
+
if name in self.ctx.enums:
|
|
152
|
+
return T(self.ctx.enums[name].rust)
|
|
153
|
+
if name in self.ctx.opaque:
|
|
154
|
+
return T(name)
|
|
155
|
+
return self._unknown(node)
|
|
156
|
+
|
|
157
|
+
def _subscript(self, node: ast.Subscript, hint: str) -> RType:
|
|
158
|
+
head = dotted(node.value).split(".")[-1]
|
|
159
|
+
return self._subscript_args(head, _elements(node.slice), node, hint)
|
|
160
|
+
|
|
161
|
+
def _subscript_args(self, head: str, args: list[ast.expr], node: ast.expr, hint: str) -> RType:
|
|
162
|
+
sub: Callable[[ast.expr], RType] = lambda a: self.map(a, hint) # noqa: E731
|
|
163
|
+
if head == "Optional" and args:
|
|
164
|
+
return option(sub(args[0]))
|
|
165
|
+
if head == "Union":
|
|
166
|
+
return self._union(args, node, hint)
|
|
167
|
+
if head == "Literal":
|
|
168
|
+
return self._literal(args, node, hint)
|
|
169
|
+
if head in WRAPPERS and args:
|
|
170
|
+
return sub(args[0])
|
|
171
|
+
if head in LISTS:
|
|
172
|
+
return self.shared(T("Vec", sub(args[0]) if args else self._any(node)))
|
|
173
|
+
if head in SETS:
|
|
174
|
+
return self.shared(T(SET, sub(args[0]) if args else self._any(node)))
|
|
175
|
+
if head in DICTS:
|
|
176
|
+
if len(args) == 2:
|
|
177
|
+
return self.shared(T(MAP, sub(args[0]), sub(args[1])))
|
|
178
|
+
return self.shared(T(MAP, STR, self._any(node)))
|
|
179
|
+
if head in ("tuple", "Tuple"):
|
|
180
|
+
return self._tuple(args, node, hint)
|
|
181
|
+
if head == "Callable" and len(args) == 2 and isinstance(args[0], ast.List):
|
|
182
|
+
inputs = ", ".join(self.map(a, hint).rust() for a in args[0].elts)
|
|
183
|
+
output = self.map(args[1], hint)
|
|
184
|
+
arrow = "" if output == UNIT else f" -> {output.rust()}"
|
|
185
|
+
return T(f"impl Fn({inputs}){arrow}")
|
|
186
|
+
return self._unknown(node)
|
|
187
|
+
|
|
188
|
+
def _tuple(self, args: list[ast.expr], node: ast.expr, hint: str) -> RType:
|
|
189
|
+
if not args:
|
|
190
|
+
return T("Vec", self._any(node))
|
|
191
|
+
if len(args) == 2 and isinstance(args[1], ast.Constant) and args[1].value is Ellipsis:
|
|
192
|
+
return T("Vec", self.map(args[0], hint))
|
|
193
|
+
if len(args) == 1 and isinstance(args[0], ast.Tuple) and not args[0].elts:
|
|
194
|
+
return UNIT
|
|
195
|
+
return T("tuple", *(self.map(a, hint) for a in args))
|
|
196
|
+
|
|
197
|
+
def _any(self, node: ast.AST) -> RType:
|
|
198
|
+
self.ctx.col.diag(
|
|
199
|
+
"PY2RS007", node, "unparameterised container: Value elements", severity="info"
|
|
200
|
+
)
|
|
201
|
+
return VALUE
|
|
202
|
+
|
|
203
|
+
def _unknown(self, node: ast.AST) -> RType:
|
|
204
|
+
text = ast.unparse(node)
|
|
205
|
+
marker = self.ctx.col.todo("PY2RS005", node, f"type {text}", kind="type")
|
|
206
|
+
ident = "".join(c if c.isalnum() else "_" for c in text)
|
|
207
|
+
return T(f"Py2rsUnmapped_{ident} /* {marker} */")
|
|
208
|
+
|
|
209
|
+
# -- Literal and Union -> enums -------------------------------------------------------
|
|
210
|
+
def _literal(self, args: list[ast.expr], node: ast.expr, hint: str) -> RType:
|
|
211
|
+
values = [a.value for a in args if isinstance(a, ast.Constant)]
|
|
212
|
+
if len(values) != len(args) or not values:
|
|
213
|
+
return self._unknown(node)
|
|
214
|
+
kinds = {type(v) for v in values}
|
|
215
|
+
if kinds == {str}:
|
|
216
|
+
return self._string_enum([str(v) for v in values], hint)
|
|
217
|
+
if kinds <= {int, bool} and len(kinds) == 1:
|
|
218
|
+
self.ctx.col.diag(
|
|
219
|
+
"PY2RS009", node, "Literal of ints/bools maps to its base type", severity="info"
|
|
220
|
+
)
|
|
221
|
+
return BOOL if kinds == {bool} else INT
|
|
222
|
+
return self._unknown(node)
|
|
223
|
+
|
|
224
|
+
def _string_enum(self, values: list[str], hint: str) -> RType:
|
|
225
|
+
key = tuple(values)
|
|
226
|
+
if key not in self._enum_names:
|
|
227
|
+
name = self._fresh(camel(hint) or "Kind")
|
|
228
|
+
taken: set[str] = set()
|
|
229
|
+
variants = []
|
|
230
|
+
table: dict[object, str] = {}
|
|
231
|
+
for i, value in enumerate(values):
|
|
232
|
+
vname = variant_name(value, i, taken)
|
|
233
|
+
table[value] = vname
|
|
234
|
+
attrs = [ir.Attribute("serde", [("rename", value)])] if vname != value else []
|
|
235
|
+
variants.append(ir.Variant(vname, attrs=attrs))
|
|
236
|
+
self.ctx.lit_enums[name] = table
|
|
237
|
+
self._enum_names[key] = name
|
|
238
|
+
self.generated.append(ir.EnumDef(name, variants, self.ctx.derives(*ENUM_DERIVES)))
|
|
239
|
+
self._register(name)
|
|
240
|
+
return T(self._enum_names[key])
|
|
241
|
+
|
|
242
|
+
def _fresh(self, base: str) -> str:
|
|
243
|
+
name, n = base, 1
|
|
244
|
+
while name in self._used or name in {m.rust for m in self.ctx.models.values()}:
|
|
245
|
+
n += 1
|
|
246
|
+
name = f"{base}{n}"
|
|
247
|
+
self._used.add(name)
|
|
248
|
+
return name
|
|
249
|
+
|
|
250
|
+
def _union(self, members: list[ast.expr], node: ast.expr, hint: str) -> RType:
|
|
251
|
+
non_none = [m for m in members if not (isinstance(m, ast.Constant) and m.value is None)]
|
|
252
|
+
has_none = len(non_none) != len(members)
|
|
253
|
+
mapped = [self.map(m, hint) for m in non_none]
|
|
254
|
+
unique = list(dict.fromkeys(mapped))
|
|
255
|
+
if len(unique) == 1:
|
|
256
|
+
result = unique[0]
|
|
257
|
+
elif set(unique) == {INT, FLOAT}:
|
|
258
|
+
self.ctx.col.diag("PY2RS009", node, "int | float maps to f64", severity="info")
|
|
259
|
+
result = FLOAT
|
|
260
|
+
else:
|
|
261
|
+
result = self._union_enum(unique, node)
|
|
262
|
+
return option(result) if has_none else result
|
|
263
|
+
|
|
264
|
+
def _union_enum(self, types: list[RType], node: ast.AST) -> RType:
|
|
265
|
+
names = [_union_variant(t) for t in types]
|
|
266
|
+
enum_name = "Or".join(dict.fromkeys(names))
|
|
267
|
+
if enum_name not in self._used:
|
|
268
|
+
self._used.add(enum_name)
|
|
269
|
+
taken: set[str] = set()
|
|
270
|
+
variants = []
|
|
271
|
+
for name, ty in zip(names, types, strict=False):
|
|
272
|
+
vname = name
|
|
273
|
+
while vname in taken:
|
|
274
|
+
vname += "2"
|
|
275
|
+
taken.add(vname)
|
|
276
|
+
variants.append(ir.Variant(vname, payload=ty))
|
|
277
|
+
self.ctx.unions[enum_name] = [
|
|
278
|
+
(v.name, t) for v, t in zip(variants, types, strict=False)
|
|
279
|
+
]
|
|
280
|
+
derives = self.ctx.derives("Debug", "Clone", "PartialEq", "Serialize", "Deserialize")
|
|
281
|
+
self.generated.append(
|
|
282
|
+
ir.EnumDef(
|
|
283
|
+
enum_name,
|
|
284
|
+
variants,
|
|
285
|
+
derives,
|
|
286
|
+
attrs=[ir.Attribute("serde", [("untagged", None)])],
|
|
287
|
+
)
|
|
288
|
+
)
|
|
289
|
+
self._register(enum_name)
|
|
290
|
+
self.ctx.col.diag(
|
|
291
|
+
"PY2RS008", node, f"union -> untagged enum {enum_name}", severity="info"
|
|
292
|
+
)
|
|
293
|
+
return T(enum_name)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _union_variant(ty: RType) -> str:
|
|
297
|
+
if ty.name == "String":
|
|
298
|
+
return "Str"
|
|
299
|
+
if ty.name == "i64":
|
|
300
|
+
return "Int"
|
|
301
|
+
if ty.name == "f64":
|
|
302
|
+
return "Float"
|
|
303
|
+
if ty.name == "bool":
|
|
304
|
+
return "Bool"
|
|
305
|
+
if ty.name == "Vec":
|
|
306
|
+
return "List" + (_union_variant(arg(ty)) if ty.args and arg(ty).known else "")
|
|
307
|
+
if ty.name == MAP:
|
|
308
|
+
return "Dict"
|
|
309
|
+
if ty.name == "Option":
|
|
310
|
+
return "Opt" + _union_variant(arg(ty))
|
|
311
|
+
clean = "".join(c for c in ty.name if c.isalnum())
|
|
312
|
+
return camel(clean) or "Other"
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _elements(slice_node: ast.expr) -> list[ast.expr]:
|
|
316
|
+
return list(slice_node.elts) if isinstance(slice_node, ast.Tuple) else [slice_node]
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _flatten_or(node: ast.expr) -> list[ast.expr]:
|
|
320
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
|
|
321
|
+
return _flatten_or(node.left) + _flatten_or(node.right)
|
|
322
|
+
return [node]
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _esc(text: str) -> str:
|
|
326
|
+
return text.replace("\\", "\\\\").replace('"', '\\"')
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Lowering of Python constructs to the IR."""
|