python2rust 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. python2rust/__init__.py +8 -0
  2. python2rust/__main__.py +5 -0
  3. python2rust/_core.py +44 -0
  4. python2rust/agent/__init__.py +0 -0
  5. python2rust/agent/agents.py +333 -0
  6. python2rust/agent/apply.py +516 -0
  7. python2rust/agent/finish.py +295 -0
  8. python2rust/agent/fixers.py +229 -0
  9. python2rust/agent/loop.py +441 -0
  10. python2rust/agent/patches.py +1165 -0
  11. python2rust/agent/port.py +579 -0
  12. python2rust/agent/prompts/judge_v2.md +96 -0
  13. python2rust/agent/review.py +34 -0
  14. python2rust/agent/rustlex.py +232 -0
  15. python2rust/cli/__init__.py +0 -0
  16. python2rust/cli/doctor.py +62 -0
  17. python2rust/cli/inputs.py +105 -0
  18. python2rust/cli/main.py +1162 -0
  19. python2rust/cli/ops.py +642 -0
  20. python2rust/cli/workflow.py +178 -0
  21. python2rust/core/__init__.py +38 -0
  22. python2rust/core/config.py +263 -0
  23. python2rust/core/constructs.py +124 -0
  24. python2rust/core/diagnostics.py +280 -0
  25. python2rust/core/emit/__init__.py +5 -0
  26. python2rust/core/emit/crates.py +51 -0
  27. python2rust/core/emit/render.py +561 -0
  28. python2rust/core/emit/schema.py +168 -0
  29. python2rust/core/emit/translate.py +304 -0
  30. python2rust/core/frontend/__init__.py +1 -0
  31. python2rust/core/frontend/module.py +896 -0
  32. python2rust/core/frontend/names.py +129 -0
  33. python2rust/core/frontend/project.py +277 -0
  34. python2rust/core/frontend/project_imports.py +173 -0
  35. python2rust/core/frontend/symbols.py +132 -0
  36. python2rust/core/frontend/walrus.py +59 -0
  37. python2rust/core/ir/__init__.py +1 -0
  38. python2rust/core/ir/nodes.py +675 -0
  39. python2rust/core/ir/rtypes.py +122 -0
  40. python2rust/core/ir/types.py +326 -0
  41. python2rust/core/lower/__init__.py +1 -0
  42. python2rust/core/lower/calls.py +1125 -0
  43. python2rust/core/lower/context.py +223 -0
  44. python2rust/core/lower/exceptions.py +317 -0
  45. python2rust/core/lower/exprs.py +845 -0
  46. python2rust/core/lower/fstrings.py +141 -0
  47. python2rust/core/lower/funcs.py +276 -0
  48. python2rust/core/lower/lowerer.py +366 -0
  49. python2rust/core/lower/modelcalls.py +195 -0
  50. python2rust/core/lower/models.py +645 -0
  51. python2rust/core/lower/stmts.py +722 -0
  52. python2rust/core/lower/testing.py +601 -0
  53. python2rust/core/lower/validation.py +253 -0
  54. python2rust/core/passes/__init__.py +1 -0
  55. python2rust/core/passes/aliasing.py +311 -0
  56. python2rust/core/passes/analysis.py +207 -0
  57. python2rust/core/passes/devirt.py +329 -0
  58. python2rust/core/passes/ownership.py +259 -0
  59. python2rust/core/passes/raises.py +275 -0
  60. python2rust/core/rt_lib.rs +2071 -0
  61. python2rust/data/README.md +81 -0
  62. python2rust/data/py2many_builtins.toml +4744 -0
  63. python2rust/errors.py +28 -0
  64. python2rust/py.typed +0 -0
  65. python2rust/report/__init__.py +0 -0
  66. python2rust/report/constructs.py +31 -0
  67. python2rust/report/contract.py +688 -0
  68. python2rust/report/corpus.py +323 -0
  69. python2rust/report/explain.py +168 -0
  70. python2rust/report/schemas.py +914 -0
  71. python2rust/server/__init__.py +0 -0
  72. python2rust/server/mcp_server.py +289 -0
  73. python2rust/server/mcp_workflow.py +100 -0
  74. python2rust/skill/SKILL.md +214 -0
  75. python2rust/verify/__init__.py +0 -0
  76. python2rust/verify/check.py +1135 -0
  77. python2rust/verify/equiv/__init__.py +1264 -0
  78. python2rust/verify/equiv/compare.py +455 -0
  79. python2rust/verify/equiv/harness.py +505 -0
  80. python2rust/verify/equiv/judge.py +358 -0
  81. python2rust/verify/equiv/procs.py +255 -0
  82. python2rust/verify/equiv/runner.py +248 -0
  83. python2rust/verify/equiv/types.py +543 -0
  84. python2rust/verify/keystore.py +76 -0
  85. python2rust/verify/ladder.py +396 -0
  86. python2rust/verify/sandbox.py +370 -0
  87. python2rust/verify/testrun.py +280 -0
  88. python2rust/workflow/__init__.py +0 -0
  89. python2rust/workflow/brief.py +312 -0
  90. python2rust/workflow/interview.py +366 -0
  91. python2rust/workflow/layout.py +103 -0
  92. python2rust/workflow/planner.py +409 -0
  93. python2rust/workflow/project.py +134 -0
  94. python2rust/workflow/schemas.py +265 -0
  95. python2rust/workflow/state.py +392 -0
  96. python2rust/workflow/staticscan.py +209 -0
  97. python2rust-0.1.0.dist-info/METADATA +395 -0
  98. python2rust-0.1.0.dist-info/RECORD +102 -0
  99. python2rust-0.1.0.dist-info/WHEEL +4 -0
  100. python2rust-0.1.0.dist-info/entry_points.txt +4 -0
  101. python2rust-0.1.0.dist-info/licenses/LICENSE +21 -0
  102. python2rust-0.1.0.dist-info/licenses/NOTICE +65 -0
@@ -0,0 +1,845 @@
1
+ """Expression lowering: ast.expr -> typed IR expression."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+
7
+ from ..ir import nodes as ir
8
+ from ..ir.rtypes import (
9
+ BOOL,
10
+ BYTES,
11
+ FLOAT,
12
+ INT,
13
+ MAP,
14
+ SET,
15
+ SHARED,
16
+ STR,
17
+ UNIT,
18
+ UNKNOWN,
19
+ VALUE,
20
+ RType,
21
+ T,
22
+ arg,
23
+ compatible,
24
+ is_copy,
25
+ peel,
26
+ unify,
27
+ ) # fmt: skip
28
+ from ..ir.types import dotted
29
+ from . import fstrings
30
+ from .lowerer import Lowerer, Unsupported, bin_, int_lit, is_none, not_
31
+
32
+ I64_MAX = 2**63 - 1
33
+ ARITH = {ast.Add: "+", ast.Sub: "-", ast.Mult: "*"}
34
+ BITS = {ast.BitAnd: "&", ast.BitOr: "|", ast.BitXor: "^", ast.LShift: "<<", ast.RShift: ">>"}
35
+ CMP = {ast.Eq: "==", ast.NotEq: "!=", ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">="}
36
+ SIMPLE_NODES = (ast.Name, ast.Constant, ast.Attribute)
37
+ USIZE, U32 = T("usize"), T("u32")
38
+
39
+
40
+ def nonneg(e: ir.RExpr) -> bool:
41
+ """Structurally known to be >= 0 (literals, len(), sums/products of those)."""
42
+ if isinstance(e, ir.Lit):
43
+ return (ir.lit_int(e) or 0) >= 0 and e.kind == "int"
44
+ if isinstance(e, ir.Cast):
45
+ return isinstance(e.operand, ir.Method) and e.operand.name in ("len", "count")
46
+ return isinstance(e, ir.Bin) and e.op in ("+", "*") and nonneg(e.left) and nonneg(e.right)
47
+
48
+
49
+ def usize(e: ir.RExpr) -> ir.RExpr:
50
+ """A Python count/size operand as usize (negative counts mean zero)."""
51
+ inner = e if nonneg(e) else ir.method(e, "max", int_lit(0), ty=INT)
52
+ return ir.Cast(operand=inner, ty=USIZE)
53
+
54
+
55
+ def cmp_operand(e: ir.RExpr) -> ir.RExpr:
56
+ return ir.Deref(operand=e, ty=peel(e.ty)) if e.ty.name in ("&", "&mut") else e
57
+
58
+
59
+ class ExprLowerer(Lowerer):
60
+ def expr(self, node: ast.expr) -> ir.RExpr:
61
+ handler = getattr(self, f"expr_{type(node).__name__}", None)
62
+ if handler is None:
63
+ raise Unsupported("PY2RS004", f"{type(node).__name__} expression", node)
64
+ out = handler(node)
65
+ if out.span is None:
66
+ out.span = self.sp(node)
67
+ return self.as_view(out) if self.shared else out
68
+
69
+ def as_view(self, out: ir.RExpr) -> ir.RExpr:
70
+ """The VALUE of a Python object: `handle.borrow()` for a handle, and a fresh handle around
71
+ a freshly built list/dict/set/instance (so that moving it moves a handle)."""
72
+ if isinstance(out, ir.Borrow):
73
+ return out
74
+ ty = out.ty
75
+ if ty.name == SHARED:
76
+ return ir.Borrow(operand=out, ty=ty.args[0], span=out.span)
77
+ if ty.name in ("&", "&mut") or not self.mutable_ty(ty):
78
+ return out
79
+ if isinstance(out, ir.Var) and out.name in self.plain:
80
+ return out # a devirtualised local: the value itself
81
+ inner = self.inner_ty(ty)
82
+ leaves = (
83
+ [out.then, out.other]
84
+ if isinstance(out, ir.IfX)
85
+ else [out.tail]
86
+ if isinstance(out, ir.BlockX)
87
+ else []
88
+ )
89
+ if leaves and all(isinstance(x, ir.Borrow) for x in leaves):
90
+ out.ty = T(SHARED, inner) # the branches yield handles when moved
91
+ return ir.Borrow(operand=out, ty=inner, span=out.span)
92
+ handle = ir.Call(
93
+ func=ir.Path(path="rt::Shared::new"), args=[out], ty=T(SHARED, inner), span=out.span
94
+ )
95
+ return ir.Borrow(operand=handle, ty=inner, span=out.span)
96
+
97
+ def drift(self, code: str, node: ast.AST, what: str) -> None:
98
+ self.ctx.col.drift(code, node, what)
99
+
100
+ # -- literals and names ---------------------------------------------------------------
101
+ def expr_Constant(self, node: ast.Constant) -> ir.RExpr:
102
+ v = node.value
103
+ if v is None:
104
+ return ir.Lit(kind="none", ty=T("Option", UNKNOWN))
105
+ if isinstance(v, bool):
106
+ return ir.lit("bool", v, BOOL)
107
+ if isinstance(v, int):
108
+ if v > I64_MAX or v < -I64_MAX - 1:
109
+ raise Unsupported("PY2RS009", "integer literal outside the i64 range", node)
110
+ return ir.lit("int", v, INT)
111
+ if isinstance(v, float):
112
+ return ir.lit("float", v, FLOAT)
113
+ if isinstance(v, str):
114
+ return ir.lit("str", v, STR)
115
+ if isinstance(v, bytes):
116
+ return ir.lit("bytes", v, BYTES)
117
+ raise Unsupported("PY2RS004", f"{type(v).__name__} literal", node)
118
+
119
+ def expr_Name(self, node: ast.Name) -> ir.RExpr:
120
+ var = self.lookup(node.id)
121
+ if var:
122
+ hazard = self.alias_hazards.get(id(node))
123
+ if hazard and self._shares_mutable(var.ty, hazard[1]):
124
+ why = hazard[0]
125
+ raise Unsupported(
126
+ "PY2RS040",
127
+ f"aliasing: {why}; Python shares the object, Rust would copy it",
128
+ node,
129
+ )
130
+ return self.var(var)
131
+ const = self.ctx.consts.get(node.id)
132
+ if const:
133
+ return ir.Path(path=const.rust, ty=const.ty, borrowed=const.borrowed)
134
+ raise Unsupported("PY2RS004", f"unresolved name {node.id}", node)
135
+
136
+ def _shares_mutable(self, ty: RType, elements: bool) -> bool:
137
+ """Can a copy of a value of type `ty` (or of its elements) be observed to differ?"""
138
+ ty = peel(ty)
139
+ mutable = ty.name in ("Vec", MAP, SET) or self.ctx.model_by_rust(ty.name) is not None
140
+ if not elements:
141
+ return mutable
142
+ inner = arg(ty, 1) if ty.name == MAP else arg(ty) if ty.args else ty
143
+ return self._shares_mutable(inner, False) if mutable else False
144
+
145
+ def expr_Attribute(self, node: ast.Attribute) -> ir.RExpr:
146
+ if isinstance(node.value, ast.Name):
147
+ enum = self.ctx.enums.get(node.value.id)
148
+ if enum and node.attr in enum.members:
149
+ return ir.Path(path=f"{enum.rust}::{enum.members[node.attr]}", ty=T(enum.rust))
150
+ name = dotted(node)
151
+ if not self.lookup(name.split(".")[0]) and (value := self._project_value(name)) is not None:
152
+ return value
153
+ entry = self.ctx.library_entry(name)
154
+ if entry and not self.lookup(name.split(".")[0]):
155
+ self.ctx.templates += 1
156
+ return ir.Template(template=entry["rust"], ty=self.ctx.library_type(entry))
157
+ base = self.expr(node.value)
158
+ model = self.ctx.model_by_rust(peel(base.ty).name)
159
+ if model:
160
+ info = next((f for f in model.fields.values() if f.py_name == node.attr), None)
161
+ if info:
162
+ return ir.Attr(base=base, name=info.rust, ty=info.ty)
163
+ raise Unsupported("PY2RS029", f"attribute .{node.attr} of {peel(base.ty).rust()}", node)
164
+
165
+ def _project_value(self, name: str) -> ir.RExpr | None:
166
+ """`m.CONST`, `m.Enum.MEMBER` through an imported project module."""
167
+ member = self.ctx.project_member(name)
168
+ if member is not None and member[0].kind == "const":
169
+ sym, prefix = member
170
+ rust = sym.obj.rust
171
+ path = f"&*{prefix}::{rust[2:]}" if rust.startswith("&*") else f"{prefix}::{rust}"
172
+ return ir.Path(path=path, ty=sym.obj.ty, borrowed=sym.obj.borrowed)
173
+ head, _, attr = name.rpartition(".")
174
+ enum_member = self.ctx.project_member(head) if "." in head else None
175
+ if enum_member is not None and enum_member[0].kind == "enum":
176
+ sym, prefix = enum_member
177
+ if attr in sym.obj.members:
178
+ path = f"{prefix}::{sym.obj.rust}::{sym.obj.members[attr]}"
179
+ return ir.Path(path=path, ty=T(sym.obj.rust))
180
+ return None
181
+
182
+ # -- operators ------------------------------------------------------------------------
183
+ def expr_UnaryOp(self, node: ast.UnaryOp) -> ir.RExpr:
184
+ if isinstance(node.op, ast.Not):
185
+ return not_(self.cond(node.operand))
186
+ e = self.expr(node.operand)
187
+ ty = peel(e.ty)
188
+ if isinstance(node.op, ast.USub) and ty in (INT, FLOAT):
189
+ if isinstance(e, ir.Lit) and isinstance(e.value, int | float):
190
+ return ir.lit(e.kind, -e.value, ty)
191
+ if ty == INT and self.ctx.cfg.int_overflow != "native":
192
+ self.drift("PY2RS041", node, "i64 negation")
193
+ if self.ctx.cfg.int_overflow == "wrapping":
194
+ return ir.method(e, "wrapping_neg", ty=INT)
195
+ return ir.rt("neg", e, ty=INT)
196
+ return ir.Un(op="-", operand=e, ty=ty)
197
+ if isinstance(node.op, ast.UAdd) and ty in (INT, FLOAT):
198
+ return e
199
+ if isinstance(node.op, ast.Invert) and ty == INT:
200
+ return ir.Un(op="!", operand=e, ty=INT)
201
+ raise Unsupported("PY2RS038", f"unary operator on {ty.rust()}", node)
202
+
203
+ def numeric(self, a: ir.RExpr, b: ir.RExpr) -> tuple[ir.RExpr, ir.RExpr, RType]:
204
+ ta, tb = peel(a.ty), peel(b.ty)
205
+ if FLOAT in (ta, tb) and {ta, tb} <= {INT, FLOAT}:
206
+ return self.coerce(a, FLOAT, promote=True), self.coerce(b, FLOAT, promote=True), FLOAT
207
+ return a, b, ta if ta == tb else UNKNOWN
208
+
209
+ def expr_BinOp(self, node: ast.BinOp) -> ir.RExpr:
210
+ a, b = self.expr(node.left), self.expr(node.right)
211
+ op = type(node.op)
212
+ special = self._seq_op(node, op, a, b)
213
+ if special:
214
+ return special
215
+ a, b, ty = self.numeric(a, b)
216
+ if op in ARITH:
217
+ if ty not in (INT, FLOAT) and not ty.unknown:
218
+ raise Unsupported(
219
+ "PY2RS038", f"operator on {peel(a.ty).rust()} and {peel(b.ty).rust()}", node
220
+ )
221
+ if ty == INT:
222
+ return self.int_op(ARITH[op], a, b, node)
223
+ return bin_(ARITH[op], a, b, ty)
224
+ if ty not in (INT, FLOAT):
225
+ raise Unsupported("PY2RS036", "arithmetic on operands of unknown type", node)
226
+ if op is ast.Div:
227
+ fa, fb = self.coerce(a, FLOAT, promote=True), self.coerce(b, FLOAT, promote=True)
228
+ if self.catches("ZeroDivisionError"):
229
+ return self.question(ir.rt("try_div", fa, fb), FLOAT, node)
230
+ if isinstance(fb, ir.Lit) and fb.value: # a non-zero literal divisor cannot raise
231
+ return bin_("/", fa, fb, FLOAT)
232
+ self.drift("PY2RS046", node, "float division by zero panics")
233
+ return ir.rt("div", fa, fb, ty=FLOAT)
234
+ if op in (ast.FloorDiv, ast.Mod):
235
+ return self._floor_op(op, a, b, ty, node)
236
+ if op is ast.Pow:
237
+ return self._pow(node, a, b, ty)
238
+ if op in BITS and ty == INT:
239
+ return bin_(BITS[op], a, b, INT)
240
+ raise Unsupported("PY2RS038", f"operator {op.__name__}", node)
241
+
242
+ def int_op(self, sym: str, a: ir.RExpr, b: ir.RExpr, node: ast.AST) -> ir.RExpr:
243
+ """`a <sym> b` on i64 according to the overflow policy (checked panics, wrapping wraps)."""
244
+ self.drift("PY2RS041", node, "i64 arithmetic")
245
+ name = {"+": "add", "-": "sub", "*": "mul"}[sym]
246
+ mode = self.ctx.cfg.int_overflow
247
+ if mode == "native":
248
+ return bin_(sym, a, b, INT)
249
+ if mode == "wrapping":
250
+ return ir.method(a, f"wrapping_{name}", b, ty=INT)
251
+ return ir.rt(name, a, b, ty=INT)
252
+
253
+ def _floor_op(self, op: type, a: ir.RExpr, b: ir.RExpr, ty: RType, node: ast.AST) -> ir.RExpr:
254
+ floor = op is ast.FloorDiv
255
+ if ty == FLOAT:
256
+ name = "floordiv_f" if floor else "floormod_f"
257
+ if self.catches("ZeroDivisionError"):
258
+ return self.question(ir.rt(f"try_{name}", a, b), FLOAT, node)
259
+ self.drift("PY2RS046", node, "float floor division/modulo by zero panics")
260
+ return ir.rt(name, a, b, ty=FLOAT)
261
+ if nonneg(a) and (ir.lit_int(b) or 0) > 0:
262
+ return bin_("/" if floor else "%", a, b, INT)
263
+ if self.catches("ZeroDivisionError"):
264
+ return self.question(
265
+ ir.rt("try_floordiv" if floor else "try_floormod", a, b), INT, node
266
+ )
267
+ return ir.rt("floordiv" if floor else "floormod", a, b, ty=INT)
268
+
269
+ def _pow(self, node: ast.AST, a: ir.RExpr, b: ir.RExpr, ty: RType) -> ir.RExpr:
270
+ if ty == FLOAT:
271
+ return ir.method(a, "powf", b, ty=FLOAT)
272
+ self.drift("PY2RS041", node, "i64 power")
273
+ if not nonneg(b):
274
+ raise Unsupported("PY2RS038", "integer ** with a possibly negative exponent", node)
275
+ mode = self.ctx.cfg.int_overflow
276
+ if mode == "checked":
277
+ return ir.rt("pow", a, b, ty=INT)
278
+ exp = b if ir.lit_int(b) is not None else ir.Cast(operand=b, ty=U32)
279
+ return ir.method(a, "wrapping_pow" if mode == "wrapping" else "pow", exp, ty=INT)
280
+
281
+ def _seq_op(self, node: ast.BinOp, op: type, a: ir.RExpr, b: ir.RExpr) -> ir.RExpr | None:
282
+ ta, tb = peel(a.ty), peel(b.ty)
283
+ if op is ast.Add and ta == STR and tb == STR:
284
+ return ir.Macro(name="format", args=[a, b], template="{}{}", ty=STR)
285
+ if op is ast.Add and ta.name == "Vec" and ta == tb:
286
+ both = ir.method(ir.method(a, "iter"), "chain", ir.method(b, "iter"))
287
+ return ir.method(
288
+ ir.method(both, "cloned"), "collect", ty=ta, turbofish=T("Vec", UNKNOWN)
289
+ )
290
+ if op is ast.Mult:
291
+ if tb.name in ("String", "Vec") and ta == INT:
292
+ a, b, ta, tb = b, a, tb, ta
293
+ if tb == INT and ta == STR:
294
+ return ir.method(a, "repeat", usize(b), ty=STR)
295
+ if (
296
+ not self.shared
297
+ and tb == INT
298
+ and ta.name == "Vec"
299
+ and self._shares_mutable(ta, True)
300
+ ):
301
+ raise Unsupported(
302
+ "PY2RS040",
303
+ "list repetition shares one mutable element between all copies",
304
+ node,
305
+ )
306
+ if tb == INT and isinstance(node.left, ast.List) and len(node.left.elts) == 1:
307
+ first = self.expr(node.left.elts[0])
308
+ return ir.Macro(name="vec_repeat", args=[first, usize(b)], ty=T("Vec", first.ty))
309
+ if tb == INT and ta.name == "Vec":
310
+ rep = ir.Call(func=ir.Path(path="std::iter::repeat_n"), args=[a, usize(b)])
311
+ return ir.method(
312
+ ir.method(rep, "flatten"), "collect", ty=ta, turbofish=T("Vec", UNKNOWN)
313
+ )
314
+ return None
315
+
316
+ # -- boolean logic and comparisons ----------------------------------------------------
317
+ def cond(self, node: ast.expr) -> ir.RExpr:
318
+ """`node` as a Rust bool, applying Python truthiness to each operand."""
319
+ if isinstance(node, ast.BoolOp):
320
+ op = "&&" if isinstance(node.op, ast.And) else "||"
321
+ out = self.cond(node.values[0])
322
+ for v in node.values[1:]:
323
+ out = bin_(op, out, self.cond(v), BOOL)
324
+ return out
325
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
326
+ return not_(self.cond(node.operand))
327
+ return self.truthy(self.expr(node), node)
328
+
329
+ def expr_BoolOp(self, node: ast.BoolOp) -> ir.RExpr:
330
+ vals = [self.expr(v) for v in node.values]
331
+ if all(peel(v.ty) == BOOL for v in vals):
332
+ return self.cond(node)
333
+ out = vals[0]
334
+ for v in vals[1:]: # `a or b or c` is `(a or b) or c`: each step yields an operand
335
+ out = self._logic(node, out, v, isinstance(node.op, ast.Or))
336
+ return out
337
+
338
+ def _logic(self, node: ast.BoolOp, a: ir.RExpr, b: ir.RExpr, is_or: bool) -> ir.RExpr:
339
+ """`a or b` / `a and b` return one of the operands (never a bool), `b` only when needed."""
340
+ ta, tb = peel(a.ty), peel(b.ty)
341
+ if is_or and ta.name == "Option":
342
+ inner = arg(ta)
343
+ probe = ir.Var(name="v", ty=T("&", inner))
344
+ keep = ir.Closure(params=[ir.PVar("v")], body=self.truthy(probe, node))
345
+ owned = ir.CloneX(operand=a, ty=ta) if ir.is_place(a) else a # filter() consumes
346
+ filtered = ir.method(owned, "filter", keep, ty=ta)
347
+ if tb.name == "Option":
348
+ return ir.method(
349
+ filtered, "or_else", ir.Closure(params=[], body=b), ty=unify(ta, tb)
350
+ )
351
+ lazy = ir.Closure(params=[], body=self.coerce(b, inner))
352
+ return ir.method(filtered, "unwrap_or_else", lazy, ty=inner)
353
+ ty = unify(ta, tb)
354
+ if not ty.known:
355
+ raise Unsupported("PY2RS036", "and/or on operands of unknown or mixed type", node)
356
+ a, b = self.coerce(a, ty), self.coerce(b, ty)
357
+ if ir.is_place(a):
358
+ test = self.truthy(ir.dup(a), node)
359
+ then, other = (a, b) if is_or else (b, ir.dup(a))
360
+ return ir.IfX(cond=test, then=then, other=other, ty=ty)
361
+ name = f"tmp_{node.lineno}_{node.col_offset}" # evaluate a non-trivial left operand once
362
+ held = ir.Var(name=name, ty=ty)
363
+ then, other = (held, b) if is_or else (b, ir.dup(held))
364
+ out = ir.IfX(cond=self.truthy(ir.dup(held), node), then=then, other=other, ty=ty)
365
+ return ir.BlockX(stmts=[ir.Let(ir.PVar(name), ty, a)], tail=out, ty=ty)
366
+
367
+ def expr_Compare(self, node: ast.Compare) -> ir.RExpr:
368
+ operands = [node.left, *node.comparators]
369
+ parts: list[ir.RExpr] = []
370
+ for i, op in enumerate(node.ops):
371
+ if i and not isinstance(operands[i], SIMPLE_NODES):
372
+ raise Unsupported(
373
+ "PY2RS038", "chained comparison with a computed middle operand", node
374
+ )
375
+ parts.append(self._compare(node, op, operands[i], operands[i + 1]))
376
+ out = parts[0]
377
+ for p in parts[1:]:
378
+ out = bin_("&&", out, p, BOOL)
379
+ return out
380
+
381
+ def _compare(
382
+ self, node: ast.AST, op: ast.cmpop, a_node: ast.expr, b_node: ast.expr
383
+ ) -> ir.RExpr:
384
+ if isinstance(op, (ast.In, ast.NotIn)):
385
+ found = self._contains(self.expr(a_node), b_node, node)
386
+ return not_(found) if isinstance(op, ast.NotIn) else found
387
+ a, b = self.expr(a_node), self.expr(b_node)
388
+ nones = [x for x in (a, b) if is_none(x)]
389
+ if nones and isinstance(op, (ast.Is, ast.IsNot, ast.Eq, ast.NotEq)):
390
+ other = b if a is nones[0] else a
391
+ return self._none_test(node, other, isinstance(op, (ast.IsNot, ast.NotEq)))
392
+ sym = CMP.get(type(op))
393
+ if sym is None:
394
+ raise Unsupported("PY2RS038", f"comparison {type(op).__name__}", node)
395
+ return self._cmp(a, sym, b)
396
+
397
+ def _pair(self, a: ir.RExpr, b: ir.RExpr) -> tuple[ir.RExpr, ir.RExpr]:
398
+ """Bring two compared operands to a common Rust type (Some(..), Literal variant, int -> f64)."""
399
+ ta, tb = peel(a.ty), peel(b.ty)
400
+ lit_enums = self.ctx.lit_enums
401
+ if ta.name == "Option" and tb.name != "Option":
402
+ return a, self.coerce(b, ta)
403
+ if (tb.name == "Option" and ta.name != "Option") or tb.name in lit_enums:
404
+ return self.coerce(a, tb), b
405
+ if ta.name in lit_enums:
406
+ return a, self.coerce(b, ta)
407
+ if ta == STR and tb == STR:
408
+ return self.as_str(a), self.as_str(b)
409
+ a, b, _ = self.numeric(a, b)
410
+ return a, b
411
+
412
+ def _none_test(self, node: ast.AST, value: ir.RExpr, negate: bool) -> ir.RExpr:
413
+ """`x is None` for Option, JSON values (null) and nested Option<Value>."""
414
+ ty = peel(value.ty)
415
+ if ty == VALUE:
416
+ test = ir.method(value, "is_null", ty=BOOL)
417
+ return not_(test) if negate else test
418
+ if ty.name == "Option" and arg(ty) == VALUE:
419
+ is_value = ir.method(ir.Var(name="v", ty=T("&", VALUE)), "is_null", ty=BOOL)
420
+ closure = ir.Closure(params=[ir.PVar("v")], body=not_(is_value))
421
+ some = ir.method(ir.method(value, "as_ref"), "is_some_and", closure, ty=BOOL)
422
+ return some if negate else not_(some)
423
+ if ty.name == "Option":
424
+ return ir.method(value, "is_some" if negate else "is_none", ty=BOOL)
425
+ if not ty.known or ty.name.startswith("Py2rsUnmapped") or is_none(value):
426
+ raise Unsupported("PY2RS036", "`is None` on a value of unknown type", node)
427
+ return ir.lit("bool", negate, BOOL) # a typed non-Optional value is never None
428
+
429
+ def _cmp(self, a: ir.RExpr, sym: str, b: ir.RExpr) -> ir.RExpr:
430
+ a, b = self._pair(a, b)
431
+ return bin_(sym, cmp_operand(a), cmp_operand(b), BOOL)
432
+
433
+ def _contains(self, item: ir.RExpr, box: ast.expr, node: ast.AST) -> ir.RExpr:
434
+ ti = peel(item.ty)
435
+ consts = (
436
+ isinstance(box, (ast.Tuple, ast.List, ast.Set))
437
+ and box.elts
438
+ and all(
439
+ isinstance(e, ast.Constant)
440
+ and isinstance(e.value, (str, int))
441
+ and not isinstance(e.value, bool)
442
+ for e in box.elts
443
+ )
444
+ )
445
+ if consts and ti in (STR, INT):
446
+ pats: list[ir.Pat] = [ir.PExpr(self.expr(e)) for e in box.elts]
447
+ subject = self.as_str(item) if ti == STR else item
448
+ return ir.Macro(name="matches", args=[subject], pat=ir.POr(pats), ty=BOOL)
449
+ c = self.expr(box)
450
+ name = peel(c.ty).name
451
+ if name == MAP:
452
+ return ir.method(c, "contains_key", self.ref_of(item), ty=BOOL)
453
+ if name in (SET, "String") and (name == SET or ti == STR):
454
+ return ir.method(c, "contains", self.ref_of(item), ty=BOOL)
455
+ if name == "Vec":
456
+ test = ir.Closure(
457
+ params=[ir.PVar("e")],
458
+ body=bin_(
459
+ "==",
460
+ ir.Deref(operand=ir.Var(name="e", ty=T("&", ti)), ty=ti),
461
+ cmp_operand(item),
462
+ BOOL,
463
+ ),
464
+ )
465
+ return ir.method(ir.method(c, "iter"), "any", test, ty=BOOL)
466
+ raise Unsupported("PY2RS038", f"`in` on {peel(c.ty).rust()}", node)
467
+
468
+ def expr_IfExp(self, node: ast.IfExp) -> ir.RExpr:
469
+ test, a, b = self.cond(node.test), self.expr(node.body), self.expr(node.orelse)
470
+ ty = unify(peel(a.ty), peel(b.ty))
471
+ return ir.IfX(cond=test, then=self.coerce(a, ty), other=self.coerce(b, ty), ty=ty)
472
+
473
+ # -- containers, subscripts -----------------------------------------------------------
474
+ def _elements(self, nodes: list[ast.expr]) -> tuple[list[ir.RExpr], RType]:
475
+ items = []
476
+ for n in nodes:
477
+ if isinstance(n, ast.Starred):
478
+ raise Unsupported("PY2RS034", "starred expression in a literal", n)
479
+ items.append(self.expr(n))
480
+ ty = UNKNOWN
481
+ for it in items:
482
+ found = peel(it.ty)
483
+ if not (compatible(ty, found) or compatible(found, ty)):
484
+ # a heterogeneous literal: JSON values, which keep each element's own type
485
+ self.ctx.col.diag(
486
+ "PY2RS007", nodes[0], "mixed-type literal becomes JSON values", severity="info"
487
+ )
488
+ return [self.coerce(i, VALUE) for i in items], VALUE
489
+ ty = unify(ty, found)
490
+ return [self.coerce(i, ty) for i in items], ty
491
+
492
+ def expr_List(self, node: ast.List) -> ir.RExpr:
493
+ items, ty = self._elements(node.elts)
494
+ if not items:
495
+ return ir.Call(func=ir.Path(path="Vec::new"), ty=T("Vec", UNKNOWN))
496
+ return ir.Macro(name="vec", args=items, ty=T("Vec", ty))
497
+
498
+ def expr_Tuple(self, node: ast.Tuple) -> ir.RExpr:
499
+ items = [self.expr(n) for n in node.elts]
500
+ return ir.TupleX(
501
+ elems=items, ty=T("tuple", *(peel(i.ty) for i in items)) if items else UNIT
502
+ )
503
+
504
+ def expr_Set(self, node: ast.Set) -> ir.RExpr:
505
+ items, ty = self._elements(node.elts)
506
+ arr = ir.ArrayX(elems=items, ty=T("Array", ty))
507
+ return ir.Call(func=ir.Path(path=f"{SET}::from"), args=[arr], ty=T(SET, ty))
508
+
509
+ def expr_Dict(self, node: ast.Dict) -> ir.RExpr:
510
+ if any(k is None for k in node.keys):
511
+ raise Unsupported("PY2RS034", "dict unpacking **x in a literal", node)
512
+ keys, kt = self._elements([k for k in node.keys if k is not None])
513
+ vals, vt = self._elements(node.values)
514
+ if not keys:
515
+ return ir.Call(func=ir.Path(path=f"{MAP}::new"), ty=T(MAP, UNKNOWN, UNKNOWN))
516
+ pairs = ir.ArrayX(
517
+ elems=[ir.TupleX(elems=[k, v]) for k, v in zip(keys, vals, strict=False)],
518
+ ty=T("Array", UNKNOWN),
519
+ )
520
+ return ir.Call(func=ir.Path(path=f"{MAP}::from"), args=[pairs], ty=T(MAP, kt, vt))
521
+
522
+ def expr_Subscript(self, node: ast.Subscript) -> ir.RExpr:
523
+ base = self.expr(node.value)
524
+ if isinstance(node.slice, ast.Slice):
525
+ return self._slice(node, base, node.slice)
526
+ index = self.expr(node.slice)
527
+ tb, ti = peel(base.ty), peel(index.ty)
528
+ if tb.name == MAP and self.catches("KeyError"):
529
+ found = ir.method(ir.method(base, "get", self.ref_of(index)), "cloned")
530
+ absent = ir.Closure(params=[], body=ir.rt("key_error", ir.Ref(operand=ir.dup(index))))
531
+ return self.question(ir.method(found, "ok_or_else", absent), arg(tb, 1), node)
532
+ if tb.name == "serde_json::Value" and ti in (STR, INT):
533
+ fn, key = ("value_item", self.as_str(index)) if ti == STR else ("value_at", index)
534
+ call = ir.rt(fn, self.ref_of(base), key, ty=VALUE)
535
+ if self.catches("KeyError" if ti == STR else "IndexError"):
536
+ return self.question(call, VALUE, node)
537
+ self.drift(
538
+ "PY2RS045", node, "indexing JSON data panics instead of raising KeyError/IndexError"
539
+ )
540
+ return ir.rt("or_panic", call, ty=VALUE)
541
+ if tb.name == MAP:
542
+ return ir.Index(base=base, index=self.ref_of(index), ty=arg(tb, 1))
543
+ if ti != INT and not ti.unknown:
544
+ raise Unsupported("PY2RS038", f"subscript with a {ti.rust()} index", node)
545
+ if self.catches("IndexError"):
546
+ if tb.name == "Vec":
547
+ checked = ir.rt("try_idx", index, ir.method(ir.dup(base), "len", ty=USIZE))
548
+ return ir.Index(base=base, index=self.question(checked, USIZE, node), ty=arg(tb))
549
+ if tb == STR:
550
+ checked = ir.rt("try_str_item", self.ref_of(base), index, ty=STR)
551
+ return self.question(checked, STR, node)
552
+ self.drift("PY2RS045", node, "indexing panics instead of raising IndexError/KeyError")
553
+ if tb.name == "Vec":
554
+ lit = ir.lit_int(index)
555
+ direct = lit is not None and lit >= 0
556
+ pos = (
557
+ index
558
+ if direct
559
+ else ir.rt("idx", index, ir.method(ir.dup(base), "len", ty=USIZE), ty=USIZE)
560
+ )
561
+ return ir.Index(base=base, index=pos, ty=arg(tb))
562
+ if tb.name == "String":
563
+ return ir.rt("str_index", self.ref_of(base), index, ty=STR)
564
+ pos_lit = ir.lit_int(index)
565
+ if tb.name == "tuple" and pos_lit is not None and 0 <= pos_lit < len(tb.args):
566
+ return ir.Attr(base=base, name=str(pos_lit), ty=tb.args[pos_lit])
567
+ raise Unsupported("PY2RS019", f"subscript on a value of type {tb.rust()}", node)
568
+
569
+ def _slice(self, node: ast.Subscript, base: ir.RExpr, sl: ast.Slice) -> ir.RExpr:
570
+ tb = peel(base.ty)
571
+ if tb.name not in ("String", "Vec"):
572
+ raise Unsupported("PY2RS023", f"slice of {tb.rust()}", node)
573
+ step = self.expr(sl.step) if sl.step else None
574
+ if step is not None and not (isinstance(step, ir.Lit) and step.value == 1):
575
+ if isinstance(step, ir.Lit) and step.value == -1 and not sl.lower and not sl.upper:
576
+ if tb == STR:
577
+ chars = ir.method(ir.method(base, "chars"), "rev")
578
+ return ir.method(chars, "collect", ty=STR, turbofish=STR)
579
+ rev = ir.method(ir.method(ir.method(base, "iter"), "rev"), "cloned")
580
+ return ir.method(rev, "collect", ty=tb, turbofish=T("Vec", UNKNOWN))
581
+ raise Unsupported("PY2RS023", "slice step other than 1 or a full reverse", node)
582
+
583
+ def bound(part: ast.expr | None) -> ir.RExpr:
584
+ if part is None:
585
+ return ir.Lit(kind="none", ty=T("Option", INT))
586
+ value = self.expr(part)
587
+ if isinstance(value, ir.Call) and isinstance(value.func, ir.Path):
588
+ op = value.func.path.removeprefix("rt::")
589
+ if value.func.path.startswith("rt::") and op in ("add", "sub", "mul", "neg"):
590
+ # Values beyond i64 clamp to the same slice endpoint as the saturated value.
591
+ operand, *args = value.args
592
+ value = ir.method(operand, f"saturating_{op}", *args, ty=INT)
593
+ return ir.Call(func=ir.Path(path="Some"), args=[value], ty=T("Option", INT))
594
+
595
+ fn = "str_slice" if tb == STR else "list_slice"
596
+ return ir.rt(fn, self.ref_of(base), bound(sl.lower), bound(sl.upper), ty=tb)
597
+
598
+ # -- strings, lambdas, comprehensions -------------------------------------------------
599
+ def expr_JoinedStr(self, node: ast.JoinedStr) -> ir.RExpr:
600
+ return fstrings.joined(self, node)
601
+
602
+ def expr_Lambda(self, node: ast.Lambda, param_types: list[RType] | None = None) -> ir.RExpr:
603
+ a = node.args
604
+ if a.vararg or a.kwarg or a.kwonlyargs or a.defaults:
605
+ raise Unsupported("PY2RS015", "lambda with defaults or variadic parameters", node)
606
+ if (
607
+ param_types is None
608
+ ): # a stored or returned closure: Python reads names when it is called
609
+ own = {p.arg for p in a.posonlyargs + a.args}
610
+ late = {
611
+ n.id
612
+ for n in ast.walk(node.body)
613
+ if isinstance(n, ast.Name)
614
+ and n.id not in own
615
+ and (n.id in self.late_bound or any(n.id in c for c in self.comp_vars))
616
+ }
617
+ if late:
618
+ raise Unsupported(
619
+ "PY2RS026",
620
+ f"closure reads {sorted(late)[0]}, which changes after the closure is made",
621
+ node,
622
+ )
623
+ self.push()
624
+ try:
625
+ params: list[ir.Pat] = []
626
+ for i, p in enumerate(a.posonlyargs + a.args):
627
+ ty = param_types[i] if param_types and i < len(param_types) else UNKNOWN
628
+ params.append(ir.PVar(self.declare(p.arg, ty).rust))
629
+ self.closure_depth += 1
630
+ try:
631
+ body = self.expr(node.body)
632
+ finally:
633
+ self.closure_depth -= 1
634
+ finally:
635
+ self.pop()
636
+ closure = ir.Closure(
637
+ params=params, body=body, ty=T("Fn", peel(body.ty)), move=param_types is None
638
+ )
639
+ if param_types is not None:
640
+ return closure
641
+ # an escaping closure owns what it captures: a clone of each handle or value, so the
642
+ # function can keep using its own (the closure shares the Python object)
643
+ own = {p.arg for p in a.posonlyargs + a.args}
644
+ caught: list[ir.RStmt] = []
645
+ for name in dict.fromkeys(
646
+ n.id for n in ast.walk(node.body) if isinstance(n, ast.Name) and n.id not in own
647
+ ):
648
+ var = self.lookup(name)
649
+ if var is not None and not is_copy(peel(var.ty)) and var.ty.name not in ("Fn", "?"):
650
+ clone = ir.CloneX(operand=ir.Var(name=var.rust, ty=var.ty), ty=var.ty)
651
+ caught.append(ir.Let(ir.PVar(var.rust), None, clone))
652
+ if not caught:
653
+ return closure
654
+ return ir.BlockX(stmts=caught, tail=closure, ty=closure.ty)
655
+
656
+ def bind_target(self, target: ast.expr, ty: RType, allow_mut: bool = False) -> ir.Pat:
657
+ """Declare the names bound by a for/comprehension target; return the Rust pattern."""
658
+ if isinstance(target, ast.Name):
659
+ if target.id == "_":
660
+ return ir.PWild()
661
+ return ir.PVar(
662
+ self.declare(target.id, ty).rust,
663
+ allow_mut and target.id in self.mutated and ty.name != "&mut",
664
+ )
665
+ if isinstance(target, ast.Tuple) and not any(
666
+ isinstance(e, ast.Starred) for e in target.elts
667
+ ):
668
+ kids = [
669
+ ty.args[i] if ty.name == "tuple" and i < len(ty.args) else UNKNOWN
670
+ for i in range(len(target.elts))
671
+ ]
672
+ return ir.PTuple(
673
+ [self.bind_target(e, k, allow_mut) for e, k in zip(target.elts, kids, strict=False)]
674
+ )
675
+ raise Unsupported("PY2RS035", "unsupported loop target", target)
676
+
677
+ def _may_raise(self, node: ast.AST) -> bool:
678
+ """Can evaluating `node` raise an error that a try could catch (index, key, division,
679
+ int()/float(), a fallible function, a raising library call)?"""
680
+ for n in ast.walk(node):
681
+ if isinstance(n, ast.Subscript) and isinstance(n.ctx, ast.Load):
682
+ if not isinstance(n.slice, ast.Slice):
683
+ return True
684
+ elif isinstance(n, ast.BinOp) and isinstance(n.op, ast.FloorDiv | ast.Mod | ast.Div):
685
+ if not (isinstance(n.right, ast.Constant) and n.right.value):
686
+ return True
687
+ elif isinstance(n, ast.Call):
688
+ f = n.func
689
+ if isinstance(f, ast.Name):
690
+ sig = self.ctx.sigs.get(f.id)
691
+ if (
692
+ f.id in ("int", "float")
693
+ and n.args
694
+ and not isinstance(n.args[0], ast.Constant)
695
+ ):
696
+ return True
697
+ if sig is not None and sig.fallible:
698
+ return True
699
+ entry = self.ctx.library_entry(dotted(f))
700
+ if entry and entry.get("raises"):
701
+ return True
702
+ return False
703
+
704
+ def _comp(
705
+ self, node: ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp, kind: str
706
+ ) -> ir.RExpr:
707
+ if any(g.is_async for g in node.generators):
708
+ raise Unsupported("PY2RS011", "async comprehension", node)
709
+ self.push()
710
+ self.comp_vars.append(
711
+ {n.id for g in node.generators for n in ast.walk(g.target) if isinstance(n, ast.Name)}
712
+ )
713
+ try:
714
+ if (self.catch_stack or self.fallible) and self._may_raise(node):
715
+ # `?` and labelled breaks cannot leave a closure: loops carry the error out
716
+ if kind == "gen":
717
+ self.drift("PY2RS059", node, "generator evaluated eagerly")
718
+ return self._comp_loops(node, "list" if kind == "gen" else kind)
719
+ if len(node.generators) == 1:
720
+ return self._comp_chain(node, kind)
721
+ return self._comp_loops(node, kind)
722
+ finally:
723
+ self.comp_vars.pop()
724
+ self.pop()
725
+
726
+ def _comp_elt(
727
+ self, node: ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp
728
+ ) -> tuple[ir.RExpr, RType]:
729
+ if isinstance(node, ast.DictComp):
730
+ k, v = self.expr(node.key), self.expr(node.value)
731
+ ty = T("tuple", peel(k.ty), peel(v.ty))
732
+ return ir.TupleX(elems=[k, v], ty=ty), ty
733
+ assert not isinstance(node, ast.DictComp)
734
+ e = self.expr(node.elt)
735
+ return e, peel(e.ty)
736
+
737
+ def _comp_type(self, kind: str, ety: RType) -> RType:
738
+ if kind == "set":
739
+ return T(SET, ety)
740
+ if kind == "dict":
741
+ return T(MAP, arg(ety, 0), arg(ety, 1))
742
+ return T("Vec", ety)
743
+
744
+ def _comp_chain(
745
+ self, node: ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp, kind: str
746
+ ) -> ir.RExpr:
747
+ gen = node.generators[0]
748
+ it = self.as_iter(self.expr(gen.iter), gen.iter)
749
+ pat = self.bind_target(gen.target, arg(it.ty))
750
+ self.closure_depth += 1 # the filter/map bodies below are closures
751
+ try:
752
+ conds = [self.cond(c) for c in gen.ifs]
753
+ elt, ety = self._comp_elt(node)
754
+ finally:
755
+ self.closure_depth -= 1
756
+ if conds:
757
+ test = conds[0]
758
+ for c in conds[1:]:
759
+ test = bin_("&&", test, c, BOOL)
760
+ some = ir.Call(func=ir.Path(path="Some"), args=[elt], ty=T("Option", ety))
761
+ body = ir.IfX(
762
+ cond=test,
763
+ then=some,
764
+ other=ir.Lit(kind="none", ty=T("Option", ety)),
765
+ ty=T("Option", ety),
766
+ )
767
+ chain = ir.method(
768
+ it, "filter_map", ir.Closure(params=[pat], body=body), ty=T("Iter", ety)
769
+ )
770
+ else:
771
+ chain = ir.method(it, "map", ir.Closure(params=[pat], body=elt), ty=T("Iter", ety))
772
+ if kind == "gen":
773
+ return chain
774
+ ty = self._comp_type(kind, ety)
775
+ return ir.method(chain, "collect", ty=ty, turbofish=ty)
776
+
777
+ def _comp_loops(
778
+ self, node: ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp, kind: str
779
+ ) -> ir.RExpr:
780
+ """Several `for` clauses: nested loops filling a collection inside a block expression."""
781
+ spans: list[tuple[ir.Pat, ir.RExpr, list[ir.RExpr]]] = []
782
+ for gen in node.generators:
783
+ it = self.as_iter(self.expr(gen.iter), gen.iter)
784
+ pat = self.bind_target(gen.target, arg(it.ty))
785
+ spans.append((pat, it, [self.cond(c) for c in gen.ifs]))
786
+ elt, ety = self._comp_elt(node)
787
+ ty = self._comp_type(kind, ety)
788
+ out = ir.Var(name="out", ty=ty)
789
+ if kind == "set":
790
+ add = ir.method(out, "insert", elt)
791
+ elif kind == "dict":
792
+ add = ir.method(
793
+ out,
794
+ "insert",
795
+ ir.Attr(base=ir.dup(elt), name="0"),
796
+ ir.Attr(base=ir.dup(elt), name="1"),
797
+ )
798
+ else:
799
+ add = ir.method(out, "push", elt)
800
+ inner: list[ir.RStmt] = [ir.ExprS(add)]
801
+ for pat, it, conds in reversed(spans):
802
+ for c in reversed(conds):
803
+ inner = [ir.IfS(c, inner)]
804
+ inner = [ir.ForS(pat, it, inner)]
805
+ new = ir.Call(func=ir.Path(path=f"{ty.name}::new"), ty=ty)
806
+ stmts: list[ir.RStmt] = [ir.Let(ir.PVar("out", True), ty, new), *inner]
807
+ tail: ir.RExpr = (
808
+ ir.method(ir.Var(name="out", ty=ty), "into_iter", ty=T("Iter", ety))
809
+ if kind == "gen"
810
+ else ir.Var(name="out", ty=ty)
811
+ )
812
+ return ir.BlockX(stmts=stmts, tail=tail, ty=T("Iter", ety) if kind == "gen" else ty)
813
+
814
+ def expr_ListComp(self, node: ast.ListComp) -> ir.RExpr:
815
+ return self._comp(node, "list")
816
+
817
+ def expr_SetComp(self, node: ast.SetComp) -> ir.RExpr:
818
+ return self._comp(node, "set")
819
+
820
+ def expr_DictComp(self, node: ast.DictComp) -> ir.RExpr:
821
+ return self._comp(node, "dict")
822
+
823
+ def expr_GeneratorExp(self, node: ast.GeneratorExp) -> ir.RExpr:
824
+ return self._comp(node, "gen")
825
+
826
+ def expr_NamedExpr(self, node: ast.NamedExpr) -> ir.RExpr:
827
+ raise Unsupported(
828
+ "PY2RS021", "walrus (:=) inside an expression that cannot be hoisted", node
829
+ )
830
+
831
+ def expr_Await(self, node: ast.Await) -> ir.RExpr:
832
+ """`await f(x)` -> `f(x).await`; a fallible async function adds the `?` after it."""
833
+ operand = self.expr(node.value)
834
+ fut = peel(operand.ty)
835
+ if fut.name != "Future":
836
+ raise Unsupported("PY2RS011", "await of a value that is not a known coroutine", node)
837
+ awaited = ir.AwaitX(operand=operand, ty=arg(fut), span=operand.span)
838
+ if len(fut.args) > 1: # Future<T, PyError>: the coroutine can raise
839
+ return self.question(awaited, arg(fut), node)
840
+ return awaited
841
+
842
+ def expr_Yield(self, node: ast.Yield) -> ir.RExpr:
843
+ raise Unsupported("PY2RS027", "yield", node)
844
+
845
+ expr_YieldFrom = expr_Yield