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,722 @@
|
|
|
1
|
+
"""Statement lowering: ast.stmt -> IR statements. A failing statement becomes a todo!()."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
|
|
7
|
+
from ..emit.render import expr as expr_text
|
|
8
|
+
from ..frontend.names import camel, const_name
|
|
9
|
+
from ..frontend.walrus import hoist_walrus
|
|
10
|
+
from ..ir import nodes as ir
|
|
11
|
+
from ..ir.rtypes import (
|
|
12
|
+
BOOL,
|
|
13
|
+
FLOAT,
|
|
14
|
+
INT,
|
|
15
|
+
MAP,
|
|
16
|
+
SET,
|
|
17
|
+
STR,
|
|
18
|
+
UNIT,
|
|
19
|
+
UNKNOWN,
|
|
20
|
+
RType,
|
|
21
|
+
T,
|
|
22
|
+
arg,
|
|
23
|
+
compatible,
|
|
24
|
+
peel,
|
|
25
|
+
unify,
|
|
26
|
+
)
|
|
27
|
+
from . import fstrings
|
|
28
|
+
from .calls import expect
|
|
29
|
+
from .exceptions import ExceptionLowerer
|
|
30
|
+
from .lowerer import NotFresh, Unsupported, Var, local_name
|
|
31
|
+
|
|
32
|
+
ARITH_SYM = {ast.Add: "+", ast.Sub: "-", ast.Mult: "*"}
|
|
33
|
+
# Statements that map to a dedicated TODO code instead of the generic "unsupported statement".
|
|
34
|
+
STMT_CODES = {
|
|
35
|
+
"TryStar": ("PY2RS012", "try/except*"),
|
|
36
|
+
"AsyncWith": ("PY2RS025", "async with"),
|
|
37
|
+
"AsyncFor": ("PY2RS011", "async for"),
|
|
38
|
+
"FunctionDef": ("PY2RS026", "nested function"),
|
|
39
|
+
"AsyncFunctionDef": ("PY2RS026", "nested async function"),
|
|
40
|
+
"ClassDef": ("PY2RS026", "nested class"),
|
|
41
|
+
"Global": ("PY2RS028", "global"),
|
|
42
|
+
"Nonlocal": ("PY2RS028", "nonlocal"),
|
|
43
|
+
}
|
|
44
|
+
MUTABLE_TYPES = ("Vec", MAP, SET)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _root(node: ast.expr) -> str | None:
|
|
48
|
+
while isinstance(node, (ast.Subscript, ast.Attribute)):
|
|
49
|
+
node = node.value
|
|
50
|
+
return node.id if isinstance(node, ast.Name) else None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class StmtLowerer(ExceptionLowerer):
|
|
54
|
+
def __init__(self, *a, **kw) -> None:
|
|
55
|
+
super().__init__(*a, **kw)
|
|
56
|
+
self.hoisted: dict[str, Var] = {}
|
|
57
|
+
self.leaky: set[str] = set()
|
|
58
|
+
self.reassigned: set[str] = set() # names bound more than once (no type narrowing)
|
|
59
|
+
self._tmp = 0
|
|
60
|
+
|
|
61
|
+
# -- blocks ---------------------------------------------------------------------------
|
|
62
|
+
def block(self, stmts: list[ast.stmt], tail: bool = False, after: int = 0) -> list[ir.RStmt]:
|
|
63
|
+
out: list[ir.RStmt] = []
|
|
64
|
+
prev = after
|
|
65
|
+
for i, s in enumerate(stmts):
|
|
66
|
+
out += [
|
|
67
|
+
ir.CommentS(c[3:], span=self.sp(s)) for c in self.ctx.take_comments(prev, s.lineno)
|
|
68
|
+
]
|
|
69
|
+
prev = s.end_lineno or s.lineno
|
|
70
|
+
depth = len(self.frames)
|
|
71
|
+
try:
|
|
72
|
+
made = self.stmt(s, tail and i == len(stmts) - 1)
|
|
73
|
+
except Unsupported as exc:
|
|
74
|
+
del self.frames[depth:]
|
|
75
|
+
made = self._failed(s, exc.code, exc.construct, exc.node, exc.hint)
|
|
76
|
+
except NotFresh:
|
|
77
|
+
raise # the whole body is lowered again with this local as a handle
|
|
78
|
+
except Exception as exc:
|
|
79
|
+
del self.frames[depth:]
|
|
80
|
+
made = self._failed(s, "PY2RS002", f"{type(exc).__name__}: {exc}"[:120], s, None)
|
|
81
|
+
for st in made:
|
|
82
|
+
if st.span is None:
|
|
83
|
+
st.span = self.sp(s)
|
|
84
|
+
out += made
|
|
85
|
+
return out
|
|
86
|
+
|
|
87
|
+
def _failed(
|
|
88
|
+
self, s: ast.stmt, code: str, construct: str, node: ast.AST | None, hint: str | None
|
|
89
|
+
) -> list[ir.RStmt]:
|
|
90
|
+
marker = self.ctx.col.todo(code, node or s, construct, hint=hint)
|
|
91
|
+
todo = ir.TodoX(marker=marker)
|
|
92
|
+
targets = (
|
|
93
|
+
s.targets
|
|
94
|
+
if isinstance(s, ast.Assign)
|
|
95
|
+
else [s.target]
|
|
96
|
+
if isinstance(s, ast.AnnAssign)
|
|
97
|
+
else []
|
|
98
|
+
)
|
|
99
|
+
names = [t.id for t in targets if isinstance(t, ast.Name)]
|
|
100
|
+
if len(names) == 1 and len(targets) == 1:
|
|
101
|
+
var = self.lookup(names[0])
|
|
102
|
+
if var:
|
|
103
|
+
return [ir.Assign(self.var(var), todo)]
|
|
104
|
+
self.declare(names[0], UNKNOWN)
|
|
105
|
+
return [ir.Let(ir.PVar(local_name(names[0]), names[0] in self.mutated), None, todo)]
|
|
106
|
+
return [ir.TodoS(marker)]
|
|
107
|
+
|
|
108
|
+
def stmt(self, s: ast.stmt, tail: bool) -> list[ir.RStmt]:
|
|
109
|
+
name = type(s).__name__
|
|
110
|
+
if name in STMT_CODES:
|
|
111
|
+
code, what = STMT_CODES[name]
|
|
112
|
+
raise Unsupported(code, what, s)
|
|
113
|
+
handler = getattr(self, f"st_{name}", None)
|
|
114
|
+
if handler is None:
|
|
115
|
+
raise Unsupported("PY2RS003", f"{name} statement", s)
|
|
116
|
+
return handler(s, tail) if name == "Return" else handler(s)
|
|
117
|
+
|
|
118
|
+
def scoped(self, stmts: list[ast.stmt], after: int) -> list[ir.RStmt]:
|
|
119
|
+
self.push()
|
|
120
|
+
try:
|
|
121
|
+
return self.block(stmts, after=after)
|
|
122
|
+
finally:
|
|
123
|
+
self.pop()
|
|
124
|
+
|
|
125
|
+
def _tmp_name(self) -> str:
|
|
126
|
+
self._tmp += 1
|
|
127
|
+
return f"tmp{self._tmp}"
|
|
128
|
+
|
|
129
|
+
# -- simple statements ----------------------------------------------------------------
|
|
130
|
+
def _import(self, s: ast.Import | ast.ImportFrom) -> list[ir.RStmt]:
|
|
131
|
+
"""A function-local import is fine when the type system or the library map consumes it."""
|
|
132
|
+
module = getattr(s, "module", None) or ""
|
|
133
|
+
for a in s.names:
|
|
134
|
+
full = f"{module}.{a.name}" if isinstance(s, ast.ImportFrom) else a.name
|
|
135
|
+
mod, name = (module, a.name) if isinstance(s, ast.ImportFrom) else (a.name, "")
|
|
136
|
+
if not self.ctx.import_consumed(mod, name):
|
|
137
|
+
raise Unsupported("PY2RS010", f"import {full} inside a function", s)
|
|
138
|
+
local = a.asname or (a.name if name else a.name.split(".")[0])
|
|
139
|
+
self.ctx.imports.setdefault(local, full if name else mod)
|
|
140
|
+
return []
|
|
141
|
+
|
|
142
|
+
def st_Import(self, s: ast.Import) -> list[ir.RStmt]:
|
|
143
|
+
return self._import(s)
|
|
144
|
+
|
|
145
|
+
def st_ImportFrom(self, s: ast.ImportFrom) -> list[ir.RStmt]:
|
|
146
|
+
return self._import(s)
|
|
147
|
+
|
|
148
|
+
def st_Pass(self, s: ast.Pass) -> list[ir.RStmt]:
|
|
149
|
+
return []
|
|
150
|
+
|
|
151
|
+
def st_Break(self, s: ast.Break) -> list[ir.RStmt]:
|
|
152
|
+
return [ir.Break()]
|
|
153
|
+
|
|
154
|
+
def st_Continue(self, s: ast.Continue) -> list[ir.RStmt]:
|
|
155
|
+
return [ir.Continue()]
|
|
156
|
+
|
|
157
|
+
def _value_step(self, name: str) -> list[ir.RStmt]:
|
|
158
|
+
"""Where `py2rs_run` assigns a module value, or reaches the TODO stub that replaced it."""
|
|
159
|
+
kind, payload, _ = self.ctx.value_steps[name]
|
|
160
|
+
if kind == "stub":
|
|
161
|
+
assert isinstance(payload, str)
|
|
162
|
+
stub = ir.Call(func=ir.Path(path=f"py2rs_todo_{payload}"), args=[], ty=UNIT)
|
|
163
|
+
return [ir.ExprS(stub)]
|
|
164
|
+
assert isinstance(payload, tuple)
|
|
165
|
+
value_ast, ty, local = payload # ty: the cell's type
|
|
166
|
+
value = self.coerce(self.expr(value_ast), ty)
|
|
167
|
+
cell = ir.Ref(operand=ir.Path(path=const_name(name)))
|
|
168
|
+
return [ir.ExprS(ir.rt("module_set_tl" if local else "module_set", cell, value, ty=UNIT))]
|
|
169
|
+
|
|
170
|
+
def st_Expr(self, s: ast.Expr) -> list[ir.RStmt]:
|
|
171
|
+
if isinstance(s.value, ast.Constant):
|
|
172
|
+
return []
|
|
173
|
+
v = s.value
|
|
174
|
+
if (
|
|
175
|
+
isinstance(v, ast.Call)
|
|
176
|
+
and isinstance(v.func, ast.Name)
|
|
177
|
+
and v.func.id == "__py2rs_value__"
|
|
178
|
+
):
|
|
179
|
+
return self._value_step(ast.literal_eval(v.args[0]))
|
|
180
|
+
return [ir.ExprS(self.expr(s.value))]
|
|
181
|
+
|
|
182
|
+
def st_Return(self, s: ast.Return, tail: bool = False) -> list[ir.RStmt]:
|
|
183
|
+
if s.value is None or (
|
|
184
|
+
isinstance(s.value, ast.Constant) and s.value.value is None and self.ret == UNIT
|
|
185
|
+
):
|
|
186
|
+
if self.fallible:
|
|
187
|
+
return [ir.Return(self._ok(ir.Lit(kind="unit")), tail)]
|
|
188
|
+
return [] if tail else [ir.Return(None)]
|
|
189
|
+
if self.ret == UNIT:
|
|
190
|
+
raise Unsupported("PY2RS038", "return with a value in a function returning None", s)
|
|
191
|
+
value = self.coerce(self.expr(s.value), self.ret)
|
|
192
|
+
return [ir.Return(self._ok(value) if self.fallible else value, tail)]
|
|
193
|
+
|
|
194
|
+
def _ok(self, value: ir.RExpr) -> ir.RExpr:
|
|
195
|
+
return ir.Call(func=ir.Path(path="Ok"), args=[value])
|
|
196
|
+
|
|
197
|
+
def st_Assert(self, s: ast.Assert) -> list[ir.RStmt]:
|
|
198
|
+
found = self._narrowable(s.test, ast.IsNot) if s.msg is None else None
|
|
199
|
+
if found is not None: # the assert also narrows the type
|
|
200
|
+
name, var = found
|
|
201
|
+
inner = arg(var.ty)
|
|
202
|
+
value = ir.CloneX(operand=self.var(var), ty=var.ty)
|
|
203
|
+
checked = expect(value, f"AssertionError: {name} is not None", inner)
|
|
204
|
+
narrowed = self.declare(name, inner)
|
|
205
|
+
return [ir.Let(ir.PVar(narrowed.rust, name in self.mutated), None, checked)]
|
|
206
|
+
args = [self.cond(s.test)]
|
|
207
|
+
if s.msg is not None:
|
|
208
|
+
args.append(fstrings.display(self, self.expr(s.msg), s))
|
|
209
|
+
return [ir.ExprS(ir.Macro(name="assert", args=args, ty=UNIT))]
|
|
210
|
+
|
|
211
|
+
def st_Delete(self, s: ast.Delete) -> list[ir.RStmt]:
|
|
212
|
+
out: list[ir.RStmt] = []
|
|
213
|
+
for t in s.targets:
|
|
214
|
+
if not isinstance(t, ast.Subscript) or isinstance(t.slice, ast.Slice):
|
|
215
|
+
raise Unsupported("PY2RS003", "del of anything but d[k] / xs[i]", s)
|
|
216
|
+
base, key = self.expr(t.value), self.expr(t.slice)
|
|
217
|
+
kind = peel(base.ty).name
|
|
218
|
+
if kind == MAP:
|
|
219
|
+
self.drift("PY2RS045", s, "del d[k] panics instead of raising KeyError")
|
|
220
|
+
removed = ir.method(base, "shift_remove", self.ref_of(key))
|
|
221
|
+
out.append(ir.ExprS(expect(removed, "KeyError", arg(base.ty, 1))))
|
|
222
|
+
elif kind == "Vec":
|
|
223
|
+
pos = ir.rt(
|
|
224
|
+
"idx", key, ir.method(ir.dup(base), "len", ty=T("usize")), ty=T("usize")
|
|
225
|
+
)
|
|
226
|
+
out.append(ir.ExprS(ir.method(base, "remove", pos)))
|
|
227
|
+
else:
|
|
228
|
+
raise Unsupported("PY2RS003", f"del on {peel(base.ty).rust()}", s)
|
|
229
|
+
return out
|
|
230
|
+
|
|
231
|
+
# -- assignment -----------------------------------------------------------------------
|
|
232
|
+
def bind(self, name: str, e: ir.RExpr, declared: RType | None = None) -> list[ir.RStmt]:
|
|
233
|
+
"""Bind or rebind local `name` to `e`."""
|
|
234
|
+
var, et = self.lookup(name), peel(e.ty)
|
|
235
|
+
if var is not None and declared is None and not compatible(var.ty, et):
|
|
236
|
+
var = None # Python rebinding to another type: shadow with a new let
|
|
237
|
+
if var is not None and declared is None:
|
|
238
|
+
if not var.ty.known:
|
|
239
|
+
merged = unify(peel(var.ty), et)
|
|
240
|
+
var.ty = self.inner_ty(merged) if var.rust in self.plain else self.store_ty(merged)
|
|
241
|
+
return [ir.Assign(self.var(var), self.coerce(e, var.ty))]
|
|
242
|
+
if name in self.hoist and name not in self.hoisted and declared is None:
|
|
243
|
+
hv = self.hoisted[name] = Var(local_name(name), self.store_ty(et))
|
|
244
|
+
self.frames[0][name] = hv
|
|
245
|
+
return [ir.Assign(self.var(hv), e)]
|
|
246
|
+
ty = declared or et
|
|
247
|
+
if name in self.plain_py and self.shared:
|
|
248
|
+
plain = self._plain_let(name, e, declared)
|
|
249
|
+
if plain is not None:
|
|
250
|
+
return plain
|
|
251
|
+
new = self.declare(name, ty)
|
|
252
|
+
ty = self.store_ty(ty)
|
|
253
|
+
note = (
|
|
254
|
+
ty
|
|
255
|
+
if ty.name not in ("?", "Fn", "Iter", "Future") and "impl " not in ty.rust()
|
|
256
|
+
else None
|
|
257
|
+
)
|
|
258
|
+
return [ir.Let(ir.PVar(new.rust, name in self.mutated), note, self.coerce(e, ty))]
|
|
259
|
+
|
|
260
|
+
def _plain_let(self, name: str, e: ir.RExpr, declared: RType | None) -> list[ir.RStmt] | None:
|
|
261
|
+
"""`x = <fresh list/dict/instance>` for a local nobody else can hold: a plain value."""
|
|
262
|
+
if not self.mutable_ty(peel(e.ty)):
|
|
263
|
+
return None # an int or str: nothing to devirtualise
|
|
264
|
+
fresh = (
|
|
265
|
+
isinstance(e, ir.Borrow)
|
|
266
|
+
and isinstance(e.operand, ir.Call)
|
|
267
|
+
and isinstance(e.operand.func, ir.Path)
|
|
268
|
+
and e.operand.func.path == "rt::Shared::new"
|
|
269
|
+
)
|
|
270
|
+
if not fresh or name in self.hoist:
|
|
271
|
+
raise NotFresh(name) # an alias or a call result: keep the handle
|
|
272
|
+
assert isinstance(e, ir.Borrow) and isinstance(e.operand, ir.Call)
|
|
273
|
+
value = e.operand.args[0]
|
|
274
|
+
ty = self.inner_ty(peel(declared) if declared is not None else peel(e.ty))
|
|
275
|
+
var = self.declare(name, ty, plain=True)
|
|
276
|
+
self.plain.add(var.rust)
|
|
277
|
+
return [ir.Let(ir.PVar(var.rust, name in self.mutated), ty, self.coerce(value, ty))]
|
|
278
|
+
|
|
279
|
+
def assign_to(self, target: ast.expr, e: ir.RExpr) -> list[ir.RStmt]:
|
|
280
|
+
if isinstance(target, ast.Name):
|
|
281
|
+
return self.bind(target.id, e)
|
|
282
|
+
if isinstance(target, ast.Subscript) and not isinstance(target.slice, ast.Slice):
|
|
283
|
+
base = self.expr(target.value)
|
|
284
|
+
if peel(base.ty).name == MAP:
|
|
285
|
+
key = self.coerce(self.expr(target.slice), arg(base.ty, 0))
|
|
286
|
+
value = self.coerce(e, arg(base.ty, 1))
|
|
287
|
+
self._refine(target.value, T(MAP, peel(key.ty), peel(value.ty)))
|
|
288
|
+
return [ir.ExprS(ir.method(base, "insert", key, value))]
|
|
289
|
+
if isinstance(target, ast.Attribute):
|
|
290
|
+
self._frozen_check(target)
|
|
291
|
+
if isinstance(target, (ast.Subscript, ast.Attribute)):
|
|
292
|
+
pre, lhs = self._place(self._place_of(self.expr(target)))
|
|
293
|
+
return [*pre, ir.Assign(lhs, self.coerce(e, lhs.ty))]
|
|
294
|
+
raise Unsupported("PY2RS003", f"assignment to {type(target).__name__}", target)
|
|
295
|
+
|
|
296
|
+
def _place_of(self, e: ir.RExpr) -> ir.RExpr:
|
|
297
|
+
"""The place a store goes to: a field or element holding a handle is assigned as a whole
|
|
298
|
+
(`h.items = other`), not through the borrow of the object it holds."""
|
|
299
|
+
if isinstance(e, ir.Borrow) and isinstance(e.operand, ir.Attr | ir.Index):
|
|
300
|
+
return e.operand
|
|
301
|
+
return e
|
|
302
|
+
|
|
303
|
+
def _frozen_check(self, target: ast.Attribute) -> None:
|
|
304
|
+
"""Assigning to a field of a frozen model or dataclass raises in Python."""
|
|
305
|
+
model = self.ctx.model_by_rust(peel(self.expr(target.value).ty).name)
|
|
306
|
+
if model is not None and model.frozen:
|
|
307
|
+
raise Unsupported(
|
|
308
|
+
"PY2RS018", f"assignment to {target.attr} of a frozen {model.rust} raises", target
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
def _place(self, lhs: ir.RExpr) -> tuple[list[ir.RStmt], ir.RExpr]:
|
|
312
|
+
"""`xs[f(i)] = v` through a `&mut Vec` does not borrow-check; compute the index first."""
|
|
313
|
+
if isinstance(lhs, ir.Call | ir.Method | ir.Template | ir.Question):
|
|
314
|
+
raise Unsupported("PY2RS003", "assignment into JSON data or a computed value", None)
|
|
315
|
+
if isinstance(lhs, ir.Index) and isinstance(lhs.index, ir.Call | ir.Question):
|
|
316
|
+
name = self._tmp_name()
|
|
317
|
+
let = ir.Let(ir.PVar(name), None, lhs.index)
|
|
318
|
+
lhs.index = ir.Var(name=name, ty=T("usize"))
|
|
319
|
+
return [let], lhs
|
|
320
|
+
return [], lhs
|
|
321
|
+
|
|
322
|
+
def _alias_check(self, targets: list[ast.expr], value: ast.expr, e: ir.RExpr) -> None:
|
|
323
|
+
"""`b = a` shares one list in Python; Rust clones it, so later mutation would diverge."""
|
|
324
|
+
if self.shared or not isinstance(value, (ast.Name, ast.Attribute, ast.Subscript)):
|
|
325
|
+
return # with handles `b = a` shares the object, as in Python
|
|
326
|
+
ty = peel(e.ty)
|
|
327
|
+
if ty.name not in MUTABLE_TYPES and self.ctx.model_by_rust(ty.name) is None:
|
|
328
|
+
return
|
|
329
|
+
names = {_root(value)} | {t.id for t in targets if isinstance(t, ast.Name)}
|
|
330
|
+
hit = names & self.container_mut
|
|
331
|
+
if hit:
|
|
332
|
+
raise Unsupported(
|
|
333
|
+
"PY2RS040",
|
|
334
|
+
f"aliasing of mutable {ty.rust()} ({sorted(n for n in hit if n)[0]} is mutated in place)",
|
|
335
|
+
value,
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
def st_Assign(self, s: ast.Assign) -> list[ir.RStmt]:
|
|
339
|
+
value = self.expr(s.value)
|
|
340
|
+
self._alias_check(s.targets, s.value, value)
|
|
341
|
+
out: list[ir.RStmt] = []
|
|
342
|
+
handle: ir.RExpr | None = None
|
|
343
|
+
if self.shared and len(s.targets) > 1 and isinstance(value, ir.Borrow):
|
|
344
|
+
# `a = b = []`: one object, two names (not two evaluations)
|
|
345
|
+
tmp = self._tmp_name()
|
|
346
|
+
out.append(ir.Let(ir.PVar(tmp), None, value))
|
|
347
|
+
handle = ir.Var(name=tmp, ty=value.operand.ty)
|
|
348
|
+
for i, target in enumerate(s.targets):
|
|
349
|
+
if handle is not None:
|
|
350
|
+
e: ir.RExpr = ir.Borrow(operand=ir.dup(handle), ty=value.ty)
|
|
351
|
+
else:
|
|
352
|
+
e = value if i == 0 else ir.dup(value)
|
|
353
|
+
out += (
|
|
354
|
+
self._unpack(target, e, s)
|
|
355
|
+
if isinstance(target, (ast.Tuple, ast.List))
|
|
356
|
+
else self.assign_to(target, e)
|
|
357
|
+
)
|
|
358
|
+
return out
|
|
359
|
+
|
|
360
|
+
def _unpack(self, target: ast.Tuple | ast.List, e: ir.RExpr, s: ast.stmt) -> list[ir.RStmt]:
|
|
361
|
+
ty = peel(e.ty)
|
|
362
|
+
if any(isinstance(x, ast.Starred) for x in target.elts):
|
|
363
|
+
raise Unsupported("PY2RS003", "starred unpacking target", s)
|
|
364
|
+
if ty.name != "tuple" or len(ty.args) != len(target.elts):
|
|
365
|
+
raise Unsupported("PY2RS019", f"unpacking a value of type {ty.rust()}", s)
|
|
366
|
+
names = [x for x in target.elts if isinstance(x, ast.Name)]
|
|
367
|
+
if len(names) == len(target.elts) and all(
|
|
368
|
+
not self.lookup(n.id) and n.id not in self.hoist for n in names
|
|
369
|
+
):
|
|
370
|
+
pats = [
|
|
371
|
+
ir.PVar(self.declare(n.id, t).rust, n.id in self.mutated)
|
|
372
|
+
for n, t in zip(names, ty.args, strict=False)
|
|
373
|
+
]
|
|
374
|
+
note = self.store_ty(ty) if ty.known else None
|
|
375
|
+
return [ir.Let(ir.PTuple(list(pats)), note, e)]
|
|
376
|
+
temps = [self._tmp_name() for _ in target.elts]
|
|
377
|
+
out: list[ir.RStmt] = [ir.Let(ir.PTuple([ir.PVar(t) for t in temps]), None, e)]
|
|
378
|
+
for x, tmp, t in zip(target.elts, temps, ty.args, strict=False):
|
|
379
|
+
out += self.assign_to(x, ir.Var(name=tmp, ty=t))
|
|
380
|
+
return out
|
|
381
|
+
|
|
382
|
+
def st_AnnAssign(self, s: ast.AnnAssign) -> list[ir.RStmt]:
|
|
383
|
+
if not isinstance(s.target, ast.Name):
|
|
384
|
+
raise Unsupported("PY2RS003", "annotated assignment to an attribute", s)
|
|
385
|
+
name = s.target.id
|
|
386
|
+
ty = self.mapper.map(s.annotation, camel(name))
|
|
387
|
+
if s.value is None:
|
|
388
|
+
return [ir.Let(ir.PVar(self.declare(name, ty).rust, name in self.mutated), ty, None)]
|
|
389
|
+
return self.bind(name, self.expr(s.value), declared=ty)
|
|
390
|
+
|
|
391
|
+
def st_AugAssign(self, s: ast.AugAssign) -> list[ir.RStmt]:
|
|
392
|
+
op, tgt = type(s.op), s.target
|
|
393
|
+
rhs = self.expr(s.value)
|
|
394
|
+
if isinstance(tgt, ast.Subscript) and not isinstance(tgt.slice, ast.Slice):
|
|
395
|
+
base = self.expr(tgt.value)
|
|
396
|
+
if peel(base.ty).name == MAP and op in ARITH_SYM and arg(base.ty, 1) in (INT, FLOAT):
|
|
397
|
+
got = expect(
|
|
398
|
+
ir.method(base, "get_mut", self.ref_of(self.expr(tgt.slice))),
|
|
399
|
+
"KeyError",
|
|
400
|
+
arg(base.ty, 1),
|
|
401
|
+
)
|
|
402
|
+
slot, value = (
|
|
403
|
+
ir.Deref(operand=got, ty=arg(base.ty, 1)),
|
|
404
|
+
self.coerce(rhs, arg(base.ty, 1)),
|
|
405
|
+
)
|
|
406
|
+
if arg(base.ty, 1) == INT and self.ctx.cfg.int_overflow != "native":
|
|
407
|
+
return [ir.Assign(slot, self.int_op(ARITH_SYM[op], ir.dup(slot), value, s))]
|
|
408
|
+
return [ir.Assign(slot, value, f"{ARITH_SYM[op]}=")]
|
|
409
|
+
if isinstance(tgt, ast.Attribute):
|
|
410
|
+
self._frozen_check(tgt)
|
|
411
|
+
pre, cur = self._place(self._place_of(self.expr(tgt)))
|
|
412
|
+
tc, tr = peel(cur.ty), peel(rhs.ty)
|
|
413
|
+
if pre:
|
|
414
|
+
return [*pre, *self._aug(s, op, tgt, cur, tc, tr, rhs)]
|
|
415
|
+
return self._aug(s, op, tgt, cur, tc, tr, rhs)
|
|
416
|
+
|
|
417
|
+
def _aug(
|
|
418
|
+
self,
|
|
419
|
+
s: ast.AugAssign,
|
|
420
|
+
op: type,
|
|
421
|
+
tgt: ast.expr,
|
|
422
|
+
cur: ir.RExpr,
|
|
423
|
+
tc: RType,
|
|
424
|
+
tr: RType,
|
|
425
|
+
rhs: ir.RExpr,
|
|
426
|
+
) -> list[ir.RStmt]:
|
|
427
|
+
if tc == STR and op is ast.Add and tr == STR:
|
|
428
|
+
return [ir.ExprS(ir.method(cur, "push_str", self.as_str(rhs)))]
|
|
429
|
+
if tc.name == "Vec" and op is ast.Add:
|
|
430
|
+
return [ir.ExprS(ir.method(cur, "extend", self.as_iter(rhs, s)))]
|
|
431
|
+
if op in ARITH_SYM and tc in (INT, FLOAT) and tr in (INT, FLOAT) and (tc in (tr, FLOAT)):
|
|
432
|
+
if tc == INT and self.ctx.cfg.int_overflow != "native":
|
|
433
|
+
return [ir.Assign(cur, self.int_op(ARITH_SYM[op], ir.dup(cur), rhs, s))]
|
|
434
|
+
if tc == INT:
|
|
435
|
+
self.drift_i64(s)
|
|
436
|
+
return [ir.Assign(cur, self.coerce(rhs, tc), f"{ARITH_SYM[op]}=")]
|
|
437
|
+
combined = ast.copy_location(ast.BinOp(left=tgt, op=s.op, right=s.value), s)
|
|
438
|
+
return self.assign_to(tgt, self.expr(combined))
|
|
439
|
+
|
|
440
|
+
def drift_i64(self, s: ast.AST) -> None:
|
|
441
|
+
self.ctx.col.drift("PY2RS041", s, "i64 arithmetic")
|
|
442
|
+
|
|
443
|
+
# -- control flow ---------------------------------------------------------------------
|
|
444
|
+
def _hoist(
|
|
445
|
+
self, test: ast.expr, allowed: bool, s: ast.stmt
|
|
446
|
+
) -> tuple[list[tuple[str, ast.expr]], ast.expr]:
|
|
447
|
+
hoisted = hoist_walrus(test)
|
|
448
|
+
if hoisted is None or (hoisted[0] and not allowed):
|
|
449
|
+
raise Unsupported("PY2RS021", "walrus (:=) in a position that cannot be hoisted", s)
|
|
450
|
+
return hoisted
|
|
451
|
+
|
|
452
|
+
def _lets(self, binds: list[tuple[str, ast.expr]]) -> list[ir.RStmt]:
|
|
453
|
+
return [st for name, value in binds for st in self.bind(name, self.expr(value))]
|
|
454
|
+
|
|
455
|
+
def _narrowable(self, test: ast.expr, op: type) -> tuple[str, Var] | None:
|
|
456
|
+
"""`x is None` / `x is not None` where x is an Option local that is never reassigned."""
|
|
457
|
+
if not (
|
|
458
|
+
isinstance(test, ast.Compare)
|
|
459
|
+
and len(test.ops) == 1
|
|
460
|
+
and isinstance(test.ops[0], op)
|
|
461
|
+
and isinstance(test.left, ast.Name)
|
|
462
|
+
and isinstance(test.comparators[0], ast.Constant)
|
|
463
|
+
and test.comparators[0].value is None
|
|
464
|
+
):
|
|
465
|
+
return None
|
|
466
|
+
var = self.lookup(test.left.id)
|
|
467
|
+
if var is None or var.ty.name != "Option" or test.left.id in self.reassigned:
|
|
468
|
+
return None
|
|
469
|
+
return test.left.id, var
|
|
470
|
+
|
|
471
|
+
def _narrow_guard(self, s: ast.If) -> list[ir.RStmt] | None:
|
|
472
|
+
"""`if x is None: return` -> `let x = match x.clone() { Some(v) => v, None => { return } };`"""
|
|
473
|
+
found = self._narrowable(s.test, ast.Is)
|
|
474
|
+
exits = (ast.Return, ast.Raise, ast.Continue, ast.Break)
|
|
475
|
+
if found is None or s.orelse or not isinstance(s.body[-1], exits):
|
|
476
|
+
return None
|
|
477
|
+
name, var = found
|
|
478
|
+
inner = arg(var.ty)
|
|
479
|
+
body = self.scoped(s.body, s.lineno)
|
|
480
|
+
value = ir.Var(name="v", ty=inner)
|
|
481
|
+
arms = [
|
|
482
|
+
ir.Arm(
|
|
483
|
+
ir.PExpr(ir.Call(func=ir.Path(path="Some"), args=[value])),
|
|
484
|
+
[ir.Return(value, tail=True)],
|
|
485
|
+
),
|
|
486
|
+
ir.Arm(ir.PExpr(ir.Lit(kind="none")), body),
|
|
487
|
+
]
|
|
488
|
+
subject = ir.CloneX(operand=self.var(var), ty=var.ty)
|
|
489
|
+
narrowed = self.declare(name, inner)
|
|
490
|
+
init = ir.BlockX(stmts=[ir.MatchS(subject, arms)], ty=inner)
|
|
491
|
+
return [ir.Let(ir.PVar(narrowed.rust, name in self.mutated), None, init)]
|
|
492
|
+
|
|
493
|
+
def st_If(self, s: ast.If) -> list[ir.RStmt]:
|
|
494
|
+
guard = self._narrow_guard(s)
|
|
495
|
+
if guard is not None:
|
|
496
|
+
return guard
|
|
497
|
+
binds, test = self._hoist(s.test, True, s)
|
|
498
|
+
return [*self._lets(binds), self._if_chain(s, test)]
|
|
499
|
+
|
|
500
|
+
def _if_chain(self, s: ast.If, test: ast.expr) -> ir.IfS:
|
|
501
|
+
cond = self.cond(test)
|
|
502
|
+
then = self.scoped(s.body, s.lineno)
|
|
503
|
+
other: list[ir.RStmt] | None = None
|
|
504
|
+
if len(s.orelse) == 1 and isinstance(s.orelse[0], ast.If):
|
|
505
|
+
nested = s.orelse[0]
|
|
506
|
+
other = [self._if_chain(nested, self._hoist(nested.test, False, nested)[1])]
|
|
507
|
+
other[0].span = self.sp(nested)
|
|
508
|
+
elif s.orelse:
|
|
509
|
+
other = self.scoped(s.orelse, s.body[-1].end_lineno or s.lineno)
|
|
510
|
+
return ir.IfS(cond, then, other)
|
|
511
|
+
|
|
512
|
+
def st_While(self, s: ast.While) -> list[ir.RStmt]:
|
|
513
|
+
if s.orelse:
|
|
514
|
+
raise Unsupported("PY2RS003", "while/else", s)
|
|
515
|
+
binds, test = self._hoist(s.test, True, s)
|
|
516
|
+
if not binds:
|
|
517
|
+
return [ir.WhileS(self.cond(test), self.scoped(s.body, s.lineno))]
|
|
518
|
+
self.push()
|
|
519
|
+
try:
|
|
520
|
+
lets = self._lets(binds)
|
|
521
|
+
guard = ir.IfS(ir.Un(op="!", operand=self.cond(test), ty=BOOL), [ir.Break()])
|
|
522
|
+
body = self.block(s.body, after=s.lineno)
|
|
523
|
+
finally:
|
|
524
|
+
self.pop()
|
|
525
|
+
return [ir.LoopS([*lets, guard, *body])]
|
|
526
|
+
|
|
527
|
+
def st_For(self, s: ast.For) -> list[ir.RStmt]:
|
|
528
|
+
if s.orelse:
|
|
529
|
+
raise Unsupported("PY2RS003", "for/else", s)
|
|
530
|
+
if any(isinstance(n, ast.Name) and n.id in self.leaky for n in ast.walk(s.target)):
|
|
531
|
+
raise Unsupported("PY2RS039", "loop variable used after the loop", s)
|
|
532
|
+
inplace = self._inplace_iter(s)
|
|
533
|
+
source = None if inplace else self.expr(s.iter)
|
|
534
|
+
if (
|
|
535
|
+
source is not None
|
|
536
|
+
and self.shared
|
|
537
|
+
and isinstance(source, ir.Borrow)
|
|
538
|
+
and peel(source.ty).name == "Vec"
|
|
539
|
+
and not isinstance(s.target, ast.Starred)
|
|
540
|
+
):
|
|
541
|
+
return self._index_loop(s, source)
|
|
542
|
+
it = inplace or self.as_iter(source if source is not None else self.expr(s.iter), s.iter)
|
|
543
|
+
if (
|
|
544
|
+
isinstance(it, ir.Method)
|
|
545
|
+
and it.name == "into_iter"
|
|
546
|
+
and isinstance(it.recv, ir.Method)
|
|
547
|
+
and it.recv.name == "collect"
|
|
548
|
+
and any(isinstance(part, ir.Borrow) for part in ir.walk(it.recv))
|
|
549
|
+
):
|
|
550
|
+
if any(
|
|
551
|
+
isinstance(node, ast.Call | ast.Delete)
|
|
552
|
+
or (isinstance(node, ast.Subscript) and isinstance(node.ctx, ast.Store))
|
|
553
|
+
for statement in s.body
|
|
554
|
+
for node in ast.walk(statement)
|
|
555
|
+
):
|
|
556
|
+
self.drift("PY2RS063", s, "loop body may mutate the iterated container")
|
|
557
|
+
it = self._owned_iterator(it)
|
|
558
|
+
self.push()
|
|
559
|
+
try:
|
|
560
|
+
pat, rebinds = self._loop_target(s.target, arg(it.ty))
|
|
561
|
+
body = self.block(s.body, after=s.lineno)
|
|
562
|
+
finally:
|
|
563
|
+
self.pop()
|
|
564
|
+
return [ir.ForS(pat, it, [*rebinds, *body])]
|
|
565
|
+
|
|
566
|
+
def _index_loop(self, s: ast.For, source: ir.Borrow) -> list[ir.RStmt]:
|
|
567
|
+
"""`for x in xs` over a list is index-based, like Python's list iterator: elements added
|
|
568
|
+
during the loop are visited, and no borrow is held while the body runs."""
|
|
569
|
+
out: list[ir.RStmt] = []
|
|
570
|
+
handle = source.operand
|
|
571
|
+
if not isinstance(handle, ir.Var): # evaluate `for x in f():` once
|
|
572
|
+
seq = self._tmp_name()
|
|
573
|
+
out.append(ir.Let(ir.PVar(seq), None, handle))
|
|
574
|
+
handle = ir.Var(name=seq, ty=handle.ty)
|
|
575
|
+
idx = self._tmp_name()
|
|
576
|
+
out.append(ir.Let(ir.PVar(idx, True), None, ir.lit("int", 0, T("usize"), None)))
|
|
577
|
+
elem = arg(source.ty)
|
|
578
|
+
size = ir.method(ir.Borrow(operand=ir.dup(handle), ty=source.ty), "len", ty=T("usize"))
|
|
579
|
+
cond = ir.Bin(op="<", left=ir.Var(name=idx, ty=T("usize")), right=size, ty=BOOL)
|
|
580
|
+
item = ir.Index(
|
|
581
|
+
base=ir.Borrow(operand=ir.dup(handle), ty=source.ty),
|
|
582
|
+
index=ir.Var(name=idx, ty=T("usize")),
|
|
583
|
+
ty=elem,
|
|
584
|
+
)
|
|
585
|
+
self.push()
|
|
586
|
+
try:
|
|
587
|
+
pat, rebinds = self._loop_target(s.target, elem)
|
|
588
|
+
step = ir.Assign(
|
|
589
|
+
ir.Var(name=idx, ty=T("usize")), ir.lit("int", 1, T("usize"), None), "+="
|
|
590
|
+
)
|
|
591
|
+
body = [ir.Let(pat, None, item), step, *rebinds, *self.block(s.body, after=s.lineno)]
|
|
592
|
+
finally:
|
|
593
|
+
self.pop()
|
|
594
|
+
return [*out, ir.WhileS(cond, body)]
|
|
595
|
+
|
|
596
|
+
def _inplace_iter(self, s: ast.For) -> ir.RExpr | None:
|
|
597
|
+
"""`for a in accs: a.total += 5` changes the elements of `accs`, so the loop borrows them
|
|
598
|
+
mutably (a clone would be changed instead). Only a local list or dict values qualify."""
|
|
599
|
+
names = {n.id for n in ast.walk(s.target) if isinstance(n, ast.Name)}
|
|
600
|
+
if not names & self.loop_inplace:
|
|
601
|
+
return None
|
|
602
|
+
src, method = s.iter, "iter_mut"
|
|
603
|
+
if (
|
|
604
|
+
isinstance(src, ast.Call)
|
|
605
|
+
and isinstance(src.func, ast.Attribute)
|
|
606
|
+
and src.func.attr == "values"
|
|
607
|
+
and not src.args
|
|
608
|
+
):
|
|
609
|
+
src, method = src.func.value, "values_mut"
|
|
610
|
+
if isinstance(src, ast.Name) and isinstance(s.target, ast.Name):
|
|
611
|
+
base = self.expr(src)
|
|
612
|
+
ty = peel(base.ty)
|
|
613
|
+
elem = arg(ty, 1) if ty.name == MAP else arg(ty)
|
|
614
|
+
mutable = elem.name in MUTABLE_TYPES or self.ctx.model_by_rust(elem.name) is not None
|
|
615
|
+
if mutable and ty.name == ("Vec" if method == "iter_mut" else MAP):
|
|
616
|
+
return ir.method(base, method, ty=T("Iter", T("&mut", elem)))
|
|
617
|
+
if not mutable:
|
|
618
|
+
return None # an int or str element is rebound, not changed in place
|
|
619
|
+
raise Unsupported(
|
|
620
|
+
"PY2RS040",
|
|
621
|
+
"the loop variable is changed in place; iterate a local list (or its values()) directly",
|
|
622
|
+
s,
|
|
623
|
+
)
|
|
624
|
+
|
|
625
|
+
def _loop_target(self, target: ast.expr, ty: RType) -> tuple[ir.Pat, list[ir.RStmt]]:
|
|
626
|
+
"""Names bound before the loop are ASSIGNED by it (Python keeps the last value after the
|
|
627
|
+
loop), so the Rust pattern uses a fresh name and the body starts with the assignment."""
|
|
628
|
+
if isinstance(target, ast.Name) and target.id != "_":
|
|
629
|
+
existing = self.lookup(target.id)
|
|
630
|
+
if existing is None:
|
|
631
|
+
return self.bind_target(target, ty, allow_mut=True), []
|
|
632
|
+
if not compatible(existing.ty, ty):
|
|
633
|
+
raise Unsupported("PY2RS039", f"loop changes the type of {target.id}", target)
|
|
634
|
+
tmp = f"{existing.rust.removeprefix('r#')}_item"
|
|
635
|
+
value = ir.Var(name=tmp, ty=ty)
|
|
636
|
+
return ir.PVar(tmp), [ir.Assign(self.var(existing), self.coerce(value, existing.ty))]
|
|
637
|
+
if isinstance(target, ast.Tuple) and not any(
|
|
638
|
+
isinstance(e, ast.Starred) for e in target.elts
|
|
639
|
+
):
|
|
640
|
+
kids = [
|
|
641
|
+
ty.args[i] if ty.name == "tuple" and i < len(ty.args) else UNKNOWN
|
|
642
|
+
for i in range(len(target.elts))
|
|
643
|
+
]
|
|
644
|
+
parts = [self._loop_target(e, k) for e, k in zip(target.elts, kids, strict=False)]
|
|
645
|
+
return ir.PTuple([p for p, _ in parts]), [st for _, sts in parts for st in sts]
|
|
646
|
+
return self.bind_target(target, ty, allow_mut=True), []
|
|
647
|
+
|
|
648
|
+
# -- match ----------------------------------------------------------------------------
|
|
649
|
+
def _is_enum(self, ty: RType) -> bool:
|
|
650
|
+
return ty.name in self.ctx.lit_enums or any(
|
|
651
|
+
e.rust == ty.name for e in self.ctx.enums.values()
|
|
652
|
+
)
|
|
653
|
+
|
|
654
|
+
def st_Match(self, s: ast.Match) -> list[ir.RStmt]:
|
|
655
|
+
subject = self.expr(s.subject)
|
|
656
|
+
ty = peel(subject.ty)
|
|
657
|
+
if ty == STR:
|
|
658
|
+
subject = self.as_str(subject)
|
|
659
|
+
elif ty not in (INT, BOOL) and not self._is_enum(ty):
|
|
660
|
+
raise Unsupported("PY2RS020", f"match on a value of type {ty.rust()}", s)
|
|
661
|
+
arms: list[ir.Arm] = []
|
|
662
|
+
catch_all = False
|
|
663
|
+
for case in s.cases:
|
|
664
|
+
self.push()
|
|
665
|
+
try:
|
|
666
|
+
pat = self._pattern(case.pattern, ty)
|
|
667
|
+
guard = self.cond(case.guard) if case.guard else None
|
|
668
|
+
body = self.block(case.body, after=case.pattern.lineno)
|
|
669
|
+
finally:
|
|
670
|
+
self.pop()
|
|
671
|
+
catch_all |= (
|
|
672
|
+
isinstance(case.pattern, ast.MatchAs)
|
|
673
|
+
and case.pattern.pattern is None
|
|
674
|
+
and guard is None
|
|
675
|
+
)
|
|
676
|
+
arms.append(ir.Arm(pat, body, guard, span=self.sp(case.pattern)))
|
|
677
|
+
if not catch_all and not self._exhaustive(ty, arms):
|
|
678
|
+
arms.append(ir.Arm(ir.PWild(), []))
|
|
679
|
+
return [ir.MatchS(subject, arms)]
|
|
680
|
+
|
|
681
|
+
def _exhaustive(self, ty: RType, arms: list[ir.Arm]) -> bool:
|
|
682
|
+
"""Do the (unguarded) literal/path patterns cover every value of a bool or enum subject?"""
|
|
683
|
+
seen: set[str] = set()
|
|
684
|
+
stack: list[ir.Pat] = [a.pat for a in arms if a.guard is None]
|
|
685
|
+
while stack:
|
|
686
|
+
p = stack.pop()
|
|
687
|
+
if isinstance(p, ir.POr):
|
|
688
|
+
stack += p.alts
|
|
689
|
+
elif isinstance(p, ir.PExpr):
|
|
690
|
+
seen.add(expr_text(p.expr))
|
|
691
|
+
if ty == BOOL:
|
|
692
|
+
return {"true", "false"} <= seen
|
|
693
|
+
table = self.ctx.lit_enums.get(ty.name)
|
|
694
|
+
variants = (
|
|
695
|
+
set(table.values())
|
|
696
|
+
if table
|
|
697
|
+
else next(
|
|
698
|
+
(set(e.members.values()) for e in self.ctx.enums.values() if e.rust == ty.name),
|
|
699
|
+
set(),
|
|
700
|
+
)
|
|
701
|
+
)
|
|
702
|
+
return bool(variants) and {f"{ty.name}::{v}" for v in variants} <= seen
|
|
703
|
+
|
|
704
|
+
def _pattern(self, p: ast.pattern, ty: RType) -> ir.Pat:
|
|
705
|
+
if isinstance(p, ast.MatchValue):
|
|
706
|
+
lit = self.expr(p.value)
|
|
707
|
+
if self._is_enum(ty):
|
|
708
|
+
lit = self.coerce(lit, ty)
|
|
709
|
+
if peel(lit.ty) not in (STR, INT, BOOL) and peel(lit.ty) != ty:
|
|
710
|
+
raise Unsupported("PY2RS020", f"value pattern of type {peel(lit.ty).rust()}", p)
|
|
711
|
+
return ir.PExpr(lit)
|
|
712
|
+
if isinstance(p, ast.MatchSingleton) and isinstance(p.value, bool):
|
|
713
|
+
return ir.PExpr(ir.lit("bool", p.value, BOOL))
|
|
714
|
+
if isinstance(p, ast.MatchOr):
|
|
715
|
+
return ir.POr([self._pattern(x, ty) for x in p.patterns])
|
|
716
|
+
if isinstance(p, ast.MatchAs):
|
|
717
|
+
inner = self._pattern(p.pattern, ty) if p.pattern else None
|
|
718
|
+
if p.name is None:
|
|
719
|
+
return inner or ir.PWild()
|
|
720
|
+
bound = self.declare(p.name, ty).rust
|
|
721
|
+
return ir.PBind(bound, inner) if inner else ir.PVar(bound)
|
|
722
|
+
raise Unsupported("PY2RS020", f"{type(p).__name__} pattern", p)
|