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,455 @@
|
|
|
1
|
+
"""Comparing what the Python function returned with what the Rust function returned.
|
|
2
|
+
|
|
3
|
+
`strict`: byte equality of the serialised outputs. `functional` (default): canonical JSON compare
|
|
4
|
+
(ints exact, floats exact unless a tolerance is set, NaN/inf explicit, strings exact, dict key order
|
|
5
|
+
checked, exceptions compared by kind), then the rule normalisers of the project's `[equivalence]`
|
|
6
|
+
profile. A difference is either *hard* (a value, shape, null, result-vs-exception difference: the
|
|
7
|
+
functions differ, no judge is asked) or *soft* (only text layout or dict key order differ: a
|
|
8
|
+
judge may rule on it, otherwise `needs-judgement`). Soft is narrow: a string differing only in
|
|
9
|
+
whitespace, Unicode form or JSON layout, a dict's key order. A different letter, digit, sign or
|
|
10
|
+
point, or a reordered list, is hard. Ints outside i64 turn a difference into an
|
|
11
|
+
overflow *drift* finding instead of a plain failure.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import math
|
|
18
|
+
import re
|
|
19
|
+
import tomllib
|
|
20
|
+
import unicodedata
|
|
21
|
+
from collections.abc import Sequence
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from python2rust.errors import UsageError
|
|
27
|
+
from python2rust.verify.equiv.types import Ty, has_bigint
|
|
28
|
+
|
|
29
|
+
# Python exception class -> normalised Rust error kinds that mean the same (extend in the profile).
|
|
30
|
+
DEFAULT_ERROR_KINDS: dict[str, list[str]] = {
|
|
31
|
+
"ZeroDivisionError": ["zerodivision", "divisionbyzero", "divbyzero", "dividebyzero", "division"],
|
|
32
|
+
"ValueError": ["value", "invalidvalue", "invalidinput", "badvalue", "parse", "parseint", "parsefloat"],
|
|
33
|
+
"KeyError": ["key", "keynotfound", "missingkey", "notfound", "nosuchkey"],
|
|
34
|
+
"IndexError": ["index", "indexoutofrange", "indexoutofbounds", "outofbounds", "outofrange"],
|
|
35
|
+
"TypeError": ["type", "typemismatch", "wrongtype"],
|
|
36
|
+
"OverflowError": ["overflow"],
|
|
37
|
+
"AttributeError": ["attribute", "missingattribute"],
|
|
38
|
+
"AssertionError": ["assertion", "assertionfailed"],
|
|
39
|
+
"RuntimeError": ["runtime"],
|
|
40
|
+
"NotImplementedError": ["notimplemented"],
|
|
41
|
+
} # fmt: skip
|
|
42
|
+
|
|
43
|
+
_KNOWN_KEYS = {
|
|
44
|
+
"ignore_keys", "regex", "set_order", "float_tolerance", "error_text_ignore", "whitespace",
|
|
45
|
+
"dict_order", "bigint", "error_kinds", "accept_judged",
|
|
46
|
+
} # fmt: skip
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class Profile:
|
|
51
|
+
"""The `[equivalence]` table of the project TOML."""
|
|
52
|
+
|
|
53
|
+
ignore_keys: frozenset[str] = frozenset()
|
|
54
|
+
regex: list[tuple[str, str]] = field(default_factory=list) # (pattern, replacement)
|
|
55
|
+
set_order: bool | frozenset[str] = False # compare lists as multisets (all / listed functions)
|
|
56
|
+
rel: float = 0.0
|
|
57
|
+
abs: float = 0.0
|
|
58
|
+
error_text_ignore: bool = True
|
|
59
|
+
whitespace: bool = False
|
|
60
|
+
dict_order: bool = True
|
|
61
|
+
# "fail" (default): outputs that differ because of an int outside i64 fail the function, inputs
|
|
62
|
+
# Rust cannot even represent are listed as drift; "report": all of it is only listed; "strict":
|
|
63
|
+
# unrepresentable inputs fail too.
|
|
64
|
+
bigint: str = "fail"
|
|
65
|
+
error_kinds: dict[str, list[str]] = field(default_factory=dict)
|
|
66
|
+
# A human's standing decision (the user edits python2rust.toml; no tool writes it) that judged
|
|
67
|
+
# passes count. Not part of the comparison, so not part of `to_dict` or the judge cache key.
|
|
68
|
+
accept_judged: bool = False
|
|
69
|
+
|
|
70
|
+
def to_dict(self) -> dict[str, Any]:
|
|
71
|
+
"""Canonical JSON form (also the judge cache key's profile part)."""
|
|
72
|
+
return {
|
|
73
|
+
"ignore_keys": sorted(self.ignore_keys),
|
|
74
|
+
"regex": [list(r) for r in self.regex],
|
|
75
|
+
"set_order": self.set_order
|
|
76
|
+
if isinstance(self.set_order, bool)
|
|
77
|
+
else sorted(self.set_order),
|
|
78
|
+
"float_tolerance": {"rel": self.rel, "abs": self.abs},
|
|
79
|
+
"error_text_ignore": self.error_text_ignore,
|
|
80
|
+
"whitespace": self.whitespace,
|
|
81
|
+
"dict_order": self.dict_order,
|
|
82
|
+
"bigint": self.bigint,
|
|
83
|
+
"error_kinds": {k: sorted(v) for k, v in sorted(self.error_kinds.items())},
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
def unordered(self, fn: str) -> bool:
|
|
87
|
+
return self.set_order if isinstance(self.set_order, bool) else fn in self.set_order
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def load_profile(config_path: str | None) -> Profile:
|
|
91
|
+
"""`[equivalence]` from the config (a table owned by the CLI, like `[patch_gate]`)."""
|
|
92
|
+
if not config_path:
|
|
93
|
+
return Profile()
|
|
94
|
+
try:
|
|
95
|
+
data = tomllib.loads(Path(config_path).read_text(encoding="utf-8"))
|
|
96
|
+
except (OSError, tomllib.TOMLDecodeError) as exc:
|
|
97
|
+
raise UsageError(f"cannot read config {config_path}: {exc}") from exc
|
|
98
|
+
t = data.get("equivalence", {})
|
|
99
|
+
if not isinstance(t, dict):
|
|
100
|
+
raise UsageError("[equivalence] must be a table")
|
|
101
|
+
if unknown := sorted(set(t) - _KNOWN_KEYS):
|
|
102
|
+
raise UsageError(f"unknown [equivalence] key(s): {', '.join(unknown)}")
|
|
103
|
+
p = Profile()
|
|
104
|
+
try:
|
|
105
|
+
p.ignore_keys = frozenset(_strs(t.get("ignore_keys", []), "ignore_keys"))
|
|
106
|
+
for item in t.get("regex", []):
|
|
107
|
+
re.compile(item["pattern"])
|
|
108
|
+
p.regex.append((item["pattern"], item.get("replace", "")))
|
|
109
|
+
so = t.get("set_order", False)
|
|
110
|
+
p.set_order = so if isinstance(so, bool) else frozenset(_strs(so, "set_order"))
|
|
111
|
+
tol = t.get("float_tolerance", 0.0)
|
|
112
|
+
if isinstance(tol, dict):
|
|
113
|
+
p.rel, p.abs = float(tol.get("rel", 0.0)), float(tol.get("abs", 0.0))
|
|
114
|
+
else:
|
|
115
|
+
p.rel = float(tol)
|
|
116
|
+
p.error_text_ignore = bool(t.get("error_text_ignore", True))
|
|
117
|
+
p.whitespace = bool(t.get("whitespace", False))
|
|
118
|
+
p.dict_order = bool(t.get("dict_order", True))
|
|
119
|
+
p.bigint = str(t.get("bigint", "fail"))
|
|
120
|
+
p.accept_judged = t.get("accept_judged", False)
|
|
121
|
+
if not isinstance(p.accept_judged, bool):
|
|
122
|
+
raise ValueError("accept_judged must be true or false")
|
|
123
|
+
p.error_kinds = {k: _strs(v, "error_kinds") for k, v in t.get("error_kinds", {}).items()}
|
|
124
|
+
except (KeyError, TypeError, ValueError, re.error) as exc:
|
|
125
|
+
raise UsageError(f"invalid [equivalence] profile: {exc}") from exc
|
|
126
|
+
if p.bigint not in ("report", "fail", "strict"):
|
|
127
|
+
raise UsageError("[equivalence] bigint must be 'report', 'fail' or 'strict'")
|
|
128
|
+
return p
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _strs(v: Any, name: str) -> list[str]:
|
|
132
|
+
if not isinstance(v, list) or not all(isinstance(s, str) for s in v):
|
|
133
|
+
raise ValueError(f"{name} must be a list of strings")
|
|
134
|
+
return v
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
# --- errors -------------------------------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _norm_kind(s: str) -> str:
|
|
141
|
+
s = re.sub(r"(Error|Exception)$", "", s) or s
|
|
142
|
+
return re.sub(r"[^a-z0-9]", "", s.lower())
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def kinds_match(py_names: list[str], rust_kind: str, profile: Profile) -> bool:
|
|
146
|
+
"""Does Rust error kind `rust_kind` stand for the Python exception (or one of its bases)?"""
|
|
147
|
+
r = _norm_kind(rust_kind)
|
|
148
|
+
table = {**DEFAULT_ERROR_KINDS, **profile.error_kinds}
|
|
149
|
+
# `Exception` / `BaseException` are in the MRO of every Python exception: a Rust kind called
|
|
150
|
+
# "Exception" (or "Error") would otherwise stand for all of them. It may only stand for a Python
|
|
151
|
+
# exception that IS one of those classes.
|
|
152
|
+
generic = {"Exception", "BaseException"}
|
|
153
|
+
own = py_names[0] if py_names else ""
|
|
154
|
+
names = [n for n in py_names if n not in generic or n == own]
|
|
155
|
+
for name in names:
|
|
156
|
+
if r == _norm_kind(name) or r in {_norm_kind(k) for k in table.get(name, [])}:
|
|
157
|
+
return True
|
|
158
|
+
return False
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
# --- values -------------------------------------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _is_num(v: Any) -> bool:
|
|
165
|
+
return type(v) in (int, float)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _float_eq(a: float, b: float, p: Profile) -> bool:
|
|
169
|
+
if math.isnan(a) or math.isnan(b):
|
|
170
|
+
return math.isnan(a) and math.isnan(b)
|
|
171
|
+
if math.isinf(a) or math.isinf(b):
|
|
172
|
+
return a == b
|
|
173
|
+
if a == b: # 0.0 == -0.0 in IEEE, but the sign is observable (1/x, repr, copysign)
|
|
174
|
+
return a != 0 or math.copysign(1.0, a) == math.copysign(1.0, b)
|
|
175
|
+
d = abs(a - b)
|
|
176
|
+
return (p.rel > 0 and d <= p.rel * max(abs(a), abs(b))) or (p.abs > 0 and d <= p.abs)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def presentation_only(a: str, b: str) -> bool:
|
|
180
|
+
"""Do two different strings differ only in layout? (NFKC form, whitespace, or JSON layout.)
|
|
181
|
+
|
|
182
|
+
Anything else (a letter, digit, sign, point or punctuation mark) is a different value and must
|
|
183
|
+
never reach a judge as "presentation": a judge can be talked into `same`.
|
|
184
|
+
"""
|
|
185
|
+
|
|
186
|
+
def squashed(x: str) -> str:
|
|
187
|
+
return "".join(unicodedata.normalize("NFKC", x).split())
|
|
188
|
+
|
|
189
|
+
if squashed(a) == squashed(b):
|
|
190
|
+
return True
|
|
191
|
+
if not all(x.lstrip()[:1] in ("{", "[") for x in (a, b)):
|
|
192
|
+
return False # a bare number such as 1.50 vs 1.5 is a numeric difference, not layout
|
|
193
|
+
try:
|
|
194
|
+
return _json_canon(a) == _json_canon(b)
|
|
195
|
+
except ValueError:
|
|
196
|
+
return False
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _json_canon(text: str) -> str:
|
|
200
|
+
return json.dumps(json.loads(text), sort_keys=True, ensure_ascii=False)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _text(s: str, p: Profile) -> str:
|
|
204
|
+
for pattern, repl in p.regex:
|
|
205
|
+
s = re.sub(pattern, repl, s)
|
|
206
|
+
return " ".join(s.split()) if p.whitespace else s
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _canon(v: Any, p: Profile) -> str:
|
|
210
|
+
def walk(x: Any) -> Any:
|
|
211
|
+
if isinstance(x, str):
|
|
212
|
+
return _text(x, p)
|
|
213
|
+
if isinstance(x, list | tuple):
|
|
214
|
+
return [walk(i) for i in x]
|
|
215
|
+
if isinstance(x, dict):
|
|
216
|
+
return {k: walk(i) for k, i in x.items() if k not in p.ignore_keys}
|
|
217
|
+
if isinstance(x, float) and not math.isfinite(x):
|
|
218
|
+
return str(x)
|
|
219
|
+
return x
|
|
220
|
+
|
|
221
|
+
return json.dumps(walk(v), sort_keys=True, ensure_ascii=False)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def drift_fails(res: CaseResult, profile: Profile) -> bool:
|
|
225
|
+
"""Does an overflow-drift case count as a failure under the profile's `bigint` mode?"""
|
|
226
|
+
if res.kind != "drift":
|
|
227
|
+
return False
|
|
228
|
+
if profile.bigint == "strict":
|
|
229
|
+
return True
|
|
230
|
+
if profile.bigint == "report":
|
|
231
|
+
return False
|
|
232
|
+
return any(d["kind"] != "input-unrepresentable" for d in res.diffs)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def drift_reason(res: CaseResult, profile: Profile) -> str:
|
|
236
|
+
"""Why an overflow-drift case failed, with the exact way a human changes the policy."""
|
|
237
|
+
return (
|
|
238
|
+
f"{res.reason} (bigint = {profile.bigint!r}). Rust ints are 64-bit and Python ints are not; "
|
|
239
|
+
'to list such inputs instead of failing, a human sets [equivalence] bigint = "report" in '
|
|
240
|
+
"python2rust.toml. Do not use --no-equiv for this."
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _d(path: str, kind: str, py: Any, rs: Any, soft: bool = False) -> dict[str, Any]:
|
|
245
|
+
return {"path": path, "kind": kind, "python": _safe(py), "rust": _safe(rs), "soft": soft}
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _safe(v: Any) -> Any:
|
|
249
|
+
if isinstance(v, float) and not math.isfinite(v):
|
|
250
|
+
return {"$f": str(v)}
|
|
251
|
+
return v
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def diff_values(py: Any, rs: Any, ty: Any, path: str, fn: str, p: Profile) -> list[dict[str, Any]]:
|
|
255
|
+
"""Differences between two decoded JSON values under `ty` (empty list = equal)."""
|
|
256
|
+
k = ty[0]
|
|
257
|
+
if k == "opt":
|
|
258
|
+
if py is None or rs is None:
|
|
259
|
+
return [] if py is None and rs is None else [_d(path, "null", py, rs)]
|
|
260
|
+
return diff_values(py, rs, ty[1], path, fn, p)
|
|
261
|
+
if k == "any":
|
|
262
|
+
k = _infer(py)
|
|
263
|
+
ty = _any_ty(k)
|
|
264
|
+
if k == "float":
|
|
265
|
+
if not (_is_num(py) and _is_num(rs)):
|
|
266
|
+
return [_d(path, "type", py, rs)]
|
|
267
|
+
return [] if _float_eq(float(py), float(rs), p) else [_d(path, "value", py, rs)]
|
|
268
|
+
if k in ("int", "bool", "none"):
|
|
269
|
+
same = py == rs and type(py) is type(rs)
|
|
270
|
+
return [] if same else [_d(path, "type" if type(py) is not type(rs) else "value", py, rs)]
|
|
271
|
+
if k == "str":
|
|
272
|
+
if not (isinstance(py, str) and isinstance(rs, str)):
|
|
273
|
+
return [_d(path, "type", py, rs)]
|
|
274
|
+
a, b = _text(py, p), _text(rs, p)
|
|
275
|
+
return [] if a == b else [_d(path, "text", py, rs, soft=presentation_only(a, b))]
|
|
276
|
+
if k in ("list", "tuple", "tuplev"):
|
|
277
|
+
if not (isinstance(py, list) and isinstance(rs, list)):
|
|
278
|
+
return [_d(path, "type", py, rs)]
|
|
279
|
+
if len(py) != len(rs):
|
|
280
|
+
return [_d(path, "length", len(py), len(rs))]
|
|
281
|
+
|
|
282
|
+
def child(i: int) -> Any:
|
|
283
|
+
return ty[1][i] if k == "tuple" else ty[1]
|
|
284
|
+
|
|
285
|
+
if p.unordered(fn):
|
|
286
|
+
py, rs = sorted(py, key=lambda x: _canon(x, p)), sorted(rs, key=lambda x: _canon(x, p))
|
|
287
|
+
out: list[dict[str, Any]] = []
|
|
288
|
+
for i, (a, b) in enumerate(zip(py, rs, strict=True)):
|
|
289
|
+
out += diff_values(a, b, child(i), f"{path}[{i}]", fn, p)
|
|
290
|
+
if out and k != "tuple":
|
|
291
|
+
sa = sorted(py, key=lambda x: _canon(x, p))
|
|
292
|
+
sb = sorted(rs, key=lambda x: _canon(x, p))
|
|
293
|
+
if [_canon(x, p) for x in sa] == [_canon(x, p) for x in sb]:
|
|
294
|
+
return [_d(path, "order", py, rs)] # a list's order is observable: hard
|
|
295
|
+
return out
|
|
296
|
+
if k == "dict":
|
|
297
|
+
if not (isinstance(py, dict) and isinstance(rs, dict)):
|
|
298
|
+
return [_d(path, "type", py, rs)]
|
|
299
|
+
pk = [x for x in py if x not in p.ignore_keys]
|
|
300
|
+
rk = [x for x in rs if x not in p.ignore_keys]
|
|
301
|
+
if set(pk) != set(rk):
|
|
302
|
+
return [_d(path, "keys", sorted(set(pk) - set(rk)), sorted(set(rk) - set(pk)))]
|
|
303
|
+
sub = ty[1] if ty[1:] else ("any",)
|
|
304
|
+
out = []
|
|
305
|
+
for key in pk:
|
|
306
|
+
out += diff_values(py[key], rs[key], sub, f"{path}.{key}", fn, p)
|
|
307
|
+
if not out and p.dict_order and pk != rk:
|
|
308
|
+
return [_d(path, "order", pk, rk, soft=True)]
|
|
309
|
+
return out
|
|
310
|
+
return [_d(path, "type", py, rs)]
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _any_ty(kind: str) -> Any:
|
|
314
|
+
return (kind, ("any",)) if kind in ("list", "dict") else (kind,)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _infer(v: Any) -> str:
|
|
318
|
+
if v is None:
|
|
319
|
+
return "none"
|
|
320
|
+
if isinstance(v, bool):
|
|
321
|
+
return "bool"
|
|
322
|
+
if isinstance(v, int):
|
|
323
|
+
return "int"
|
|
324
|
+
if isinstance(v, float):
|
|
325
|
+
return "float"
|
|
326
|
+
if isinstance(v, str):
|
|
327
|
+
return "str"
|
|
328
|
+
if isinstance(v, list):
|
|
329
|
+
return "list"
|
|
330
|
+
return "dict"
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
# --- one case -----------------------------------------------------------------------------------
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
@dataclass
|
|
337
|
+
class CaseResult:
|
|
338
|
+
kind: str # same | hard | soft | drift | skip
|
|
339
|
+
diffs: list[dict[str, Any]] = field(default_factory=list)
|
|
340
|
+
reason: str = ""
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _ser(v: Any) -> str:
|
|
344
|
+
return json.dumps(v, ensure_ascii=False, separators=(",", ":"))
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _status(reply: dict[str, Any]) -> str:
|
|
348
|
+
for key in (
|
|
349
|
+
"__timeout__",
|
|
350
|
+
"__memory__",
|
|
351
|
+
"__output__",
|
|
352
|
+
"__dead__",
|
|
353
|
+
"unencodable",
|
|
354
|
+
"skip",
|
|
355
|
+
"err",
|
|
356
|
+
"ok",
|
|
357
|
+
):
|
|
358
|
+
if key in reply:
|
|
359
|
+
return key
|
|
360
|
+
return "__dead__"
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _unquote(msg: str) -> str:
|
|
364
|
+
return msg[1:-1] if len(msg) >= 2 and msg[0] == msg[-1] == '"' else msg
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def compare_case(
|
|
368
|
+
args: list[Any],
|
|
369
|
+
py: dict[str, Any],
|
|
370
|
+
rs: dict[str, Any],
|
|
371
|
+
ret: Ty,
|
|
372
|
+
fn: str,
|
|
373
|
+
profile: Profile,
|
|
374
|
+
*,
|
|
375
|
+
strict: bool = False,
|
|
376
|
+
observations: Sequence[tuple[int, Ty]] = (),
|
|
377
|
+
) -> CaseResult:
|
|
378
|
+
"""Classify one input: same, skip (cannot compare), hard / soft difference, or drift."""
|
|
379
|
+
ps, rst = _status(py), _status(rs)
|
|
380
|
+
if ps in ("__timeout__", "__memory__", "__output__", "__dead__", "unencodable"):
|
|
381
|
+
why = {"__timeout__": "python timed out", "__memory__": "python hit the memory limit",
|
|
382
|
+
"__output__": "python output limit exceeded",
|
|
383
|
+
"__dead__": "python runner died", "unencodable": f"python returned {py.get('unencodable')}"}[ps] # fmt: skip
|
|
384
|
+
return CaseResult("skip", reason=why)
|
|
385
|
+
bigint = has_bigint(args) or (ps == "ok" and has_bigint(py["ok"]))
|
|
386
|
+
if rst == "skip":
|
|
387
|
+
if ps == "ok":
|
|
388
|
+
return CaseResult(
|
|
389
|
+
"drift",
|
|
390
|
+
[_d("", "input-unrepresentable", args, rs["skip"])],
|
|
391
|
+
"input not representable in the Rust types",
|
|
392
|
+
)
|
|
393
|
+
return CaseResult("skip", reason=f"rust cannot take the input ({rs['skip']})")
|
|
394
|
+
if rst in ("__timeout__", "__memory__", "__output__", "__dead__"):
|
|
395
|
+
what = {
|
|
396
|
+
"__timeout__": "timed out",
|
|
397
|
+
"__memory__": "hit the memory limit",
|
|
398
|
+
"__output__": "output limit exceeded",
|
|
399
|
+
}.get(rst, "crashed (abort)")
|
|
400
|
+
return CaseResult("hard", [_d("", "rust", _brief(py), f"rust {what}")], f"rust {what}")
|
|
401
|
+
|
|
402
|
+
def settle(diffs: list[dict[str, Any]]) -> CaseResult:
|
|
403
|
+
if not diffs:
|
|
404
|
+
return CaseResult("same")
|
|
405
|
+
if bigint:
|
|
406
|
+
return CaseResult("drift", diffs, "overflow: a Python int outside i64")
|
|
407
|
+
soft = all(d["soft"] for d in diffs) and not strict
|
|
408
|
+
return CaseResult("soft" if soft else "hard", diffs)
|
|
409
|
+
|
|
410
|
+
if observations:
|
|
411
|
+
pafter, rafter = py.get("args_after", []), rs.get("args_after", [])
|
|
412
|
+
if len(pafter) != len(observations) or len(rafter) != len(observations):
|
|
413
|
+
return CaseResult("hard", [_d("/args_after", "missing-observation", pafter, rafter)])
|
|
414
|
+
diffs = []
|
|
415
|
+
for (index, ty), pvalue, rvalue in zip(observations, pafter, rafter, strict=True):
|
|
416
|
+
pointer = f"/args_after/{index}"
|
|
417
|
+
if strict:
|
|
418
|
+
if _ser(pvalue) != _ser(rvalue):
|
|
419
|
+
diffs.append(_d(pointer, "bytes", pvalue, rvalue))
|
|
420
|
+
else:
|
|
421
|
+
diffs.extend(diff_values(pvalue, rvalue, ty, pointer, fn, profile))
|
|
422
|
+
if diffs:
|
|
423
|
+
return CaseResult("hard", diffs, "mutable argument state differs")
|
|
424
|
+
if ps == "err" or rst == "err":
|
|
425
|
+
if ps != rst:
|
|
426
|
+
return settle([_d("", "result-vs-exception", _brief(py), _brief(rs))])
|
|
427
|
+
if not kinds_match(py.get("mro", [py["err"]]), str(rs["err"]), profile):
|
|
428
|
+
return settle([_d("", "error-kind", py["err"], rs["err"])])
|
|
429
|
+
compare_text = strict or not profile.error_text_ignore
|
|
430
|
+
if compare_text and _unquote(str(rs.get("msg", ""))) != str(py.get("msg", "")):
|
|
431
|
+
a, b = _unquote(str(rs.get("msg", ""))), str(py.get("msg", ""))
|
|
432
|
+
return settle(
|
|
433
|
+
[
|
|
434
|
+
_d(
|
|
435
|
+
"",
|
|
436
|
+
"error-text",
|
|
437
|
+
py.get("msg"),
|
|
438
|
+
rs.get("msg"),
|
|
439
|
+
soft=presentation_only(a, b) and not strict,
|
|
440
|
+
)
|
|
441
|
+
]
|
|
442
|
+
)
|
|
443
|
+
return CaseResult("same")
|
|
444
|
+
if strict:
|
|
445
|
+
a, b = _ser(py["ok"]), _ser(rs["ok"])
|
|
446
|
+
return settle([] if a == b else [_d("", "bytes", a, b)])
|
|
447
|
+
return settle(diff_values(py["ok"], rs["ok"], ret, "", fn, profile))
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _brief(reply: dict[str, Any]) -> Any:
|
|
451
|
+
if "ok" in reply:
|
|
452
|
+
return {"ok": _safe(reply["ok"])}
|
|
453
|
+
if "err" in reply:
|
|
454
|
+
return {"err": reply["err"]}
|
|
455
|
+
return {k: v for k, v in reply.items() if k.startswith("__") or k in ("skip", "unencodable")}
|