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,896 @@
|
|
|
1
|
+
"""Module-level translation: imports, aliases, constants, classes and functions in source order."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import copy
|
|
7
|
+
from collections import Counter
|
|
8
|
+
from contextlib import suppress
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from graphlib import CycleError, TopologicalSorter
|
|
11
|
+
|
|
12
|
+
from ..ir import nodes as ir
|
|
13
|
+
from ..ir.rtypes import BOOL, FLOAT, INT, STR, T, peel
|
|
14
|
+
from ..ir.types import TypeMapper, dotted
|
|
15
|
+
from ..lower.calls import CallLowerer
|
|
16
|
+
from ..lower.context import CONSUMED_MODULES, ConstInfo, Ctx, FuncSig, ModelInfo
|
|
17
|
+
from ..lower.funcs import build_sig, convention, docstring, lower_function, todo_item
|
|
18
|
+
from ..lower.lowerer import Unsupported
|
|
19
|
+
from ..lower.models import lower_class, lower_newtype, register_class
|
|
20
|
+
from ..lower.testing import is_fixture, is_test_class, is_test_function, is_test_module, lower_tests
|
|
21
|
+
from ..lower.validation import enforceable_meta, read_config
|
|
22
|
+
from ..passes import ownership
|
|
23
|
+
from ..passes.analysis import Analysis, analyze
|
|
24
|
+
from ..passes.raises import analyze_raises
|
|
25
|
+
from .names import camel, const_name
|
|
26
|
+
from .project_imports import project_import
|
|
27
|
+
|
|
28
|
+
TYPE_HEADS = {
|
|
29
|
+
"Optional", "Union", "Literal", "Annotated", "List", "Dict", "Set", "Tuple", "FrozenSet", "Sequence",
|
|
30
|
+
"Mapping", "list", "dict", "set", "tuple", "frozenset", "Callable", "Final",
|
|
31
|
+
} # fmt: skip
|
|
32
|
+
CONST_FNS = {
|
|
33
|
+
f"rt::{n}" for n in ("add", "sub", "mul", "neg", "abs", "pow")
|
|
34
|
+
} # `const fn`s in the runtime crate
|
|
35
|
+
LOGGER_FACTORIES = {"getLogger", "get_logger", "getlogger"}
|
|
36
|
+
SIMPLE_TYPES = {"str", "int", "float", "bool", "bytes", "Any", "object"}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class Deferred:
|
|
41
|
+
"""A function whose signature is known; its body is lowered after all signatures exist."""
|
|
42
|
+
|
|
43
|
+
node: ast.FunctionDef | ast.AsyncFunctionDef
|
|
44
|
+
sig: FuncSig
|
|
45
|
+
ana: Analysis
|
|
46
|
+
todos_before: int
|
|
47
|
+
todos_sig: int
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class Build:
|
|
52
|
+
module: ir.Module
|
|
53
|
+
stats: Counter[str]
|
|
54
|
+
not_clean: tuple[str, ...] = () # Rust names of the items counted not clean
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def looks_like_type(ctx: Ctx, node: ast.expr) -> bool:
|
|
58
|
+
if isinstance(node, ast.Name):
|
|
59
|
+
return (
|
|
60
|
+
node.id in SIMPLE_TYPES
|
|
61
|
+
or node.id in ctx.models
|
|
62
|
+
or node.id in ctx.enums
|
|
63
|
+
or node.id in ctx.aliases
|
|
64
|
+
)
|
|
65
|
+
if isinstance(node, ast.Subscript):
|
|
66
|
+
return dotted(node.value).split(".")[-1] in TYPE_HEADS
|
|
67
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
|
|
68
|
+
return looks_like_type(ctx, node.left) and looks_like_type(ctx, node.right)
|
|
69
|
+
return isinstance(node, ast.Constant) and node.value is None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def ast_depth(node: ast.AST) -> int:
|
|
73
|
+
"""Maximum nesting depth of `node` (iterative, so hostile input cannot overflow the stack)."""
|
|
74
|
+
deepest, stack = 0, [(node, 1)]
|
|
75
|
+
while stack:
|
|
76
|
+
n, d = stack.pop()
|
|
77
|
+
deepest = max(deepest, d)
|
|
78
|
+
stack.extend((c, d + 1) for c in ast.iter_child_nodes(n))
|
|
79
|
+
return deepest
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# -- imports ------------------------------------------------------------------------------
|
|
83
|
+
def lower_import(ctx: Ctx, node: ast.Import | ast.ImportFrom) -> list[ir.Item]:
|
|
84
|
+
items: list[ir.Item] = []
|
|
85
|
+
if isinstance(node, ast.ImportFrom):
|
|
86
|
+
module = ("." * node.level) + (node.module or "")
|
|
87
|
+
pairs = [(module, a.name, a.asname or a.name) for a in node.names]
|
|
88
|
+
else:
|
|
89
|
+
pairs = [(a.name, "", a.asname or a.name.split(".")[0]) for a in node.names]
|
|
90
|
+
for alias, (module, name, local) in zip(node.names, pairs, strict=True):
|
|
91
|
+
full = f"{module}.{name}" if name else module
|
|
92
|
+
if full in ctx.cfg.model_bases:
|
|
93
|
+
continue # registered by `register_model_bases` before the classes
|
|
94
|
+
inside = project_import(ctx, node, alias)
|
|
95
|
+
if inside is not None:
|
|
96
|
+
items += inside
|
|
97
|
+
continue
|
|
98
|
+
if module in CONSUMED_MODULES or module.split(".")[0] == "pydantic":
|
|
99
|
+
continue
|
|
100
|
+
if (
|
|
101
|
+
name or module.split(".")[-1]
|
|
102
|
+
) in ctx.cfg.type_map: # datetime, uuid, decimal: mapped types
|
|
103
|
+
continue
|
|
104
|
+
mapped = ctx.cfg.import_map.get(module)
|
|
105
|
+
library = any(k == full or k.startswith(full + ".") for k in ctx.cfg.library_map)
|
|
106
|
+
if mapped is not None:
|
|
107
|
+
ctx.imports[local] = full
|
|
108
|
+
ctx.opaque.add(local)
|
|
109
|
+
target = f"{mapped}::{name}" if name else mapped
|
|
110
|
+
ctx.uses.append(f"use {target}{' as ' + local if local != name else ''};")
|
|
111
|
+
elif library:
|
|
112
|
+
ctx.imports[local] = full if name else module
|
|
113
|
+
else:
|
|
114
|
+
# Not a TODO: nothing can be patched into an import. Every USE of the name is its
|
|
115
|
+
# own TODO; the comment and the diagnostic keep the import visible.
|
|
116
|
+
root = module.lstrip(".").split(".")[0] or "."
|
|
117
|
+
ctx.imports_unmapped[root] = ctx.imports_unmapped.get(root, 0) + 1
|
|
118
|
+
ctx.col.diag(
|
|
119
|
+
"PY2RS010", node, f"import {full} is not mapped", construct=f"import {full}"
|
|
120
|
+
)
|
|
121
|
+
items.append(ir.CommentItem([f"// python2rust PY2RS010: import {full} is not mapped"]))
|
|
122
|
+
return items
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# -- constants ----------------------------------------------------------------------------
|
|
126
|
+
def _literal_kind(node: ast.expr) -> type | None:
|
|
127
|
+
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
|
|
128
|
+
node = node.operand
|
|
129
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, (bool, int, float, str)):
|
|
130
|
+
return type(node.value)
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def lower_const(
|
|
135
|
+
ctx: Ctx, mapper: TypeMapper, name: str, ann: ast.expr | None, value: ast.expr, stmt: ast.stmt
|
|
136
|
+
) -> list[ir.Item]:
|
|
137
|
+
rust = const_name(name)
|
|
138
|
+
lw = CallLowerer(ctx, mapper) # constants may call builtins and library functions
|
|
139
|
+
span = ir.span_of(stmt, ctx.col.file)
|
|
140
|
+
declared = mapper.map(ann, rust) if ann is not None else None
|
|
141
|
+
try:
|
|
142
|
+
if (
|
|
143
|
+
not lw.shared
|
|
144
|
+
and isinstance(value, (ast.List, ast.Tuple))
|
|
145
|
+
and value.elts
|
|
146
|
+
and len({_literal_kind(e) for e in value.elts}) == 1
|
|
147
|
+
and _literal_kind(value.elts[0])
|
|
148
|
+
not in (None, str) # str lists are `Vec<String>` statics
|
|
149
|
+
):
|
|
150
|
+
elems = [lw.expr(e) for e in value.elts]
|
|
151
|
+
ety = peel(elems[0].ty)
|
|
152
|
+
arr = ir.Ref(operand=ir.ArrayX(elems=elems))
|
|
153
|
+
ctx.consts[name] = ConstInfo(rust, T("Vec", ety), True)
|
|
154
|
+
return [ir.Const(rust, T("&", T("[]", ety)), arr, "const", "pub ", span=span)]
|
|
155
|
+
e = lw.expr(value)
|
|
156
|
+
ty = peel(e.ty)
|
|
157
|
+
if declared is not None and not ty.known:
|
|
158
|
+
ty = declared
|
|
159
|
+
if ty.name in ("Iter", "Fn", "Future"):
|
|
160
|
+
raise Unsupported("PY2RS032", f"module value {name} is a lazy {ty.name}", stmt)
|
|
161
|
+
if ty.known and lw.shared and lw.mutable_ty(ty):
|
|
162
|
+
# a Python object at module level: one handle for the whole program (one thread)
|
|
163
|
+
stored, init = lw.store_ty(ty), ownership.expr(e, True)
|
|
164
|
+
if ctx.cfg.shared == "arc":
|
|
165
|
+
ctx.consts[name] = ConstInfo(f"(&*{rust}).clone()", stored, False)
|
|
166
|
+
return [ir.Const(rust, stored, init, "static", "pub ", span=span)]
|
|
167
|
+
ctx.consts[name] = ConstInfo(f"{rust}.with(rt::Shared::clone)", stored, False)
|
|
168
|
+
return [ir.Const(rust, stored, init, "thread_static", "pub ", span=span)]
|
|
169
|
+
if ty.known and not (_const_evaluable(e) and ty in (INT, FLOAT, BOOL, STR)):
|
|
170
|
+
if name in ctx.mutated_globals:
|
|
171
|
+
raise Unsupported(
|
|
172
|
+
"PY2RS032", f"module value {name} is mutated by functions (shared state)", stmt
|
|
173
|
+
)
|
|
174
|
+
ctx.consts[name] = ConstInfo(f"&*{rust}", ty, True) # computed once, on first use
|
|
175
|
+
return [ir.Const(rust, ty, ownership.expr(e, True), "static", "pub ", span=span)]
|
|
176
|
+
if _const_evaluable(e) and ty in (INT, FLOAT, BOOL, STR):
|
|
177
|
+
ty = declared or ty
|
|
178
|
+
if ty == STR:
|
|
179
|
+
ctx.consts[name] = ConstInfo(rust, STR, True)
|
|
180
|
+
return [ir.Const(rust, T("&", T("str")), e, "const", "pub ", span=span)]
|
|
181
|
+
ctx.consts[name] = ConstInfo(rust, ty)
|
|
182
|
+
return [ir.Const(rust, ty, lw.coerce(e, ty), "const", "pub ", span=span)]
|
|
183
|
+
raise Unsupported("PY2RS032", f"module value {name} is not a literal", stmt)
|
|
184
|
+
except Unsupported as exc:
|
|
185
|
+
return [
|
|
186
|
+
todo_item(
|
|
187
|
+
ctx,
|
|
188
|
+
"PY2RS032" if exc.code != "PY2RS032" else exc.code,
|
|
189
|
+
stmt,
|
|
190
|
+
exc.construct,
|
|
191
|
+
"const",
|
|
192
|
+
)
|
|
193
|
+
]
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _const_evaluable(e: ir.RExpr) -> bool:
|
|
197
|
+
if isinstance(e, ir.Lit):
|
|
198
|
+
return e.kind in ("int", "float", "bool", "str")
|
|
199
|
+
if isinstance(e, ir.Path):
|
|
200
|
+
return not e.borrowed
|
|
201
|
+
if isinstance(e, ir.Bin):
|
|
202
|
+
return e.op in "+-*" and _const_evaluable(e.left) and _const_evaluable(e.right)
|
|
203
|
+
if isinstance(e, ir.Call) and isinstance(e.func, ir.Path) and e.func.path in CONST_FNS:
|
|
204
|
+
return all(_const_evaluable(a) for a in e.args)
|
|
205
|
+
if isinstance(e, (ir.Un, ir.Cast)):
|
|
206
|
+
return _const_evaluable(e.operand)
|
|
207
|
+
return False
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _mut_passed(ctx: Ctx, node: ast.AST) -> set[str]:
|
|
211
|
+
"""Names handed to a `&mut` parameter of a function in this module."""
|
|
212
|
+
out: set[str] = set()
|
|
213
|
+
for call in (
|
|
214
|
+
n for n in ast.walk(node) if isinstance(n, ast.Call) and isinstance(n.func, ast.Name)
|
|
215
|
+
):
|
|
216
|
+
assert isinstance(call.func, ast.Name)
|
|
217
|
+
sig = ctx.sigs.get(call.func.id)
|
|
218
|
+
if sig is None:
|
|
219
|
+
continue
|
|
220
|
+
plain = [p for p in sig.params if p.kind == "pos"]
|
|
221
|
+
by_name = {p.name: p for p in sig.params}
|
|
222
|
+
pairs = list(zip(call.args, plain, strict=False)) + [
|
|
223
|
+
(k.value, by_name[k.arg]) for k in call.keywords if k.arg in by_name
|
|
224
|
+
]
|
|
225
|
+
for value, param in pairs:
|
|
226
|
+
while isinstance(value, (ast.Subscript, ast.Attribute)):
|
|
227
|
+
value = value.value
|
|
228
|
+
if param.conv == "&mut" and isinstance(value, ast.Name):
|
|
229
|
+
out.add(value.id)
|
|
230
|
+
return out
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def propagate_mut(ctx: Ctx, deferred: list[Deferred]) -> None:
|
|
234
|
+
"""A value passed on to a `&mut` parameter must itself be mutable (a fixpoint over the call graph)."""
|
|
235
|
+
changed = True
|
|
236
|
+
while changed:
|
|
237
|
+
changed = False
|
|
238
|
+
for d in deferred:
|
|
239
|
+
ana = d.ana
|
|
240
|
+
new = _mut_passed(ctx, d.node) - ana.method_mut
|
|
241
|
+
if not new:
|
|
242
|
+
continue
|
|
243
|
+
ana.method_mut |= new
|
|
244
|
+
ana.mutated |= new
|
|
245
|
+
for p in d.sig.params:
|
|
246
|
+
if p.name in new and p.kind in ("pos", "kwonly"):
|
|
247
|
+
p.conv = convention(ctx, p.name, p.ty, ana)
|
|
248
|
+
p.mutable = p.name in ana.mutated and not p.conv
|
|
249
|
+
changed = True
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
# -- the module ---------------------------------------------------------------------------
|
|
253
|
+
def register_model_bases(ctx: Ctx, tree: ast.Module) -> None:
|
|
254
|
+
"""Imports listed in `model_bases` behave like local Pydantic base classes with that config."""
|
|
255
|
+
for node in tree.body:
|
|
256
|
+
if not isinstance(node, ast.ImportFrom):
|
|
257
|
+
continue
|
|
258
|
+
for a in node.names:
|
|
259
|
+
options = ctx.cfg.model_bases.get(f"{'.' * node.level}{node.module or ''}.{a.name}")
|
|
260
|
+
if options is not None:
|
|
261
|
+
local = a.asname or a.name
|
|
262
|
+
keywords = [ast.keyword(arg=k, value=ast.Constant(v)) for k, v in options.items()]
|
|
263
|
+
config = ast.Call(func=ast.Name(id="ConfigDict"), args=[], keywords=keywords)
|
|
264
|
+
assign = ast.Assign(targets=[ast.Name(id="model_config")], value=config)
|
|
265
|
+
fake = ast.ClassDef(
|
|
266
|
+
name=a.name,
|
|
267
|
+
bases=[],
|
|
268
|
+
keywords=[],
|
|
269
|
+
body=[assign],
|
|
270
|
+
decorator_list=[],
|
|
271
|
+
type_params=[],
|
|
272
|
+
)
|
|
273
|
+
ctx.models[local] = ModelInfo(a.name, config=read_config(fake, None))
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def build_module(tree: ast.Module, ctx: Ctx, mapper: TypeMapper) -> Build:
|
|
277
|
+
stats: Counter[str] = Counter()
|
|
278
|
+
module = ir.Module()
|
|
279
|
+
module.doc, body = docstring(tree.body)
|
|
280
|
+
module.uses = ctx.uses
|
|
281
|
+
register_model_bases(ctx, tree)
|
|
282
|
+
for stmt in tree.body:
|
|
283
|
+
if isinstance(stmt, ast.ClassDef):
|
|
284
|
+
register_class(ctx, stmt)
|
|
285
|
+
slots: list[ir.Item | Deferred] = []
|
|
286
|
+
test_module = ctx.cfg.tests and is_test_module(tree, ctx.col.file)
|
|
287
|
+
script = Script(list(body))
|
|
288
|
+
if not test_module:
|
|
289
|
+
script = _split_script(tree, body, ctx)
|
|
290
|
+
body = script.keep
|
|
291
|
+
ctx.volatile, ctx.async_entry = script.volatile, script.async_entry
|
|
292
|
+
probes = [n for n in tree.body if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef)]
|
|
293
|
+
if script.stmts:
|
|
294
|
+
probes.append(_synthetic("py2rs_probe", [copy.deepcopy(st) for st in script.stmts], True))
|
|
295
|
+
for fn in probes: # module values that functions or the import-time script change in place
|
|
296
|
+
params = {a.arg for a in [*fn.args.posonlyargs, *fn.args.args, *fn.args.kwonlyargs]}
|
|
297
|
+
found = analyze(fn, params)
|
|
298
|
+
ctx.mutated_globals |= (found.method_mut | found.attr_mut) - params
|
|
299
|
+
prev = body[0].lineno - 1 if body else 0
|
|
300
|
+
for stmt in body:
|
|
301
|
+
comments = ctx.take_comments(prev, stmt.lineno)
|
|
302
|
+
prev = stmt.end_lineno or stmt.lineno
|
|
303
|
+
if comments:
|
|
304
|
+
slots.append(ir.CommentItem(comments))
|
|
305
|
+
start = ctx.col.mark()
|
|
306
|
+
name = getattr(stmt, "name", "<module>")
|
|
307
|
+
if not isinstance(name, str): # `type X = ...` keeps its name in a Name node
|
|
308
|
+
name = getattr(name, "id", "<module>")
|
|
309
|
+
deep = ast_depth(stmt)
|
|
310
|
+
if deep > ctx.cfg.max_depth:
|
|
311
|
+
slots.append(
|
|
312
|
+
todo_item(
|
|
313
|
+
ctx, "PY2RS050", stmt, f"nesting depth {deep} exceeds {ctx.cfg.max_depth}"
|
|
314
|
+
)
|
|
315
|
+
)
|
|
316
|
+
continue
|
|
317
|
+
if test_module and (is_test_function(stmt) or is_test_class(stmt) or _is_fixture(stmt)):
|
|
318
|
+
continue # lowered by tests.lower_tests into `mod tests`
|
|
319
|
+
try:
|
|
320
|
+
with ctx.col.enclosing(name):
|
|
321
|
+
slots += _top(ctx, mapper, stmt, stats, start)
|
|
322
|
+
except Exception as exc:
|
|
323
|
+
slots.append(todo_item(ctx, "PY2RS002", stmt, f"{type(exc).__name__}: {exc}"[:120]))
|
|
324
|
+
entry = _run_function(ctx, script, stats)
|
|
325
|
+
if entry is not None:
|
|
326
|
+
slots += _top(ctx, mapper, entry, stats, ctx.col.mark())
|
|
327
|
+
stats["functions_total"] -= 1 # the run function is generated, not translated source
|
|
328
|
+
tree.body.append(entry)
|
|
329
|
+
propagate_mut(ctx, [s for s in slots if isinstance(s, Deferred)])
|
|
330
|
+
seeds = ctx.project.index.catchable if ctx.project is not None else None
|
|
331
|
+
escapes, propagates = analyze_raises(tree, ctx, seeds) # which functions return Result
|
|
332
|
+
for slot in slots:
|
|
333
|
+
if isinstance(slot, Deferred):
|
|
334
|
+
slot.sig.fallible = bool(escapes.get(slot.node.name))
|
|
335
|
+
slot.sig.raises = frozenset(escapes.get(slot.node.name, ()))
|
|
336
|
+
slot.sig.propagates = frozenset(propagates.get(slot.node.name, ()))
|
|
337
|
+
functions: set[str] = set()
|
|
338
|
+
for slot in slots:
|
|
339
|
+
if not isinstance(slot, Deferred):
|
|
340
|
+
module.items.append(slot)
|
|
341
|
+
continue
|
|
342
|
+
before = ctx.col.mark()
|
|
343
|
+
with ctx.col.enclosing(slot.node.name):
|
|
344
|
+
lowered = lower_function(ctx, mapper, slot.node, slot.sig, slot.ana)
|
|
345
|
+
module.items += [*mapper.flush(), *lowered]
|
|
346
|
+
if slot.node.name == SCRIPT_FN:
|
|
347
|
+
calls = [
|
|
348
|
+
ir.ExprS(ir.Call(func=ir.Path(path=path), args=[], ty=ir.UNIT))
|
|
349
|
+
for path in _dependency_inits(ctx)
|
|
350
|
+
]
|
|
351
|
+
for item in lowered: # imported modules run first, like Python's import
|
|
352
|
+
if isinstance(item, ir.Function) and item.name == SCRIPT_FN:
|
|
353
|
+
item.body = [*calls, *item.body]
|
|
354
|
+
module.items += _entry_items(ctx, slot.sig)
|
|
355
|
+
continue
|
|
356
|
+
functions.add(slot.node.name)
|
|
357
|
+
ctx.set_status(slot.node.name, before, slot.todos_sig == 0)
|
|
358
|
+
if ctx.cfg.tests:
|
|
359
|
+
with ctx.col.enclosing("tests"):
|
|
360
|
+
result = lower_tests(ctx, mapper, tree, ctx.col.file, test_module)
|
|
361
|
+
ctx.tests = result.entries
|
|
362
|
+
if result.items:
|
|
363
|
+
cfg_test = ir.Attribute("cfg", [("test", None)])
|
|
364
|
+
module.items.append(ir.ModItem("tests", result.items, [cfg_test], ["use super::*;"]))
|
|
365
|
+
first_async = next((n for n in tree.body if isinstance(n, ast.AsyncFunctionDef)), None)
|
|
366
|
+
if first_async is not None and ctx.cfg.shared == "rc":
|
|
367
|
+
ctx.col.diag(
|
|
368
|
+
"PY2RS060",
|
|
369
|
+
first_async,
|
|
370
|
+
"async code: handles are Rc; use shared = 'arc' if the runtime needs Send futures",
|
|
371
|
+
severity="info",
|
|
372
|
+
construct="shared",
|
|
373
|
+
)
|
|
374
|
+
_mark_recursion_drift(ctx, tree, functions)
|
|
375
|
+
dirty = _count_clean(ctx, tree, stats, functions)
|
|
376
|
+
stats["functions_clean_if_init_run"] = stats["functions_clean"]
|
|
377
|
+
stats["models_clean_if_init_run"] = stats["models_clean"]
|
|
378
|
+
cells = any(kind == "cell" for kind, *_ in ctx.value_steps.values())
|
|
379
|
+
if script.effects or cells:
|
|
380
|
+
stats["module_init_effects"] = 1
|
|
381
|
+
if not ctx.cfg.assume_module_init:
|
|
382
|
+
ctx.col.diag(
|
|
383
|
+
"PY2RS058",
|
|
384
|
+
script.first_effect,
|
|
385
|
+
"statements and values computed at import time run in py2rs_module_init()",
|
|
386
|
+
severity="info",
|
|
387
|
+
construct="module init",
|
|
388
|
+
)
|
|
389
|
+
stats["functions_clean"] = stats["models_clean"] = 0
|
|
390
|
+
stats["models_clean_modulo_int_range"] = 0
|
|
391
|
+
dirty = {*ctx.status}
|
|
392
|
+
return Build(module, stats, tuple(sorted(_rust_name(ctx, n) for n in dirty)))
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _rust_name(ctx: Ctx, name: str) -> str:
|
|
396
|
+
if name in ctx.sigs:
|
|
397
|
+
return ctx.sigs[name].rust
|
|
398
|
+
if name in ctx.models:
|
|
399
|
+
return ctx.models[name].rust
|
|
400
|
+
return const_name(name) if name.isupper() else camel(name)
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _run_function(
|
|
404
|
+
ctx: Ctx, script: Script, stats: Counter[str]
|
|
405
|
+
) -> ast.FunctionDef | ast.AsyncFunctionDef | None:
|
|
406
|
+
"""The synthetic `py2rs_run(py2rs_main)`: import-time statements and module value markers,
|
|
407
|
+
in source order."""
|
|
408
|
+
steps = [
|
|
409
|
+
(line, ast.Expr(ast.Call(ast.Name(VALUE_MARKER, ast.Load()), [ast.Constant(name)], [])))
|
|
410
|
+
for name, (kind, _, line) in ctx.value_steps.items()
|
|
411
|
+
if kind in ("cell", "stub")
|
|
412
|
+
]
|
|
413
|
+
ordered = sorted([*((st.lineno, st) for st in script.stmts), *steps], key=lambda pair: pair[0])
|
|
414
|
+
if not ordered and not _dependency_inits(ctx):
|
|
415
|
+
return None
|
|
416
|
+
if not ordered: # only imported modules to initialise
|
|
417
|
+
ordered = [(1, ast.Pass(lineno=1, col_offset=0, end_lineno=1, end_col_offset=0))]
|
|
418
|
+
nodes = []
|
|
419
|
+
for line, st in ordered:
|
|
420
|
+
st.lineno = st.end_lineno = line if isinstance(st, ast.Expr) else st.lineno
|
|
421
|
+
nodes.append(st)
|
|
422
|
+
return _synthetic(SCRIPT_FN, nodes, True)
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _dependency_inits(ctx: Ctx) -> list[str]:
|
|
426
|
+
"""Rust paths of the `py2rs_module_init` of the imported project modules that have one, in the
|
|
427
|
+
order Python imports them."""
|
|
428
|
+
if ctx.project is None:
|
|
429
|
+
return []
|
|
430
|
+
index = ctx.project.index
|
|
431
|
+
return [
|
|
432
|
+
f"{index.rust_path(dep)}::py2rs_module_init"
|
|
433
|
+
for dep in ctx.init_deps
|
|
434
|
+
if dep != ctx.project.module and dep in index.modules and index.modules[dep].has_init
|
|
435
|
+
]
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _mark_recursion_drift(ctx: Ctx, tree: ast.Module, functions: set[str]) -> None:
|
|
439
|
+
nodes = {
|
|
440
|
+
n.name: n
|
|
441
|
+
for n in tree.body
|
|
442
|
+
if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef) and n.name in functions
|
|
443
|
+
}
|
|
444
|
+
graph = TopologicalSorter(
|
|
445
|
+
{
|
|
446
|
+
name: {
|
|
447
|
+
call.func.id
|
|
448
|
+
for call in ast.walk(node)
|
|
449
|
+
if isinstance(call, ast.Call)
|
|
450
|
+
and isinstance(call.func, ast.Name)
|
|
451
|
+
and call.func.id in nodes
|
|
452
|
+
}
|
|
453
|
+
for name, node in nodes.items()
|
|
454
|
+
}
|
|
455
|
+
)
|
|
456
|
+
with suppress(CycleError):
|
|
457
|
+
graph.prepare() # acyclic functions can still be removed
|
|
458
|
+
remaining = set(nodes)
|
|
459
|
+
while ready := graph.get_ready():
|
|
460
|
+
remaining.difference_update(ready)
|
|
461
|
+
graph.done(*ready)
|
|
462
|
+
for name in sorted(remaining):
|
|
463
|
+
with ctx.col.enclosing(name):
|
|
464
|
+
ctx.col.drift("PY2RS061", nodes[name], "recursive calls")
|
|
465
|
+
ctx.status[name] = ctx.status_mod[name] = False
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _count_clean(ctx: Ctx, tree: ast.Module, stats: Counter[str], functions: set[str]) -> set[str]:
|
|
469
|
+
"""clean = no TODO or unenforced behaviour of its own, and no reference to a symbol that has
|
|
470
|
+
one (transitively; cycle-safe): its translation is only as good as what it uses."""
|
|
471
|
+
refs: dict[str, set[str]] = {}
|
|
472
|
+
for node in tree.body:
|
|
473
|
+
name = getattr(node, "name", None) or (
|
|
474
|
+
node.targets[0].id
|
|
475
|
+
if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name)
|
|
476
|
+
else node.target.id
|
|
477
|
+
if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name)
|
|
478
|
+
else None
|
|
479
|
+
)
|
|
480
|
+
if name in ctx.status:
|
|
481
|
+
used = {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
|
|
482
|
+
refs[name] = (used | _string_names(node)) & set(ctx.status) - {name}
|
|
483
|
+
|
|
484
|
+
def spread(status: dict[str, bool]) -> set[str]:
|
|
485
|
+
dirty = {n for n, clean in status.items() if not clean}
|
|
486
|
+
changed = True
|
|
487
|
+
while changed:
|
|
488
|
+
changed = False
|
|
489
|
+
for name, uses in refs.items():
|
|
490
|
+
if name not in dirty and uses & dirty:
|
|
491
|
+
dirty.add(name)
|
|
492
|
+
changed = True
|
|
493
|
+
return dirty
|
|
494
|
+
|
|
495
|
+
strict, modulo = spread(ctx.status), spread(ctx.status_mod)
|
|
496
|
+
stats["functions_clean"] += len(functions - modulo) # int ranges only concern model input
|
|
497
|
+
stats["models_clean"] += len(ctx.model_names - strict)
|
|
498
|
+
stats["models_clean_modulo_int_range"] += len(ctx.model_names - modulo)
|
|
499
|
+
for name in ctx.model_names & set(ctx.models):
|
|
500
|
+
ctx.models[name].dirty = name in modulo
|
|
501
|
+
return (
|
|
502
|
+
(functions & modulo)
|
|
503
|
+
| (ctx.model_names & strict)
|
|
504
|
+
| {n for n in modulo | strict if n not in functions and n not in ctx.model_names}
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _string_names(node: ast.AST) -> set[str]:
|
|
509
|
+
"""Identifiers inside string annotations (`"Span"`)."""
|
|
510
|
+
out: set[str] = set()
|
|
511
|
+
for n in ast.walk(node):
|
|
512
|
+
if isinstance(n, ast.Constant) and isinstance(n.value, str) and n.value.isidentifier():
|
|
513
|
+
out.add(n.value)
|
|
514
|
+
return out
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
SCRIPT_FN = "py2rs_run" # the import-time statements of a module, in source order
|
|
518
|
+
VALUE_MARKER = "__py2rs_value__" # `__py2rs_value__("NAME")`: where a module value is assigned
|
|
519
|
+
MAIN_FLAG = "py2rs_main" # parameter of the run function: true for `python module.py`
|
|
520
|
+
PURE_CALLS = {
|
|
521
|
+
"len", "str", "int", "float", "bool", "list", "dict", "set", "tuple", "frozenset", "sorted",
|
|
522
|
+
"min", "max", "sum", "abs", "range", "enumerate", "zip", "reversed", "any", "all", "round",
|
|
523
|
+
"repr", "ord", "chr", "bytes", "isinstance",
|
|
524
|
+
} # fmt: skip
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
@dataclass
|
|
528
|
+
class Script:
|
|
529
|
+
keep: list[ast.stmt] # definitions and module values, in order
|
|
530
|
+
stmts: list[ast.stmt] = field(
|
|
531
|
+
default_factory=list
|
|
532
|
+
) # run at import time (main guards rewritten)
|
|
533
|
+
volatile: set[str] = field(default_factory=set) # module names assigned more than once
|
|
534
|
+
async_entry: bool = False # the script calls asyncio.run(..)
|
|
535
|
+
effects: bool = False # statements other than the main guard run at import time
|
|
536
|
+
first_effect: ast.stmt | None = None
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _is_definition(stmt: ast.stmt) -> bool:
|
|
540
|
+
if isinstance(stmt, ast.Import | ast.ImportFrom | ast.ClassDef | ast.TypeAlias):
|
|
541
|
+
return True
|
|
542
|
+
if isinstance(stmt, ast.FunctionDef | ast.AsyncFunctionDef):
|
|
543
|
+
return True
|
|
544
|
+
if isinstance(stmt, ast.Expr):
|
|
545
|
+
return isinstance(stmt.value, ast.Constant) # docstrings and bare literals
|
|
546
|
+
if isinstance(stmt, ast.Assign):
|
|
547
|
+
return len(stmt.targets) == 1 and isinstance(stmt.targets[0], ast.Name)
|
|
548
|
+
return (
|
|
549
|
+
isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name) and bool(stmt.value)
|
|
550
|
+
)
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _is_main_block(stmt: ast.stmt) -> bool:
|
|
554
|
+
if not isinstance(stmt, ast.If) or stmt.orelse:
|
|
555
|
+
return False
|
|
556
|
+
t = stmt.test
|
|
557
|
+
return (
|
|
558
|
+
isinstance(t, ast.Compare)
|
|
559
|
+
and isinstance(t.left, ast.Name)
|
|
560
|
+
and t.left.id == "__name__"
|
|
561
|
+
and len(t.ops) == 1
|
|
562
|
+
and isinstance(t.ops[0], ast.Eq)
|
|
563
|
+
and isinstance(t.comparators[0], ast.Constant)
|
|
564
|
+
and t.comparators[0].value == "__main__"
|
|
565
|
+
)
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
class _AsyncRun(ast.NodeTransformer):
|
|
569
|
+
"""`asyncio.run(coro)` at the top level of a script is an `await` in its async entry point."""
|
|
570
|
+
|
|
571
|
+
found = False
|
|
572
|
+
|
|
573
|
+
def visit_Call(self, node: ast.Call) -> ast.AST:
|
|
574
|
+
self.generic_visit(node)
|
|
575
|
+
if dotted(node.func) == "asyncio.run" and len(node.args) == 1 and not node.keywords:
|
|
576
|
+
self.found = True
|
|
577
|
+
return ast.copy_location(ast.Await(value=node.args[0]), node)
|
|
578
|
+
return node
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _synthetic(
|
|
582
|
+
name: str, stmts: list[ast.stmt], main_flag: bool = False
|
|
583
|
+
) -> ast.FunctionDef | ast.AsyncFunctionDef:
|
|
584
|
+
rewrite = _AsyncRun()
|
|
585
|
+
stmts = [rewrite.visit(s) for s in stmts]
|
|
586
|
+
make = ast.AsyncFunctionDef if rewrite.found else ast.FunctionDef
|
|
587
|
+
flag = ast.arg(arg=MAIN_FLAG, annotation=ast.Name(id="bool", ctx=ast.Load()))
|
|
588
|
+
fn = make(
|
|
589
|
+
name=name,
|
|
590
|
+
args=ast.arguments(
|
|
591
|
+
posonlyargs=[],
|
|
592
|
+
args=[flag] if main_flag else [],
|
|
593
|
+
kwonlyargs=[],
|
|
594
|
+
kw_defaults=[],
|
|
595
|
+
defaults=[],
|
|
596
|
+
),
|
|
597
|
+
body=stmts,
|
|
598
|
+
decorator_list=[],
|
|
599
|
+
returns=ast.Constant(None),
|
|
600
|
+
type_params=[],
|
|
601
|
+
)
|
|
602
|
+
ast.copy_location(fn, stmts[0])
|
|
603
|
+
return ast.fix_missing_locations(fn)
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def _stored_names(stmts: list[ast.stmt], top: bool, counts: Counter[str], nested: set[str]) -> None:
|
|
607
|
+
"""Names a module-level statement assigns (nested: inside a loop, branch or with block)."""
|
|
608
|
+
|
|
609
|
+
def names(t: ast.AST) -> list[str]:
|
|
610
|
+
return [n.id for n in ast.walk(t) if isinstance(n, ast.Name)]
|
|
611
|
+
|
|
612
|
+
for s in stmts:
|
|
613
|
+
found: list[str] = []
|
|
614
|
+
match s:
|
|
615
|
+
case ast.Assign():
|
|
616
|
+
found = [n for t in s.targets for n in names(t)]
|
|
617
|
+
case ast.AnnAssign() if s.value is not None:
|
|
618
|
+
found = names(s.target)
|
|
619
|
+
case ast.AugAssign():
|
|
620
|
+
found = names(s.target)
|
|
621
|
+
nested.update(found) # `x += 1` always changes an existing value
|
|
622
|
+
case ast.For() | ast.AsyncFor():
|
|
623
|
+
found = names(s.target)
|
|
624
|
+
for n in found:
|
|
625
|
+
counts[n] += 1
|
|
626
|
+
if not top:
|
|
627
|
+
nested.add(n)
|
|
628
|
+
if isinstance(s, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
|
|
629
|
+
continue
|
|
630
|
+
for block in ("body", "orelse", "finalbody"):
|
|
631
|
+
inner = getattr(s, block, None)
|
|
632
|
+
if isinstance(inner, list) and inner and isinstance(inner[0], ast.stmt):
|
|
633
|
+
_stored_names(inner, False, counts, nested)
|
|
634
|
+
for h in getattr(s, "handlers", []):
|
|
635
|
+
_stored_names(h.body, False, counts, nested)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def _split_script(tree: ast.Module, body: list[ast.stmt], ctx: Ctx) -> Script:
|
|
639
|
+
"""Module-level statements that are not definitions run at import time in Python. Rust has no
|
|
640
|
+
such thing: they become `py2rs_run(main)` (in source order, with module values assigned where
|
|
641
|
+
Python assigns them), run once through `py2rs_module_init()` or `py2rs_main()`."""
|
|
642
|
+
script = Script([])
|
|
643
|
+
for stmt in body:
|
|
644
|
+
if _is_main_block(stmt):
|
|
645
|
+
assert isinstance(stmt, ast.If)
|
|
646
|
+
guard = ast.If(test=ast.Name(id=MAIN_FLAG, ctx=ast.Load()), body=stmt.body, orelse=[])
|
|
647
|
+
script.stmts.append(ast.copy_location(guard, stmt))
|
|
648
|
+
elif _is_definition(stmt):
|
|
649
|
+
script.keep.append(stmt)
|
|
650
|
+
else:
|
|
651
|
+
script.stmts.append(stmt)
|
|
652
|
+
if not script.effects:
|
|
653
|
+
script.effects, script.first_effect = True, stmt
|
|
654
|
+
counts: Counter[str] = Counter()
|
|
655
|
+
nested: set[str] = set()
|
|
656
|
+
_stored_names(body, True, counts, nested)
|
|
657
|
+
script.volatile = {n for n, c in counts.items() if c > 1} | nested
|
|
658
|
+
script.async_entry = any(
|
|
659
|
+
isinstance(n, ast.Call) and dotted(n.func) == "asyncio.run"
|
|
660
|
+
for st in script.stmts
|
|
661
|
+
for n in ast.walk(st)
|
|
662
|
+
)
|
|
663
|
+
tree.body = script.keep
|
|
664
|
+
return script
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def _effectful(ctx: Ctx, value: ast.expr) -> bool:
|
|
668
|
+
"""Does computing a module value run code with side effects (a call of a module function)?"""
|
|
669
|
+
for n in ast.walk(value):
|
|
670
|
+
if isinstance(n, ast.Call):
|
|
671
|
+
name = dotted(n.func)
|
|
672
|
+
if isinstance(n.func, ast.Name) and n.func.id in PURE_CALLS:
|
|
673
|
+
continue
|
|
674
|
+
if name in ctx.cfg.library_map or ctx.library_entry(name):
|
|
675
|
+
continue
|
|
676
|
+
if isinstance(n.func, ast.Name) and (n.func.id in ctx.models or n.func.id in ctx.enums):
|
|
677
|
+
continue
|
|
678
|
+
if isinstance(n.func, ast.Attribute):
|
|
679
|
+
continue # a method call on a value
|
|
680
|
+
return True
|
|
681
|
+
return False
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def _entry_items(ctx: Ctx, sig: FuncSig) -> list[ir.Item]:
|
|
685
|
+
"""`py2rs_module_init()` and `py2rs_main()`: the idempotent entry points of the run function."""
|
|
686
|
+
|
|
687
|
+
def run(main: bool) -> ir.RExpr:
|
|
688
|
+
call: ir.RExpr = ir.Call(
|
|
689
|
+
func=ir.Path(path=SCRIPT_FN), args=[ir.lit("bool", main, BOOL)], ty=ir.UNIT
|
|
690
|
+
)
|
|
691
|
+
if sig.is_async:
|
|
692
|
+
call = ir.AwaitX(operand=call, ty=ir.UNIT)
|
|
693
|
+
if sig.fallible:
|
|
694
|
+
call = ir.Call(func=ir.Path(path="rt::or_panic"), args=[call], ty=ir.UNIT)
|
|
695
|
+
return call
|
|
696
|
+
|
|
697
|
+
items: list[ir.Item] = []
|
|
698
|
+
if sig.is_async: # no idempotence guard: a Once cannot wrap an async block
|
|
699
|
+
for name, main in (("py2rs_module_init", False), ("py2rs_main", True)):
|
|
700
|
+
items.append(ir.Function(name, [], ir.UNIT, [ir.ExprS(run(main))], is_async=True))
|
|
701
|
+
return items
|
|
702
|
+
items.append(
|
|
703
|
+
ir.Const(
|
|
704
|
+
"PY2RS_INIT",
|
|
705
|
+
T("rt::ModuleInit"),
|
|
706
|
+
ir.Path(path="rt::ModuleInit::new()"),
|
|
707
|
+
"static_plain",
|
|
708
|
+
"",
|
|
709
|
+
)
|
|
710
|
+
)
|
|
711
|
+
for name, helper, main in (
|
|
712
|
+
("py2rs_module_init", "module_init", False),
|
|
713
|
+
("py2rs_main", "module_main", True),
|
|
714
|
+
):
|
|
715
|
+
guarded = ir.Call(
|
|
716
|
+
func=ir.Path(path=f"rt::{helper}"),
|
|
717
|
+
args=[
|
|
718
|
+
ir.Ref(operand=ir.Path(path="PY2RS_INIT")),
|
|
719
|
+
ir.Closure(params=[], body=run(main)),
|
|
720
|
+
],
|
|
721
|
+
ty=ir.UNIT,
|
|
722
|
+
)
|
|
723
|
+
items.append(ir.Function(name, [], ir.UNIT, [ir.ExprS(guarded)]))
|
|
724
|
+
return items
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def _is_fixture(stmt: ast.stmt) -> bool:
|
|
728
|
+
return isinstance(stmt, ast.FunctionDef | ast.AsyncFunctionDef) and is_fixture(stmt)
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
def _top(
|
|
732
|
+
ctx: Ctx, mapper: TypeMapper, stmt: ast.stmt, stats: Counter[str], start: tuple[int, int, int]
|
|
733
|
+
) -> list[ir.Item | Deferred]:
|
|
734
|
+
if isinstance(stmt, (ast.Import, ast.ImportFrom)):
|
|
735
|
+
return [*lower_import(ctx, stmt)]
|
|
736
|
+
if isinstance(stmt, ast.ClassDef):
|
|
737
|
+
res = lower_class(ctx, mapper, stmt)
|
|
738
|
+
stats["functions_total"] += res.methods
|
|
739
|
+
if res.is_model:
|
|
740
|
+
stats["models_total"] += 1
|
|
741
|
+
ctx.model_names.add(stmt.name)
|
|
742
|
+
ctx.set_status(stmt.name, start)
|
|
743
|
+
return [*res.items]
|
|
744
|
+
if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
745
|
+
stats["functions_total"] += 1
|
|
746
|
+
try:
|
|
747
|
+
ana = analyze(
|
|
748
|
+
stmt,
|
|
749
|
+
{a.arg for a in stmt.args.posonlyargs + stmt.args.args + stmt.args.kwonlyargs}
|
|
750
|
+
| {a.arg for a in (stmt.args.vararg, stmt.args.kwarg) if a},
|
|
751
|
+
)
|
|
752
|
+
sig = build_sig(ctx, mapper, stmt, ana)
|
|
753
|
+
except Unsupported as exc:
|
|
754
|
+
return [todo_item(ctx, exc.code, exc.node or stmt, exc.construct)]
|
|
755
|
+
if stmt.name != SCRIPT_FN: # the entry point is not an importable name
|
|
756
|
+
ctx.sigs[stmt.name] = sig
|
|
757
|
+
return [
|
|
758
|
+
*mapper.flush(),
|
|
759
|
+
Deferred(stmt, sig, ana, start[0], int(not ctx.col.clean_since(start))),
|
|
760
|
+
]
|
|
761
|
+
if isinstance(stmt, ast.TypeAlias):
|
|
762
|
+
return _alias(ctx, mapper, stmt.name.id, stmt.value, stmt)
|
|
763
|
+
if (
|
|
764
|
+
isinstance(stmt, ast.Assign)
|
|
765
|
+
and len(stmt.targets) == 1
|
|
766
|
+
and isinstance(stmt.targets[0], ast.Name)
|
|
767
|
+
):
|
|
768
|
+
return _assign(ctx, mapper, stmt.targets[0].id, None, stmt.value, stmt, stats, start)
|
|
769
|
+
if (
|
|
770
|
+
isinstance(stmt, ast.AnnAssign)
|
|
771
|
+
and isinstance(stmt.target, ast.Name)
|
|
772
|
+
and stmt.value is not None
|
|
773
|
+
):
|
|
774
|
+
if dotted(stmt.annotation).split(".")[-1] == "TypeAlias":
|
|
775
|
+
return _alias(ctx, mapper, stmt.target.id, stmt.value, stmt)
|
|
776
|
+
return _assign(ctx, mapper, stmt.target.id, stmt.annotation, stmt.value, stmt, stats, start)
|
|
777
|
+
if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant):
|
|
778
|
+
return []
|
|
779
|
+
what = (
|
|
780
|
+
"if __name__ == '__main__'"
|
|
781
|
+
if _is_main_guard(stmt)
|
|
782
|
+
else f"module-level {type(stmt).__name__}"
|
|
783
|
+
)
|
|
784
|
+
return [todo_item(ctx, "PY2RS003", stmt, what)]
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
def _is_main_guard(stmt: ast.stmt) -> bool:
|
|
788
|
+
return (
|
|
789
|
+
isinstance(stmt, ast.If)
|
|
790
|
+
and isinstance(stmt.test, ast.Compare)
|
|
791
|
+
and "__name__" in ast.unparse(stmt.test)
|
|
792
|
+
)
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
def _assign(
|
|
796
|
+
ctx: Ctx,
|
|
797
|
+
mapper: TypeMapper,
|
|
798
|
+
name: str,
|
|
799
|
+
ann: ast.expr | None,
|
|
800
|
+
value: ast.expr,
|
|
801
|
+
stmt: ast.stmt,
|
|
802
|
+
stats: Counter[str],
|
|
803
|
+
start: tuple[int, int, int],
|
|
804
|
+
) -> list[ir.Item | Deferred]:
|
|
805
|
+
if name == "__all__":
|
|
806
|
+
return []
|
|
807
|
+
if isinstance(value, ast.Call) and dotted(value.func).split(".")[-1] in LOGGER_FACTORIES:
|
|
808
|
+
ctx.loggers.add(
|
|
809
|
+
name
|
|
810
|
+
) # `logger = logging.getLogger(...)`: logger calls become tracing macros
|
|
811
|
+
return []
|
|
812
|
+
if isinstance(value, ast.Call) and dotted(value.func).split(".")[-1] == "NewType":
|
|
813
|
+
assert isinstance(stmt, ast.Assign)
|
|
814
|
+
newtype = lower_newtype(ctx, mapper, stmt)
|
|
815
|
+
stats["models_total"] += 1
|
|
816
|
+
ctx.model_names.add(name)
|
|
817
|
+
ctx.set_status(name, start)
|
|
818
|
+
return [*newtype]
|
|
819
|
+
if ann is None and looks_like_type(ctx, value):
|
|
820
|
+
return _alias(ctx, mapper, name, value, stmt)
|
|
821
|
+
items: list[ir.Item | Deferred] = []
|
|
822
|
+
if name in ctx.volatile:
|
|
823
|
+
message = f"module value {name} is assigned more than once"
|
|
824
|
+
items.append(todo_item(ctx, "PY2RS032", stmt, message, "const"))
|
|
825
|
+
elif _effectful(ctx, value):
|
|
826
|
+
items.extend(lower_cell(ctx, mapper, name, ann, value, stmt))
|
|
827
|
+
else:
|
|
828
|
+
items.extend(lower_const(ctx, mapper, name, ann, value, stmt))
|
|
829
|
+
for item in items:
|
|
830
|
+
if isinstance(item, ir.TodoItem):
|
|
831
|
+
ident = "".join(c if c.isalnum() else "_" for c in item.marker.split()[1])
|
|
832
|
+
ctx.value_steps[name] = ("stub", ident, stmt.lineno)
|
|
833
|
+
ctx.status[name] = ctx.status_mod[name] = False
|
|
834
|
+
return items
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
def lower_cell(
|
|
838
|
+
ctx: Ctx, mapper: TypeMapper, name: str, ann: ast.expr | None, value: ast.expr, stmt: ast.stmt
|
|
839
|
+
) -> list[ir.Item]:
|
|
840
|
+
"""A module value computed by a call: assigned by `py2rs_run` where Python assigns it, read
|
|
841
|
+
through an accessor that runs the module init first when it has not run yet."""
|
|
842
|
+
rust = const_name(name)
|
|
843
|
+
span = ir.span_of(stmt, ctx.col.file)
|
|
844
|
+
try:
|
|
845
|
+
if ctx.async_entry:
|
|
846
|
+
raise Unsupported(
|
|
847
|
+
"PY2RS032", f"module value {name} in a module that runs asyncio.run", stmt
|
|
848
|
+
)
|
|
849
|
+
lw = CallLowerer(ctx, mapper)
|
|
850
|
+
e = lw.expr(value) # only for its type: the statement is lowered in py2rs_run
|
|
851
|
+
declared = mapper.map(ann, rust) if ann is not None else None
|
|
852
|
+
ty = declared if declared is not None and declared.known else peel(e.ty)
|
|
853
|
+
if not ty.known or ty.name in ("Iter", "Fn", "Future"):
|
|
854
|
+
raise Unsupported("PY2RS032", f"module value {name} has no usable type", stmt)
|
|
855
|
+
except Unsupported as exc:
|
|
856
|
+
return [todo_item(ctx, "PY2RS032", stmt, exc.construct, "const")]
|
|
857
|
+
accessor = f"py2rs_get_{rust.lower()}"
|
|
858
|
+
local = lw.shared and lw.mutable_ty(ty) and ctx.cfg.shared != "arc" # Rc is not Sync
|
|
859
|
+
ty = lw.store_ty(ty)
|
|
860
|
+
ctx.value_steps[name] = ("cell", (value, ty, local), stmt.lineno)
|
|
861
|
+
args: list[ir.RExpr] = [
|
|
862
|
+
ir.Ref(operand=ir.Path(path=rust)),
|
|
863
|
+
ir.lit("str", name, STR),
|
|
864
|
+
ir.Path(path="py2rs_module_init"),
|
|
865
|
+
]
|
|
866
|
+
if local:
|
|
867
|
+
ctx.consts[name] = ConstInfo(f"{accessor}()", ty, False, accessor)
|
|
868
|
+
cell_ty = T(f"std::cell::OnceCell<{ty.rust()}>")
|
|
869
|
+
cell = ir.Const(
|
|
870
|
+
rust, cell_ty, ir.Path(path="std::cell::OnceCell::new()"), "thread_static", "pub ",
|
|
871
|
+
span=span,
|
|
872
|
+
) # fmt: skip
|
|
873
|
+
fetch = ir.Call(func=ir.Path(path="rt::module_value_tl"), args=args, ty=ty)
|
|
874
|
+
return [cell, ir.Function(accessor, [], ty, [ir.Return(fetch, True)])]
|
|
875
|
+
ctx.consts[name] = ConstInfo(f"{accessor}()", ty, True, accessor)
|
|
876
|
+
cell = ir.Const(rust, ty, ir.Path(path="std::sync::OnceLock::new()"), "cell", "pub ", span=span)
|
|
877
|
+
ref_ty = T(f"&'static {ty.rust()}")
|
|
878
|
+
fetch = ir.Call(func=ir.Path(path="rt::module_value"), args=args, ty=ref_ty)
|
|
879
|
+
return [cell, ir.Function(accessor, [], ref_ty, [ir.Return(fetch, True)])]
|
|
880
|
+
|
|
881
|
+
|
|
882
|
+
def _alias(
|
|
883
|
+
ctx: Ctx, mapper: TypeMapper, name: str, value: ast.expr, stmt: ast.stmt
|
|
884
|
+
) -> list[ir.Item | Deferred]:
|
|
885
|
+
ty, meta = mapper.map_meta(value, name)
|
|
886
|
+
ctx.aliases[name] = ty
|
|
887
|
+
items: list[ir.Item | Deferred] = [*mapper.flush()]
|
|
888
|
+
if meta:
|
|
889
|
+
ctx.alias_meta[name] = meta
|
|
890
|
+
for m in meta:
|
|
891
|
+
if not enforceable_meta(m):
|
|
892
|
+
what = f"{name}: annotation metadata {ast.unparse(m)} is not translated"
|
|
893
|
+
items.append(todo_item(ctx, "PY2RS018", stmt, what, "config"))
|
|
894
|
+
if ty.name != camel(name): # `Mode = Literal[...]` already generated an enum called Mode
|
|
895
|
+
items.append(ir.TypeAlias(camel(name), ty, span=ir.span_of(stmt, ctx.col.file)))
|
|
896
|
+
return items
|