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,223 @@
|
|
|
1
|
+
"""Module-level translation context: symbol tables, imports and source comments."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import io
|
|
7
|
+
import tokenize
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
10
|
+
|
|
11
|
+
from ..config import Config
|
|
12
|
+
from ..diagnostics import Collector
|
|
13
|
+
from ..ir import nodes as ir
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from ..frontend.symbols import ProjectContext, Symbol
|
|
17
|
+
|
|
18
|
+
from ..frontend.names import mangle
|
|
19
|
+
from ..ir.rtypes import BOOL, BYTES, FLOAT, INT, STR, UNIT, UNKNOWN, VALUE, RType, T, option
|
|
20
|
+
|
|
21
|
+
# Imports the type system consumes itself: they never produce output or diagnostics.
|
|
22
|
+
CONSUMED_MODULES = frozenset(
|
|
23
|
+
{
|
|
24
|
+
"__future__", "typing", "typing_extensions", "dataclasses", "enum", "pydantic",
|
|
25
|
+
"collections.abc", "abc", "types", "annotated_types", "pytest", "unittest", "doctest", "contextlib", "logging", "structlog",
|
|
26
|
+
}
|
|
27
|
+
) # fmt: skip
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parse_type_spec(spec: str) -> RType:
|
|
31
|
+
"""Library-map `returns`: int float str bool value bytes unit, option:X, vec:X, type:<rust>."""
|
|
32
|
+
base = {
|
|
33
|
+
"int": INT, "float": FLOAT, "str": STR, "bool": BOOL, "value": VALUE, "bytes": BYTES,
|
|
34
|
+
"unit": UNIT,
|
|
35
|
+
} # fmt: skip
|
|
36
|
+
if spec in base:
|
|
37
|
+
return base[spec]
|
|
38
|
+
if spec.startswith("option:"):
|
|
39
|
+
return option(parse_type_spec(spec[7:]))
|
|
40
|
+
if spec.startswith("vec:"):
|
|
41
|
+
return T("Vec", parse_type_spec(spec[4:]))
|
|
42
|
+
if spec.startswith("type:"):
|
|
43
|
+
return T(spec[5:])
|
|
44
|
+
return UNKNOWN
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class ParamSig:
|
|
49
|
+
name: str
|
|
50
|
+
rust: str
|
|
51
|
+
ty: RType
|
|
52
|
+
conv: str = "" # "" by value, "&" shared borrow, "&mut" mutable borrow
|
|
53
|
+
default: ast.expr | None = None
|
|
54
|
+
kind: str = "pos" # "pos" | "kwonly" | "vararg" | "kwarg"
|
|
55
|
+
mutable: bool = False
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class FuncSig:
|
|
60
|
+
name: str
|
|
61
|
+
rust: str
|
|
62
|
+
params: list[ParamSig]
|
|
63
|
+
ret: RType
|
|
64
|
+
fallible: bool = False # an exception can escape: the Rust function returns Result
|
|
65
|
+
raises: frozenset[str] = frozenset() # exception classes that can escape (callers use it)
|
|
66
|
+
propagates: frozenset[str] = frozenset() # built-in errors reported as Result (lowering)
|
|
67
|
+
is_async: bool = False
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass
|
|
71
|
+
class FieldInfo:
|
|
72
|
+
py_name: str
|
|
73
|
+
rust: str
|
|
74
|
+
ty: RType
|
|
75
|
+
default: ir.RExpr | None # Rust expression used when the field is omitted, None if required
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass
|
|
79
|
+
class ModelInfo:
|
|
80
|
+
rust: str
|
|
81
|
+
fields: dict[str, FieldInfo] = field(default_factory=dict)
|
|
82
|
+
ir_fields: list = field(default_factory=list) # ir.FieldDef copies, for subclasses
|
|
83
|
+
newtype: RType | None = None
|
|
84
|
+
source: str = "model" # model | dataclass | typeddict | namedtuple
|
|
85
|
+
unchecked: bool = False # something Pydantic does is not translated (validators, options)
|
|
86
|
+
validated: bool = False # constraints/transforms: a struct literal would skip them
|
|
87
|
+
config: object = None # validation.ModelFlags, inherited by subclasses
|
|
88
|
+
frozen: bool = False # attribute assignment raises in Python (frozen model/dataclass)
|
|
89
|
+
dirty: bool = False # not clean: a TODO or unenforced behaviour (subclasses inherit it)
|
|
90
|
+
inexact: bool = False # parsing differs from Pydantic for some inputs (drift on a field)
|
|
91
|
+
aliased: bool = False # some field's wire name differs from its Python name
|
|
92
|
+
binary: bool = False # has bytes fields
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass
|
|
96
|
+
class EnumInfo:
|
|
97
|
+
rust: str
|
|
98
|
+
members: dict[str, str] = field(default_factory=dict) # python member -> Rust variant
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass
|
|
102
|
+
class ConstInfo:
|
|
103
|
+
rust: str # the path expression, e.g. `LIMIT` or `&*TABLE`
|
|
104
|
+
ty: RType
|
|
105
|
+
borrowed: bool = False # const/static item: already `&T`, converted when moved
|
|
106
|
+
accessor: str | None = None # a module value read through `accessor()` (import that name)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass
|
|
110
|
+
class Ctx:
|
|
111
|
+
cfg: Config
|
|
112
|
+
col: Collector
|
|
113
|
+
sigs: dict[str, FuncSig] = field(default_factory=dict)
|
|
114
|
+
models: dict[str, ModelInfo] = field(default_factory=dict)
|
|
115
|
+
enums: dict[str, EnumInfo] = field(default_factory=dict)
|
|
116
|
+
lit_enums: dict[str, dict[object, str]] = field(
|
|
117
|
+
default_factory=dict
|
|
118
|
+
) # rust enum -> value -> variant
|
|
119
|
+
unions: dict[str, list[tuple[str, RType]]] = field(default_factory=dict) # untagged enums
|
|
120
|
+
aliases: dict[str, RType] = field(default_factory=dict)
|
|
121
|
+
consts: dict[str, ConstInfo] = field(default_factory=dict)
|
|
122
|
+
imports: dict[str, str] = field(default_factory=dict) # local name -> dotted original
|
|
123
|
+
opaque: set[str] = field(default_factory=set) # names imported through import_map
|
|
124
|
+
uses: list[str] = field(default_factory=list) # `use` lines from import_map
|
|
125
|
+
tests: list = field(default_factory=list) # tests.TestEntry rows
|
|
126
|
+
exceptions: dict[str, str | None] = field(default_factory=dict) # exception class -> parent
|
|
127
|
+
project: ProjectContext | None = None # set in project mode
|
|
128
|
+
module_aliases: dict[str, str] = field(default_factory=dict) # local name -> project module
|
|
129
|
+
imported_names: set[str] = field(default_factory=set) # names that came from project imports
|
|
130
|
+
reexports: dict[str, tuple[str, str]] = field(default_factory=dict) # local -> (module, name)
|
|
131
|
+
unresolved: dict[str, int] = field(default_factory=dict) # missing project module -> count
|
|
132
|
+
imports_unmapped: dict[str, int] = field(
|
|
133
|
+
default_factory=dict
|
|
134
|
+
) # root module -> unmapped imports
|
|
135
|
+
features: set[str] = field(default_factory=set) # python2rust-rt features the output needs
|
|
136
|
+
loggers: set[str] = field(default_factory=set) # module-level names bound to a logger
|
|
137
|
+
init_deps: list[str] = field(default_factory=list) # project modules imported, in import order
|
|
138
|
+
volatile: set[str] = field(default_factory=set) # module names assigned more than once
|
|
139
|
+
async_entry: bool = False # the module script calls asyncio.run
|
|
140
|
+
value_steps: dict[str, tuple[str, object, int]] = field(default_factory=dict) # name -> step
|
|
141
|
+
status: dict[str, bool] = field(default_factory=dict) # module item -> own clean
|
|
142
|
+
status_mod: dict[str, bool] = field(default_factory=dict) # ... ignoring the i64 model limit
|
|
143
|
+
model_names: set[str] = field(default_factory=set)
|
|
144
|
+
mutated_globals: set[str] = field(default_factory=set) # module names that functions mutate
|
|
145
|
+
templates: int = 0 # ir.Template uses: the one place user-supplied Rust text enters the IR
|
|
146
|
+
schemas: list[str] = field(default_factory=list) # Rust names deriving ToSchema (for api_docs)
|
|
147
|
+
alias_meta: dict[str, list[ast.expr]] = field(
|
|
148
|
+
default_factory=dict
|
|
149
|
+
) # Annotated[...] metadata of aliases
|
|
150
|
+
_comments: list[tuple[int, str]] = field(default_factory=list)
|
|
151
|
+
|
|
152
|
+
def load_comments(self) -> None:
|
|
153
|
+
"""Collect whole-line comments so they can be re-attached before the next statement."""
|
|
154
|
+
try:
|
|
155
|
+
tokens = list(tokenize.generate_tokens(io.StringIO(self.col.source).readline))
|
|
156
|
+
except tokenize.TokenError, SyntaxError:
|
|
157
|
+
return
|
|
158
|
+
lines = self.col.source.splitlines()
|
|
159
|
+
for tok in tokens:
|
|
160
|
+
if tok.type == tokenize.COMMENT and lines[tok.start[0] - 1].lstrip().startswith("#"):
|
|
161
|
+
text = tok.string.lstrip("#").strip()
|
|
162
|
+
if not text.startswith(("!", "type:", "noqa", "fmt:")):
|
|
163
|
+
self._comments.append((tok.start[0], text))
|
|
164
|
+
|
|
165
|
+
def take_comments(self, after: int, before: int) -> list[str]:
|
|
166
|
+
"""Pop (in order) the pending comments on lines strictly between `after` and `before`."""
|
|
167
|
+
taken = [f"// {text}".rstrip() for line, text in self._comments if after < line < before]
|
|
168
|
+
self._comments = [c for c in self._comments if not after < c[0] < before]
|
|
169
|
+
return taken
|
|
170
|
+
|
|
171
|
+
def derives(self, *base: str, schema: bool = True) -> list[str]:
|
|
172
|
+
"""Derive list for a generated type; adds ToSchema when schema generation is on."""
|
|
173
|
+
out = list(base)
|
|
174
|
+
if schema and self.cfg.schema_enabled:
|
|
175
|
+
out.append("ToSchema")
|
|
176
|
+
return out
|
|
177
|
+
|
|
178
|
+
def model_by_rust(self, rust: str) -> ModelInfo | None:
|
|
179
|
+
return next((m for m in self.models.values() if m.rust == rust), None)
|
|
180
|
+
|
|
181
|
+
def project_member(self, dotted_name: str) -> tuple[Symbol, str] | None:
|
|
182
|
+
"""`m.func` / `a.b.c.func` through an imported project module: (symbol, Rust path prefix)."""
|
|
183
|
+
parts = dotted_name.split(".")
|
|
184
|
+
target = self.module_aliases.get(parts[0])
|
|
185
|
+
if self.project is None or target is None or len(parts) < 2:
|
|
186
|
+
return None
|
|
187
|
+
middle = parts[1:-1]
|
|
188
|
+
sym = self.project.index.lookup(".".join([target, *middle]), parts[-1])
|
|
189
|
+
if sym is None:
|
|
190
|
+
return None
|
|
191
|
+
return sym, "::".join(mangle(p) for p in [parts[0], *middle])
|
|
192
|
+
|
|
193
|
+
def import_consumed(self, module: str, name: str = "") -> bool:
|
|
194
|
+
"""Does the type system, a mapped type or the library map consume this import?"""
|
|
195
|
+
if module in CONSUMED_MODULES or module.split(".")[0] == "pydantic":
|
|
196
|
+
return True
|
|
197
|
+
if (name or module.split(".")[-1]) in self.cfg.type_map:
|
|
198
|
+
return True
|
|
199
|
+
full = f"{module}.{name}" if name else module
|
|
200
|
+
return any(k == full or k.startswith(full + ".") for k in self.cfg.library_map)
|
|
201
|
+
|
|
202
|
+
def set_status(self, name: str, start: tuple[int, int, int], extra: bool = True) -> None:
|
|
203
|
+
"""Record whether the module item `name` (lowered since `start`) is clean on its own."""
|
|
204
|
+
self.status[name] = extra and self.col.clean_since(start)
|
|
205
|
+
self.status_mod[name] = extra and self.col.clean_since(start, modulo_int_range=True)
|
|
206
|
+
|
|
207
|
+
def library_entry(self, dotted_name: str) -> dict[str, str] | None:
|
|
208
|
+
lib = self.cfg.library_map
|
|
209
|
+
return lib.get(self.resolve(dotted_name)) or lib.get(dotted_name)
|
|
210
|
+
|
|
211
|
+
def library_type(self, entry: dict[str, str]) -> RType:
|
|
212
|
+
returns = entry.get("returns", "")
|
|
213
|
+
if returns.startswith("future"): # "future" or "future:int": awaitable library call
|
|
214
|
+
return T(
|
|
215
|
+
"Future", parse_type_spec(returns.partition(":")[2]) if ":" in returns else UNIT
|
|
216
|
+
)
|
|
217
|
+
return parse_type_spec(returns)
|
|
218
|
+
|
|
219
|
+
def resolve(self, dotted: str) -> str:
|
|
220
|
+
"""Resolve the first component of a dotted name through the import table."""
|
|
221
|
+
head, _, rest = dotted.partition(".")
|
|
222
|
+
base = self.imports.get(head, head)
|
|
223
|
+
return f"{base}.{rest}" if rest else base
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""raise / try / except / else / finally / `with suppress` -> Result values and labeled blocks.
|
|
2
|
+
|
|
3
|
+
A `try` body is a labeled block `'tryN: { ... Ok(()) }` yielding `Result<(), rt::PyError>`; a raise,
|
|
4
|
+
or a fallible call inside it, is `break 'tryN Err(..)`, so `return`/`break`/`continue` in the body
|
|
5
|
+
keep working natively. After the block a `match` runs the handlers (`Err(e) if e.is_a(&K)`), the
|
|
6
|
+
`else` clause (the `Ok` arm) and propagates anything else (`return Err(e)`, or a break to the next
|
|
7
|
+
enclosing try). `finally` runs after the handler `match` and before the error propagates; it is
|
|
8
|
+
unsupported (a TODO) when the try, its handlers or its else contain `return`/`break`/`continue`,
|
|
9
|
+
and, like all drop-style cleanup, it does not run on a panic. Exception kinds form the static tree
|
|
10
|
+
in `python2rust-rt` (`ExcKind`); `except A, B` is `is_a` guards, so base classes catch subclasses.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import ast
|
|
16
|
+
|
|
17
|
+
from ..ir import nodes as ir
|
|
18
|
+
from ..ir.rtypes import BOOL, UNIT, RType, T
|
|
19
|
+
from ..ir.types import dotted
|
|
20
|
+
from ..passes.raises import class_name, handler_kinds, is_a, kind_ref, parents
|
|
21
|
+
from .lowerer import Unsupported, Var, local_name
|
|
22
|
+
from .modelcalls import ModelCalls
|
|
23
|
+
|
|
24
|
+
PYERR = T("rt::PyError")
|
|
25
|
+
RESULT_UNIT = T("Result", UNIT, PYERR)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _ok(value: ir.RExpr) -> ir.RExpr:
|
|
29
|
+
return ir.Call(func=ir.Path(path="Ok"), args=[value], ty=T("Result", value.ty, PYERR))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _err(value: ir.RExpr) -> ir.RExpr:
|
|
33
|
+
return ir.Call(func=ir.Path(path="Err"), args=[value])
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _has_exit(stmts: list[ast.stmt], in_loop: bool = False) -> bool:
|
|
37
|
+
"""Does `stmts` contain a return, or a break/continue that leaves them?"""
|
|
38
|
+
for st in stmts:
|
|
39
|
+
for node in ast.walk(st):
|
|
40
|
+
if isinstance(node, ast.Return):
|
|
41
|
+
return True
|
|
42
|
+
if isinstance(st, ast.Break | ast.Continue) and not in_loop:
|
|
43
|
+
return True
|
|
44
|
+
loop = isinstance(st, ast.For | ast.While | ast.AsyncFor)
|
|
45
|
+
for fld in ("body", "orelse", "finalbody"):
|
|
46
|
+
inner = getattr(st, fld, None)
|
|
47
|
+
if isinstance(inner, list) and _has_exit(inner, in_loop or (loop and fld == "body")):
|
|
48
|
+
return True
|
|
49
|
+
for h in getattr(st, "handlers", []):
|
|
50
|
+
if _has_exit(h.body, in_loop):
|
|
51
|
+
return True
|
|
52
|
+
return False
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ExceptionLowerer(ModelCalls):
|
|
56
|
+
def scoped(self, stmts: list[ast.stmt], after: int) -> list[ir.RStmt]:
|
|
57
|
+
raise NotImplementedError
|
|
58
|
+
|
|
59
|
+
def block(self, stmts: list[ast.stmt], tail: bool = False, after: int = 0) -> list[ir.RStmt]:
|
|
60
|
+
raise NotImplementedError
|
|
61
|
+
|
|
62
|
+
# -- helpers ----------------------------------------------------------------------------
|
|
63
|
+
def kind_expr(self, name: str | None, node: ast.AST) -> ir.RExpr:
|
|
64
|
+
path = kind_ref(self.ctx, name) if name else None
|
|
65
|
+
if path is None:
|
|
66
|
+
raise Unsupported(
|
|
67
|
+
"PY2RS024", f"unknown exception class {name}: add it to exception_map", node
|
|
68
|
+
)
|
|
69
|
+
return ir.Ref(operand=ir.Path(path=path), ty=T("&", T("rt::ExcKind")))
|
|
70
|
+
|
|
71
|
+
def propagate(self, err: ir.RExpr, node: ast.AST) -> ir.RStmt:
|
|
72
|
+
if self.try_labels:
|
|
73
|
+
return ir.Break(label=self.try_labels[-1], value=_err(err))
|
|
74
|
+
if not self.fallible:
|
|
75
|
+
raise Unsupported(
|
|
76
|
+
"PY2RS024", "an exception escapes a function that is not fallible", node
|
|
77
|
+
)
|
|
78
|
+
return ir.Return(_err(err))
|
|
79
|
+
|
|
80
|
+
def unhandled(self, err: ir.RExpr, node: ast.AST) -> ir.RStmt:
|
|
81
|
+
"""Propagate `err`; in a function that cannot fail it is unreachable, so it is a panic."""
|
|
82
|
+
if self.try_labels or self.fallible:
|
|
83
|
+
return self.propagate(err, node)
|
|
84
|
+
macro = ir.Macro(name="panic", args=[err], template="unhandled exception: {}")
|
|
85
|
+
return ir.ExprS(macro)
|
|
86
|
+
|
|
87
|
+
def _message(self, exc: ast.expr) -> ir.RExpr:
|
|
88
|
+
if not isinstance(exc, ast.Call) or not exc.args:
|
|
89
|
+
return ir.lit("str", "", ir.UNKNOWN)
|
|
90
|
+
if len(exc.args) > 1 or exc.keywords:
|
|
91
|
+
raise Unsupported("PY2RS024", "exception with several arguments or keywords", exc)
|
|
92
|
+
arg0 = self.expr(exc.args[0])
|
|
93
|
+
shown = self._shown(arg0, exc)
|
|
94
|
+
return shown
|
|
95
|
+
|
|
96
|
+
def _is_str(self, node: ast.expr) -> bool:
|
|
97
|
+
from ..ir.rtypes import STR, peel
|
|
98
|
+
|
|
99
|
+
return peel(self.expr(node).ty) == STR
|
|
100
|
+
|
|
101
|
+
def _shown(self, e: ir.RExpr, node: ast.AST) -> ir.RExpr:
|
|
102
|
+
from ..ir.rtypes import INT, peel
|
|
103
|
+
from .fstrings import display
|
|
104
|
+
|
|
105
|
+
shown = display(self, e, node)
|
|
106
|
+
return ir.method(shown, "to_string", ty=ir.UNKNOWN) if peel(e.ty) == INT else shown
|
|
107
|
+
|
|
108
|
+
# -- raise -------------------------------------------------------------------------------
|
|
109
|
+
def st_Raise(self, s: ast.Raise) -> list[ir.RStmt]:
|
|
110
|
+
if s.exc is None:
|
|
111
|
+
if not self.handlers:
|
|
112
|
+
raise Unsupported("PY2RS024", "bare raise outside an except block", s)
|
|
113
|
+
return [self.propagate(ir.Var(name=self.handlers[-1][0], ty=PYERR), s)]
|
|
114
|
+
if isinstance(s.exc, ast.Name) and (var := self.lookup(s.exc.id)) and var.ty == PYERR:
|
|
115
|
+
return [self.propagate(self.var(var), s)] # `raise e` re-raises the caught error
|
|
116
|
+
name = class_name(s.exc)
|
|
117
|
+
kind = self.kind_expr(name, s)
|
|
118
|
+
if not isinstance(s.exc, ast.Call) or not s.exc.args:
|
|
119
|
+
err: ir.RExpr = ir.Call(func=ir.Path(path="rt::PyError::bare"), args=[kind], ty=PYERR)
|
|
120
|
+
else:
|
|
121
|
+
if (
|
|
122
|
+
name
|
|
123
|
+
and is_a(name, "KeyError", parents(self.ctx))
|
|
124
|
+
and not self._is_str(s.exc.args[0])
|
|
125
|
+
):
|
|
126
|
+
raise Unsupported("PY2RS024", "KeyError with an argument that is not a str", s)
|
|
127
|
+
err = ir.Call(
|
|
128
|
+
func=ir.Path(path="rt::PyError::new"), args=[kind, self._message(s.exc)], ty=PYERR
|
|
129
|
+
)
|
|
130
|
+
if s.cause is not None and not (
|
|
131
|
+
isinstance(s.cause, ast.Constant) and s.cause.value is None
|
|
132
|
+
):
|
|
133
|
+
cause = self.expr(s.cause)
|
|
134
|
+
if cause.ty != PYERR:
|
|
135
|
+
raise Unsupported("PY2RS024", "`raise ... from` needs a caught exception", s)
|
|
136
|
+
err = ir.method(err, "with_cause", cause, ty=PYERR)
|
|
137
|
+
return [self.propagate(err, s)]
|
|
138
|
+
|
|
139
|
+
# -- try ---------------------------------------------------------------------------------
|
|
140
|
+
def _next_label(self) -> int:
|
|
141
|
+
self._labels += 1
|
|
142
|
+
return self._labels
|
|
143
|
+
|
|
144
|
+
def _handler_guard(self, var: str, kinds: list[str] | None, node: ast.AST) -> ir.RExpr | None:
|
|
145
|
+
if kinds is None:
|
|
146
|
+
return None
|
|
147
|
+
tests = [
|
|
148
|
+
ir.method(ir.Var(name=var, ty=PYERR), "is_a", self.kind_expr(k, node), ty=BOOL)
|
|
149
|
+
for k in kinds
|
|
150
|
+
]
|
|
151
|
+
out = tests[0]
|
|
152
|
+
for t in tests[1:]:
|
|
153
|
+
out = ir.Bin(op="||", left=out, right=t, ty=BOOL)
|
|
154
|
+
return out
|
|
155
|
+
|
|
156
|
+
def st_Try(self, s: ast.Try) -> list[ir.RStmt]:
|
|
157
|
+
n = self._next_label()
|
|
158
|
+
label, rname = f"try{n}", f"res{n}"
|
|
159
|
+
table = parents(self.ctx)
|
|
160
|
+
pairs = [(h, handler_kinds(h)) for h in s.handlers]
|
|
161
|
+
guarded: set[str] = set()
|
|
162
|
+
for h, kinds in pairs:
|
|
163
|
+
for k in kinds if kinds is not None else ["BaseException"]:
|
|
164
|
+
if k not in table and k not in self.ctx.cfg.exception_map:
|
|
165
|
+
raise Unsupported("PY2RS012", f"unknown exception class {k} in except", h)
|
|
166
|
+
guarded.add(k)
|
|
167
|
+
if s.finalbody and _has_exit(
|
|
168
|
+
[*s.body, *s.orelse, *(b for h in s.handlers for b in h.body)]
|
|
169
|
+
):
|
|
170
|
+
raise Unsupported(
|
|
171
|
+
"PY2RS012", "try/finally containing return, break or continue", s,
|
|
172
|
+
hint="the finally block would be skipped on that exit; restructure or port by hand",
|
|
173
|
+
) # fmt: skip
|
|
174
|
+
out_names = self._bound_by(s)
|
|
175
|
+
self.hoist -= set(out_names) # they leave the block as the Ok value instead
|
|
176
|
+
self.try_labels.append(label)
|
|
177
|
+
self.catch_stack.append(guarded)
|
|
178
|
+
self.push()
|
|
179
|
+
try:
|
|
180
|
+
body = self.block(s.body, after=s.lineno)
|
|
181
|
+
values = [self.lookup(n) for n in out_names]
|
|
182
|
+
finally:
|
|
183
|
+
self.pop()
|
|
184
|
+
self.try_labels.pop()
|
|
185
|
+
self.catch_stack.pop()
|
|
186
|
+
found = [(n, v) for n, v in zip(out_names, values, strict=True) if v is not None]
|
|
187
|
+
if found:
|
|
188
|
+
return self._try_value(s, n, label, rname, body, pairs, found)
|
|
189
|
+
block = ir.BlockX(stmts=body, tail=_ok(ir.Lit(kind="unit")), label=label, ty=RESULT_UNIT)
|
|
190
|
+
stmts: list[ir.RStmt] = [ir.Let(ir.PVar(rname), RESULT_UNIT, block)]
|
|
191
|
+
hlabel = f"hdl{n}"
|
|
192
|
+
if s.finalbody:
|
|
193
|
+
self.try_labels.append(hlabel) # errors in handlers/else must still run `finally`
|
|
194
|
+
try:
|
|
195
|
+
arms = self._arms(s, n, pairs)
|
|
196
|
+
finally:
|
|
197
|
+
if s.finalbody:
|
|
198
|
+
self.try_labels.pop()
|
|
199
|
+
match = ir.MatchS(ir.Var(name=rname, ty=RESULT_UNIT), arms)
|
|
200
|
+
if not s.finalbody:
|
|
201
|
+
return [*stmts, match]
|
|
202
|
+
hblock = ir.BlockX(
|
|
203
|
+
stmts=[match], tail=_ok(ir.Lit(kind="unit")), label=hlabel, ty=RESULT_UNIT
|
|
204
|
+
)
|
|
205
|
+
out = f"out{n}"
|
|
206
|
+
fin = self.scoped(s.finalbody, s.body[-1].end_lineno or s.lineno)
|
|
207
|
+
rethrow = ir.MatchS(
|
|
208
|
+
ir.Var(name=out, ty=RESULT_UNIT),
|
|
209
|
+
[
|
|
210
|
+
ir.Arm(
|
|
211
|
+
ir.PExpr(_err(ir.Var(name="e"))),
|
|
212
|
+
[self.unhandled(ir.Var(name="e", ty=PYERR), s)],
|
|
213
|
+
),
|
|
214
|
+
ir.Arm(ir.PWild(), []),
|
|
215
|
+
],
|
|
216
|
+
)
|
|
217
|
+
return [*stmts, ir.Let(ir.PVar(out), RESULT_UNIT, hblock), *fin, rethrow]
|
|
218
|
+
|
|
219
|
+
def _arms(
|
|
220
|
+
self, s: ast.Try, n: int, pairs: list[tuple[ast.ExceptHandler, list[str] | None]]
|
|
221
|
+
) -> list[ir.Arm]:
|
|
222
|
+
ok_body = self.scoped(s.orelse, s.body[-1].end_lineno or s.lineno) if s.orelse else []
|
|
223
|
+
arms = [ir.Arm(ir.PExpr(_ok(ir.Lit(kind="unit"))), ok_body)]
|
|
224
|
+
for i, (h, kinds) in enumerate(pairs):
|
|
225
|
+
var = local_name(h.name) if h.name else f"err{n}_{i}"
|
|
226
|
+
self.push()
|
|
227
|
+
try:
|
|
228
|
+
if h.name:
|
|
229
|
+
self.declare(h.name, PYERR)
|
|
230
|
+
self.handlers.append((var, set(kinds or ["BaseException"])))
|
|
231
|
+
body = self.block(h.body, after=h.lineno)
|
|
232
|
+
finally:
|
|
233
|
+
self.handlers.pop()
|
|
234
|
+
self.pop()
|
|
235
|
+
guard = self._handler_guard(var, kinds, h)
|
|
236
|
+
arms.append(ir.Arm(ir.PExpr(_err(ir.Var(name=var))), body, guard))
|
|
237
|
+
last = f"e{n}"
|
|
238
|
+
tail = self.unhandled(ir.Var(name=last, ty=PYERR), s)
|
|
239
|
+
arms.append(ir.Arm(ir.PExpr(_err(ir.Var(name=last))), [tail]))
|
|
240
|
+
return arms
|
|
241
|
+
|
|
242
|
+
def _bound_by(self, s: ast.Try) -> list[str]:
|
|
243
|
+
"""Names the try body introduces and later code reads, when every handler leaves the flow."""
|
|
244
|
+
exits = (ast.Return, ast.Raise, ast.Continue, ast.Break)
|
|
245
|
+
if s.finalbody or not all(isinstance(h.body[-1], exits) for h in s.handlers):
|
|
246
|
+
return []
|
|
247
|
+
names: list[str] = []
|
|
248
|
+
for st in s.body:
|
|
249
|
+
targets = st.targets if isinstance(st, ast.Assign) else []
|
|
250
|
+
if isinstance(st, ast.AnnAssign) and st.value is not None:
|
|
251
|
+
targets = [st.target]
|
|
252
|
+
for t in targets:
|
|
253
|
+
if isinstance(t, ast.Name) and t.id in self.hoist and self.lookup(t.id) is None:
|
|
254
|
+
names.append(t.id)
|
|
255
|
+
return list(dict.fromkeys(names))
|
|
256
|
+
|
|
257
|
+
def _try_value(
|
|
258
|
+
self,
|
|
259
|
+
s: ast.Try,
|
|
260
|
+
n: int,
|
|
261
|
+
label: str,
|
|
262
|
+
rname: str,
|
|
263
|
+
body: list[ir.RStmt],
|
|
264
|
+
pairs: list[tuple[ast.ExceptHandler, list[str] | None]],
|
|
265
|
+
found: list[tuple[str, Var]],
|
|
266
|
+
) -> list[ir.RStmt]:
|
|
267
|
+
"""`let (x,) = match 'try: {...; Ok((x,))} { Ok(v) => v, Err(..) => return .. };`"""
|
|
268
|
+
|
|
269
|
+
def values() -> ir.RExpr:
|
|
270
|
+
items: list[ir.RExpr] = [ir.Var(name=v.rust, ty=v.ty) for _, v in found]
|
|
271
|
+
return ir.TupleX(elems=items, ty=T("tuple", *(v.ty for _, v in found)))
|
|
272
|
+
|
|
273
|
+
ty = T("Result", T("tuple", *(v.ty for _, v in found)), PYERR)
|
|
274
|
+
block = ir.BlockX(stmts=body, tail=_ok(values()), label=label, ty=ty)
|
|
275
|
+
self.push()
|
|
276
|
+
try:
|
|
277
|
+
for name, v in found:
|
|
278
|
+
self.frames[-1][name] = v
|
|
279
|
+
arms = self._arms(s, n, pairs)
|
|
280
|
+
finally:
|
|
281
|
+
self.pop()
|
|
282
|
+
arms[0] = ir.Arm(ir.PExpr(_ok(values())), [*arms[0].body, ir.Return(values(), tail=True)])
|
|
283
|
+
match = ir.MatchS(ir.Var(name=rname, ty=ty), arms)
|
|
284
|
+
pats: list[ir.Pat] = []
|
|
285
|
+
for name, v in found:
|
|
286
|
+
self.frames[-1][name] = v
|
|
287
|
+
pats.append(ir.PVar(v.rust, name in self.mutated))
|
|
288
|
+
return [
|
|
289
|
+
ir.Let(ir.PVar(rname), None, block),
|
|
290
|
+
ir.Let(ir.PTuple(pats), None, ir.BlockX(stmts=[match])),
|
|
291
|
+
]
|
|
292
|
+
|
|
293
|
+
# -- with --------------------------------------------------------------------------------
|
|
294
|
+
def st_With(self, s: ast.With) -> list[ir.RStmt]:
|
|
295
|
+
item = s.items[0].context_expr if len(s.items) == 1 else None
|
|
296
|
+
if (
|
|
297
|
+
isinstance(item, ast.Call)
|
|
298
|
+
and dotted(item.func).split(".")[-1] == "suppress"
|
|
299
|
+
and item.args
|
|
300
|
+
):
|
|
301
|
+
handler = ast.ExceptHandler(
|
|
302
|
+
type=item.args[0]
|
|
303
|
+
if len(item.args) == 1
|
|
304
|
+
else ast.Tuple(elts=list(item.args), ctx=ast.Load()),
|
|
305
|
+
name=None,
|
|
306
|
+
body=[ast.Pass()],
|
|
307
|
+
)
|
|
308
|
+
node = ast.Try(body=s.body, handlers=[handler], orelse=[], finalbody=[])
|
|
309
|
+
ast.copy_location(node, s)
|
|
310
|
+
ast.copy_location(handler, s)
|
|
311
|
+
ast.fix_missing_locations(node)
|
|
312
|
+
return self.st_Try(node)
|
|
313
|
+
raise Unsupported("PY2RS025", "with (only contextlib.suppress is lowered)", s)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def result_of(ty: RType) -> RType:
|
|
317
|
+
return T("Result", ty, PYERR)
|