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,259 @@
|
|
|
1
|
+
"""Ownership pass: insert `.clone()` / `.to_string()` wherever a place is moved out.
|
|
2
|
+
|
|
3
|
+
Lowering emits plain places (`xs`, `p.name`, `xs[i]`). This pass walks each function once and
|
|
4
|
+
decides, from the parent node, whether a use moves (MOVE) or only borrows (BORROW).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from ..ir import nodes as ir
|
|
10
|
+
from ..ir.rtypes import NOT_CLONED, SHARED, STR, is_copy, is_ref, peel
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _needs_clone(ty) -> bool:
|
|
14
|
+
if ty.name.startswith("impl "): # a closure parameter is passed on, never cloned
|
|
15
|
+
return False
|
|
16
|
+
return is_ref(ty) or not (is_copy(ty) or ty.name in NOT_CLONED)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _moved_value(e: ir.RExpr) -> ir.RExpr:
|
|
20
|
+
"""Wrap `e` (a place or const in a moving position) so that it yields an owned value."""
|
|
21
|
+
ty = peel(e.ty)
|
|
22
|
+
if isinstance(e, ir.Lit):
|
|
23
|
+
return ir.method(e, "to_string", ty=STR) if e.kind == "str" else e
|
|
24
|
+
if isinstance(e, ir.Path):
|
|
25
|
+
if not e.borrowed:
|
|
26
|
+
return e
|
|
27
|
+
name = {"String": "to_string", "Vec": "to_vec"}.get(ty.name, "clone")
|
|
28
|
+
return ir.method(e, name, ty=ty)
|
|
29
|
+
if isinstance(e, (ir.Var, ir.Attr, ir.Index, ir.Deref)) and _needs_clone(e.ty):
|
|
30
|
+
return ir.CloneX(operand=e, ty=ty, span=e.span)
|
|
31
|
+
return e
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
MUTATING = frozenset(
|
|
35
|
+
[
|
|
36
|
+
"push",
|
|
37
|
+
"push_back",
|
|
38
|
+
"push_front",
|
|
39
|
+
"insert",
|
|
40
|
+
"pop",
|
|
41
|
+
"remove",
|
|
42
|
+
"clear",
|
|
43
|
+
"sort",
|
|
44
|
+
"sort_by",
|
|
45
|
+
"sort_by_key",
|
|
46
|
+
"sort_unstable",
|
|
47
|
+
"reverse",
|
|
48
|
+
"truncate",
|
|
49
|
+
"push_str",
|
|
50
|
+
"insert_str",
|
|
51
|
+
"extend",
|
|
52
|
+
"extend_from_slice",
|
|
53
|
+
"drain",
|
|
54
|
+
"append",
|
|
55
|
+
"retain",
|
|
56
|
+
"retain_mut",
|
|
57
|
+
"swap",
|
|
58
|
+
"swap_remove",
|
|
59
|
+
"shift_remove",
|
|
60
|
+
"swap_remove_index",
|
|
61
|
+
"shift_insert",
|
|
62
|
+
"entry",
|
|
63
|
+
"get_mut",
|
|
64
|
+
"iter_mut",
|
|
65
|
+
"values_mut",
|
|
66
|
+
"last_mut",
|
|
67
|
+
"first_mut",
|
|
68
|
+
"dedup",
|
|
69
|
+
"rotate_left",
|
|
70
|
+
"rotate_right",
|
|
71
|
+
"split_off",
|
|
72
|
+
"resize",
|
|
73
|
+
"insert_full",
|
|
74
|
+
"pop_front",
|
|
75
|
+
"pop_back",
|
|
76
|
+
"or_insert",
|
|
77
|
+
"or_insert_with",
|
|
78
|
+
"or_default",
|
|
79
|
+
]
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def mark_mut(e: ir.RExpr) -> None:
|
|
84
|
+
"""`e` is changed in place: the handle borrow it reads through becomes `borrow_mut()`."""
|
|
85
|
+
if isinstance(e, ir.Borrow):
|
|
86
|
+
e.mut = True
|
|
87
|
+
elif isinstance(e, ir.Index | ir.Attr):
|
|
88
|
+
mark_mut(e.base)
|
|
89
|
+
elif isinstance(e, ir.Deref | ir.Ref | ir.CloneX):
|
|
90
|
+
mark_mut(e.operand)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _fresh(e: ir.RExpr) -> bool:
|
|
94
|
+
"""A value nobody else holds: moving it needs no handle clone."""
|
|
95
|
+
return isinstance(e, ir.Call | ir.Macro | ir.StructLit | ir.Method | ir.TupleX | ir.ArrayX)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _moved(e: ir.RExpr) -> ir.RExpr:
|
|
99
|
+
"""Wrap `e` (a place or const in a moving position) so that it yields an owned value."""
|
|
100
|
+
if isinstance(e, ir.Borrow): # moving a Python object moves a handle: a clone of the HANDLE
|
|
101
|
+
handle = e.operand
|
|
102
|
+
return handle if _fresh(handle) else ir.CloneX(operand=handle, ty=handle.ty, span=e.span)
|
|
103
|
+
return _moved_value(e)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def expr(e: ir.RExpr, move: bool) -> ir.RExpr:
|
|
107
|
+
match e:
|
|
108
|
+
case ir.Borrow():
|
|
109
|
+
e.operand = expr(e.operand, False)
|
|
110
|
+
return _moved(e) if move else e
|
|
111
|
+
case ir.Attr():
|
|
112
|
+
e.base = expr(e.base, False)
|
|
113
|
+
case ir.Index():
|
|
114
|
+
e.base, e.index = expr(e.base, False), expr(e.index, False)
|
|
115
|
+
case (
|
|
116
|
+
ir.Deref() | ir.Cast() | ir.Un() | ir.Ref() | ir.CloneX() | ir.Question() | ir.AwaitX()
|
|
117
|
+
):
|
|
118
|
+
e.operand = expr(e.operand, False)
|
|
119
|
+
if isinstance(e, ir.Ref) and e.mut:
|
|
120
|
+
mark_mut(e.operand)
|
|
121
|
+
if isinstance(e, ir.Ref) and isinstance(e.operand, ir.Borrow):
|
|
122
|
+
e.operand.deref = True # `&*h.borrow()`: a reference to the value, not to the guard
|
|
123
|
+
case ir.Template(): # templates are written for plain values: pass a copy of the value
|
|
124
|
+
e.args = [_value(expr(a, False)) for a in e.args]
|
|
125
|
+
case ir.Call():
|
|
126
|
+
e.func, e.args = expr(e.func, False), [expr(a, True) for a in e.args]
|
|
127
|
+
case ir.Method():
|
|
128
|
+
e.recv, e.args = expr(e.recv, False), [expr(a, True) for a in e.args]
|
|
129
|
+
if e.name in MUTATING:
|
|
130
|
+
mark_mut(e.recv)
|
|
131
|
+
if (
|
|
132
|
+
isinstance(e.recv, ir.Borrow)
|
|
133
|
+
and any(isinstance(n, ir.Borrow) for a in e.args for n in ir.walk(a))
|
|
134
|
+
): # `xs.borrow_mut().push(xs.borrow().len())` would panic: evaluate arguments first
|
|
135
|
+
return _args_first(e)
|
|
136
|
+
case ir.Macro():
|
|
137
|
+
by_move = e.name in ("vec", "vec_repeat", "json")
|
|
138
|
+
e.args = [
|
|
139
|
+
expr(a, by_move and not (e.name == "vec_repeat" and i == 1))
|
|
140
|
+
for i, a in enumerate(e.args)
|
|
141
|
+
]
|
|
142
|
+
case ir.Bin():
|
|
143
|
+
e.left, e.right = expr(e.left, False), expr(e.right, False)
|
|
144
|
+
for side in (e.left, e.right):
|
|
145
|
+
if isinstance(side, ir.Borrow):
|
|
146
|
+
side.deref = True # operators compare values, not guards
|
|
147
|
+
case ir.RangeX():
|
|
148
|
+
e.lo, e.hi = expr(e.lo, False), expr(e.hi, False)
|
|
149
|
+
case ir.Closure():
|
|
150
|
+
e.body = expr(e.body, True)
|
|
151
|
+
case ir.IfX():
|
|
152
|
+
e.cond, e.then, e.other = expr(e.cond, False), expr(e.then, True), expr(e.other, True)
|
|
153
|
+
case ir.BlockX():
|
|
154
|
+
block(e.stmts)
|
|
155
|
+
keep = isinstance(e.tail, ir.Var) and not is_ref(e.tail.ty) # the block's last use
|
|
156
|
+
e.tail = expr(e.tail, not keep) if e.tail is not None else None
|
|
157
|
+
case ir.TupleX() | ir.ArrayX():
|
|
158
|
+
e.elems = [expr(x, True) for x in e.elems]
|
|
159
|
+
case ir.StructLit():
|
|
160
|
+
e.fields = [(n, expr(v, True)) for n, v in e.fields]
|
|
161
|
+
if e.base is not None:
|
|
162
|
+
e.base = expr(e.base, False)
|
|
163
|
+
return _moved(e) if move else e
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _value(e: ir.RExpr) -> ir.RExpr:
|
|
167
|
+
"""The value of a handle expression (a shallow copy), for code that takes plain values."""
|
|
168
|
+
if isinstance(e, ir.Borrow):
|
|
169
|
+
return ir.CloneX(operand=e, ty=e.ty, span=e.span)
|
|
170
|
+
return _moved(e)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _args_first(call: ir.Method) -> ir.RExpr:
|
|
174
|
+
"""`{ let a0 = arg0; ..; recv.method(a0, ..) }`: the arguments borrow before the receiver does."""
|
|
175
|
+
stmts: list[ir.RStmt] = []
|
|
176
|
+
names: list[ir.RExpr] = []
|
|
177
|
+
for i, a in enumerate(call.args):
|
|
178
|
+
name = f"arg_{i}"
|
|
179
|
+
stmts.append(ir.Let(ir.PVar(name), None, a))
|
|
180
|
+
names.append(ir.Var(name=name, ty=a.ty))
|
|
181
|
+
call.args = names
|
|
182
|
+
return ir.BlockX(stmts=stmts, tail=call, ty=call.ty, span=call.span)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _opt(e: ir.RExpr | None, move: bool) -> ir.RExpr | None:
|
|
186
|
+
return expr(e, move) if e is not None else None
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _has_borrow(e: ir.RExpr) -> bool:
|
|
190
|
+
return any(isinstance(n, ir.Borrow) for n in ir.walk(e))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def block(stmts: list[ir.RStmt]) -> None:
|
|
194
|
+
out: list[ir.RStmt] = []
|
|
195
|
+
for s in stmts:
|
|
196
|
+
out.append(s)
|
|
197
|
+
_statement(s, out)
|
|
198
|
+
stmts[:] = out
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _statement(s: ir.RStmt, out: list[ir.RStmt]) -> None:
|
|
202
|
+
match s:
|
|
203
|
+
case ir.Let():
|
|
204
|
+
s.init = _opt(s.init, True)
|
|
205
|
+
case ir.Assign():
|
|
206
|
+
s.lhs, s.rhs = expr(s.lhs, False), expr(s.rhs, True)
|
|
207
|
+
mark_mut(s.lhs)
|
|
208
|
+
lhs = s.lhs
|
|
209
|
+
if _has_borrow(s.rhs) and (
|
|
210
|
+
_has_borrow(lhs)
|
|
211
|
+
or (
|
|
212
|
+
isinstance(lhs, ir.Var)
|
|
213
|
+
and lhs.ty.name == SHARED
|
|
214
|
+
and any(isinstance(n, ir.Var) and n.name == lhs.name for n in ir.walk(s.rhs))
|
|
215
|
+
)
|
|
216
|
+
):
|
|
217
|
+
# Finish RHS reads before acquiring a mutable guard or replacing the handle.
|
|
218
|
+
out.insert(len(out) - 1, ir.Let(ir.PVar("rhs"), None, s.rhs))
|
|
219
|
+
s.rhs = ir.Var(name="rhs", ty=s.rhs.ty)
|
|
220
|
+
case ir.ExprS():
|
|
221
|
+
s.expr = expr(s.expr, False)
|
|
222
|
+
case ir.Break():
|
|
223
|
+
s.value = _opt(s.value, True)
|
|
224
|
+
case ir.Return() if (
|
|
225
|
+
isinstance(s.value, ir.Call)
|
|
226
|
+
and isinstance(s.value.func, ir.Path)
|
|
227
|
+
and s.value.func.path == "rt::Shared::new"
|
|
228
|
+
and isinstance(s.value.args[0], ir.Var)
|
|
229
|
+
):
|
|
230
|
+
pass # `return plain_local`: the local is moved into its handle, nothing to clone
|
|
231
|
+
case ir.Return():
|
|
232
|
+
keep = isinstance(s.value, ir.Var) and not is_ref(
|
|
233
|
+
s.value.ty
|
|
234
|
+
) # the function ends: a move is fine
|
|
235
|
+
handle_local = isinstance(s.value, ir.Borrow) and isinstance(s.value.operand, ir.Var)
|
|
236
|
+
s.value = _opt(s.value, not keep)
|
|
237
|
+
if handle_local and isinstance(s.value, ir.CloneX):
|
|
238
|
+
s.value = s.value.operand # the local dies with the function: move the handle
|
|
239
|
+
case ir.IfS():
|
|
240
|
+
s.cond = expr(s.cond, False)
|
|
241
|
+
block(s.then)
|
|
242
|
+
block(s.other or [])
|
|
243
|
+
case ir.WhileS():
|
|
244
|
+
s.cond = expr(s.cond, False)
|
|
245
|
+
block(s.body)
|
|
246
|
+
case ir.LoopS():
|
|
247
|
+
block(s.body)
|
|
248
|
+
case ir.ForS():
|
|
249
|
+
s.iter = expr(s.iter, True)
|
|
250
|
+
block(s.body)
|
|
251
|
+
case ir.MatchS():
|
|
252
|
+
s.subject = expr(s.subject, False)
|
|
253
|
+
for arm in s.arms:
|
|
254
|
+
arm.guard = _opt(arm.guard, False)
|
|
255
|
+
block(arm.body)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def apply(fn: ir.Function) -> None:
|
|
259
|
+
block(fn.body)
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""Exception kinds and the raise-set analysis (which exceptions can escape which function).
|
|
2
|
+
|
|
3
|
+
A function is *fallible* (returns `Result<T, rt::PyError>`) when an exception can escape it: an
|
|
4
|
+
explicit `raise` that no enclosing `except` catches, or a call to a fallible function of the same
|
|
5
|
+
module (fixpoint over the call graph). Python's built-in operation errors (`xs[i]`, `d[k]`, `int(s)`,
|
|
6
|
+
division) are Results only inside a `try` that catches them, and panics elsewhere (drift PY2RS045):
|
|
7
|
+
making every index a Result would make nearly every function fallible. Unknown callees are not
|
|
8
|
+
followed (a call to an unknown function is already a TODO).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import ast
|
|
14
|
+
from collections.abc import Mapping
|
|
15
|
+
|
|
16
|
+
from ..frontend.names import const_name
|
|
17
|
+
from ..ir.types import dotted
|
|
18
|
+
from ..lower.context import Ctx
|
|
19
|
+
|
|
20
|
+
BUILTIN_PARENTS: dict[str, str | None] = {
|
|
21
|
+
"BaseException": None,
|
|
22
|
+
"Exception": "BaseException",
|
|
23
|
+
"ArithmeticError": "Exception",
|
|
24
|
+
"ZeroDivisionError": "ArithmeticError",
|
|
25
|
+
"OverflowError": "ArithmeticError",
|
|
26
|
+
"LookupError": "Exception",
|
|
27
|
+
"IndexError": "LookupError",
|
|
28
|
+
"KeyError": "LookupError",
|
|
29
|
+
"ValueError": "Exception",
|
|
30
|
+
"JSONDecodeError": "ValueError",
|
|
31
|
+
"ValidationError": "ValueError",
|
|
32
|
+
"error": "Exception",
|
|
33
|
+
"TypeError": "Exception",
|
|
34
|
+
"AttributeError": "Exception",
|
|
35
|
+
"AssertionError": "Exception",
|
|
36
|
+
"RuntimeError": "Exception",
|
|
37
|
+
"NotImplementedError": "RuntimeError",
|
|
38
|
+
"OSError": "Exception",
|
|
39
|
+
"FileNotFoundError": "OSError",
|
|
40
|
+
"TimeoutError": "OSError",
|
|
41
|
+
"StopIteration": "Exception",
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
RUST_KIND_NAMES = {"error": "RE_ERROR"} # re.error is spelled RE_ERROR in python2rust-rt
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def parents(ctx: Ctx) -> dict[str, str | None]:
|
|
49
|
+
return {**BUILTIN_PARENTS, **ctx.exceptions}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def is_a(kind: str, ancestor: str, table: dict[str, str | None]) -> bool:
|
|
53
|
+
seen: set[str] = set()
|
|
54
|
+
cur: str | None = kind
|
|
55
|
+
while cur is not None and cur not in seen:
|
|
56
|
+
if cur == ancestor:
|
|
57
|
+
return True
|
|
58
|
+
seen.add(cur)
|
|
59
|
+
cur = table.get(cur)
|
|
60
|
+
return False
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def kind_ref(ctx: Ctx, name: str) -> str | None:
|
|
64
|
+
"""The Rust path of the static `ExcKind` for a Python exception class (None if unknown)."""
|
|
65
|
+
mapped = ctx.cfg.exception_map.get(name)
|
|
66
|
+
if mapped:
|
|
67
|
+
return mapped
|
|
68
|
+
if name in BUILTIN_PARENTS:
|
|
69
|
+
return f"rt::kinds::{RUST_KIND_NAMES.get(name) or const_name(name)}"
|
|
70
|
+
return const_name(name) if name in ctx.exceptions else None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def class_name(node: ast.expr | None) -> str | None:
|
|
74
|
+
"""`ValueError`, `errors.MyError` -> the last component; calls give their callee's name."""
|
|
75
|
+
if isinstance(node, ast.Call):
|
|
76
|
+
node = node.func
|
|
77
|
+
return dotted(node).split(".")[-1] if node is not None else None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def handler_kinds(h: ast.ExceptHandler) -> list[str] | None:
|
|
81
|
+
"""The class names an `except` clause catches (None for a bare `except:`)."""
|
|
82
|
+
if h.type is None:
|
|
83
|
+
return None
|
|
84
|
+
nodes = h.type.elts if isinstance(h.type, ast.Tuple) else [h.type]
|
|
85
|
+
return [n for n in (class_name(x) for x in nodes) if n]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class _Escapes:
|
|
89
|
+
def __init__(self, ctx: Ctx, esc: dict[str, set[str]]) -> None:
|
|
90
|
+
self.ctx = ctx
|
|
91
|
+
self.table = parents(ctx)
|
|
92
|
+
self.esc = esc
|
|
93
|
+
|
|
94
|
+
def visit(self, node: ast.AST, caught: list[set[str]], handler: set[str] | None) -> set[str]:
|
|
95
|
+
out: set[str] = set()
|
|
96
|
+
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda | ast.ClassDef):
|
|
97
|
+
return out
|
|
98
|
+
if isinstance(node, ast.Try | ast.TryStar):
|
|
99
|
+
guarded: set[str] = set()
|
|
100
|
+
for h in node.handlers:
|
|
101
|
+
kinds = handler_kinds(h)
|
|
102
|
+
guarded |= set(kinds) if kinds is not None else {"BaseException"}
|
|
103
|
+
for st in node.body:
|
|
104
|
+
out |= self.visit(st, [*caught, guarded], handler)
|
|
105
|
+
for h in node.handlers:
|
|
106
|
+
held = set(handler_kinds(h) or ["BaseException"])
|
|
107
|
+
for st in h.body:
|
|
108
|
+
out |= self.visit(st, caught, held)
|
|
109
|
+
for st in [*node.orelse, *node.finalbody]:
|
|
110
|
+
out |= self.visit(st, caught, handler)
|
|
111
|
+
return out
|
|
112
|
+
if isinstance(node, ast.Raise):
|
|
113
|
+
kind = class_name(node.exc) if node.exc is not None else None
|
|
114
|
+
if node.exc is None or kind not in self.table:
|
|
115
|
+
kinds = handler if handler else {"Exception"}
|
|
116
|
+
else:
|
|
117
|
+
kinds = {kind}
|
|
118
|
+
out |= self._filter(kinds, caught)
|
|
119
|
+
elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
|
|
120
|
+
name = node.func.id
|
|
121
|
+
if name in self.esc:
|
|
122
|
+
out |= self._filter(self.esc[name], caught)
|
|
123
|
+
elif name in self.ctx.sigs: # imported from another module of the project
|
|
124
|
+
out |= self._filter(set(self.ctx.sigs[name].raises), caught)
|
|
125
|
+
for child in ast.iter_child_nodes(node):
|
|
126
|
+
out |= self.visit(child, caught, handler)
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
def _filter(self, kinds: set[str], caught: list[set[str]]) -> set[str]:
|
|
130
|
+
return {k for k in kinds if not any(is_a(k, c, self.table) for cs in caught for c in cs)}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
TEST_RAISES = {"raises", "assertRaises", "assertRaisesRegex"}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def collect_catchable(tree: ast.AST) -> set[str]:
|
|
137
|
+
"""Exception class names that some `except` clause or `pytest.raises(...)` of `tree` names."""
|
|
138
|
+
out: set[str] = set()
|
|
139
|
+
for node in ast.walk(tree):
|
|
140
|
+
if isinstance(node, ast.ExceptHandler):
|
|
141
|
+
out |= set(handler_kinds(node) or ["BaseException"])
|
|
142
|
+
elif isinstance(node, ast.Call) and dotted(node.func).split(".")[-1] in TEST_RAISES:
|
|
143
|
+
for a in node.args[:1]:
|
|
144
|
+
out |= {
|
|
145
|
+
n
|
|
146
|
+
for n in (class_name(x) for x in (a.elts if isinstance(a, ast.Tuple) else [a]))
|
|
147
|
+
if n
|
|
148
|
+
}
|
|
149
|
+
return out
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class _Sites:
|
|
153
|
+
"""Where a function can raise a built-in error, and which local functions it calls."""
|
|
154
|
+
|
|
155
|
+
def __init__(self, ctx: Ctx, funcs: Mapping[str, ast.AST]) -> None:
|
|
156
|
+
self.ctx, self.funcs = ctx, funcs
|
|
157
|
+
self.table = parents(ctx)
|
|
158
|
+
self.raising: list[tuple[str, tuple[frozenset[str], ...]]] = [] # (kind, caught)
|
|
159
|
+
self.calls: list[tuple[str, tuple[frozenset[str], ...]]] = []
|
|
160
|
+
|
|
161
|
+
def run(self, fn: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
|
|
162
|
+
for st in fn.body:
|
|
163
|
+
self.visit(st, ())
|
|
164
|
+
|
|
165
|
+
def add(self, kinds: tuple[str, ...], caught: tuple[frozenset[str], ...]) -> None:
|
|
166
|
+
self.raising += [(k, caught) for k in kinds]
|
|
167
|
+
|
|
168
|
+
def visit(self, node: ast.AST, caught: tuple[frozenset[str], ...]) -> None:
|
|
169
|
+
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda | ast.ClassDef):
|
|
170
|
+
return
|
|
171
|
+
if isinstance(node, ast.Try | ast.TryStar):
|
|
172
|
+
guarded: set[str] = set()
|
|
173
|
+
for h in node.handlers:
|
|
174
|
+
kinds = handler_kinds(h)
|
|
175
|
+
guarded |= set(kinds) if kinds is not None else {"BaseException"}
|
|
176
|
+
for st in node.body:
|
|
177
|
+
self.visit(st, (*caught, frozenset(guarded)))
|
|
178
|
+
for st in [*(s for h in node.handlers for s in h.body), *node.orelse, *node.finalbody]:
|
|
179
|
+
self.visit(st, caught)
|
|
180
|
+
return
|
|
181
|
+
match node:
|
|
182
|
+
case ast.Subscript(ctx=ast.Load(), slice=sl) if not isinstance(sl, ast.Slice):
|
|
183
|
+
self.add(("KeyError", "IndexError"), caught)
|
|
184
|
+
case ast.Subscript(ctx=ast.Store(), slice=sl) if not isinstance(sl, ast.Slice):
|
|
185
|
+
self.add(("IndexError",), caught)
|
|
186
|
+
case ast.BinOp(op=ast.FloorDiv() | ast.Mod() | ast.Div(), right=r) if not (
|
|
187
|
+
isinstance(r, ast.Constant) and isinstance(r.value, int | float) and r.value
|
|
188
|
+
):
|
|
189
|
+
self.add(("ZeroDivisionError",), caught)
|
|
190
|
+
case ast.Call(func=ast.Name(id=("int" | "float")), args=[first, *_]) if not isinstance(
|
|
191
|
+
first, ast.Constant
|
|
192
|
+
):
|
|
193
|
+
self.add(("ValueError",), caught)
|
|
194
|
+
case ast.Call(func=ast.Attribute(attr=("model_validate" | "model_validate_json"))):
|
|
195
|
+
self.add(("ValidationError",), caught)
|
|
196
|
+
case ast.Call(func=f):
|
|
197
|
+
name = dotted(f)
|
|
198
|
+
entry = self.ctx.library_entry(name)
|
|
199
|
+
if entry and entry.get("raises"):
|
|
200
|
+
self.add((entry["raises"],), caught)
|
|
201
|
+
if isinstance(f, ast.Name) and (f.id in self.funcs or f.id in self.ctx.sigs):
|
|
202
|
+
self.calls.append((f.id, caught))
|
|
203
|
+
for child in ast.iter_child_nodes(node):
|
|
204
|
+
self.visit(child, caught)
|
|
205
|
+
|
|
206
|
+
def uncaught(self, kind: str, caught: tuple[frozenset[str], ...]) -> bool:
|
|
207
|
+
return not any(is_a(kind, c, self.table) for cs in caught for c in cs)
|
|
208
|
+
|
|
209
|
+
def wanted(self, kind: str, caught: tuple[frozenset[str], ...], want: set[str]) -> bool:
|
|
210
|
+
"""Does a try in `caught`, or a caller that wants `want`, need `kind` as an exception?"""
|
|
211
|
+
if any(is_a(kind, c, self.table) for cs in caught for c in cs):
|
|
212
|
+
return True # caught here, so a Result is needed up to that try
|
|
213
|
+
return self.uncaught(kind, caught) and any(is_a(kind, w, self.table) for w in want)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def analyze_raises(
|
|
217
|
+
tree: ast.Module, ctx: Ctx, seeds: set[str] | None = None
|
|
218
|
+
) -> tuple[dict[str, set[str]], dict[str, set[str]]]:
|
|
219
|
+
"""(escapes, propagates) per top-level function.
|
|
220
|
+
|
|
221
|
+
`escapes`: exception class names that can escape a function (explicit raises and the built-in
|
|
222
|
+
errors some caller catches); a non-empty set makes it return `Result<_, PyError>`.
|
|
223
|
+
`propagates`: the built-in error classes the function must report as a Result because a try in
|
|
224
|
+
some caller catches them, or because of `seeds` (the classes caught elsewhere in the project),
|
|
225
|
+
or every class under config `builtin_errors = "always"`.
|
|
226
|
+
"""
|
|
227
|
+
funcs = {n.name: n for n in tree.body if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef)}
|
|
228
|
+
esc: dict[str, set[str]] = {name: set() for name in funcs}
|
|
229
|
+
walker = _Escapes(ctx, esc)
|
|
230
|
+
for _ in range(len(funcs) + 2):
|
|
231
|
+
changed = False
|
|
232
|
+
for name, fn in funcs.items():
|
|
233
|
+
found: set[str] = set()
|
|
234
|
+
for st in fn.body:
|
|
235
|
+
found |= walker.visit(st, [], None)
|
|
236
|
+
if found != esc[name]:
|
|
237
|
+
esc[name], changed = found, True
|
|
238
|
+
if not changed:
|
|
239
|
+
break
|
|
240
|
+
sites: dict[str, _Sites] = {}
|
|
241
|
+
for name, fn in funcs.items():
|
|
242
|
+
sites[name] = _Sites(ctx, funcs)
|
|
243
|
+
sites[name].run(fn)
|
|
244
|
+
table = parents(ctx)
|
|
245
|
+
outside = (seeds or set()) | (
|
|
246
|
+
set(BUILTIN_PARENTS) if ctx.cfg.builtin_errors == "always" else set()
|
|
247
|
+
)
|
|
248
|
+
may: dict[str, set[str]] = {name: set() for name in funcs} # built-in errors that can escape
|
|
249
|
+
need: dict[str, set[str]] = {name: set() for name in funcs}
|
|
250
|
+
for _ in range(2 * len(funcs) + 4):
|
|
251
|
+
changed = False
|
|
252
|
+
for name, st in sites.items():
|
|
253
|
+
may_now = {k for k, caught in st.raising if st.uncaught(k, caught)}
|
|
254
|
+
for callee, caught in st.calls:
|
|
255
|
+
known = may.get(callee, set())
|
|
256
|
+
may_now |= {k for k in known if st.uncaught(k, caught)}
|
|
257
|
+
want_here = need[name] | {k for k in may_now if any(is_a(k, o, table) for o in outside)}
|
|
258
|
+
for callee, caught in st.calls:
|
|
259
|
+
if callee not in funcs:
|
|
260
|
+
continue
|
|
261
|
+
mine = may.get(callee, set())
|
|
262
|
+
wanted = {k for k in mine if st.wanted(k, caught, want_here)}
|
|
263
|
+
if not wanted <= need[callee]:
|
|
264
|
+
need[callee] |= wanted
|
|
265
|
+
changed = True
|
|
266
|
+
if may_now != may[name]:
|
|
267
|
+
may[name], changed = may_now, True
|
|
268
|
+
if not changed:
|
|
269
|
+
break
|
|
270
|
+
propagates: dict[str, set[str]] = {}
|
|
271
|
+
for name in funcs:
|
|
272
|
+
direct = {k for k in may[name] if any(is_a(k, o, table) for o in outside)}
|
|
273
|
+
propagates[name] = (need[name] | direct) & may[name] if may[name] else set()
|
|
274
|
+
esc[name] = esc[name] | propagates[name]
|
|
275
|
+
return esc, propagates
|