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,253 @@
|
|
|
1
|
+
"""Pydantic behaviour of model fields: what the generated Rust enforces and what it cannot.
|
|
2
|
+
|
|
3
|
+
Enforced through a generated `deserialize_with` function (python2rust-rt feature `pydantic`): lax
|
|
4
|
+
coercion of int/float/bool (also inside Option and list), `ge/gt/le/lt/multiple_of`,
|
|
5
|
+
`min_length/max_length`, `pattern`, strip/lower/upper (field, `StringConstraints` or
|
|
6
|
+
`model_config`), and "required means present" for Optional fields without a default.
|
|
7
|
+
|
|
8
|
+
Everything else is never silently dropped: validators and unknown `Annotated` metadata, unknown
|
|
9
|
+
`Field`/`model_config` options and constraints on unsupported types become TODOs; differences that
|
|
10
|
+
cannot be a TODO (coercion for maps/sets/dates, integers beyond i64) are drift entries that keep
|
|
11
|
+
the model out of `models_clean`.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import ast
|
|
17
|
+
from dataclasses import dataclass, field, replace
|
|
18
|
+
|
|
19
|
+
from ..ir.rtypes import SHARED, RType
|
|
20
|
+
from ..ir.types import dotted
|
|
21
|
+
|
|
22
|
+
Rule = tuple[str, int | float | str | None]
|
|
23
|
+
|
|
24
|
+
NUMERIC_RULES = {"ge": "Ge", "gt": "Gt", "le": "Le", "lt": "Lt", "multiple_of": "MultipleOf"}
|
|
25
|
+
LENGTH_RULES = {
|
|
26
|
+
"min_length": "MinLength",
|
|
27
|
+
"max_length": "MaxLength",
|
|
28
|
+
"min_items": "MinLength",
|
|
29
|
+
"max_items": "MaxLength",
|
|
30
|
+
}
|
|
31
|
+
TRANSFORMS = {"strip_whitespace": "Strip", "to_lower": "Lower", "to_upper": "Upper"}
|
|
32
|
+
KNOWN_KWARGS = frozenset(NUMERIC_RULES) | frozenset(LENGTH_RULES) | frozenset(TRANSFORMS) | {
|
|
33
|
+
"default", "default_factory", "alias", "validation_alias", "serialization_alias", "description",
|
|
34
|
+
"title", "examples", "example", "deprecated", "json_schema_extra", "pattern", "strict", "exclude",
|
|
35
|
+
"frozen", "repr", "init", "kw_only", "compare", "hash", "metadata", "validate_default",
|
|
36
|
+
} # fmt: skip
|
|
37
|
+
SCALARS = ("i64", "f64", "bool", "String")
|
|
38
|
+
BENIGN_CONFIG = frozenset(
|
|
39
|
+
{"from_attributes", "arbitrary_types_allowed", "title", "protected_namespaces",
|
|
40
|
+
"defer_build", "use_attribute_docstrings", "json_schema_extra", "use_enum_values", "validate_by_alias"}
|
|
41
|
+
) # fmt: skip
|
|
42
|
+
CONFIG_TRANSFORMS = {
|
|
43
|
+
"str_strip_whitespace": "strip_whitespace",
|
|
44
|
+
"str_to_lower": "to_lower",
|
|
45
|
+
"str_to_upper": "to_upper",
|
|
46
|
+
}
|
|
47
|
+
CONFIG_LENGTHS = {"str_min_length": "min_length", "str_max_length": "max_length"}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def enforceable_meta(node: ast.expr) -> bool:
|
|
51
|
+
"""`Annotated[...]` metadata whose effect the field planner knows (or that has none)."""
|
|
52
|
+
if isinstance(node, ast.Constant):
|
|
53
|
+
return True
|
|
54
|
+
name = dotted(node.func if isinstance(node, ast.Call) else node).split(".")[-1]
|
|
55
|
+
return name in (
|
|
56
|
+
"Field",
|
|
57
|
+
"StringConstraints",
|
|
58
|
+
"Ge",
|
|
59
|
+
"Gt",
|
|
60
|
+
"Le",
|
|
61
|
+
"Lt",
|
|
62
|
+
"MinLen",
|
|
63
|
+
"MaxLen",
|
|
64
|
+
"MultipleOf",
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass
|
|
69
|
+
class ModelFlags:
|
|
70
|
+
forbid: bool = False
|
|
71
|
+
populate_by_name: bool = False
|
|
72
|
+
total: bool = True
|
|
73
|
+
strict: bool = False
|
|
74
|
+
frozen: bool = False # assignment to a field raises in Python
|
|
75
|
+
str_rules: dict[str, ast.expr] = field(default_factory=dict) # applied to every str field
|
|
76
|
+
problems: list[str] = field(default_factory=list) # model_config options not translated
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _literal(node: ast.expr | None) -> object:
|
|
80
|
+
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
|
|
81
|
+
inner = _literal(node.operand)
|
|
82
|
+
return -inner if isinstance(inner, int | float) else None
|
|
83
|
+
return node.value if isinstance(node, ast.Constant) else None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _config_items(value: ast.expr) -> list[tuple[str, ast.expr]] | None:
|
|
87
|
+
if isinstance(value, ast.Call):
|
|
88
|
+
return [(k.arg, k.value) for k in value.keywords if k.arg] if not value.args else None
|
|
89
|
+
if isinstance(value, ast.Dict):
|
|
90
|
+
keys = [_literal(k) for k in value.keys]
|
|
91
|
+
if all(isinstance(k, str) for k in keys):
|
|
92
|
+
return [(str(k), v) for k, v in zip(keys, value.values, strict=True)]
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def read_config(node: ast.ClassDef, parent: ModelFlags | None) -> ModelFlags:
|
|
97
|
+
"""`model_config` (and `total=False`) of a class, starting from the parent model's settings."""
|
|
98
|
+
flags = replace(parent) if parent else ModelFlags()
|
|
99
|
+
flags.str_rules, flags.problems = dict(flags.str_rules), []
|
|
100
|
+
flags.total = not any(k.arg == "total" and _literal(k.value) is False for k in node.keywords)
|
|
101
|
+
for stmt in node.body:
|
|
102
|
+
targets = stmt.targets if isinstance(stmt, ast.Assign) else [getattr(stmt, "target", None)]
|
|
103
|
+
if not any(isinstance(t, ast.Name) and t.id == "model_config" for t in targets):
|
|
104
|
+
continue
|
|
105
|
+
value = getattr(stmt, "value", None)
|
|
106
|
+
items = _config_items(value) if value is not None else None
|
|
107
|
+
if items is None:
|
|
108
|
+
flags.problems.append("a computed model_config")
|
|
109
|
+
continue
|
|
110
|
+
for key, value in items:
|
|
111
|
+
_config_key(flags, key, value)
|
|
112
|
+
return flags
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _config_key(flags: ModelFlags, key: str, value: ast.expr) -> None:
|
|
116
|
+
literal = _literal(value)
|
|
117
|
+
if key == "extra":
|
|
118
|
+
flags.forbid = literal == "forbid"
|
|
119
|
+
if literal not in ("forbid", "ignore"):
|
|
120
|
+
flags.problems.append(f"model_config extra={ast.unparse(value)}")
|
|
121
|
+
elif key in ("populate_by_name", "validate_by_name"):
|
|
122
|
+
flags.populate_by_name = bool(literal)
|
|
123
|
+
elif key == "strict":
|
|
124
|
+
flags.strict = bool(literal)
|
|
125
|
+
elif key == "frozen":
|
|
126
|
+
flags.frozen = bool(literal)
|
|
127
|
+
elif key in CONFIG_TRANSFORMS:
|
|
128
|
+
flags.str_rules[CONFIG_TRANSFORMS[key]] = value
|
|
129
|
+
elif key in CONFIG_LENGTHS:
|
|
130
|
+
flags.str_rules[CONFIG_LENGTHS[key]] = value
|
|
131
|
+
elif key not in BENIGN_CONFIG:
|
|
132
|
+
flags.problems.append(f"model_config {key}")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@dataclass
|
|
136
|
+
class FieldPlan:
|
|
137
|
+
rules: list[Rule] = field(default_factory=list)
|
|
138
|
+
validator: bool = False # needs a generated deserialize_with function
|
|
139
|
+
required_option: bool = False
|
|
140
|
+
problems: list[str] = field(default_factory=list) # cannot be enforced: TODO
|
|
141
|
+
drift: list[tuple[str, str]] = field(default_factory=list) # (code, text): not-clean
|
|
142
|
+
constrained: bool = False # constructing the model must validate too
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _deshare(ty: RType) -> RType:
|
|
146
|
+
"""The value type of a field: the `Shared` handle around lists, dicts and models is not part of
|
|
147
|
+
what the validation rules talk about."""
|
|
148
|
+
while ty.name == SHARED:
|
|
149
|
+
ty = ty.args[0]
|
|
150
|
+
return RType(ty.name, tuple(_deshare(a) for a in ty.args))
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _base(ty: RType) -> RType:
|
|
154
|
+
while ty.name in ("Option", "Vec") and ty.args:
|
|
155
|
+
ty = ty.args[0]
|
|
156
|
+
return ty
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _supported(ty: RType) -> bool:
|
|
160
|
+
return _base(ty).name in SCALARS
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _mentions(ty: RType, names: tuple[str, ...]) -> bool:
|
|
164
|
+
return ty.name in names or any(_mentions(a, names) for a in ty.args)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _bounds(plan: FieldPlan, ty: RType, kw: dict[str, ast.expr]) -> None:
|
|
168
|
+
inner = ty.args[0] if ty.name == "Option" else ty
|
|
169
|
+
for key, value in kw.items():
|
|
170
|
+
if key not in KNOWN_KWARGS:
|
|
171
|
+
plan.problems.append(f"Field option {key}")
|
|
172
|
+
continue
|
|
173
|
+
literal = _literal(value)
|
|
174
|
+
if key in TRANSFORMS:
|
|
175
|
+
if literal and inner.name == "String":
|
|
176
|
+
plan.rules.append((TRANSFORMS[key], None))
|
|
177
|
+
elif literal:
|
|
178
|
+
plan.problems.append(f"{key} on {ty.rust()}")
|
|
179
|
+
continue
|
|
180
|
+
if isinstance(value, ast.Constant) and value.value is None:
|
|
181
|
+
continue
|
|
182
|
+
if key in NUMERIC_RULES:
|
|
183
|
+
if inner.name in ("i64", "f64") and isinstance(literal, int | float):
|
|
184
|
+
plan.rules.append((NUMERIC_RULES[key], float(literal)))
|
|
185
|
+
else:
|
|
186
|
+
plan.problems.append(f"{key} on {ty.rust()}")
|
|
187
|
+
elif key in LENGTH_RULES:
|
|
188
|
+
if inner.name in ("String", "Vec") and isinstance(literal, int):
|
|
189
|
+
plan.rules.append((LENGTH_RULES[key], literal))
|
|
190
|
+
else:
|
|
191
|
+
plan.problems.append(f"{key} on {ty.rust()}")
|
|
192
|
+
elif key == "pattern":
|
|
193
|
+
if inner.name == "String" and isinstance(literal, str):
|
|
194
|
+
plan.rules.append(("Pattern", literal))
|
|
195
|
+
else:
|
|
196
|
+
plan.problems.append(f"pattern on {ty.rust()}")
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _order(rules: list[Rule]) -> list[Rule]:
|
|
200
|
+
"""Pydantic transforms the string before it checks lengths and patterns."""
|
|
201
|
+
return sorted(rules, key=lambda r: r[0] not in ("Strip", "Lower", "Upper"))
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def plan_field(
|
|
205
|
+
ty: RType,
|
|
206
|
+
annotation: ast.expr,
|
|
207
|
+
kw: dict[str, ast.expr],
|
|
208
|
+
unknown_meta: list[str],
|
|
209
|
+
flags: ModelFlags,
|
|
210
|
+
has_default: bool,
|
|
211
|
+
bigint_ok: bool,
|
|
212
|
+
) -> FieldPlan:
|
|
213
|
+
"""What Pydantic does for one field of a BaseModel, and how much of it Rust will do."""
|
|
214
|
+
ty = _deshare(ty)
|
|
215
|
+
plan = FieldPlan()
|
|
216
|
+
plan.problems += [f"annotation metadata {m}" for m in unknown_meta]
|
|
217
|
+
inner = ty.args[0] if ty.name == "Option" else ty
|
|
218
|
+
if inner.name == "String":
|
|
219
|
+
kw = {**flags.str_rules, **kw}
|
|
220
|
+
_bounds(plan, ty, kw)
|
|
221
|
+
plan.constrained = bool(plan.rules)
|
|
222
|
+
strict = flags.strict or _literal(kw.get("strict")) is True
|
|
223
|
+
names = {
|
|
224
|
+
dotted(n).split(".")[-1]
|
|
225
|
+
for n in ast.walk(annotation)
|
|
226
|
+
if isinstance(n, ast.Name | ast.Attribute)
|
|
227
|
+
}
|
|
228
|
+
if "Literal" in names and not _mentions(ty, ("String",)) and _mentions(ty, ("i64", "bool")):
|
|
229
|
+
plan.problems.append("a Literal of ints/bools (values are not restricted)")
|
|
230
|
+
coercible = _mentions(ty, ("i64", "f64", "bool"))
|
|
231
|
+
if strict and plan.rules:
|
|
232
|
+
plan.problems.append("constraints on a strict field")
|
|
233
|
+
elif coercible and not strict and _supported(ty) and "Literal" not in names:
|
|
234
|
+
plan.validator = True
|
|
235
|
+
elif coercible and not strict:
|
|
236
|
+
plan.drift.append(("PY2RS043", "Pydantic coerces values inside this type; Rust is strict"))
|
|
237
|
+
if "Decimal" in names or _mentions(ty, ("chrono::DateTime<chrono::Utc>", "chrono::NaiveDate")):
|
|
238
|
+
plan.drift.append(("PY2RS043", "accepted input formats differ for dates/times/Decimal"))
|
|
239
|
+
if {"int", "float"} <= names and ty.name != "Vec" and _mentions(ty, ("f64",)):
|
|
240
|
+
plan.drift.append(("PY2RS043", "int | float is f64: integers are written back as floats"))
|
|
241
|
+
if _mentions(ty, ("i64", "serde_json::Value")) and not bigint_ok:
|
|
242
|
+
kinds = {r[0] for r in plan.rules}
|
|
243
|
+
bounded = bool(kinds & {"Ge", "Gt"}) and bool(kinds & {"Le", "Lt"})
|
|
244
|
+
if not bounded or _mentions(ty, ("serde_json::Value",)):
|
|
245
|
+
plan.drift.append(
|
|
246
|
+
("PY2RS056", "integers beyond i64 are accepted by Pydantic, not by Rust")
|
|
247
|
+
)
|
|
248
|
+
plan.required_option = ty.name == "Option" and not has_default
|
|
249
|
+
plan.validator = plan.validator or (plan.constrained and _supported(ty))
|
|
250
|
+
if plan.constrained and not _supported(ty):
|
|
251
|
+
plan.problems.append(f"constraints on {ty.rust()}")
|
|
252
|
+
plan.rules = _order(plan.rules)
|
|
253
|
+
return plan
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Passes over Python/IR: mutability analysis, ownership (clones), raise sets."""
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
"""May-alias check for values that are stored somewhere and mutated afterwards.
|
|
2
|
+
|
|
3
|
+
Python shares one object between every name and container that holds it; the Rust translation
|
|
4
|
+
clones a value wherever it is moved (see `ownership`). That is only equivalent while neither copy
|
|
5
|
+
changes afterwards, so a store that is followed by a mutation (of the value itself, or of the
|
|
6
|
+
container's elements while the value is still used) is reported instead of silently copied.
|
|
7
|
+
|
|
8
|
+
The check is conservative and works on source positions: it runs on the Python AST before types
|
|
9
|
+
are known, and the lowering raises PY2RS040 only when the stored name has a mutable type.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import ast
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
|
|
17
|
+
from .analysis import MUTATING_METHODS
|
|
18
|
+
|
|
19
|
+
Pos = tuple[int, int]
|
|
20
|
+
STORING_METHODS = {"append": 0, "appendleft": 0, "add": 0, "insert": 1, "push": 0}
|
|
21
|
+
SHARING_METHODS = {"extend": 0, "update": 0} # the argument's elements become shared
|
|
22
|
+
COPIERS = {"list", "dict", "set", "tuple", "sorted", "reversed", "frozenset"}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _pos(node: ast.AST) -> Pos:
|
|
26
|
+
return (getattr(node, "lineno", 0), getattr(node, "col_offset", 0))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _chain(node: ast.expr) -> tuple[str | None, int]:
|
|
30
|
+
"""(root name, number of subscripts/attributes between the root and `node`)."""
|
|
31
|
+
depth = 0
|
|
32
|
+
while isinstance(node, ast.Subscript | ast.Attribute):
|
|
33
|
+
node, depth = node.value, depth + 1
|
|
34
|
+
return (node.id, depth) if isinstance(node, ast.Name) else (None, depth)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
Path = tuple[int, ...] # the statement lists an event sits in, outermost first
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _paths(body: list[ast.stmt], prefix: Path, out: dict[int, Path]) -> None:
|
|
41
|
+
here = (*prefix, id(body))
|
|
42
|
+
for s in body:
|
|
43
|
+
out[id(s)] = here
|
|
44
|
+
for name in ("body", "orelse", "finalbody"):
|
|
45
|
+
inner = getattr(s, name, None)
|
|
46
|
+
if isinstance(inner, list) and inner and isinstance(inner[0], ast.stmt):
|
|
47
|
+
_paths(inner, here, out)
|
|
48
|
+
for h in getattr(s, "handlers", []):
|
|
49
|
+
_paths(h.body, here, out)
|
|
50
|
+
for c in getattr(s, "cases", []):
|
|
51
|
+
_paths(c.body, here, out)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class _Store:
|
|
56
|
+
node: ast.Name
|
|
57
|
+
dest: str | None # the container or alias that now holds the value
|
|
58
|
+
alias: bool # `b = a`: any mutation of `b` is a mutation of `a`
|
|
59
|
+
pos: Pos
|
|
60
|
+
loops: tuple[int, ...]
|
|
61
|
+
path: Path = ()
|
|
62
|
+
elements: bool = False # only the elements are shared (a shallow copy), not the value itself
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass
|
|
66
|
+
class _Mut:
|
|
67
|
+
name: str
|
|
68
|
+
depth: int # 0: the object itself, >= 1: reached through an element or attribute
|
|
69
|
+
pos: Pos
|
|
70
|
+
loops: tuple[int, ...]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class _Events(ast.NodeVisitor):
|
|
74
|
+
def __init__(self) -> None:
|
|
75
|
+
self.stores: list[_Store] = []
|
|
76
|
+
self.muts: list[_Mut] = []
|
|
77
|
+
self.reads: list[tuple[str, Pos, tuple[int, ...]]] = []
|
|
78
|
+
self.assigned: list[tuple[str, Pos, tuple[int, ...], Path]] = []
|
|
79
|
+
self.paths: dict[int, Path] = {}
|
|
80
|
+
self.cur: Path = ()
|
|
81
|
+
self.returns: list[tuple[str, Pos]] = []
|
|
82
|
+
self.loops: list[int] = []
|
|
83
|
+
self.loop_vars: list[tuple[str, str | None]] = [] # (loop variable, iterated root)
|
|
84
|
+
|
|
85
|
+
# -- helpers --------------------------------------------------------------------------
|
|
86
|
+
def visit(self, node: ast.AST) -> None:
|
|
87
|
+
if isinstance(node, ast.stmt):
|
|
88
|
+
saved, self.cur = self.cur, self.paths.get(id(node), self.cur)
|
|
89
|
+
super().visit(node)
|
|
90
|
+
self.cur = saved
|
|
91
|
+
else:
|
|
92
|
+
super().visit(node)
|
|
93
|
+
|
|
94
|
+
def _store(self, value: ast.expr | None, dest: str | None, alias: bool, at: ast.AST) -> None:
|
|
95
|
+
if isinstance(value, ast.Name):
|
|
96
|
+
self.stores.append(_Store(value, dest, alias, _pos(at), tuple(self.loops), self.cur))
|
|
97
|
+
|
|
98
|
+
def _share(self, value: ast.expr | None, dest: str | None, at: ast.AST) -> None:
|
|
99
|
+
"""`list(a)`, `a[:]`, `a.copy()`, `a + b`, `[*a]`, `b.extend(a)`: new container, shared elements."""
|
|
100
|
+
found: list[ast.expr] = []
|
|
101
|
+
if isinstance(value, ast.Call):
|
|
102
|
+
f = value.func
|
|
103
|
+
if isinstance(f, ast.Name) and f.id in COPIERS:
|
|
104
|
+
found = value.args[:1]
|
|
105
|
+
elif isinstance(f, ast.Attribute) and f.attr in ("copy", "keys", "values"):
|
|
106
|
+
found = [f.value]
|
|
107
|
+
elif isinstance(value, ast.Subscript) and isinstance(value.slice, ast.Slice):
|
|
108
|
+
found = [value.value]
|
|
109
|
+
elif isinstance(value, ast.BinOp) and isinstance(value.op, ast.Add):
|
|
110
|
+
found = [value.left, value.right]
|
|
111
|
+
elif isinstance(value, ast.List):
|
|
112
|
+
found = [e.value for e in value.elts if isinstance(e, ast.Starred)]
|
|
113
|
+
for n in found:
|
|
114
|
+
if isinstance(n, ast.Name):
|
|
115
|
+
self.stores.append(
|
|
116
|
+
_Store(n, dest, False, _pos(at), tuple(self.loops), self.cur, elements=True)
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
def _mut(self, target: ast.expr, at: ast.AST) -> None:
|
|
120
|
+
name, depth = _chain(target)
|
|
121
|
+
if name:
|
|
122
|
+
self.muts.append(_Mut(name, depth, _pos(at), tuple(self.loops)))
|
|
123
|
+
|
|
124
|
+
def _bind(self, target: ast.expr, at: ast.AST) -> None:
|
|
125
|
+
for n in ast.walk(target):
|
|
126
|
+
if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store):
|
|
127
|
+
self.assigned.append((n.id, _pos(at), tuple(self.loops), self.cur))
|
|
128
|
+
|
|
129
|
+
# -- visitors -------------------------------------------------------------------------
|
|
130
|
+
def visit_Name(self, node: ast.Name) -> None:
|
|
131
|
+
if isinstance(node.ctx, ast.Load):
|
|
132
|
+
self.reads.append((node.id, _pos(node), tuple(self.loops)))
|
|
133
|
+
|
|
134
|
+
def visit_Call(self, node: ast.Call) -> None:
|
|
135
|
+
f = node.func
|
|
136
|
+
if isinstance(f, ast.Attribute):
|
|
137
|
+
dest, _ = _chain(f.value)
|
|
138
|
+
slot = STORING_METHODS.get(f.attr)
|
|
139
|
+
if slot is not None and len(node.args) > slot:
|
|
140
|
+
self._store(node.args[slot], dest, False, node)
|
|
141
|
+
share = SHARING_METHODS.get(f.attr)
|
|
142
|
+
if share is not None and node.args and isinstance(node.args[0], ast.Name):
|
|
143
|
+
self.stores.append(
|
|
144
|
+
_Store(
|
|
145
|
+
node.args[0],
|
|
146
|
+
dest,
|
|
147
|
+
False,
|
|
148
|
+
_pos(node),
|
|
149
|
+
tuple(self.loops),
|
|
150
|
+
self.cur,
|
|
151
|
+
elements=True,
|
|
152
|
+
)
|
|
153
|
+
)
|
|
154
|
+
if f.attr in MUTATING_METHODS:
|
|
155
|
+
self._mut(f.value, node)
|
|
156
|
+
if isinstance(f, ast.Name) and f.id[:1].isupper(): # a constructor keeps its arguments
|
|
157
|
+
for a in [*node.args, *(k.value for k in node.keywords)]:
|
|
158
|
+
self._store(a, None, False, node)
|
|
159
|
+
self.generic_visit(node)
|
|
160
|
+
|
|
161
|
+
def visit_Return(self, node: ast.Return) -> None:
|
|
162
|
+
if node.value is not None:
|
|
163
|
+
parts = (
|
|
164
|
+
node.value.elts if isinstance(node.value, ast.Tuple | ast.List) else [node.value]
|
|
165
|
+
)
|
|
166
|
+
for p in parts:
|
|
167
|
+
if isinstance(p, ast.Name):
|
|
168
|
+
self.returns.append((p.id, _pos(node)))
|
|
169
|
+
self.generic_visit(node)
|
|
170
|
+
|
|
171
|
+
def visit_Lambda(self, node: ast.Lambda) -> None:
|
|
172
|
+
own = {a.arg for a in [*node.args.posonlyargs, *node.args.args, *node.args.kwonlyargs]}
|
|
173
|
+
for n in ast.walk(node.body): # a captured name is shared with the closure
|
|
174
|
+
if isinstance(n, ast.Name) and n.id not in own:
|
|
175
|
+
self.stores.append(_Store(n, None, False, _pos(node), tuple(self.loops), self.cur))
|
|
176
|
+
self.generic_visit(node)
|
|
177
|
+
|
|
178
|
+
def _container_literal(self, node: ast.List | ast.Tuple | ast.Set | ast.Dict) -> None:
|
|
179
|
+
items = node.values if isinstance(node, ast.Dict) else node.elts
|
|
180
|
+
for item in items:
|
|
181
|
+
self._store(item, None, False, node)
|
|
182
|
+
self.generic_visit(node)
|
|
183
|
+
|
|
184
|
+
visit_List = visit_Tuple = visit_Set = visit_Dict = _container_literal
|
|
185
|
+
|
|
186
|
+
def visit_Assign(self, node: ast.Assign) -> None:
|
|
187
|
+
self.visit(node.value)
|
|
188
|
+
for t in node.targets:
|
|
189
|
+
self._share(node.value, _chain(t)[0], node)
|
|
190
|
+
if isinstance(t, ast.Name):
|
|
191
|
+
self._store(node.value, t.id, True, node)
|
|
192
|
+
elif isinstance(t, ast.Subscript | ast.Attribute):
|
|
193
|
+
dest, _ = _chain(t)
|
|
194
|
+
self._store(node.value, dest, False, node)
|
|
195
|
+
self._mut(t, t)
|
|
196
|
+
self._bind(t, node)
|
|
197
|
+
self.visit(t)
|
|
198
|
+
|
|
199
|
+
def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
|
|
200
|
+
if node.value is not None:
|
|
201
|
+
self.visit(node.value)
|
|
202
|
+
if isinstance(node.target, ast.Name):
|
|
203
|
+
self._store(node.value, node.target.id, True, node)
|
|
204
|
+
else:
|
|
205
|
+
dest, _ = _chain(node.target)
|
|
206
|
+
self._store(node.value, dest, False, node)
|
|
207
|
+
self._mut(node.target, node.target)
|
|
208
|
+
self._bind(node.target, node)
|
|
209
|
+
|
|
210
|
+
def visit_AugAssign(self, node: ast.AugAssign) -> None:
|
|
211
|
+
self.visit(node.value)
|
|
212
|
+
if isinstance(node.op, ast.Add) and isinstance(node.value, ast.Name):
|
|
213
|
+
dest = _chain(node.target)[0] # `xs += ys` extends xs with the elements of ys
|
|
214
|
+
self._share(ast.BinOp(left=node.value, op=ast.Add(), right=node.value), dest, node)
|
|
215
|
+
if not isinstance(node.target, ast.Name):
|
|
216
|
+
self._mut(node.target, node.target)
|
|
217
|
+
self.visit(node.target)
|
|
218
|
+
|
|
219
|
+
def visit_Delete(self, node: ast.Delete) -> None:
|
|
220
|
+
for t in node.targets:
|
|
221
|
+
self._mut(t, t)
|
|
222
|
+
self.generic_visit(node)
|
|
223
|
+
|
|
224
|
+
def visit_For(self, node: ast.For | ast.AsyncFor) -> None:
|
|
225
|
+
self.visit(node.iter)
|
|
226
|
+
self.loops.append(id(node))
|
|
227
|
+
root, _ = _chain(node.iter) if isinstance(node.iter, ast.expr) else (None, 0)
|
|
228
|
+
if isinstance(node.iter, ast.Call) and isinstance(node.iter.func, ast.Attribute):
|
|
229
|
+
root, _ = _chain(node.iter.func.value) # `d.values()`, `d.items()`
|
|
230
|
+
for n in ast.walk(node.target):
|
|
231
|
+
if isinstance(n, ast.Name):
|
|
232
|
+
self.loop_vars.append((n.id, root))
|
|
233
|
+
self._bind(node.target, node)
|
|
234
|
+
for s in [*node.body, *node.orelse]:
|
|
235
|
+
self.visit(s)
|
|
236
|
+
self.loops.pop()
|
|
237
|
+
|
|
238
|
+
visit_AsyncFor = visit_For
|
|
239
|
+
|
|
240
|
+
def visit_While(self, node: ast.While) -> None:
|
|
241
|
+
self.loops.append(id(node))
|
|
242
|
+
self.generic_visit(node)
|
|
243
|
+
self.loops.pop()
|
|
244
|
+
|
|
245
|
+
def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
|
|
246
|
+
return # nested definitions are lowered on their own
|
|
247
|
+
|
|
248
|
+
visit_AsyncFunctionDef = visit_FunctionDef
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _later(ev_pos: Pos, ev_loops: tuple[int, ...], store: _Store, rebound: set[int]) -> bool:
|
|
252
|
+
"""Does an event at `ev_pos` run after `store` (in source order, or in the next iteration of a
|
|
253
|
+
loop that holds both and does not rebind the name first)?"""
|
|
254
|
+
if ev_pos > store.pos:
|
|
255
|
+
return True
|
|
256
|
+
return bool((set(ev_loops) & set(store.loops)) - rebound)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def find_hazards(fn: ast.FunctionDef | ast.AsyncFunctionDef) -> dict[int, tuple[str, bool]]:
|
|
260
|
+
"""`id(Name node)` -> (reason, only the elements are shared) for every stored name that may be
|
|
261
|
+
observed through an alias."""
|
|
262
|
+
params = {a.arg for a in [*fn.args.posonlyargs, *fn.args.args, *fn.args.kwonlyargs]}
|
|
263
|
+
ev = _Events()
|
|
264
|
+
_paths(fn.body, (), ev.paths)
|
|
265
|
+
for s in fn.body:
|
|
266
|
+
ev.visit(s)
|
|
267
|
+
# a `for x in C` whose x is mutated in place mutates the elements of C
|
|
268
|
+
muts = list(ev.muts)
|
|
269
|
+
for var, root in ev.loop_vars:
|
|
270
|
+
if root and any(m.name == var for m in ev.muts):
|
|
271
|
+
muts.append(_Mut(root, 1, min(m.pos for m in ev.muts if m.name == var), ()))
|
|
272
|
+
out: dict[int, tuple[str, bool]] = {}
|
|
273
|
+
for st in ev.stores:
|
|
274
|
+
name = st.node.id
|
|
275
|
+
rebound: set[int] = set()
|
|
276
|
+
for n, pos, loops, path in ev.assigned:
|
|
277
|
+
if n != name:
|
|
278
|
+
continue
|
|
279
|
+
before = pos < st.pos and set(loops) & set(st.loops) # fresh at each iteration
|
|
280
|
+
after = pos > st.pos and st.path[: len(path)] == path # unconditionally replaced
|
|
281
|
+
if before or after:
|
|
282
|
+
rebound |= set(loops) & set(st.loops)
|
|
283
|
+
|
|
284
|
+
used_later = any(n == name and _later(p, loops, st, rebound) for n, p, loops in ev.reads)
|
|
285
|
+
|
|
286
|
+
if st.elements:
|
|
287
|
+
depth_muts = [m for m in muts if m.name in (name, st.dest) and m.depth >= 1]
|
|
288
|
+
if any(_later(m.pos, m.loops, st, rebound) for m in depth_muts):
|
|
289
|
+
out[id(st.node)] = (f"the elements of {name} are shared and then changed", True)
|
|
290
|
+
elif any(m.name == name and _later(m.pos, m.loops, st, rebound) for m in muts):
|
|
291
|
+
out[id(st.node)] = (f"{name} is stored and then changed", False)
|
|
292
|
+
elif (
|
|
293
|
+
st.dest
|
|
294
|
+
and used_later
|
|
295
|
+
and any(
|
|
296
|
+
m.name == st.dest
|
|
297
|
+
and (st.alias or m.depth >= 1)
|
|
298
|
+
and _later(m.pos, m.loops, st, set())
|
|
299
|
+
for m in muts
|
|
300
|
+
)
|
|
301
|
+
):
|
|
302
|
+
out[id(st.node)] = (
|
|
303
|
+
f"{name} is stored in {st.dest}, which is changed while {name} is used",
|
|
304
|
+
False,
|
|
305
|
+
)
|
|
306
|
+
elif st.dest in params and any(r == name and p > st.pos for r, p in ev.returns):
|
|
307
|
+
out[id(st.node)] = (
|
|
308
|
+
f"{name} is stored in the argument {st.dest} and also returned",
|
|
309
|
+
False,
|
|
310
|
+
)
|
|
311
|
+
return out
|