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,207 @@
|
|
|
1
|
+
"""Pre-pass over a function body: which names are mutated, hoisted, or leak from loops."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
from collections import Counter, defaultdict
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
|
|
9
|
+
MUTATING_METHODS = frozenset(
|
|
10
|
+
[
|
|
11
|
+
"append",
|
|
12
|
+
"extend",
|
|
13
|
+
"insert",
|
|
14
|
+
"pop",
|
|
15
|
+
"remove",
|
|
16
|
+
"clear",
|
|
17
|
+
"sort",
|
|
18
|
+
"reverse",
|
|
19
|
+
"update",
|
|
20
|
+
"setdefault",
|
|
21
|
+
"add",
|
|
22
|
+
"discard",
|
|
23
|
+
"popitem",
|
|
24
|
+
]
|
|
25
|
+
)
|
|
26
|
+
Path = tuple[int, ...]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Analysis:
|
|
31
|
+
mutated: set[str] = field(default_factory=set) # needs `let mut` (or a by-value `mut` param)
|
|
32
|
+
reassigned: set[str] = field(default_factory=set) # rebound after the initial binding
|
|
33
|
+
method_mut: set[str] = field(default_factory=set) # mutated in place (methods, subscripts)
|
|
34
|
+
attr_mut: set[str] = field(default_factory=set) # attribute assigned
|
|
35
|
+
hoist: set[str] = field(default_factory=set) # first bound in a nested block, used outside
|
|
36
|
+
leaky_for: set[str] = field(default_factory=set) # for-loop target read after the loop
|
|
37
|
+
late_bound: set[str] = field(default_factory=set) # loop targets and reassigned names
|
|
38
|
+
loop_inplace: set[str] = field(default_factory=set) # loop targets changed in place
|
|
39
|
+
hoist_default: set[str] = field(
|
|
40
|
+
default_factory=set
|
|
41
|
+
) # hoisted out of a try: needs an initial value
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _root(node: ast.expr) -> str | None:
|
|
45
|
+
while isinstance(node, (ast.Subscript, ast.Attribute)):
|
|
46
|
+
node = node.value
|
|
47
|
+
return node.id if isinstance(node, ast.Name) else None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class _Walker:
|
|
51
|
+
def __init__(self, params: set[str]) -> None:
|
|
52
|
+
self.params = params
|
|
53
|
+
self.stores: Counter[str] = Counter()
|
|
54
|
+
self.first: dict[str, Path] = {}
|
|
55
|
+
self.uses: defaultdict[str, list[Path]] = defaultdict(list)
|
|
56
|
+
self.out = Analysis()
|
|
57
|
+
self.for_targets: set[str] = set()
|
|
58
|
+
self._next = 0
|
|
59
|
+
self.try_ids: set[int] = set()
|
|
60
|
+
self.prebound: set[str] = set() # for targets that were bound before their loop
|
|
61
|
+
self.loop_roots: list[tuple[set[str], str | None]] = [] # (loop targets, list iterated)
|
|
62
|
+
|
|
63
|
+
def sub(self, path: Path) -> Path:
|
|
64
|
+
self._next += 1
|
|
65
|
+
return (*path, self._next)
|
|
66
|
+
|
|
67
|
+
def try_block(self, path: Path) -> Path:
|
|
68
|
+
inner = self.sub(path)
|
|
69
|
+
self.try_ids.add(inner[-1])
|
|
70
|
+
return inner
|
|
71
|
+
|
|
72
|
+
def store(self, name: str, path: Path) -> None:
|
|
73
|
+
self.stores[name] += 1
|
|
74
|
+
self.first.setdefault(name, path)
|
|
75
|
+
self.uses[name].append(path)
|
|
76
|
+
|
|
77
|
+
def target(self, node: ast.expr, path: Path) -> None:
|
|
78
|
+
if isinstance(node, ast.Name):
|
|
79
|
+
self.store(node.id, path)
|
|
80
|
+
elif isinstance(node, (ast.Tuple, ast.List)):
|
|
81
|
+
for e in node.elts:
|
|
82
|
+
self.target(e, path)
|
|
83
|
+
elif isinstance(node, ast.Starred):
|
|
84
|
+
self.target(node.value, path)
|
|
85
|
+
else:
|
|
86
|
+
root = _root(node)
|
|
87
|
+
if root:
|
|
88
|
+
(self.out.method_mut if isinstance(node, ast.Subscript) else self.out.attr_mut).add(
|
|
89
|
+
root
|
|
90
|
+
)
|
|
91
|
+
self.uses[root].append(path)
|
|
92
|
+
self.expr(node, path)
|
|
93
|
+
|
|
94
|
+
def expr(self, node: ast.AST | None, path: Path) -> None:
|
|
95
|
+
for n in ast.walk(node) if node is not None else ():
|
|
96
|
+
if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load):
|
|
97
|
+
self.uses[n.id].append(path)
|
|
98
|
+
elif isinstance(n, ast.NamedExpr):
|
|
99
|
+
self.store(n.target.id, path)
|
|
100
|
+
elif (
|
|
101
|
+
isinstance(n, ast.Call)
|
|
102
|
+
and isinstance(n.func, ast.Attribute)
|
|
103
|
+
and n.func.attr in MUTATING_METHODS
|
|
104
|
+
and (root := _root(n.func.value))
|
|
105
|
+
):
|
|
106
|
+
self.out.method_mut.add(root)
|
|
107
|
+
|
|
108
|
+
def block(self, stmts: list[ast.stmt], path: Path) -> None:
|
|
109
|
+
for s in stmts:
|
|
110
|
+
self.stmt(s, path)
|
|
111
|
+
|
|
112
|
+
def stmt(self, s: ast.stmt, path: Path) -> None:
|
|
113
|
+
match s:
|
|
114
|
+
case ast.If() | ast.While():
|
|
115
|
+
self.expr(s.test, path)
|
|
116
|
+
self.block(s.body, self.sub(path))
|
|
117
|
+
self.block(s.orelse, self.sub(path))
|
|
118
|
+
case ast.For() | ast.AsyncFor():
|
|
119
|
+
self.expr(s.iter, path)
|
|
120
|
+
inner = self.sub(path)
|
|
121
|
+
bound = {n.id for n in ast.walk(s.target) if isinstance(n, ast.Name)}
|
|
122
|
+
for name in bound & (set(self.stores) | self.params): # the loop re-assigns it
|
|
123
|
+
self.out.reassigned.add(name)
|
|
124
|
+
self.prebound.add(name)
|
|
125
|
+
self.target(s.target, inner)
|
|
126
|
+
src = (
|
|
127
|
+
s.iter.func.value
|
|
128
|
+
if isinstance(s.iter, ast.Call) and isinstance(s.iter.func, ast.Attribute)
|
|
129
|
+
else s.iter
|
|
130
|
+
)
|
|
131
|
+
self.loop_roots.append((bound, _root(src)))
|
|
132
|
+
self.for_targets |= {n.id for n in ast.walk(s.target) if isinstance(n, ast.Name)}
|
|
133
|
+
self.block(s.body, inner)
|
|
134
|
+
self.block(s.orelse, self.sub(path))
|
|
135
|
+
case ast.Assign():
|
|
136
|
+
self.expr(s.value, path)
|
|
137
|
+
for t in s.targets:
|
|
138
|
+
self.target(t, path)
|
|
139
|
+
case ast.AnnAssign():
|
|
140
|
+
self.expr(s.value, path)
|
|
141
|
+
if s.value is not None:
|
|
142
|
+
self.target(s.target, path)
|
|
143
|
+
case ast.AugAssign():
|
|
144
|
+
self.expr(s.value, path)
|
|
145
|
+
self.expr(s.target, path)
|
|
146
|
+
self.target(s.target, path)
|
|
147
|
+
if isinstance(s.target, ast.Name):
|
|
148
|
+
self.out.reassigned.add(s.target.id)
|
|
149
|
+
case ast.Match():
|
|
150
|
+
self.expr(s.subject, path)
|
|
151
|
+
for case in s.cases:
|
|
152
|
+
inner = self.sub(path)
|
|
153
|
+
for n in ast.walk(case.pattern):
|
|
154
|
+
for name in (getattr(n, "name", None), getattr(n, "rest", None)):
|
|
155
|
+
if isinstance(name, str):
|
|
156
|
+
self.store(name, inner)
|
|
157
|
+
self.expr(case.guard, inner)
|
|
158
|
+
self.block(case.body, inner)
|
|
159
|
+
case ast.Try() | ast.TryStar():
|
|
160
|
+
self.block(s.body, self.try_block(path))
|
|
161
|
+
for h in s.handlers:
|
|
162
|
+
inner = self.try_block(path)
|
|
163
|
+
if h.name:
|
|
164
|
+
self.store(h.name, inner)
|
|
165
|
+
self.expr(h.type, inner)
|
|
166
|
+
self.block(h.body, inner)
|
|
167
|
+
self.block(s.orelse, self.try_block(path))
|
|
168
|
+
self.block(s.finalbody, self.try_block(path))
|
|
169
|
+
case ast.With() | ast.AsyncWith():
|
|
170
|
+
for item in s.items:
|
|
171
|
+
self.expr(item.context_expr, path)
|
|
172
|
+
self.block(s.body, self.sub(path))
|
|
173
|
+
case ast.Delete():
|
|
174
|
+
for t in s.targets:
|
|
175
|
+
self.target(t, path)
|
|
176
|
+
case ast.FunctionDef() | ast.AsyncFunctionDef() | ast.ClassDef():
|
|
177
|
+
pass
|
|
178
|
+
case _:
|
|
179
|
+
self.expr(s, path)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def analyze(fn: ast.FunctionDef | ast.AsyncFunctionDef, params: set[str]) -> Analysis:
|
|
183
|
+
w = _Walker(params)
|
|
184
|
+
w.block(fn.body, ())
|
|
185
|
+
out = w.out
|
|
186
|
+
for name, count in w.stores.items():
|
|
187
|
+
if count >= (1 if name in params else 2):
|
|
188
|
+
out.reassigned.add(name)
|
|
189
|
+
first = w.first[name]
|
|
190
|
+
outside = any(u[: len(first)] != first for u in w.uses[name])
|
|
191
|
+
if name in params or not outside:
|
|
192
|
+
continue
|
|
193
|
+
leaks = name in w.for_targets and name not in w.prebound
|
|
194
|
+
(out.leaky_for if leaks else out.hoist).add(name)
|
|
195
|
+
if name not in w.for_targets and any(p in w.try_ids for p in first):
|
|
196
|
+
out.hoist_default.add(name) # rustc cannot see that a break skips the assignment
|
|
197
|
+
changed = True
|
|
198
|
+
while changed: # `for a in xs: a.n = 1` changes the elements of xs
|
|
199
|
+
changed = False
|
|
200
|
+
for targets, root in w.loop_roots:
|
|
201
|
+
if root and root not in out.method_mut and targets & (out.method_mut | out.attr_mut):
|
|
202
|
+
out.method_mut.add(root)
|
|
203
|
+
changed = True
|
|
204
|
+
out.mutated = out.reassigned | out.method_mut | out.attr_mut
|
|
205
|
+
out.late_bound = out.reassigned | w.for_targets
|
|
206
|
+
out.loop_inplace = w.for_targets & (out.method_mut | out.attr_mut)
|
|
207
|
+
return out
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""Devirtualisation: which locals can be plain owned values instead of `Shared` handles.
|
|
2
|
+
|
|
3
|
+
Handles make Python's reference semantics true by construction. A local list, dict, set or
|
|
4
|
+
instance that nobody else can ever hold does not need one: it is assigned once, and every use is
|
|
5
|
+
a read or an in-place change through the name itself (never stored, passed to a function that
|
|
6
|
+
could keep it, aliased, captured, or iterated while it changes). Such a local lowers to a plain
|
|
7
|
+
`Vec<T>` / `IndexMap` / struct, as before handles existed. Whenever the analysis is unsure the
|
|
8
|
+
local keeps its handle, so the result is only ever an optimisation.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import ast
|
|
14
|
+
|
|
15
|
+
from .analysis import MUTATING_METHODS
|
|
16
|
+
|
|
17
|
+
# methods whose arguments are only read and whose result never aliases the receiver
|
|
18
|
+
READING = (
|
|
19
|
+
frozenset(
|
|
20
|
+
[
|
|
21
|
+
"append",
|
|
22
|
+
"pop",
|
|
23
|
+
"extend",
|
|
24
|
+
"insert",
|
|
25
|
+
"remove",
|
|
26
|
+
"clear",
|
|
27
|
+
"sort",
|
|
28
|
+
"reverse",
|
|
29
|
+
"count",
|
|
30
|
+
"index",
|
|
31
|
+
"copy",
|
|
32
|
+
"get",
|
|
33
|
+
"keys",
|
|
34
|
+
"values",
|
|
35
|
+
"items",
|
|
36
|
+
"add",
|
|
37
|
+
"discard",
|
|
38
|
+
"update",
|
|
39
|
+
"setdefault",
|
|
40
|
+
"popitem",
|
|
41
|
+
"union",
|
|
42
|
+
"intersection",
|
|
43
|
+
"difference",
|
|
44
|
+
"issubset",
|
|
45
|
+
"issuperset",
|
|
46
|
+
"join",
|
|
47
|
+
"startswith",
|
|
48
|
+
"endswith",
|
|
49
|
+
]
|
|
50
|
+
)
|
|
51
|
+
| MUTATING_METHODS
|
|
52
|
+
)
|
|
53
|
+
# builtins that only read their argument
|
|
54
|
+
READ_CALLS = frozenset(
|
|
55
|
+
[
|
|
56
|
+
"len",
|
|
57
|
+
"sum",
|
|
58
|
+
"sorted",
|
|
59
|
+
"min",
|
|
60
|
+
"max",
|
|
61
|
+
"any",
|
|
62
|
+
"all",
|
|
63
|
+
"list",
|
|
64
|
+
"tuple",
|
|
65
|
+
"set",
|
|
66
|
+
"frozenset",
|
|
67
|
+
"enumerate",
|
|
68
|
+
"zip",
|
|
69
|
+
"reversed",
|
|
70
|
+
"str",
|
|
71
|
+
"repr",
|
|
72
|
+
"bool",
|
|
73
|
+
"dict",
|
|
74
|
+
"print",
|
|
75
|
+
]
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _root(node: ast.expr) -> str | None:
|
|
80
|
+
while isinstance(node, ast.Subscript | ast.Attribute):
|
|
81
|
+
node = node.value
|
|
82
|
+
return node.id if isinstance(node, ast.Name) else None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class _Uses(ast.NodeVisitor):
|
|
86
|
+
def __init__(self, shadowed: set[str]) -> None:
|
|
87
|
+
self.shadowed = shadowed
|
|
88
|
+
self.stores: dict[str, int] = {}
|
|
89
|
+
self.bad: set[str] = set()
|
|
90
|
+
self.in_loop: set[str] = set() # loop variables and names bound by comprehensions
|
|
91
|
+
|
|
92
|
+
def escape(self, node: ast.AST) -> None:
|
|
93
|
+
"""Every name loaded below `node` escapes (it is used in a way we do not understand)."""
|
|
94
|
+
for n in ast.walk(node):
|
|
95
|
+
if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load):
|
|
96
|
+
self.bad.add(n.id)
|
|
97
|
+
|
|
98
|
+
# a name used as the receiver/base/argument of something we understand is fine; any other
|
|
99
|
+
# appearance of a Name in a load context (stored, passed on, returned inside a container...)
|
|
100
|
+
# is an escape. `_check` walks one expression with that rule.
|
|
101
|
+
def _check(self, node: ast.AST, safe: bool = False) -> None:
|
|
102
|
+
if isinstance(node, ast.Name):
|
|
103
|
+
if isinstance(node.ctx, ast.Load) and not safe:
|
|
104
|
+
self.bad.add(node.id)
|
|
105
|
+
return
|
|
106
|
+
if isinstance(node, ast.Attribute):
|
|
107
|
+
self._check(node.value, True) # `x.f`, `x.append`: a read through the name
|
|
108
|
+
return
|
|
109
|
+
if isinstance(node, ast.Subscript):
|
|
110
|
+
self._check(node.value, True)
|
|
111
|
+
self._check(node.slice)
|
|
112
|
+
return
|
|
113
|
+
if isinstance(node, ast.Call):
|
|
114
|
+
f = node.func
|
|
115
|
+
if isinstance(f, ast.Attribute):
|
|
116
|
+
receiver = f.value
|
|
117
|
+
if f.attr in READING:
|
|
118
|
+
self._check(receiver, True)
|
|
119
|
+
for a in [*node.args, *(k.value for k in node.keywords)]:
|
|
120
|
+
# arguments of reading methods: stored by append/insert/add/setdefault
|
|
121
|
+
stores = f.attr in ("append", "insert", "add", "setdefault", "appendleft")
|
|
122
|
+
self._check(
|
|
123
|
+
a,
|
|
124
|
+
not stores
|
|
125
|
+
and f.attr in ("extend", "update", "index", "count", "remove", "join"),
|
|
126
|
+
)
|
|
127
|
+
else:
|
|
128
|
+
self._check(receiver, False)
|
|
129
|
+
self.escape_args(node)
|
|
130
|
+
elif isinstance(f, ast.Name) and f.id in READ_CALLS and f.id not in self.shadowed:
|
|
131
|
+
for a in node.args:
|
|
132
|
+
self._check(a, True)
|
|
133
|
+
for k in node.keywords:
|
|
134
|
+
self._check(k.value)
|
|
135
|
+
else:
|
|
136
|
+
self.escape_args(node)
|
|
137
|
+
if not isinstance(f, ast.Name):
|
|
138
|
+
self._check(f)
|
|
139
|
+
return
|
|
140
|
+
if isinstance(node, ast.Compare):
|
|
141
|
+
self._check(node.left, True) # `k in x`, `x == y` read both sides
|
|
142
|
+
for c in node.comparators:
|
|
143
|
+
self._check(c, True)
|
|
144
|
+
return
|
|
145
|
+
if isinstance(node, ast.JoinedStr | ast.FormattedValue):
|
|
146
|
+
for c in ast.iter_child_nodes(node):
|
|
147
|
+
self._check(c, True)
|
|
148
|
+
return
|
|
149
|
+
if isinstance(node, ast.ListComp | ast.SetComp | ast.GeneratorExp | ast.DictComp):
|
|
150
|
+
for g in node.generators:
|
|
151
|
+
self._check(g.iter, True)
|
|
152
|
+
for cond in g.ifs:
|
|
153
|
+
self._check(cond)
|
|
154
|
+
for n in ast.walk(g.target):
|
|
155
|
+
if isinstance(n, ast.Name):
|
|
156
|
+
self.in_loop.add(n.id)
|
|
157
|
+
elts = [node.key, node.value] if isinstance(node, ast.DictComp) else [node.elt]
|
|
158
|
+
for e in elts:
|
|
159
|
+
self._check(e)
|
|
160
|
+
return
|
|
161
|
+
if isinstance(node, ast.Lambda):
|
|
162
|
+
self.escape(node.body)
|
|
163
|
+
return
|
|
164
|
+
for child in ast.iter_child_nodes(node):
|
|
165
|
+
self._check(child)
|
|
166
|
+
|
|
167
|
+
def escape_args(self, call: ast.Call) -> None:
|
|
168
|
+
for a in [*call.args, *(k.value for k in call.keywords)]:
|
|
169
|
+
self.escape(a)
|
|
170
|
+
|
|
171
|
+
# -- statements -----------------------------------------------------------------------
|
|
172
|
+
def visit_Assign(self, node: ast.Assign) -> None:
|
|
173
|
+
for t in node.targets:
|
|
174
|
+
if isinstance(t, ast.Name):
|
|
175
|
+
self.stores[t.id] = self.stores.get(t.id, 0) + 1
|
|
176
|
+
if len(node.targets) > 1:
|
|
177
|
+
self.bad.add(t.id) # chained: the names share one object
|
|
178
|
+
elif isinstance(t, ast.Tuple | ast.List):
|
|
179
|
+
for n in ast.walk(t):
|
|
180
|
+
if isinstance(n, ast.Name):
|
|
181
|
+
self.bad.add(n.id)
|
|
182
|
+
else:
|
|
183
|
+
self._check(t) # `x[i] = v`, `x.f = v`: a change through the name
|
|
184
|
+
self._check(node.value) # a name on the right is aliased or stored: an escape
|
|
185
|
+
|
|
186
|
+
def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
|
|
187
|
+
if isinstance(node.target, ast.Name):
|
|
188
|
+
if node.value is None:
|
|
189
|
+
self.bad.add(node.target.id)
|
|
190
|
+
else:
|
|
191
|
+
self.stores[node.target.id] = self.stores.get(node.target.id, 0) + 1
|
|
192
|
+
else:
|
|
193
|
+
self._check(node.target)
|
|
194
|
+
if node.value is not None:
|
|
195
|
+
self._check(node.value)
|
|
196
|
+
|
|
197
|
+
def visit_AugAssign(self, node: ast.AugAssign) -> None:
|
|
198
|
+
if isinstance(node.target, ast.Name):
|
|
199
|
+
self._check(node.value, True) # `xs += ys` extends xs in place; ints are not candidates
|
|
200
|
+
else:
|
|
201
|
+
self._check(node.target)
|
|
202
|
+
self._check(node.value)
|
|
203
|
+
|
|
204
|
+
def visit_Expr(self, node: ast.Expr) -> None:
|
|
205
|
+
self._check(node.value)
|
|
206
|
+
|
|
207
|
+
def visit_Return(self, node: ast.Return) -> None:
|
|
208
|
+
if isinstance(node.value, ast.Name):
|
|
209
|
+
return # moved out of the function
|
|
210
|
+
if node.value is not None:
|
|
211
|
+
self._check(node.value)
|
|
212
|
+
|
|
213
|
+
def visit_For(self, node: ast.For | ast.AsyncFor) -> None:
|
|
214
|
+
self._check(node.iter, True)
|
|
215
|
+
for n in ast.walk(node.target):
|
|
216
|
+
if isinstance(n, ast.Name):
|
|
217
|
+
self.in_loop.add(n.id)
|
|
218
|
+
root = _root(node.iter)
|
|
219
|
+
if isinstance(node.iter, ast.Call) and isinstance(node.iter.func, ast.Attribute):
|
|
220
|
+
root = _root(node.iter.func.value)
|
|
221
|
+
if root: # changing the list while iterating it needs the handle (Python allows it)
|
|
222
|
+
for n in ast.walk(ast.Module(body=node.body, type_ignores=[])):
|
|
223
|
+
if _changes(n, root):
|
|
224
|
+
self.bad.add(root)
|
|
225
|
+
for s in [*node.body, *node.orelse]:
|
|
226
|
+
self.visit(s)
|
|
227
|
+
|
|
228
|
+
visit_AsyncFor = visit_For
|
|
229
|
+
|
|
230
|
+
def visit_If(self, node: ast.If) -> None:
|
|
231
|
+
self._check(node.test)
|
|
232
|
+
for s in [*node.body, *node.orelse]:
|
|
233
|
+
self.visit(s)
|
|
234
|
+
|
|
235
|
+
def visit_While(self, node: ast.While) -> None:
|
|
236
|
+
self._check(node.test)
|
|
237
|
+
for s in [*node.body, *node.orelse]:
|
|
238
|
+
self.visit(s)
|
|
239
|
+
|
|
240
|
+
def visit_With(self, node: ast.With | ast.AsyncWith) -> None:
|
|
241
|
+
for item in node.items:
|
|
242
|
+
self.escape(item.context_expr)
|
|
243
|
+
if item.optional_vars is not None:
|
|
244
|
+
for n in ast.walk(item.optional_vars):
|
|
245
|
+
if isinstance(n, ast.Name):
|
|
246
|
+
self.bad.add(n.id)
|
|
247
|
+
for s in node.body:
|
|
248
|
+
self.visit(s)
|
|
249
|
+
|
|
250
|
+
def visit_Try(self, node: ast.Try | ast.TryStar) -> None:
|
|
251
|
+
for s in [*node.body, *node.orelse, *node.finalbody]:
|
|
252
|
+
self.visit(s)
|
|
253
|
+
for h in node.handlers:
|
|
254
|
+
for s in h.body:
|
|
255
|
+
self.visit(s)
|
|
256
|
+
|
|
257
|
+
visit_TryStar = visit_Try
|
|
258
|
+
|
|
259
|
+
def visit_Delete(self, node: ast.Delete) -> None:
|
|
260
|
+
for t in node.targets:
|
|
261
|
+
self._check(t)
|
|
262
|
+
|
|
263
|
+
def visit_Raise(self, node: ast.Raise) -> None:
|
|
264
|
+
for e in (node.exc, node.cause):
|
|
265
|
+
if e is not None:
|
|
266
|
+
self.escape(e)
|
|
267
|
+
|
|
268
|
+
def visit_Assert(self, node: ast.Assert) -> None:
|
|
269
|
+
self._check(node.test)
|
|
270
|
+
|
|
271
|
+
def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
|
|
272
|
+
self.escape(node) # a nested definition may capture anything
|
|
273
|
+
|
|
274
|
+
visit_AsyncFunctionDef = visit_FunctionDef
|
|
275
|
+
|
|
276
|
+
def visit_ClassDef(self, node: ast.ClassDef) -> None:
|
|
277
|
+
self.escape(node)
|
|
278
|
+
|
|
279
|
+
def generic_visit(self, node: ast.AST) -> None:
|
|
280
|
+
if isinstance(node, ast.stmt):
|
|
281
|
+
self.escape(node) # a statement kind we do not model: assume the worst
|
|
282
|
+
else:
|
|
283
|
+
super().generic_visit(node)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _changes(node: ast.AST, name: str) -> bool:
|
|
287
|
+
"""Does `node` change `name` in place (method call, item or attribute store, del, +=)?"""
|
|
288
|
+
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
|
|
289
|
+
return node.func.attr in MUTATING_METHODS and _root(node.func.value) == name
|
|
290
|
+
if isinstance(node, ast.Assign | ast.AugAssign | ast.AnnAssign | ast.Delete):
|
|
291
|
+
targets = node.targets if isinstance(node, ast.Assign | ast.Delete) else [node.target]
|
|
292
|
+
return any(not isinstance(t, ast.Name) and _root(t) == name for t in targets) or (
|
|
293
|
+
isinstance(node, ast.AugAssign)
|
|
294
|
+
and isinstance(node.target, ast.Name)
|
|
295
|
+
and node.target.id == name
|
|
296
|
+
)
|
|
297
|
+
return False
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def find_plain(fn: ast.FunctionDef | ast.AsyncFunctionDef, shadowed: set[str]) -> set[str]:
|
|
301
|
+
"""Names of locals that may be lowered to plain values (the lowering still checks that what is
|
|
302
|
+
assigned is a freshly built object)."""
|
|
303
|
+
params = {a.arg for a in [*fn.args.posonlyargs, *fn.args.args, *fn.args.kwonlyargs]}
|
|
304
|
+
params |= {a.arg for a in (fn.args.vararg, fn.args.kwarg) if a}
|
|
305
|
+
declared: set[str] = set()
|
|
306
|
+
local = set(params)
|
|
307
|
+
for node in ast.walk(fn):
|
|
308
|
+
if isinstance(node, ast.Global | ast.Nonlocal):
|
|
309
|
+
declared.update(node.names)
|
|
310
|
+
elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
|
|
311
|
+
local.add(node.id)
|
|
312
|
+
elif isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
|
|
313
|
+
local.add(node.name)
|
|
314
|
+
elif isinstance(node, ast.Import | ast.ImportFrom):
|
|
315
|
+
local.update(alias.asname or alias.name.split(".")[0] for alias in node.names)
|
|
316
|
+
elif isinstance(node, ast.ExceptHandler) and node.name:
|
|
317
|
+
local.add(node.name)
|
|
318
|
+
uses = _Uses(shadowed | local)
|
|
319
|
+
for s in fn.body:
|
|
320
|
+
uses.visit(s)
|
|
321
|
+
return {
|
|
322
|
+
name
|
|
323
|
+
for name, count in uses.stores.items()
|
|
324
|
+
if count == 1
|
|
325
|
+
and name not in uses.bad
|
|
326
|
+
and name not in params
|
|
327
|
+
and name not in uses.in_loop
|
|
328
|
+
and name not in declared
|
|
329
|
+
}
|