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,141 @@
1
+ """f-strings and str() -> format!, following Python's formatting rules for common specs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import re
7
+
8
+ from ..ir import nodes as ir
9
+ from ..ir.rtypes import BOOL, FLOAT, INT, STR, peel
10
+ from .lowerer import Lowerer, Unsupported
11
+
12
+ SPEC = re.compile(r"^(?:(.)?([<>^]))?([+-])?(0)?(\d+)?(,)?(?:\.(\d+))?([dfFsxXbo])?$")
13
+
14
+
15
+ def display(lw: Lowerer, e: ir.RExpr, node: ast.AST | None) -> ir.RExpr:
16
+ """An expression that yields `str(e)` as a format! argument."""
17
+ ty = peel(e.ty)
18
+ if ty.name == "uuid::Uuid":
19
+ return e
20
+ if ty.name == "rt::PyError":
21
+ return ir.Attr(base=e, name="message", ty=STR)
22
+ if ty in (STR, INT):
23
+ return e
24
+ if ty == FLOAT:
25
+ lw.ctx.col.drift("PY2RS042", node, "str(float)")
26
+ return ir.rt("fmt_float", e, ty=STR)
27
+ if ty == BOOL:
28
+ return ir.rt("fmt_bool", e, ty=STR)
29
+ raise Unsupported("PY2RS022", f"str() of a value of type {ty.rust()}", node)
30
+
31
+
32
+ def _rust_spec(lw: Lowerer, spec: str, e: ir.RExpr, node: ast.AST | None) -> tuple[str, ir.RExpr]:
33
+ m = SPEC.match(spec)
34
+ ty = peel(e.ty)
35
+ if not m or m[1] in ("{", "}"):
36
+ raise Unsupported("PY2RS022", f"format spec {spec!r}", node)
37
+ fill, align, sign, zero, width, comma, prec, kind = m.groups()
38
+ if comma:
39
+ if ty not in (INT, FLOAT) or sign or zero or kind not in (None, "d", "f", "F"):
40
+ raise Unsupported("PY2RS022", f"format spec {spec!r}", node)
41
+ if ty == FLOAT and kind not in ("f", "F"):
42
+ raise Unsupported("PY2RS022", f"',' on a float without 'f' ({spec!r})", node)
43
+ number = e if ty == INT else ir.Cast(operand=e, ty=FLOAT)
44
+ digits = int(prec or 6) if kind in ("f", "F") else 0
45
+ value = ir.Cast(operand=number, ty=FLOAT) if ty == INT and kind in ("f", "F") else e
46
+ if kind in ("f", "F"):
47
+ grouped = ir.rt("group_float", value, ir.lit("int", digits, INT), ty=STR)
48
+ else:
49
+ grouped = ir.rt("group_int", e, ty=STR)
50
+ layout = f"{fill or ''}{align or '>'}{width}" if width else ""
51
+ return layout, grouped
52
+ lit = ir.lit_int(e)
53
+ if kind in ("x", "X", "b", "o") and (lit is None or lit < 0):
54
+ raise Unsupported(
55
+ "PY2RS022",
56
+ "hex/octal/binary of an int that may be negative (Rust prints two's complement)",
57
+ node,
58
+ )
59
+ if ty == FLOAT and prec is not None and kind not in ("f", "F"):
60
+ raise Unsupported(
61
+ "PY2RS022", f"float precision without 'f' ({spec!r}) means significant digits", node
62
+ )
63
+ if kind in ("f", "F"):
64
+ if ty not in (INT, FLOAT):
65
+ raise Unsupported("PY2RS022", f"format spec {spec!r} on {ty.rust()}", node)
66
+ prec = prec or "6"
67
+ if ty == INT:
68
+ e = ir.Cast(operand=e, ty=FLOAT)
69
+ else: # nan and inf are spelled differently
70
+ e = ir.Call(func=ir.Path(path="rt::Fixed"), args=[e], ty=FLOAT)
71
+ elif (ty == FLOAT and kind is None and prec is None) or ty == BOOL:
72
+ e = display(lw, e, node)
73
+ if width and not align and (ty in (INT, FLOAT)):
74
+ align = ">"
75
+ out = (f"{fill or ''}{align}" if align else "") + (sign or "") + ("0" if zero else "")
76
+ out += (
77
+ (width or "")
78
+ + (f".{prec}" if prec else "")
79
+ + (kind if kind in ("x", "X", "b", "o") else "")
80
+ )
81
+ return out, e
82
+
83
+
84
+ def piece(lw: Lowerer, node: ast.FormattedValue) -> tuple[str, ir.RExpr]:
85
+ """(placeholder, argument) for one `{expr!c:spec}` field."""
86
+ e = lw.expr(node.value)
87
+ ty = peel(e.ty)
88
+ if node.conversion == ord("r"):
89
+ if ty == STR:
90
+ return "{}", ir.rt("repr_str", lw.as_str(e), ty=STR)
91
+ if ty == INT:
92
+ return "{}", e
93
+ raise Unsupported("PY2RS022", f"!r on a value of type {ty.rust()}", node)
94
+ if node.conversion not in (-1, ord("s")):
95
+ raise Unsupported("PY2RS022", "!a conversion", node)
96
+ spec = ""
97
+ if node.format_spec is not None:
98
+ assert isinstance(node.format_spec, ast.JoinedStr)
99
+ parts = [p.value for p in node.format_spec.values if isinstance(p, ast.Constant)]
100
+ if len(parts) != len(node.format_spec.values):
101
+ raise Unsupported("PY2RS022", "nested format spec", node)
102
+ spec = "".join(str(p) for p in parts)
103
+ if spec:
104
+ rspec, e = _rust_spec(lw, spec, e, node)
105
+ return "{:" + rspec + "}", e
106
+ return "{}", display(lw, e, node)
107
+
108
+
109
+ def joined(lw: Lowerer, node: ast.JoinedStr) -> ir.RExpr:
110
+ text: list[str] = []
111
+ args: list[ir.RExpr] = []
112
+ for part in node.values:
113
+ if isinstance(part, ast.Constant):
114
+ text.append(str(part.value).replace("{", "{{").replace("}", "}}"))
115
+ elif isinstance(part, ast.FormattedValue):
116
+ placeholder, arg = piece(lw, part)
117
+ text.append(placeholder)
118
+ args.append(arg)
119
+ if not args:
120
+ literal = "".join(str(p.value) for p in node.values if isinstance(p, ast.Constant))
121
+ return ir.lit("str", literal, STR)
122
+ if len(args) > 1 and any(isinstance(n, ir.Ref) and n.mut for n in ir.walk(args)):
123
+ return _sequenced(text, args)
124
+ return ir.Macro(name="format", args=args, template="".join(text), ty=STR)
125
+
126
+
127
+ def _sequenced(text: list[str], args: list[ir.RExpr]) -> ir.RExpr:
128
+ """`format!` borrows all its arguments at once, which a `&mut` argument cannot share. Python
129
+ evaluates the fields left to right, so each one is formatted into its own String first."""
130
+ holes = [i for i, t in enumerate(text) if t.startswith("{") and not t.startswith("{{")]
131
+ stmts: list[ir.RStmt] = []
132
+ temps: list[ir.RExpr] = []
133
+ for n, (hole, arg) in enumerate(zip(holes, args, strict=True)):
134
+ name = f"field_{n}"
135
+ stmts.append(
136
+ ir.Let(ir.PVar(name), None, ir.Macro(name="format", args=[arg], template=text[hole]))
137
+ )
138
+ temps.append(ir.Var(name=name, ty=STR))
139
+ text[hole] = "{}"
140
+ done = ir.Macro(name="format", args=temps, template="".join(text), ty=STR)
141
+ return ir.BlockX(stmts=stmts, tail=done, ty=STR)
@@ -0,0 +1,276 @@
1
+ """Function items: signatures (owned parameters, `&mut` only for in-place mutation), bodies, review flags."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import re
7
+
8
+ from ..frontend.names import fn_name
9
+ from ..ir import nodes as ir
10
+ from ..ir.rtypes import MAP, SET, STR, UNIT, RType, T
11
+ from ..ir.types import TypeMapper
12
+ from ..passes import ownership
13
+ from ..passes.aliasing import find_hazards
14
+ from ..passes.analysis import Analysis
15
+ from ..passes.devirt import find_plain
16
+ from .context import Ctx, FuncSig, ParamSig
17
+ from .lowerer import NotFresh, Unsupported, Var, local_name
18
+ from .stmts import StmtLowerer
19
+
20
+ DEFAULTABLE = {"String", "i64", "f64", "bool", "Vec", "IndexMap", "IndexSet", "Option"}
21
+ MUTABLE_DEFAULTS = (ast.List, ast.Dict, ast.Set)
22
+ Func = ast.FunctionDef | ast.AsyncFunctionDef
23
+
24
+
25
+ def todo_item(
26
+ ctx: Ctx, code: str, node: ast.AST, construct: str, kind: str = "item"
27
+ ) -> ir.TodoItem:
28
+ """A TODO in item position: Rust has no todo!() there, so it is rendered as a line comment."""
29
+ return ir.TodoItem(
30
+ marker=ctx.col.todo(code, node, construct, kind=kind), span=ir.span_of(node, ctx.col.file)
31
+ )
32
+
33
+
34
+ def convention(ctx: Ctx, name: str, ty: RType, ana: Analysis) -> str:
35
+ """How a parameter is passed: "" by value, "&mut" when the body mutates it in place."""
36
+ if ctx.cfg.shared != "off":
37
+ return "" # objects are handles: the callee gets a clone of the handle, not a &mut
38
+ if name in ana.reassigned and name not in ana.method_mut:
39
+ return ""
40
+ if name in ana.method_mut and ty.name in ("Vec", MAP, SET):
41
+ return "&mut"
42
+ if name in ana.attr_mut and ctx.model_by_rust(ty.name) is not None:
43
+ return "&mut"
44
+ return ""
45
+
46
+
47
+ def build_sig(ctx: Ctx, mapper: TypeMapper, node: Func, ana: Analysis) -> FuncSig:
48
+ """The Rust signature; raises Unsupported (the function becomes a TODO) when an annotation is missing."""
49
+ a = node.args
50
+ positional = a.posonlyargs + a.args
51
+ defaults: list[ast.expr | None] = [None] * (len(positional) - len(a.defaults)) + list(
52
+ a.defaults
53
+ )
54
+ entries = [(p, d, "pos") for p, d in zip(positional, defaults, strict=False)]
55
+ entries += [(p, d, "kwonly") for p, d in zip(a.kwonlyargs, a.kw_defaults, strict=False)]
56
+ missing = [p.arg for p, _, _ in entries if p.annotation is None]
57
+ missing += [v.arg for v in (a.vararg, a.kwarg) if v is not None and v.annotation is None]
58
+ if missing or (node.returns is None and _returns_value(node)):
59
+ what = f"parameter {missing[0]}" if missing else "return type"
60
+ raise Unsupported("PY2RS006", f"missing annotation for {what} of {node.name}()", node)
61
+ params: list[ParamSig] = []
62
+ for p, default, kind in entries:
63
+ ty = mapper.map(p.annotation, f"{node.name}_{p.arg}")
64
+ conv = convention(ctx, p.arg, ty, ana)
65
+ params.append(
66
+ ParamSig(
67
+ p.arg, local_name(p.arg), ty, conv, default, kind, p.arg in ana.mutated and not conv
68
+ )
69
+ )
70
+ if isinstance(default, MUTABLE_DEFAULTS):
71
+ if p.arg in ana.method_mut or p.arg in ana.attr_mut: # Python shares it across calls
72
+ raise Unsupported(
73
+ "PY2RS033", f"mutable default {p.arg} is shared across calls and mutated", p
74
+ )
75
+ ctx.col.diag(
76
+ "PY2RS033",
77
+ p,
78
+ f"mutable default for {p.arg} is never mutated",
79
+ severity="info",
80
+ construct=p.arg,
81
+ )
82
+ for var, kind in ((a.vararg, "vararg"), (a.kwarg, "kwarg")):
83
+ if var is None:
84
+ continue
85
+ inner = mapper.map(var.annotation, f"{node.name}_{var.arg}")
86
+ ty = T("Vec", inner) if kind == "vararg" else T(MAP, STR, inner)
87
+ params.append(ParamSig(var.arg, local_name(var.arg), ty, "", None, kind))
88
+ ctx.col.diag(
89
+ "PY2RS015",
90
+ var,
91
+ f"{'*' if kind == 'vararg' else '**'}{var.arg} became {ty.rust()}",
92
+ construct=var.arg,
93
+ )
94
+ if any(d is not None for _, d, _ in entries):
95
+ ctx.col.diag(
96
+ "PY2RS016",
97
+ node,
98
+ f"{node.name}() has default arguments",
99
+ severity="info",
100
+ construct=node.name,
101
+ )
102
+ ret = mapper.map(node.returns, f"{node.name}_result") if node.returns is not None else UNIT
103
+ rust_name = fn_name(node.name)
104
+ if rust_name != node.name:
105
+ ctx.col.diag(
106
+ "PY2RS051",
107
+ node,
108
+ f"function {node.name} is named {rust_name} in Rust",
109
+ severity="info",
110
+ construct=node.name,
111
+ )
112
+ return FuncSig(
113
+ node.name, rust_name, params, ret, is_async=isinstance(node, ast.AsyncFunctionDef)
114
+ )
115
+
116
+
117
+ def _returns_value(node: Func) -> bool:
118
+ return any(
119
+ isinstance(n, ast.Return)
120
+ and n.value is not None
121
+ and not (isinstance(n.value, ast.Constant) and n.value.value is None)
122
+ for n in ast.walk(node)
123
+ )
124
+
125
+
126
+ def _is_generator(node: Func) -> ast.AST | None:
127
+ stack: list[ast.AST] = list(node.body)
128
+ while stack:
129
+ n = stack.pop()
130
+ if isinstance(n, (ast.Yield, ast.YieldFrom)):
131
+ return n
132
+ if not isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)):
133
+ stack.extend(ast.iter_child_nodes(n))
134
+ return None
135
+
136
+
137
+ def review_reason(ctx: Ctx, node: ast.AST) -> str | None:
138
+ text = ast.get_source_segment(ctx.col.source, node) or ""
139
+ for pattern in ctx.cfg.review_patterns:
140
+ try:
141
+ if re.search(pattern, text):
142
+ return f"matches review pattern {pattern}"
143
+ except re.error:
144
+ continue
145
+ return None
146
+
147
+
148
+ def docstring(body: list[ast.stmt]) -> tuple[list[str], list[ast.stmt]]:
149
+ first = body[0] if body else None
150
+ if (
151
+ isinstance(first, ast.Expr)
152
+ and isinstance(first.value, ast.Constant)
153
+ and isinstance(first.value.value, str)
154
+ ):
155
+ return [ln.rstrip() for ln in first.value.value.strip().splitlines()], body[1:]
156
+ return [], body
157
+
158
+
159
+ def lower_function(
160
+ ctx: Ctx, mapper: TypeMapper, node: Func, sig: FuncSig, ana: Analysis
161
+ ) -> list[ir.Item]:
162
+ first_todo = len(ctx.col.todos)
163
+ items: list[ir.Item] = []
164
+ # A decorator's effect is not translated: the TODO is the first statement of the body, so
165
+ # calling the function reaches it (deleting it accepts the undecorated behaviour).
166
+ decorators = [
167
+ ir.TodoS(ctx.col.todo("PY2RS014", d, f"decorator @{ast.unparse(d)}", kind="decorator"))
168
+ for d in node.decorator_list
169
+ ]
170
+ doc, body_nodes = docstring(node.body)
171
+ gen = _is_generator(node)
172
+ body: list[ir.RStmt]
173
+ if gen is not None:
174
+ body = [ir.TodoS(ctx.col.todo("PY2RS027", gen, f"generator {node.name}"))]
175
+ else:
176
+ body = _body_devirt(ctx, mapper, node, body_nodes, sig, ana)
177
+ body = [*decorators, *body]
178
+ params = [
179
+ ir.Param(p.rust, T("&mut", p.ty) if p.conv == "&mut" else p.ty, p.mutable)
180
+ for p in sig.params
181
+ ]
182
+ ret = T("Result", sig.ret, T("rt::PyError")) if sig.fallible else sig.ret
183
+ fn = ir.Function(
184
+ sig.rust, params, ret, body, doc, "pub ",
185
+ isinstance(node, ast.AsyncFunctionDef), span=ir.span_of(node, ctx.col.file),
186
+ ) # fmt: skip
187
+ ownership.apply(fn)
188
+ items.append(fn)
189
+ reason = review_reason(ctx, node)
190
+ if reason:
191
+ ctx.col.diag(
192
+ "PY2RS030", node, f"{node.name}: {reason}", severity="info", construct=node.name
193
+ )
194
+ for t in ctx.col.todos[first_todo:]:
195
+ t.review_reason = reason
196
+ return items
197
+
198
+
199
+ def _body_devirt(
200
+ ctx: Ctx,
201
+ mapper: TypeMapper,
202
+ node: Func,
203
+ body: list[ast.stmt],
204
+ sig: FuncSig,
205
+ ana: Analysis,
206
+ ) -> list[ir.RStmt]:
207
+ """Lower the body with the locals that need no handle as plain values; a local assigned
208
+ something that may be shared goes back to a handle and the body is lowered again."""
209
+ plain = (
210
+ find_plain(
211
+ node,
212
+ (ctx.sigs.keys() | ctx.imports.keys() | ctx.consts.keys() | ctx.models.keys()),
213
+ )
214
+ - ana.hoist
215
+ if ctx.cfg.shared != "off" and ctx.cfg.devirtualize
216
+ else set()
217
+ )
218
+ while True:
219
+ snap = ctx.col.snapshot()
220
+ try:
221
+ return _body(ctx, mapper, node, body, sig, ana, plain)
222
+ except NotFresh as retry:
223
+ ctx.col.restore(snap)
224
+ plain = plain - {retry.name}
225
+
226
+
227
+ def _body(
228
+ ctx: Ctx,
229
+ mapper: TypeMapper,
230
+ node: Func,
231
+ body: list[ast.stmt],
232
+ sig: FuncSig,
233
+ ana: Analysis,
234
+ plain: set[str],
235
+ ) -> list[ir.RStmt]:
236
+ lw = StmtLowerer(ctx, mapper, sig.ret)
237
+ lw.plain_py = plain
238
+ lw.mutated, lw.hoist, lw.leaky = ana.mutated, ana.hoist, ana.leaky_for
239
+ lw.container_mut = ana.method_mut | ana.attr_mut
240
+ lw.reassigned = ana.reassigned
241
+ lw.late_bound = ana.late_bound
242
+ lw.loop_inplace = set() if lw.shared else ana.loop_inplace
243
+ lw.alias_hazards = {} if lw.shared else find_hazards(node)
244
+ lw.fallible = sig.fallible
245
+ if sig.propagates: # a caller catches these: they are Results here even outside a try
246
+ lw.catch_stack.append(set(sig.propagates))
247
+ for p in sig.params:
248
+ lw.frames[0][p.name] = Var(p.rust, T("&mut", p.ty) if p.conv == "&mut" else p.ty)
249
+ stmts = lw.block(body, tail=True, after=body[0].lineno - 1 if body else node.lineno)
250
+ decls: list[ir.RStmt] = []
251
+ for py_name, var in lw.hoisted.items():
252
+ ty = var.ty if var.ty.name != "?" else None
253
+ init = None
254
+ if py_name in ana.hoist_default and var.ty.name in DEFAULTABLE:
255
+ init = ir.Call(func=ir.Path(path="Default::default"), ty=var.ty)
256
+ elif py_name in ana.hoist_default: # rustc cannot prove it is assigned on every path
257
+ what = f"{py_name} is assigned in a try block and read after a handler falls through"
258
+ init = ir.TodoX(marker=ctx.col.todo("PY2RS012", node, what))
259
+ decls.append(ir.Let(ir.PVar(var.rust, True), ty, init))
260
+ done: list[ir.RStmt] = []
261
+ if sig.ret == UNIT:
262
+ if sig.fallible: # falling off the end of a fallible function is `Ok(())`
263
+ ok_unit = ir.Call(func=ir.Path(path="Ok"), args=[ir.Lit(kind="unit")])
264
+ done.append(ir.Return(ok_unit, tail=True))
265
+ elif not (stmts and isinstance(stmts[-1], ir.Return)):
266
+ done.append(_fall_off_end(lw, sig, node))
267
+ return decls + stmts + done
268
+
269
+
270
+ def _fall_off_end(lw: StmtLowerer, sig: FuncSig, node: Func) -> ir.RStmt:
271
+ """Python returns None when a function body ends without `return`."""
272
+ if sig.ret.name == "Option":
273
+ none = ir.Lit(kind="none", ty=sig.ret)
274
+ return ir.Return(lw._ok(none) if sig.fallible else none, tail=True)
275
+ text = f"{node.name}: the body ended without a return"
276
+ return ir.ExprS(ir.Macro(name="unreachable", template=text))