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,1125 @@
|
|
|
1
|
+
"""Call lowering: local functions, model construction, builtins, library map, str/list/dict/set methods."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import dataclasses
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
from ..frontend.symbols import Symbol
|
|
10
|
+
from ..ir import nodes as ir
|
|
11
|
+
from ..ir.rtypes import (
|
|
12
|
+
BOOL,
|
|
13
|
+
BYTES,
|
|
14
|
+
FLOAT,
|
|
15
|
+
INT,
|
|
16
|
+
MAP,
|
|
17
|
+
SET,
|
|
18
|
+
STR,
|
|
19
|
+
UNIT,
|
|
20
|
+
UNKNOWN,
|
|
21
|
+
VALUE,
|
|
22
|
+
RType,
|
|
23
|
+
T,
|
|
24
|
+
arg,
|
|
25
|
+
option,
|
|
26
|
+
peel,
|
|
27
|
+
unify,
|
|
28
|
+
)
|
|
29
|
+
from ..ir.types import dotted
|
|
30
|
+
from ..passes.raises import kind_ref
|
|
31
|
+
from . import fstrings
|
|
32
|
+
from .context import FuncSig, ModelInfo, ParamSig
|
|
33
|
+
from .exprs import ExprLowerer
|
|
34
|
+
from .lowerer import Unsupported, bin_, int_lit, not_
|
|
35
|
+
|
|
36
|
+
KIND = {
|
|
37
|
+
"String": "str", "Vec": "list", MAP: "dict", SET: "set", "serde_json::Value": "value",
|
|
38
|
+
"rt::re::Match": "match", "rt::Digest": "digest", "rt::re::Pattern": "pattern",
|
|
39
|
+
} # fmt: skip
|
|
40
|
+
LOG_LEVELS = {
|
|
41
|
+
"debug": "debug", "info": "info", "warning": "warn", "warn": "warn",
|
|
42
|
+
"error": "error", "exception": "error", "critical": "error", "fatal": "error",
|
|
43
|
+
} # fmt: skip
|
|
44
|
+
PERCENT = re.compile(r"%%|%[sdifr]|%\w")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def lit_str(text: str) -> ir.Lit:
|
|
48
|
+
return ir.lit("str", text, STR)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def expect(e: ir.RExpr, message: str, ty: RType) -> ir.RExpr:
|
|
52
|
+
return ir.method(e, "expect", ir.Ref(operand=lit_str(message), elide=True), ty=ty)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def closure(names: list[str], body: ir.RExpr) -> ir.Closure:
|
|
56
|
+
return ir.Closure(params=[ir.PVar(n) for n in names], body=body)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# isinstance targets -> the Rust type names that are instances of them (bool is an int in Python)
|
|
60
|
+
ISINSTANCE_TYPES = {
|
|
61
|
+
"str": {"String"}, "int": {"i64", "bool"}, "float": {"f64"}, "bool": {"bool"},
|
|
62
|
+
"list": {"Vec"}, "tuple": {"tuple"}, "dict": {MAP}, "set": {SET},
|
|
63
|
+
} # fmt: skip
|
|
64
|
+
JSON_TESTS = {
|
|
65
|
+
"str": "is_string", "int": "is_i64", "float": "is_f64", "bool": "is_boolean",
|
|
66
|
+
"list": "is_array", "tuple": "is_array", "dict": "is_object", "set": "is_array",
|
|
67
|
+
} # fmt: skip
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class KwBag:
|
|
71
|
+
"""Keyword arguments of a call; every keyword must be consumed or the call is a TODO."""
|
|
72
|
+
|
|
73
|
+
def __init__(self, node: ast.Call) -> None:
|
|
74
|
+
self.items = {k.arg: k.value for k in node.keywords if k.arg}
|
|
75
|
+
self.used: set[str] = set()
|
|
76
|
+
|
|
77
|
+
def get(self, name: str) -> ast.expr | None:
|
|
78
|
+
if name in self.items:
|
|
79
|
+
self.used.add(name)
|
|
80
|
+
return self.items.get(name)
|
|
81
|
+
|
|
82
|
+
def finish(self, node: ast.Call) -> None:
|
|
83
|
+
left = sorted(set(self.items) - self.used)
|
|
84
|
+
if left:
|
|
85
|
+
raise Unsupported("PY2RS019", f"unsupported keyword argument {left[0]}=", node)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class CallLowerer(ExprLowerer):
|
|
89
|
+
def expr_Call(self, node: ast.Call) -> ir.RExpr:
|
|
90
|
+
if any(isinstance(a, ast.Starred) for a in node.args) or any(
|
|
91
|
+
k.arg is None for k in node.keywords
|
|
92
|
+
):
|
|
93
|
+
raise Unsupported("PY2RS034", "argument unpacking (*xs / **kw) in a call", node)
|
|
94
|
+
if isinstance(node.func, ast.Name):
|
|
95
|
+
return self._call_name(node, node.func.id)
|
|
96
|
+
if isinstance(node.func, ast.Attribute):
|
|
97
|
+
return self._call_attr(node, node.func)
|
|
98
|
+
raise Unsupported("PY2RS019", "call of a computed callee", node)
|
|
99
|
+
|
|
100
|
+
# -- names ----------------------------------------------------------------------------
|
|
101
|
+
def _call_name(self, node: ast.Call, name: str) -> ir.RExpr:
|
|
102
|
+
var = self.lookup(name)
|
|
103
|
+
if var:
|
|
104
|
+
args = [self.expr(a) for a in node.args]
|
|
105
|
+
for a in args:
|
|
106
|
+
if isinstance(a, ir.Lit) and a.kind in ("int", "float"):
|
|
107
|
+
a.suffixed = True
|
|
108
|
+
ret = arg(var.ty) if var.ty.name == "Fn" and var.ty.args else UNKNOWN
|
|
109
|
+
return ir.Call(func=self.var(var), args=args, ty=ret)
|
|
110
|
+
if name == "isinstance" and len(node.args) == 2 and not node.keywords:
|
|
111
|
+
return self._isinstance(node)
|
|
112
|
+
if name in self.ctx.sigs:
|
|
113
|
+
return self._call_local(node, self.ctx.sigs[name])
|
|
114
|
+
model = self.ctx.models.get(name)
|
|
115
|
+
if model and model.newtype is not None:
|
|
116
|
+
(x,) = [self.expr(a) for a in node.args]
|
|
117
|
+
return ir.Call(
|
|
118
|
+
func=ir.Path(path=model.rust),
|
|
119
|
+
args=[self.coerce(x, model.newtype)],
|
|
120
|
+
ty=T(model.rust),
|
|
121
|
+
)
|
|
122
|
+
if model:
|
|
123
|
+
return self._construct(node, model)
|
|
124
|
+
handler = getattr(self, f"b_{name}", None)
|
|
125
|
+
if handler:
|
|
126
|
+
kw = KwBag(node)
|
|
127
|
+
result = handler(node, [self.expr(a) for a in node.args], kw)
|
|
128
|
+
kw.finish(node)
|
|
129
|
+
return result
|
|
130
|
+
entry = self.ctx.library_entry(name)
|
|
131
|
+
if entry:
|
|
132
|
+
return self._library(node, entry)
|
|
133
|
+
raise Unsupported("PY2RS019", f"call to unknown function {name}()", node)
|
|
134
|
+
|
|
135
|
+
def _isinstance(self, node: ast.Call) -> ir.RExpr:
|
|
136
|
+
"""`isinstance(e, ValueError)` for a caught exception: an `is_a` test on the kind tree."""
|
|
137
|
+
subject = self.expr(node.args[0])
|
|
138
|
+
classes = node.args[1].elts if isinstance(node.args[1], ast.Tuple) else [node.args[1]]
|
|
139
|
+
names = [dotted(c).split(".")[-1] for c in classes]
|
|
140
|
+
if all(n in ISINSTANCE_TYPES for n in names) and peel(subject.ty).known:
|
|
141
|
+
return self._isinstance_builtin(node, subject, names)
|
|
142
|
+
if peel(subject.ty).name != "rt::PyError" or any(
|
|
143
|
+
kind_ref(self.ctx, n) is None for n in names
|
|
144
|
+
):
|
|
145
|
+
raise Unsupported("PY2RS019", "isinstance() on this value", node)
|
|
146
|
+
tests: list[ir.RExpr] = [
|
|
147
|
+
ir.method(
|
|
148
|
+
subject if i == 0 else ir.dup(subject),
|
|
149
|
+
"is_a",
|
|
150
|
+
ir.Ref(
|
|
151
|
+
operand=ir.Path(path=str(kind_ref(self.ctx, n))), ty=T("&", T("rt::ExcKind"))
|
|
152
|
+
),
|
|
153
|
+
ty=BOOL,
|
|
154
|
+
)
|
|
155
|
+
for i, n in enumerate(names)
|
|
156
|
+
]
|
|
157
|
+
out = tests[0]
|
|
158
|
+
for t in tests[1:]:
|
|
159
|
+
out = bin_("||", out, t, BOOL)
|
|
160
|
+
return out
|
|
161
|
+
|
|
162
|
+
def _isinstance_builtin(self, node: ast.Call, subject: ir.RExpr, names: list[str]) -> ir.RExpr:
|
|
163
|
+
"""`isinstance(x, str)` on a value whose static type decides it (or a JSON value: a test)."""
|
|
164
|
+
ty = peel(subject.ty)
|
|
165
|
+
if ty.name == "Option": # None is no instance of anything
|
|
166
|
+
test = self._isinstance_builtin(node, ir.Var(name="v", ty=T("&", arg(ty))), names)
|
|
167
|
+
some = ir.method(subject, "as_ref")
|
|
168
|
+
return ir.method(
|
|
169
|
+
some, "is_some_and", ir.Closure(params=[ir.PVar("v")], body=test), ty=BOOL
|
|
170
|
+
)
|
|
171
|
+
tests: list[ir.RExpr] = []
|
|
172
|
+
for n in names:
|
|
173
|
+
want = ISINSTANCE_TYPES[n]
|
|
174
|
+
if ty.name == "serde_json::Value":
|
|
175
|
+
tests.append(ir.method(ir.dup(subject), JSON_TESTS[n], ty=BOOL))
|
|
176
|
+
else:
|
|
177
|
+
tests.append(ir.lit("bool", ty.name in want, BOOL))
|
|
178
|
+
out = tests[0]
|
|
179
|
+
for t in tests[1:]:
|
|
180
|
+
out = bin_("||", out, t, BOOL)
|
|
181
|
+
return out
|
|
182
|
+
|
|
183
|
+
def _arguments(self, node: ast.Call, entry: dict[str, str]) -> list[ast.expr]:
|
|
184
|
+
"""Positional argument nodes; `params = "s, safe='/'"` binds keywords and fills defaults."""
|
|
185
|
+
params = entry.get("params")
|
|
186
|
+
if params is None:
|
|
187
|
+
if node.keywords:
|
|
188
|
+
raise Unsupported("PY2RS019", "keyword arguments to a library_map function", node)
|
|
189
|
+
return list(node.args)
|
|
190
|
+
header = ast.parse(f"def _({params}): pass").body[0] # parsed, never executed
|
|
191
|
+
assert isinstance(header, ast.FunctionDef)
|
|
192
|
+
names = [a.arg for a in header.args.args]
|
|
193
|
+
defaults = dict(zip(reversed(names), reversed(header.args.defaults), strict=False))
|
|
194
|
+
given = dict(zip(names, node.args, strict=False))
|
|
195
|
+
for k in node.keywords:
|
|
196
|
+
if k.arg not in names or k.arg in given:
|
|
197
|
+
raise Unsupported("PY2RS019", f"unsupported keyword argument {k.arg}=", node)
|
|
198
|
+
given[k.arg] = k.value
|
|
199
|
+
if len(node.args) > len(names) or any(n not in given and n not in defaults for n in names):
|
|
200
|
+
raise Unsupported("PY2RS019", "unexpected argument count", node)
|
|
201
|
+
out = [given.get(n, defaults.get(n)) for n in names]
|
|
202
|
+
return [ast.copy_location(a, node) if not hasattr(a, "lineno") else a for a in out if a]
|
|
203
|
+
|
|
204
|
+
def _library(self, node: ast.Call, entry: dict[str, str]) -> ir.RExpr:
|
|
205
|
+
args = [self.expr(a) for a in self._arguments(node, entry)]
|
|
206
|
+
if entry.get("coerce") == "value": # e.g. json.dumps(x): any serialisable value
|
|
207
|
+
args = [self.coerce(a, VALUE) for a in args]
|
|
208
|
+
elif entry.get("coerce") == "bytes": # str arguments are accepted and encoded
|
|
209
|
+
args = [self._as_bytes(a) for a in args]
|
|
210
|
+
feature = entry.get("feature")
|
|
211
|
+
if feature:
|
|
212
|
+
if self.ctx.cfg.vendor_runtime:
|
|
213
|
+
raise Unsupported(
|
|
214
|
+
"PY2RS010",
|
|
215
|
+
f"{ast.unparse(node.func)} needs the python2rust-rt feature {feature}, "
|
|
216
|
+
"which vendor_runtime cannot provide",
|
|
217
|
+
node,
|
|
218
|
+
)
|
|
219
|
+
self.ctx.features.add(feature)
|
|
220
|
+
self.ctx.templates += 1
|
|
221
|
+
ty = self.ctx.library_type(entry)
|
|
222
|
+
call = ir.Template(template=entry["rust"], args=args, ty=ty)
|
|
223
|
+
kind = entry.get("raises")
|
|
224
|
+
if kind is None:
|
|
225
|
+
return call
|
|
226
|
+
if self.catches(kind): # the template returns a Result: propagate it into the try
|
|
227
|
+
return self.question(call, ty, node)
|
|
228
|
+
self.drift("PY2RS045", node, f"{kind} becomes a panic outside a try")
|
|
229
|
+
return ir.rt("or_panic", call, ty=ty)
|
|
230
|
+
|
|
231
|
+
def _as_bytes(self, e: ir.RExpr) -> ir.RExpr:
|
|
232
|
+
if peel(e.ty) == STR:
|
|
233
|
+
return ir.method(ir.method(e, "as_bytes"), "to_vec", ty=BYTES)
|
|
234
|
+
return e
|
|
235
|
+
|
|
236
|
+
def _log(self, node: ast.Call, method: str) -> ir.RExpr:
|
|
237
|
+
"""`logger.info("x %s", a, key=v)` -> `tracing::info!("x {} key={}", a, v)`."""
|
|
238
|
+
level = LOG_LEVELS.get(method)
|
|
239
|
+
if level is None or not node.args:
|
|
240
|
+
raise Unsupported("PY2RS019", f"logger.{method}()", node)
|
|
241
|
+
msg, rest = node.args[0], node.args[1:]
|
|
242
|
+
if isinstance(msg, ast.Constant) and isinstance(msg.value, str):
|
|
243
|
+
parts = PERCENT.split(msg.value)
|
|
244
|
+
marks = PERCENT.findall(msg.value)
|
|
245
|
+
if any(m not in ("%%", "%s", "%d", "%i", "%f", "%r") for m in marks) or len(
|
|
246
|
+
rest
|
|
247
|
+
) != sum(m != "%%" for m in marks):
|
|
248
|
+
raise Unsupported("PY2RS019", "logging call with unsupported %-formatting", node)
|
|
249
|
+
template = ""
|
|
250
|
+
for i, text in enumerate(parts):
|
|
251
|
+
template += text.replace("{", "{{").replace("}", "}}")
|
|
252
|
+
if i < len(marks):
|
|
253
|
+
template += "%" if marks[i] == "%%" else "{}"
|
|
254
|
+
shown = [fstrings.display(self, self.expr(a), node) for a in rest]
|
|
255
|
+
else:
|
|
256
|
+
if rest:
|
|
257
|
+
raise Unsupported(
|
|
258
|
+
"PY2RS019", "logging call with arguments after a computed message", node
|
|
259
|
+
)
|
|
260
|
+
template, shown = "{}", [fstrings.display(self, self.expr(msg), node)]
|
|
261
|
+
for k in node.keywords:
|
|
262
|
+
if k.arg is None or k.arg in ("exc_info", "extra", "stack_info", "stacklevel"):
|
|
263
|
+
raise Unsupported("PY2RS019", "unsupported logging keyword", node)
|
|
264
|
+
template += f" {k.arg}={{}}"
|
|
265
|
+
shown.append(fstrings.display(self, self.expr(k.value), node))
|
|
266
|
+
return ir.Macro(name=f"tracing::{level}", args=shown, template=template, ty=UNIT)
|
|
267
|
+
|
|
268
|
+
def _call_local(self, node: ast.Call, sig: FuncSig) -> ir.RExpr:
|
|
269
|
+
bound = self._bind(node, sig)
|
|
270
|
+
call = ir.Call(
|
|
271
|
+
func=ir.Path(path=sig.rust),
|
|
272
|
+
args=[self._pass(p, bound[p.name]) for p in sig.params],
|
|
273
|
+
ty=sig.ret,
|
|
274
|
+
)
|
|
275
|
+
if sig.is_async: # a coroutine: awaiting it (expr_Await) unwraps the value and the Result
|
|
276
|
+
err = (T("rt::PyError"),) if sig.fallible else ()
|
|
277
|
+
call.ty = T("Future", sig.ret, *err)
|
|
278
|
+
return call
|
|
279
|
+
return self.question(call, sig.ret, node) if sig.fallible else call
|
|
280
|
+
|
|
281
|
+
def _bind(self, node: ast.Call, sig: FuncSig) -> dict[str, ir.RExpr]:
|
|
282
|
+
plain = [p for p in sig.params if p.kind in ("pos", "kwonly")]
|
|
283
|
+
vararg = next((p for p in sig.params if p.kind == "vararg"), None)
|
|
284
|
+
kwarg = next((p for p in sig.params if p.kind == "kwarg"), None)
|
|
285
|
+
positional = [p for p in plain if p.kind == "pos"]
|
|
286
|
+
values = [self.expr(a) for a in node.args]
|
|
287
|
+
bound: dict[str, ir.RExpr] = {p.name: v for p, v in zip(positional, values, strict=False)}
|
|
288
|
+
extras = values[len(positional) :]
|
|
289
|
+
if extras and not vararg:
|
|
290
|
+
raise Unsupported("PY2RS019", f"too many arguments to {sig.name}()", node)
|
|
291
|
+
extra_kw: list[tuple[str, ir.RExpr]] = []
|
|
292
|
+
for k in node.keywords:
|
|
293
|
+
if k.arg in {p.name for p in plain} and k.arg not in bound:
|
|
294
|
+
bound[k.arg] = self.expr(k.value)
|
|
295
|
+
elif kwarg and k.arg:
|
|
296
|
+
extra_kw.append((k.arg, self.expr(k.value)))
|
|
297
|
+
else:
|
|
298
|
+
raise Unsupported("PY2RS019", f"unexpected or repeated keyword {k.arg}=", node)
|
|
299
|
+
for p in plain:
|
|
300
|
+
if p.name not in bound:
|
|
301
|
+
if p.default is None:
|
|
302
|
+
raise Unsupported(
|
|
303
|
+
"PY2RS019", f"missing argument {p.name} in call to {sig.name}()", node
|
|
304
|
+
)
|
|
305
|
+
bound[p.name] = self.expr(p.default)
|
|
306
|
+
if vararg:
|
|
307
|
+
items = [self.coerce(e, arg(vararg.ty)) for e in extras]
|
|
308
|
+
bound[vararg.name] = (
|
|
309
|
+
ir.Macro(name="vec", args=items, ty=vararg.ty)
|
|
310
|
+
if items
|
|
311
|
+
else ir.Call(func=ir.Path(path="Vec::new"), ty=vararg.ty)
|
|
312
|
+
)
|
|
313
|
+
if kwarg:
|
|
314
|
+
pairs: list[ir.RExpr] = [
|
|
315
|
+
ir.TupleX(elems=[lit_str(k), self.coerce(e, arg(kwarg.ty, 1))]) for k, e in extra_kw
|
|
316
|
+
]
|
|
317
|
+
if pairs:
|
|
318
|
+
bound[kwarg.name] = ir.Call(
|
|
319
|
+
func=ir.Path(path=f"{MAP}::from"), args=[ir.ArrayX(elems=pairs)], ty=kwarg.ty
|
|
320
|
+
)
|
|
321
|
+
else:
|
|
322
|
+
bound[kwarg.name] = ir.Call(func=ir.Path(path=f"{MAP}::new"), ty=kwarg.ty)
|
|
323
|
+
return bound
|
|
324
|
+
|
|
325
|
+
def _pass(self, p: ParamSig, e: ir.RExpr) -> ir.RExpr:
|
|
326
|
+
if p.conv == "&mut":
|
|
327
|
+
return self.mut_ref(e)
|
|
328
|
+
return self.coerce(e, p.ty)
|
|
329
|
+
|
|
330
|
+
def _construct(self, node: ast.Call, model: ModelInfo) -> ir.RExpr:
|
|
331
|
+
if model.unchecked or model.validated: # Pydantic validates on construction too
|
|
332
|
+
raise Unsupported(
|
|
333
|
+
"PY2RS017",
|
|
334
|
+
f"{model.rust}(..) would skip the model's validation: parse it instead",
|
|
335
|
+
node,
|
|
336
|
+
)
|
|
337
|
+
fields = list(model.fields.values())
|
|
338
|
+
if len(node.args) > len(fields):
|
|
339
|
+
raise Unsupported("PY2RS019", f"too many arguments to {model.rust}()", node)
|
|
340
|
+
given = {f.py_name: self.expr(a) for f, a in zip(fields, node.args, strict=False)}
|
|
341
|
+
for k in node.keywords:
|
|
342
|
+
if k.arg not in model.fields or k.arg in given:
|
|
343
|
+
raise Unsupported("PY2RS019", f"unknown or repeated field {k.arg}", node)
|
|
344
|
+
given[k.arg] = self.expr(k.value)
|
|
345
|
+
parts: list[tuple[str, ir.RExpr]] = []
|
|
346
|
+
for f in fields:
|
|
347
|
+
if f.py_name in given:
|
|
348
|
+
value = self.coerce(given[f.py_name], f.ty)
|
|
349
|
+
elif f.default is not None:
|
|
350
|
+
value = ir.dup(f.default)
|
|
351
|
+
else:
|
|
352
|
+
raise Unsupported(
|
|
353
|
+
"PY2RS019", f"missing required field {f.py_name} of {model.rust}", node
|
|
354
|
+
)
|
|
355
|
+
parts.append((f.rust, value))
|
|
356
|
+
return ir.StructLit(name=model.rust, fields=parts, ty=T(model.rust))
|
|
357
|
+
|
|
358
|
+
# -- attribute calls ------------------------------------------------------------------
|
|
359
|
+
def _call_attr(self, node: ast.Call, f: ast.Attribute) -> ir.RExpr:
|
|
360
|
+
name = dotted(f)
|
|
361
|
+
if name and not self.lookup(name.split(".")[0]):
|
|
362
|
+
entry = self.ctx.library_entry(name)
|
|
363
|
+
if entry:
|
|
364
|
+
return self._library(node, entry)
|
|
365
|
+
member = (
|
|
366
|
+
self.ctx.project_member(name) if name and not self.lookup(name.split(".")[0]) else None
|
|
367
|
+
)
|
|
368
|
+
if member is not None:
|
|
369
|
+
return self._call_member(node, *member)
|
|
370
|
+
if (
|
|
371
|
+
isinstance(f.value, ast.Name)
|
|
372
|
+
and f.value.id in self.ctx.loggers
|
|
373
|
+
and not self.lookup(f.value.id)
|
|
374
|
+
):
|
|
375
|
+
return self._log(node, f.attr)
|
|
376
|
+
recv = self.expr(f.value)
|
|
377
|
+
if peel(recv.ty).name == "Option" and hasattr(
|
|
378
|
+
self, f"m_{self._kind(arg(recv.ty))}_{f.attr}"
|
|
379
|
+
):
|
|
380
|
+
self.drift(
|
|
381
|
+
"PY2RS045", node, f".{f.attr}() on an Option panics (AttributeError) when None"
|
|
382
|
+
)
|
|
383
|
+
message = f"AttributeError: 'NoneType' object has no attribute '{f.attr}'"
|
|
384
|
+
recv = expect(ir.method(recv, "as_ref"), message, arg(recv.ty))
|
|
385
|
+
handler = getattr(self, f"m_{self._kind(peel(recv.ty))}_{f.attr}", None)
|
|
386
|
+
if handler is None:
|
|
387
|
+
raise Unsupported(
|
|
388
|
+
"PY2RS019", f"method .{f.attr}() on a value of type {peel(recv.ty).rust()}", node
|
|
389
|
+
)
|
|
390
|
+
kw = KwBag(node)
|
|
391
|
+
result = handler(node, recv, [self.expr(a) for a in node.args], kw)
|
|
392
|
+
kw.finish(node)
|
|
393
|
+
return result
|
|
394
|
+
|
|
395
|
+
@staticmethod
|
|
396
|
+
def _kind(ty: RType) -> str:
|
|
397
|
+
return "bytes" if ty == BYTES else KIND.get(ty.name, "none")
|
|
398
|
+
|
|
399
|
+
def _call_member(self, node: ast.Call, sym: Symbol, prefix: str) -> ir.RExpr:
|
|
400
|
+
"""A call through an imported project module: `m.func(x)` -> `m::func(x)`."""
|
|
401
|
+
if sym.kind == "func":
|
|
402
|
+
return self._call_local(
|
|
403
|
+
node, dataclasses.replace(sym.obj, rust=f"{prefix}::{sym.obj.rust}")
|
|
404
|
+
)
|
|
405
|
+
if sym.kind == "model":
|
|
406
|
+
from ..frontend.project_imports import use_defaults
|
|
407
|
+
|
|
408
|
+
use_defaults(self.ctx, sym)
|
|
409
|
+
return self._construct(
|
|
410
|
+
node, dataclasses.replace(sym.obj, rust=f"{prefix}::{sym.obj.rust}")
|
|
411
|
+
)
|
|
412
|
+
raise Unsupported("PY2RS019", f"call of {sym.module}.{sym.name} ({sym.kind})", node)
|
|
413
|
+
|
|
414
|
+
def _argc(
|
|
415
|
+
self, node: ast.Call, args: list[ir.RExpr], lo: int, hi: int | None = None
|
|
416
|
+
) -> list[ir.RExpr]:
|
|
417
|
+
if not lo <= len(args) <= (lo if hi is None else hi):
|
|
418
|
+
raise Unsupported(
|
|
419
|
+
"PY2RS019", f"unexpected argument count in {ast.unparse(node.func)}()", node
|
|
420
|
+
)
|
|
421
|
+
return args
|
|
422
|
+
|
|
423
|
+
def _refine(self, target: ast.expr, ty: RType) -> None:
|
|
424
|
+
if isinstance(target, ast.Name):
|
|
425
|
+
var = self.lookup(target.id)
|
|
426
|
+
if var and not var.ty.known and var.ty.name != "&mut":
|
|
427
|
+
var.ty = self.inner_ty(ty) if var.rust in self.plain else self.store_ty(ty)
|
|
428
|
+
|
|
429
|
+
def _receiver(self, node: ast.Call) -> ast.expr:
|
|
430
|
+
assert isinstance(node.func, ast.Attribute)
|
|
431
|
+
return node.func.value
|
|
432
|
+
|
|
433
|
+
def _flag(self, node: ast.expr | None) -> ir.RExpr:
|
|
434
|
+
return self.cond(node) if node is not None else ir.lit("bool", False, BOOL)
|
|
435
|
+
|
|
436
|
+
def _collect(self, e: ir.RExpr, ty: RType) -> ir.RExpr:
|
|
437
|
+
return ir.method(e, "collect", ty=ty, turbofish=ty)
|
|
438
|
+
|
|
439
|
+
# -- builtins -------------------------------------------------------------------------
|
|
440
|
+
def b_len(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
441
|
+
(x,) = self._argc(node, args, 1)
|
|
442
|
+
name = peel(x.ty).name
|
|
443
|
+
if name == "String":
|
|
444
|
+
count = ir.method(ir.method(x, "chars"), "count", ty=T("usize"))
|
|
445
|
+
elif name == "Iter":
|
|
446
|
+
count = ir.method(x, "count", ty=T("usize"))
|
|
447
|
+
elif name == "serde_json::Value":
|
|
448
|
+
return ir.rt("value_len", self.ref_of(x), ty=INT)
|
|
449
|
+
elif name in ("Vec", MAP, SET):
|
|
450
|
+
count = ir.method(x, "len", ty=T("usize"))
|
|
451
|
+
else:
|
|
452
|
+
raise Unsupported("PY2RS019", f"len() of {peel(x.ty).rust()}", node)
|
|
453
|
+
return ir.Cast(operand=count, ty=INT)
|
|
454
|
+
|
|
455
|
+
def b_range(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
456
|
+
v = self._argc(node, args, 1, 3)
|
|
457
|
+
if any(peel(a.ty) != INT for a in v):
|
|
458
|
+
raise Unsupported("PY2RS019", "range() with non-int arguments", node)
|
|
459
|
+
step = ir.lit_int(v[2]) if len(v) == 3 else None
|
|
460
|
+
it = T("Iter", INT)
|
|
461
|
+
result: ir.RExpr
|
|
462
|
+
if len(v) == 1:
|
|
463
|
+
result = ir.RangeX(lo=int_lit(0), hi=v[0], ty=it)
|
|
464
|
+
elif len(v) == 2:
|
|
465
|
+
result = ir.RangeX(lo=v[0], hi=v[1], ty=it)
|
|
466
|
+
elif step is None: # a computed step: the runtime handles sign and zero
|
|
467
|
+
result = ir.rt("range", *v, ty=it)
|
|
468
|
+
elif step > 0:
|
|
469
|
+
result = ir.method(ir.RangeX(lo=v[0], hi=v[1]), "step_by", v[2], ty=it)
|
|
470
|
+
elif step < 0:
|
|
471
|
+
lo = bin_("+", v[1], int_lit(1), INT)
|
|
472
|
+
rev = ir.method(ir.RangeX(lo=lo, hi=v[0], inclusive=True), "rev")
|
|
473
|
+
result = ir.method(rev, "step_by", int_lit(-step), ty=it)
|
|
474
|
+
else:
|
|
475
|
+
raise Unsupported("PY2RS019", "range() step must not be zero", node)
|
|
476
|
+
if any(isinstance(part, ir.Borrow) for value in v for part in ir.walk(value)):
|
|
477
|
+
return self._owned_iterator(result)
|
|
478
|
+
return result
|
|
479
|
+
|
|
480
|
+
def b_enumerate(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
481
|
+
args = self._argc(node, args, 1, 2)
|
|
482
|
+
it = self.as_iter(args[0], node)
|
|
483
|
+
start = kw.get("start")
|
|
484
|
+
first = args[1] if len(args) == 2 else self.expr(start) if start else None
|
|
485
|
+
i: ir.RExpr = ir.Cast(operand=ir.Var(name="i", ty=T("usize")), ty=INT)
|
|
486
|
+
if first is not None and not (isinstance(first, ir.Lit) and first.value == 0):
|
|
487
|
+
i = bin_("+", i, first, INT)
|
|
488
|
+
x = ir.Var(name="x", ty=arg(it.ty))
|
|
489
|
+
pair = ir.Closure(
|
|
490
|
+
params=[ir.PTuple([ir.PVar("i"), ir.PVar("x")])], body=ir.TupleX(elems=[i, x])
|
|
491
|
+
)
|
|
492
|
+
ty = T("Iter", T("tuple", INT, arg(it.ty)))
|
|
493
|
+
return ir.method(ir.method(it, "enumerate"), "map", pair, ty=ty)
|
|
494
|
+
|
|
495
|
+
def b_zip(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
496
|
+
its = [self.as_iter(a, node) for a in self._argc(node, args, 2, 3)]
|
|
497
|
+
ty = T("Iter", T("tuple", *(arg(i.ty) for i in its)))
|
|
498
|
+
zipped = ir.method(its[0], "zip", its[1], ty=ty)
|
|
499
|
+
if len(its) == 2:
|
|
500
|
+
return zipped
|
|
501
|
+
pat = ir.PTuple([ir.PTuple([ir.PVar("a"), ir.PVar("b")]), ir.PVar("c")])
|
|
502
|
+
body = ir.TupleX(elems=[ir.Var(name=n) for n in "abc"])
|
|
503
|
+
return ir.method(
|
|
504
|
+
ir.method(zipped, "zip", its[2]), "map", ir.Closure(params=[pat], body=body), ty=ty
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
def b_reversed(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
508
|
+
it = self.as_iter(self._argc(node, args, 1)[0], node)
|
|
509
|
+
return ir.method(it, "rev", ty=it.ty)
|
|
510
|
+
|
|
511
|
+
def b_sorted(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
512
|
+
it = self.as_iter(self._argc(node, args, 1)[0], node)
|
|
513
|
+
key, rev = kw.get("key"), self._flag(kw.get("reverse"))
|
|
514
|
+
self.drift("PY2RS047", node, "sorted() uses partial_cmp")
|
|
515
|
+
ty = T("Vec", arg(it.ty))
|
|
516
|
+
if key is None:
|
|
517
|
+
return ir.rt("sorted", it, rev, ty=ty)
|
|
518
|
+
if not isinstance(key, ast.Lambda):
|
|
519
|
+
raise Unsupported("PY2RS019", "sorted(key=...) needs a lambda", node)
|
|
520
|
+
return ir.rt("sorted_by_key", it, self.expr_Lambda(key, [arg(it.ty)]), rev, ty=ty)
|
|
521
|
+
|
|
522
|
+
def _minmax(self, which: str, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
523
|
+
if kw.get("key") is not None:
|
|
524
|
+
raise Unsupported("PY2RS019", f"{which}(key=...)", node)
|
|
525
|
+
self.drift("PY2RS047", node, f"{which}() uses partial_cmp")
|
|
526
|
+
default = kw.get("default")
|
|
527
|
+
if len(args) > 1:
|
|
528
|
+
common = ir.UNKNOWN
|
|
529
|
+
for a in args:
|
|
530
|
+
common = unify(common, peel(a.ty))
|
|
531
|
+
return ir.rt(
|
|
532
|
+
which,
|
|
533
|
+
ir.ArrayX(elems=[self.coerce(a, common) for a in args]),
|
|
534
|
+
ty=common if common.known else peel(args[0].ty),
|
|
535
|
+
)
|
|
536
|
+
it = self.as_iter(self._argc(node, args, 1)[0], node)
|
|
537
|
+
if default is not None:
|
|
538
|
+
d = self.coerce(self.expr(default), arg(it.ty))
|
|
539
|
+
return ir.method(ir.rt(f"{which}_opt", it), "unwrap_or", d, ty=arg(it.ty))
|
|
540
|
+
self.drift("PY2RS045", node, f"{which}() of an empty sequence panics")
|
|
541
|
+
return ir.rt(which, it, ty=arg(it.ty))
|
|
542
|
+
|
|
543
|
+
def b_min(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
544
|
+
return self._minmax("min", node, args, kw)
|
|
545
|
+
|
|
546
|
+
def b_max(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
547
|
+
return self._minmax("max", node, args, kw)
|
|
548
|
+
|
|
549
|
+
def b_sum(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
550
|
+
it = (
|
|
551
|
+
self.as_iter(args[0], node)
|
|
552
|
+
if args
|
|
553
|
+
else self.as_iter(self.expr(kw.items["iterable"]), node)
|
|
554
|
+
)
|
|
555
|
+
ty = arg(it.ty)
|
|
556
|
+
if ty not in (INT, FLOAT):
|
|
557
|
+
raise Unsupported("PY2RS019", f"sum() over {ty.rust()}", node)
|
|
558
|
+
if ty == INT:
|
|
559
|
+
self.drift("PY2RS041", node, "sum() over ints")
|
|
560
|
+
if ty == FLOAT:
|
|
561
|
+
self.drift("PY2RS042", node, "sum(floats) uses compensated summation like CPython")
|
|
562
|
+
start = (
|
|
563
|
+
self.coerce(args[1], FLOAT, promote=True)
|
|
564
|
+
if len(args) > 1
|
|
565
|
+
else ir.lit("float", 0.0, FLOAT)
|
|
566
|
+
)
|
|
567
|
+
return ir.rt("sum_f64", it, start, ty=FLOAT)
|
|
568
|
+
if self.ctx.cfg.int_overflow == "checked":
|
|
569
|
+
total: ir.RExpr = ir.rt("sum", it, ty=INT)
|
|
570
|
+
else:
|
|
571
|
+
total = ir.method(it, "sum", ty=ty, turbofish=ty)
|
|
572
|
+
return bin_("+", total, args[1], ty) if len(args) > 1 else total
|
|
573
|
+
|
|
574
|
+
def _quantifier(self, which: str, node: ast.Call, args: list[ir.RExpr]) -> ir.RExpr:
|
|
575
|
+
it = self.as_iter(self._argc(node, args, 1)[0], node)
|
|
576
|
+
ety = arg(it.ty)
|
|
577
|
+
b = ir.Var(name="b", ty=ety)
|
|
578
|
+
test = b if ety == BOOL else self.truthy(b, node)
|
|
579
|
+
return ir.method(it, which, closure(["b"], test), ty=BOOL)
|
|
580
|
+
|
|
581
|
+
def b_any(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
582
|
+
return self._quantifier("any", node, args)
|
|
583
|
+
|
|
584
|
+
def b_all(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
585
|
+
return self._quantifier("all", node, args)
|
|
586
|
+
|
|
587
|
+
def b_abs(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
588
|
+
x = self._argc(node, args, 1)[0]
|
|
589
|
+
if peel(x.ty) not in (INT, FLOAT):
|
|
590
|
+
raise Unsupported("PY2RS019", f"abs() of {peel(x.ty).rust()}", node)
|
|
591
|
+
mode = self.ctx.cfg.int_overflow
|
|
592
|
+
if peel(x.ty) == INT and mode == "checked":
|
|
593
|
+
return ir.rt("abs", x, ty=INT)
|
|
594
|
+
return ir.method(
|
|
595
|
+
x, "wrapping_abs" if peel(x.ty) == INT and mode == "wrapping" else "abs", ty=peel(x.ty)
|
|
596
|
+
)
|
|
597
|
+
|
|
598
|
+
def b_round(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
599
|
+
args = self._argc(node, args, 1, 2)
|
|
600
|
+
digits_node = kw.get("ndigits")
|
|
601
|
+
digits = args[1] if len(args) == 2 else self.expr(digits_node) if digits_node else None
|
|
602
|
+
if digits is not None:
|
|
603
|
+
if (
|
|
604
|
+
peel(args[0].ty) != FLOAT
|
|
605
|
+
or (ir.lit_int(digits) or 0) < 0
|
|
606
|
+
or ir.lit_int(digits) is None
|
|
607
|
+
):
|
|
608
|
+
raise Unsupported(
|
|
609
|
+
"PY2RS019", "round(x, n) needs a float and a literal n >= 0", node
|
|
610
|
+
)
|
|
611
|
+
self.drift("PY2RS042", node, "round(x, n)")
|
|
612
|
+
return ir.rt("round_digits", args[0], digits, ty=FLOAT)
|
|
613
|
+
x = self.coerce(args[0], FLOAT, promote=True)
|
|
614
|
+
self.drift("PY2RS045", node, "round() of nan/inf or beyond i64 panics")
|
|
615
|
+
return ir.rt("round", x, ty=INT)
|
|
616
|
+
|
|
617
|
+
def b_Decimal(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
618
|
+
"""A Decimal literal as its String (JSON) form; arithmetic on it is not translated."""
|
|
619
|
+
(x,) = self._argc(node, args, 1)
|
|
620
|
+
if isinstance(x, ir.Lit) and x.kind in ("int", "str"):
|
|
621
|
+
return lit_str(str(x.value))
|
|
622
|
+
raise Unsupported("PY2RS019", "Decimal() of a computed value", node)
|
|
623
|
+
|
|
624
|
+
def b_int(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
625
|
+
x = self._argc(node, args, 1)[0]
|
|
626
|
+
ty = peel(x.ty)
|
|
627
|
+
if ty == STR and self.catches("ValueError"):
|
|
628
|
+
return self.question(ir.rt("try_int", self.as_str(x)), INT, node)
|
|
629
|
+
if ty == STR:
|
|
630
|
+
self.drift("PY2RS045", node, "int(str) panics instead of raising ValueError")
|
|
631
|
+
return ir.rt("or_panic", ir.rt("try_int", self.as_str(x)), ty=INT)
|
|
632
|
+
if ty == FLOAT:
|
|
633
|
+
self.drift("PY2RS045", node, "int(float) of NaN/inf/huge values panics")
|
|
634
|
+
return ir.rt("float_to_int", x, ty=INT)
|
|
635
|
+
if ty == BOOL:
|
|
636
|
+
return ir.Cast(operand=x, ty=INT)
|
|
637
|
+
if ty == INT:
|
|
638
|
+
return x
|
|
639
|
+
raise Unsupported("PY2RS019", f"int() of {ty.rust()}", node)
|
|
640
|
+
|
|
641
|
+
def b_float(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
642
|
+
x = self._argc(node, args, 1)[0]
|
|
643
|
+
ty = peel(x.ty)
|
|
644
|
+
if ty == STR and self.catches("ValueError"):
|
|
645
|
+
return self.question(ir.rt("try_float", self.as_str(x)), FLOAT, node)
|
|
646
|
+
if ty == STR:
|
|
647
|
+
self.drift("PY2RS045", node, "float(str) panics instead of raising ValueError")
|
|
648
|
+
return ir.rt("or_panic", ir.rt("try_float", self.as_str(x)), ty=FLOAT)
|
|
649
|
+
if ty in (INT, FLOAT):
|
|
650
|
+
return self.coerce(x, FLOAT, promote=True)
|
|
651
|
+
raise Unsupported("PY2RS019", f"float() of {ty.rust()}", node)
|
|
652
|
+
|
|
653
|
+
def b_str(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
654
|
+
x = self._argc(node, args, 1)[0]
|
|
655
|
+
shown = fstrings.display(self, x, node)
|
|
656
|
+
return shown if shown.ty == STR else ir.method(shown, "to_string", ty=STR)
|
|
657
|
+
|
|
658
|
+
def b_bool(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
659
|
+
return self.truthy(self._argc(node, args, 1)[0], node)
|
|
660
|
+
|
|
661
|
+
def b_repr(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
662
|
+
x = self._argc(node, args, 1)[0]
|
|
663
|
+
if peel(x.ty) == STR:
|
|
664
|
+
return ir.rt("repr_str", self.as_str(x), ty=STR)
|
|
665
|
+
if peel(x.ty).name == "rt::PyError": # `KeyError('k')`, `ValueError('bad value')`
|
|
666
|
+
return ir.method(x, "repr", ty=STR)
|
|
667
|
+
return self.b_str(node, args, kw)
|
|
668
|
+
|
|
669
|
+
def b_list(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
670
|
+
if not args:
|
|
671
|
+
return ir.Call(func=ir.Path(path="Vec::new"), ty=T("Vec", UNKNOWN))
|
|
672
|
+
it = self.as_iter(self._argc(node, args, 1)[0], node)
|
|
673
|
+
return self._collect(it, T("Vec", arg(it.ty)))
|
|
674
|
+
|
|
675
|
+
b_tuple = b_list
|
|
676
|
+
|
|
677
|
+
def b_set(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
678
|
+
if not args:
|
|
679
|
+
return ir.Call(func=ir.Path(path=f"{SET}::new"), ty=T(SET, UNKNOWN))
|
|
680
|
+
it = self.as_iter(self._argc(node, args, 1)[0], node)
|
|
681
|
+
return self._collect(it, T(SET, arg(it.ty)))
|
|
682
|
+
|
|
683
|
+
b_frozenset = b_set
|
|
684
|
+
|
|
685
|
+
def b_dict(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
686
|
+
if not args:
|
|
687
|
+
return ir.Call(func=ir.Path(path=f"{MAP}::new"), ty=T(MAP, UNKNOWN, UNKNOWN))
|
|
688
|
+
it = self.as_iter(self._argc(node, args, 1)[0], node)
|
|
689
|
+
pair = arg(it.ty)
|
|
690
|
+
if pair.name != "tuple" or len(pair.args) != 2:
|
|
691
|
+
raise Unsupported("PY2RS019", "dict() needs an iterable of pairs", node)
|
|
692
|
+
return self._collect(it, T(MAP, *pair.args))
|
|
693
|
+
|
|
694
|
+
def b_ord(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
695
|
+
x = self._argc(node, args, 1)[0]
|
|
696
|
+
first = ir.method(ir.method(x, "chars"), "next")
|
|
697
|
+
return ir.Cast(
|
|
698
|
+
operand=expect(first, "TypeError: ord() expected a character", T("char")), ty=INT
|
|
699
|
+
)
|
|
700
|
+
|
|
701
|
+
def b_chr(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
702
|
+
x = ir.Cast(operand=self._argc(node, args, 1)[0], ty=T("u32"))
|
|
703
|
+
ch = ir.Call(func=ir.Path(path="char::from_u32"), args=[x])
|
|
704
|
+
return ir.method(
|
|
705
|
+
expect(ch, "ValueError: chr() arg not in range", T("char")), "to_string", ty=STR
|
|
706
|
+
)
|
|
707
|
+
|
|
708
|
+
def b_print(self, node: ast.Call, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
709
|
+
if kw.items:
|
|
710
|
+
raise Unsupported("PY2RS019", "print() with keyword arguments", node)
|
|
711
|
+
shown = [fstrings.display(self, a, node) for a in args]
|
|
712
|
+
return ir.Macro(name="println", args=shown, template=" ".join(["{}"] * len(shown)), ty=UNIT)
|
|
713
|
+
|
|
714
|
+
# -- str methods ----------------------------------------------------------------------
|
|
715
|
+
def m_str_rsplit(
|
|
716
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
717
|
+
) -> ir.RExpr:
|
|
718
|
+
args = self._argc(node, args, 1, 2)
|
|
719
|
+
limit = kw.get("maxsplit")
|
|
720
|
+
count = args[1] if len(args) == 2 else self.expr(limit) if limit is not None else None
|
|
721
|
+
if count is None:
|
|
722
|
+
return self.m_str_split(node, s, args, kw)
|
|
723
|
+
return ir.rt("rsplit_n", self.as_str(s), self.as_str(args[0]), count, ty=T("Vec", STR))
|
|
724
|
+
|
|
725
|
+
def m_str_splitlines(
|
|
726
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
727
|
+
) -> ir.RExpr:
|
|
728
|
+
self._argc(node, args, 0)
|
|
729
|
+
self.drift("PY2RS044", node, "splitlines() splits on \\n and \\r\\n only")
|
|
730
|
+
to_s = closure(["p"], ir.method(ir.Var(name="p"), "to_string", ty=STR))
|
|
731
|
+
return self._collect(ir.method(ir.method(s, "lines"), "map", to_s), T("Vec", STR))
|
|
732
|
+
|
|
733
|
+
def m_value_get(self, node: ast.Call, v: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
734
|
+
args = self._argc(node, args, 1, 2)
|
|
735
|
+
found = ir.method(
|
|
736
|
+
ir.method(v, "get", self.ref_of(args[0])), "cloned", ty=T("Option", VALUE)
|
|
737
|
+
)
|
|
738
|
+
if len(args) == 1 or (isinstance(args[1], ir.Lit) and args[1].kind == "none"):
|
|
739
|
+
return found
|
|
740
|
+
return ir.method(found, "unwrap_or", self.coerce(args[1], VALUE), ty=VALUE)
|
|
741
|
+
|
|
742
|
+
def m_str_encode(
|
|
743
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
744
|
+
) -> ir.RExpr:
|
|
745
|
+
if args and not (
|
|
746
|
+
isinstance(args[0], ir.Lit) and str(args[0].value).lower() in ("utf-8", "utf8")
|
|
747
|
+
):
|
|
748
|
+
raise Unsupported("PY2RS019", "encode() with an encoding other than utf-8", node)
|
|
749
|
+
return self._as_bytes(s)
|
|
750
|
+
|
|
751
|
+
def m_bytes_decode(
|
|
752
|
+
self, node: ast.Call, b: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
753
|
+
) -> ir.RExpr:
|
|
754
|
+
if args and not (
|
|
755
|
+
isinstance(args[0], ir.Lit) and str(args[0].value).lower() in ("utf-8", "utf8")
|
|
756
|
+
):
|
|
757
|
+
raise Unsupported("PY2RS019", "decode() with an encoding other than utf-8", node)
|
|
758
|
+
self.drift("PY2RS045", node, "decode() of invalid UTF-8 panics instead of raising")
|
|
759
|
+
text = ir.Call(func=ir.Path(path="String::from_utf8"), args=[b], ty=T("Result", STR))
|
|
760
|
+
return expect(text, "UnicodeDecodeError: invalid utf-8", STR)
|
|
761
|
+
|
|
762
|
+
def m_match_group(
|
|
763
|
+
self, node: ast.Call, m: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
764
|
+
) -> ir.RExpr:
|
|
765
|
+
self.drift("PY2RS045", node, "group(n) of a group that did not match panics (Python: None)")
|
|
766
|
+
if not args:
|
|
767
|
+
return ir.method(m, "group", int_lit(0), ty=STR)
|
|
768
|
+
(g,) = self._argc(node, args, 1)
|
|
769
|
+
if peel(g.ty) == STR:
|
|
770
|
+
return ir.method(m, "named", self.as_str(g), ty=STR)
|
|
771
|
+
return ir.method(m, "group", g, ty=STR)
|
|
772
|
+
|
|
773
|
+
def m_match_groups(
|
|
774
|
+
self, node: ast.Call, m: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
775
|
+
) -> ir.RExpr:
|
|
776
|
+
self._argc(node, args, 0)
|
|
777
|
+
return ir.method(m, "groups", ty=T("Vec", STR))
|
|
778
|
+
|
|
779
|
+
def m_match_start(
|
|
780
|
+
self, node: ast.Call, m: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
781
|
+
) -> ir.RExpr:
|
|
782
|
+
return ir.method(m, "start", ty=INT)
|
|
783
|
+
|
|
784
|
+
def m_match_end(self, node: ast.Call, m: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
785
|
+
return ir.method(m, "end", ty=INT)
|
|
786
|
+
|
|
787
|
+
def _pat_call(self, name: str, p: ir.RExpr, args: list[ir.RExpr], ty: RType) -> ir.RExpr:
|
|
788
|
+
return ir.method(p, name, *[self.as_str(a) for a in args], ty=ty)
|
|
789
|
+
|
|
790
|
+
def m_pattern_search(
|
|
791
|
+
self, node: ast.Call, p: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
792
|
+
) -> ir.RExpr:
|
|
793
|
+
return self._pat_call("search", p, self._argc(node, args, 1), option(T("rt::re::Match")))
|
|
794
|
+
|
|
795
|
+
def m_pattern_match(
|
|
796
|
+
self, node: ast.Call, p: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
797
|
+
) -> ir.RExpr:
|
|
798
|
+
return self._pat_call("match_", p, self._argc(node, args, 1), option(T("rt::re::Match")))
|
|
799
|
+
|
|
800
|
+
def m_pattern_fullmatch(
|
|
801
|
+
self, node: ast.Call, p: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
802
|
+
) -> ir.RExpr:
|
|
803
|
+
return self._pat_call("fullmatch", p, self._argc(node, args, 1), option(T("rt::re::Match")))
|
|
804
|
+
|
|
805
|
+
def m_pattern_sub(
|
|
806
|
+
self, node: ast.Call, p: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
807
|
+
) -> ir.RExpr:
|
|
808
|
+
return self._pat_call("sub", p, self._argc(node, args, 2), STR)
|
|
809
|
+
|
|
810
|
+
def m_pattern_findall(
|
|
811
|
+
self, node: ast.Call, p: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
812
|
+
) -> ir.RExpr:
|
|
813
|
+
return self._pat_call("findall", p, self._argc(node, args, 1), T("Vec", STR))
|
|
814
|
+
|
|
815
|
+
def m_pattern_split(
|
|
816
|
+
self, node: ast.Call, p: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
817
|
+
) -> ir.RExpr:
|
|
818
|
+
return self._pat_call("split", p, self._argc(node, args, 1), T("Vec", STR))
|
|
819
|
+
|
|
820
|
+
def m_digest_hexdigest(
|
|
821
|
+
self, node: ast.Call, d: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
822
|
+
) -> ir.RExpr:
|
|
823
|
+
return ir.method(d, "hexdigest", ty=STR)
|
|
824
|
+
|
|
825
|
+
def m_digest_digest(
|
|
826
|
+
self, node: ast.Call, d: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
827
|
+
) -> ir.RExpr:
|
|
828
|
+
return ir.method(d, "digest", ty=BYTES)
|
|
829
|
+
|
|
830
|
+
def m_str_split(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
831
|
+
args = self._argc(node, args, 0, 2)
|
|
832
|
+
limit = kw.get("maxsplit")
|
|
833
|
+
sep = args[0] if args else None
|
|
834
|
+
if len(args) == 2 or limit is not None:
|
|
835
|
+
if sep is None:
|
|
836
|
+
raise Unsupported("PY2RS019", "split(None, maxsplit)", node)
|
|
837
|
+
n = args[1] if len(args) == 2 or limit is None else self.expr(limit)
|
|
838
|
+
count = ir.Cast(operand=bin_("+", n, int_lit(1), INT), ty=T("usize"))
|
|
839
|
+
head = ir.method(s, "splitn", count, self.ref_of(sep))
|
|
840
|
+
elif sep is not None:
|
|
841
|
+
head = ir.method(s, "split", self.ref_of(sep))
|
|
842
|
+
else:
|
|
843
|
+
return ir.rt("split_whitespace", self.as_str(s), ty=T("Vec", STR))
|
|
844
|
+
to_s = closure(["p"], ir.method(ir.Var(name="p"), "to_string", ty=STR))
|
|
845
|
+
return self._collect(ir.method(head, "map", to_s), T("Vec", STR))
|
|
846
|
+
|
|
847
|
+
def _trim(self, name: str, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr]) -> ir.RExpr:
|
|
848
|
+
args = self._argc(node, args, 0, 1)
|
|
849
|
+
if not args: # Python's whitespace, which includes U+001C..U+001F
|
|
850
|
+
helper = {"trim": "strip", "trim_start": "lstrip", "trim_end": "rstrip"}[name]
|
|
851
|
+
return ir.rt(helper, self.as_str(s), ty=STR)
|
|
852
|
+
has = closure(["c"], ir.method(ir.dup(args[0]), "contains", ir.Var(name="c"), ty=BOOL))
|
|
853
|
+
stripped = ir.method(s, f"{name}_matches", has)
|
|
854
|
+
return ir.method(stripped, "to_string", ty=STR)
|
|
855
|
+
|
|
856
|
+
def m_str_strip(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
857
|
+
return self._trim("trim", node, s, args)
|
|
858
|
+
|
|
859
|
+
def m_str_lstrip(
|
|
860
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
861
|
+
) -> ir.RExpr:
|
|
862
|
+
return self._trim("trim_start", node, s, args)
|
|
863
|
+
|
|
864
|
+
def m_str_rstrip(
|
|
865
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
866
|
+
) -> ir.RExpr:
|
|
867
|
+
return self._trim("trim_end", node, s, args)
|
|
868
|
+
|
|
869
|
+
def m_str_join(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
870
|
+
(parts,) = self._argc(node, args, 1)
|
|
871
|
+
if arg(parts.ty) != STR:
|
|
872
|
+
raise Unsupported("PY2RS019", f"str.join over {peel(parts.ty).rust()}", node)
|
|
873
|
+
if peel(parts.ty).name != "Vec":
|
|
874
|
+
parts = self._collect(self.as_iter(parts, node), T("Vec", STR))
|
|
875
|
+
return ir.method(parts, "join", self.as_str(s), ty=STR)
|
|
876
|
+
|
|
877
|
+
def m_str_replace(
|
|
878
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
879
|
+
) -> ir.RExpr:
|
|
880
|
+
args = self._argc(node, args, 2, 3)
|
|
881
|
+
old, new = self.ref_of(args[0]), self.as_str(args[1])
|
|
882
|
+
if len(args) == 3:
|
|
883
|
+
return ir.method(
|
|
884
|
+
s, "replacen", old, new, ir.Cast(operand=args[2], ty=T("usize")), ty=STR
|
|
885
|
+
)
|
|
886
|
+
return ir.method(s, "replace", old, new, ty=STR)
|
|
887
|
+
|
|
888
|
+
def _affix(self, rust: str, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr]) -> ir.RExpr:
|
|
889
|
+
(x,) = self._argc(node, args, 1)
|
|
890
|
+
if isinstance(x, ir.TupleX) and x.elems and all(peel(e.ty) == STR for e in x.elems):
|
|
891
|
+
tests = [self._affix(rust, node, ir.dup(s), [e]) for e in x.elems] # any of them
|
|
892
|
+
out = tests[0]
|
|
893
|
+
for t in tests[1:]:
|
|
894
|
+
out = bin_("||", out, t, BOOL)
|
|
895
|
+
return out
|
|
896
|
+
if peel(x.ty) != STR:
|
|
897
|
+
raise Unsupported("PY2RS019", f"{rust} with a {peel(x.ty).rust()} argument", node)
|
|
898
|
+
return ir.method(s, rust, self.ref_of(x), ty=BOOL)
|
|
899
|
+
|
|
900
|
+
def m_str_startswith(
|
|
901
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
902
|
+
) -> ir.RExpr:
|
|
903
|
+
return self._affix("starts_with", node, s, args)
|
|
904
|
+
|
|
905
|
+
def m_str_endswith(
|
|
906
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
907
|
+
) -> ir.RExpr:
|
|
908
|
+
return self._affix("ends_with", node, s, args)
|
|
909
|
+
|
|
910
|
+
def m_str_lower(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
911
|
+
self.drift("PY2RS044", node, "lower()")
|
|
912
|
+
return ir.method(s, "to_lowercase", ty=STR)
|
|
913
|
+
|
|
914
|
+
def m_str_upper(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
915
|
+
self.drift("PY2RS044", node, "upper()")
|
|
916
|
+
return ir.method(s, "to_uppercase", ty=STR)
|
|
917
|
+
|
|
918
|
+
def m_str_find(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
919
|
+
(x,) = self._argc(node, args, 1)
|
|
920
|
+
return ir.rt("str_find", self.as_str(s), self.as_str(x), ty=INT)
|
|
921
|
+
|
|
922
|
+
def m_str_count(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
923
|
+
(x,) = self._argc(node, args, 1)
|
|
924
|
+
return ir.Cast(operand=ir.method(ir.method(s, "matches", self.ref_of(x)), "count"), ty=INT)
|
|
925
|
+
|
|
926
|
+
def _predicate(self, test: str, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr]) -> ir.RExpr:
|
|
927
|
+
self._argc(node, args, 0)
|
|
928
|
+
self.drift("PY2RS044", node, f"str.{test}")
|
|
929
|
+
each = closure(["c"], ir.method(ir.Var(name="c"), test, ty=BOOL))
|
|
930
|
+
every = ir.method(ir.method(ir.dup(s), "chars"), "all", each, ty=BOOL)
|
|
931
|
+
return bin_("&&", not_(ir.method(s, "is_empty", ty=BOOL)), every, BOOL)
|
|
932
|
+
|
|
933
|
+
def m_str_isdigit(
|
|
934
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
935
|
+
) -> ir.RExpr:
|
|
936
|
+
return self._predicate("is_ascii_digit", node, s, args)
|
|
937
|
+
|
|
938
|
+
def m_str_isalpha(
|
|
939
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
940
|
+
) -> ir.RExpr:
|
|
941
|
+
return self._predicate("is_alphabetic", node, s, args)
|
|
942
|
+
|
|
943
|
+
def m_str_isalnum(
|
|
944
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
945
|
+
) -> ir.RExpr:
|
|
946
|
+
return self._predicate("is_alphanumeric", node, s, args)
|
|
947
|
+
|
|
948
|
+
def m_str_isspace(
|
|
949
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
950
|
+
) -> ir.RExpr:
|
|
951
|
+
return self._predicate("is_whitespace", node, s, args)
|
|
952
|
+
|
|
953
|
+
def _unaffix(self, rust: str, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr]) -> ir.RExpr:
|
|
954
|
+
(x,) = self._argc(node, args, 1)
|
|
955
|
+
stripped = ir.method(self.as_str(s), rust, self.ref_of(x))
|
|
956
|
+
return ir.method(
|
|
957
|
+
ir.method(stripped, "unwrap_or", self.as_str(ir.dup(s))), "to_string", ty=STR
|
|
958
|
+
)
|
|
959
|
+
|
|
960
|
+
def m_str_removeprefix(
|
|
961
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
962
|
+
) -> ir.RExpr:
|
|
963
|
+
return self._unaffix("strip_prefix", node, s, args)
|
|
964
|
+
|
|
965
|
+
def m_str_removesuffix(
|
|
966
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
967
|
+
) -> ir.RExpr:
|
|
968
|
+
return self._unaffix("strip_suffix", node, s, args)
|
|
969
|
+
|
|
970
|
+
# -- list methods ---------------------------------------------------------------------
|
|
971
|
+
def m_list_append(
|
|
972
|
+
self, node: ast.Call, xs: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
973
|
+
) -> ir.RExpr:
|
|
974
|
+
(x,) = self._argc(node, args, 1)
|
|
975
|
+
item = self.coerce(x, arg(xs.ty))
|
|
976
|
+
self._refine(self._receiver(node), T("Vec", peel(item.ty)))
|
|
977
|
+
return ir.method(xs, "push", item, ty=UNIT)
|
|
978
|
+
|
|
979
|
+
def m_list_insert(
|
|
980
|
+
self, node: ast.Call, xs: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
981
|
+
) -> ir.RExpr:
|
|
982
|
+
i, x = self._argc(node, args, 2)
|
|
983
|
+
item = self.coerce(x, arg(xs.ty))
|
|
984
|
+
self._refine(self._receiver(node), T("Vec", peel(item.ty)))
|
|
985
|
+
size = ir.method(ir.dup(xs), "len", ty=T("usize"))
|
|
986
|
+
at = ir.rt("insert_at", self.coerce(i, INT), size, ty=T("usize"))
|
|
987
|
+
return ir.method(xs, "insert", at, item, ty=UNIT)
|
|
988
|
+
|
|
989
|
+
def m_list_extend(
|
|
990
|
+
self, node: ast.Call, xs: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
991
|
+
) -> ir.RExpr:
|
|
992
|
+
(it,) = self._argc(node, args, 1)
|
|
993
|
+
if isinstance(xs, ir.Var) and isinstance(it, ir.Var) and xs.name == it.name:
|
|
994
|
+
return ir.method(xs, "extend_from_within", ir.Path(path=".."), ty=UNIT)
|
|
995
|
+
items = self.as_iter(it, node)
|
|
996
|
+
self._refine(self._receiver(node), T("Vec", arg(items.ty)))
|
|
997
|
+
return ir.method(xs, "extend", items, ty=UNIT)
|
|
998
|
+
|
|
999
|
+
def m_list_pop(self, node: ast.Call, xs: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
1000
|
+
args = self._argc(node, args, 0, 1)
|
|
1001
|
+
self.drift("PY2RS045", node, "pop() panics instead of raising IndexError")
|
|
1002
|
+
if not args:
|
|
1003
|
+
return expect(ir.method(xs, "pop"), "IndexError: pop from empty list", arg(xs.ty))
|
|
1004
|
+
pos = ir.rt("idx", args[0], ir.method(ir.dup(xs), "len", ty=T("usize")), ty=T("usize"))
|
|
1005
|
+
return ir.method(xs, "remove", pos, ty=arg(xs.ty))
|
|
1006
|
+
|
|
1007
|
+
def m_list_sort(
|
|
1008
|
+
self, node: ast.Call, xs: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
1009
|
+
) -> ir.RExpr:
|
|
1010
|
+
self._argc(node, args, 0)
|
|
1011
|
+
key, rev = kw.get("key"), self._flag(kw.get("reverse"))
|
|
1012
|
+
self.drift("PY2RS047", node, "sort() uses partial_cmp")
|
|
1013
|
+
if key is None:
|
|
1014
|
+
return ir.rt("sort", self.mut_ref(xs), rev, ty=UNIT)
|
|
1015
|
+
if not isinstance(key, ast.Lambda):
|
|
1016
|
+
raise Unsupported("PY2RS019", "sort(key=...) needs a lambda", node)
|
|
1017
|
+
return ir.rt(
|
|
1018
|
+
"sort_by_key", self.mut_ref(xs), self.expr_Lambda(key, [arg(xs.ty)]), rev, ty=UNIT
|
|
1019
|
+
)
|
|
1020
|
+
|
|
1021
|
+
def m_list_reverse(
|
|
1022
|
+
self, node: ast.Call, xs: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
1023
|
+
) -> ir.RExpr:
|
|
1024
|
+
return ir.method(xs, "reverse", ty=UNIT)
|
|
1025
|
+
|
|
1026
|
+
def m_list_clear(
|
|
1027
|
+
self, node: ast.Call, xs: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
1028
|
+
) -> ir.RExpr:
|
|
1029
|
+
return ir.method(xs, "clear", ty=UNIT)
|
|
1030
|
+
|
|
1031
|
+
def m_list_copy(
|
|
1032
|
+
self, node: ast.Call, xs: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
1033
|
+
) -> ir.RExpr:
|
|
1034
|
+
return self._clone_container(xs)
|
|
1035
|
+
|
|
1036
|
+
def _clone_container(self, x: ir.RExpr) -> ir.RExpr:
|
|
1037
|
+
"""A new container with the same elements (handles are shared, like Python's copy())."""
|
|
1038
|
+
return ir.method(x, "clone", ty=peel(x.ty)) if self.shared else x
|
|
1039
|
+
|
|
1040
|
+
# -- dict methods ---------------------------------------------------------------------
|
|
1041
|
+
def m_dict_get(self, node: ast.Call, d: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
1042
|
+
args = self._argc(node, args, 1, 2)
|
|
1043
|
+
v = arg(d.ty, 1)
|
|
1044
|
+
found = ir.method(ir.method(d, "get", self.ref_of(args[0])), "cloned", ty=T("Option", v))
|
|
1045
|
+
if len(args) == 1 or (isinstance(args[1], ir.Lit) and args[1].kind == "none"):
|
|
1046
|
+
if v.name == "Option": # a stored None and a missing key are both None
|
|
1047
|
+
return ir.method(found, "flatten", ty=v)
|
|
1048
|
+
return found
|
|
1049
|
+
return ir.method(found, "unwrap_or", self.coerce(args[1], v), ty=v)
|
|
1050
|
+
|
|
1051
|
+
def m_dict_setdefault(
|
|
1052
|
+
self, node: ast.Call, d: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
1053
|
+
) -> ir.RExpr:
|
|
1054
|
+
k, v = self._argc(node, args, 2)
|
|
1055
|
+
entry = ir.method(d, "entry", self.coerce(k, arg(d.ty, 0)))
|
|
1056
|
+
return ir.method(
|
|
1057
|
+
ir.method(entry, "or_insert", self.coerce(v, arg(d.ty, 1))), "clone", ty=arg(d.ty, 1)
|
|
1058
|
+
)
|
|
1059
|
+
|
|
1060
|
+
def m_dict_pop(self, node: ast.Call, d: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
1061
|
+
args = self._argc(node, args, 1, 2)
|
|
1062
|
+
taken = ir.method(d, "shift_remove", self.ref_of(args[0]))
|
|
1063
|
+
if len(args) == 1:
|
|
1064
|
+
self.drift("PY2RS045", node, "pop() panics instead of raising KeyError")
|
|
1065
|
+
return expect(taken, "KeyError", arg(d.ty, 1))
|
|
1066
|
+
return ir.method(taken, "unwrap_or", self.coerce(args[1], arg(d.ty, 1)), ty=arg(d.ty, 1))
|
|
1067
|
+
|
|
1068
|
+
def m_dict_items(
|
|
1069
|
+
self, node: ast.Call, d: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
1070
|
+
) -> ir.RExpr:
|
|
1071
|
+
k, v = ir.Var(name="k"), ir.Var(name="v")
|
|
1072
|
+
body = ir.TupleX(elems=[ir.method(k, "clone"), ir.method(v, "clone")])
|
|
1073
|
+
pair = ir.Closure(params=[ir.PTuple([ir.PVar("k"), ir.PVar("v")])], body=body)
|
|
1074
|
+
item = T("Iter", T("tuple", *peel(d.ty).args))
|
|
1075
|
+
return self._snapshot(d, ir.method(ir.method(d, "iter"), "map", pair, ty=item), item)
|
|
1076
|
+
|
|
1077
|
+
def m_dict_keys(self, node: ast.Call, d: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
1078
|
+
item = T("Iter", arg(d.ty, 0))
|
|
1079
|
+
return self._snapshot(d, ir.method(ir.method(d, "keys"), "cloned", ty=item), item)
|
|
1080
|
+
|
|
1081
|
+
def m_dict_values(
|
|
1082
|
+
self, node: ast.Call, d: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
1083
|
+
) -> ir.RExpr:
|
|
1084
|
+
item = T("Iter", arg(d.ty, 1))
|
|
1085
|
+
return self._snapshot(d, ir.method(ir.method(d, "values"), "cloned", ty=item), item)
|
|
1086
|
+
|
|
1087
|
+
def m_dict_update(
|
|
1088
|
+
self, node: ast.Call, d: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
1089
|
+
) -> ir.RExpr:
|
|
1090
|
+
(other,) = self._argc(node, args, 1)
|
|
1091
|
+
return ir.method(d, "extend", self.m_dict_items(node, other, [], kw), ty=UNIT)
|
|
1092
|
+
|
|
1093
|
+
def m_dict_clear(
|
|
1094
|
+
self, node: ast.Call, d: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
1095
|
+
) -> ir.RExpr:
|
|
1096
|
+
return ir.method(d, "clear", ty=UNIT)
|
|
1097
|
+
|
|
1098
|
+
def m_dict_copy(self, node: ast.Call, d: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
1099
|
+
return self._clone_container(d)
|
|
1100
|
+
|
|
1101
|
+
# -- set methods ----------------------------------------------------------------------
|
|
1102
|
+
def m_set_add(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
1103
|
+
(x,) = self._argc(node, args, 1)
|
|
1104
|
+
item = self.coerce(x, arg(s.ty))
|
|
1105
|
+
self._refine(self._receiver(node), T(SET, peel(item.ty)))
|
|
1106
|
+
return ir.method(s, "insert", item, ty=UNIT)
|
|
1107
|
+
|
|
1108
|
+
def m_set_discard(
|
|
1109
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
1110
|
+
) -> ir.RExpr:
|
|
1111
|
+
(x,) = self._argc(node, args, 1)
|
|
1112
|
+
remove = "shift_remove" if self.ctx.cfg.set_type == "indexset" else "remove"
|
|
1113
|
+
return ir.method(s, remove, self.ref_of(x), ty=UNIT)
|
|
1114
|
+
|
|
1115
|
+
def m_set_update(
|
|
1116
|
+
self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag
|
|
1117
|
+
) -> ir.RExpr:
|
|
1118
|
+
(it,) = self._argc(node, args, 1)
|
|
1119
|
+
return ir.method(s, "extend", self.as_iter(it, node), ty=UNIT)
|
|
1120
|
+
|
|
1121
|
+
def m_set_clear(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
1122
|
+
return ir.method(s, "clear", ty=UNIT)
|
|
1123
|
+
|
|
1124
|
+
def m_set_copy(self, node: ast.Call, s: ir.RExpr, args: list[ir.RExpr], kw: KwBag) -> ir.RExpr:
|
|
1125
|
+
return self._clone_container(s)
|