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.
Files changed (102) hide show
  1. python2rust/__init__.py +8 -0
  2. python2rust/__main__.py +5 -0
  3. python2rust/_core.py +44 -0
  4. python2rust/agent/__init__.py +0 -0
  5. python2rust/agent/agents.py +333 -0
  6. python2rust/agent/apply.py +516 -0
  7. python2rust/agent/finish.py +295 -0
  8. python2rust/agent/fixers.py +229 -0
  9. python2rust/agent/loop.py +441 -0
  10. python2rust/agent/patches.py +1165 -0
  11. python2rust/agent/port.py +579 -0
  12. python2rust/agent/prompts/judge_v2.md +96 -0
  13. python2rust/agent/review.py +34 -0
  14. python2rust/agent/rustlex.py +232 -0
  15. python2rust/cli/__init__.py +0 -0
  16. python2rust/cli/doctor.py +62 -0
  17. python2rust/cli/inputs.py +105 -0
  18. python2rust/cli/main.py +1162 -0
  19. python2rust/cli/ops.py +642 -0
  20. python2rust/cli/workflow.py +178 -0
  21. python2rust/core/__init__.py +38 -0
  22. python2rust/core/config.py +263 -0
  23. python2rust/core/constructs.py +124 -0
  24. python2rust/core/diagnostics.py +280 -0
  25. python2rust/core/emit/__init__.py +5 -0
  26. python2rust/core/emit/crates.py +51 -0
  27. python2rust/core/emit/render.py +561 -0
  28. python2rust/core/emit/schema.py +168 -0
  29. python2rust/core/emit/translate.py +304 -0
  30. python2rust/core/frontend/__init__.py +1 -0
  31. python2rust/core/frontend/module.py +896 -0
  32. python2rust/core/frontend/names.py +129 -0
  33. python2rust/core/frontend/project.py +277 -0
  34. python2rust/core/frontend/project_imports.py +173 -0
  35. python2rust/core/frontend/symbols.py +132 -0
  36. python2rust/core/frontend/walrus.py +59 -0
  37. python2rust/core/ir/__init__.py +1 -0
  38. python2rust/core/ir/nodes.py +675 -0
  39. python2rust/core/ir/rtypes.py +122 -0
  40. python2rust/core/ir/types.py +326 -0
  41. python2rust/core/lower/__init__.py +1 -0
  42. python2rust/core/lower/calls.py +1125 -0
  43. python2rust/core/lower/context.py +223 -0
  44. python2rust/core/lower/exceptions.py +317 -0
  45. python2rust/core/lower/exprs.py +845 -0
  46. python2rust/core/lower/fstrings.py +141 -0
  47. python2rust/core/lower/funcs.py +276 -0
  48. python2rust/core/lower/lowerer.py +366 -0
  49. python2rust/core/lower/modelcalls.py +195 -0
  50. python2rust/core/lower/models.py +645 -0
  51. python2rust/core/lower/stmts.py +722 -0
  52. python2rust/core/lower/testing.py +601 -0
  53. python2rust/core/lower/validation.py +253 -0
  54. python2rust/core/passes/__init__.py +1 -0
  55. python2rust/core/passes/aliasing.py +311 -0
  56. python2rust/core/passes/analysis.py +207 -0
  57. python2rust/core/passes/devirt.py +329 -0
  58. python2rust/core/passes/ownership.py +259 -0
  59. python2rust/core/passes/raises.py +275 -0
  60. python2rust/core/rt_lib.rs +2071 -0
  61. python2rust/data/README.md +81 -0
  62. python2rust/data/py2many_builtins.toml +4744 -0
  63. python2rust/errors.py +28 -0
  64. python2rust/py.typed +0 -0
  65. python2rust/report/__init__.py +0 -0
  66. python2rust/report/constructs.py +31 -0
  67. python2rust/report/contract.py +688 -0
  68. python2rust/report/corpus.py +323 -0
  69. python2rust/report/explain.py +168 -0
  70. python2rust/report/schemas.py +914 -0
  71. python2rust/server/__init__.py +0 -0
  72. python2rust/server/mcp_server.py +289 -0
  73. python2rust/server/mcp_workflow.py +100 -0
  74. python2rust/skill/SKILL.md +214 -0
  75. python2rust/verify/__init__.py +0 -0
  76. python2rust/verify/check.py +1135 -0
  77. python2rust/verify/equiv/__init__.py +1264 -0
  78. python2rust/verify/equiv/compare.py +455 -0
  79. python2rust/verify/equiv/harness.py +505 -0
  80. python2rust/verify/equiv/judge.py +358 -0
  81. python2rust/verify/equiv/procs.py +255 -0
  82. python2rust/verify/equiv/runner.py +248 -0
  83. python2rust/verify/equiv/types.py +543 -0
  84. python2rust/verify/keystore.py +76 -0
  85. python2rust/verify/ladder.py +396 -0
  86. python2rust/verify/sandbox.py +370 -0
  87. python2rust/verify/testrun.py +280 -0
  88. python2rust/workflow/__init__.py +0 -0
  89. python2rust/workflow/brief.py +312 -0
  90. python2rust/workflow/interview.py +366 -0
  91. python2rust/workflow/layout.py +103 -0
  92. python2rust/workflow/planner.py +409 -0
  93. python2rust/workflow/project.py +134 -0
  94. python2rust/workflow/schemas.py +265 -0
  95. python2rust/workflow/state.py +392 -0
  96. python2rust/workflow/staticscan.py +209 -0
  97. python2rust-0.1.0.dist-info/METADATA +395 -0
  98. python2rust-0.1.0.dist-info/RECORD +102 -0
  99. python2rust-0.1.0.dist-info/WHEEL +4 -0
  100. python2rust-0.1.0.dist-info/entry_points.txt +4 -0
  101. python2rust-0.1.0.dist-info/licenses/LICENSE +21 -0
  102. python2rust-0.1.0.dist-info/licenses/NOTICE +65 -0
@@ -0,0 +1,543 @@
1
+ """The type model behind `verify --level equiv`.
2
+
3
+ Two small models, both parsed from text, never from running the user's code:
4
+
5
+ * `Ty`: a JSON-able shape parsed from a Python annotation (`int`, `list[str]`, `dict[str, int]`,
6
+ `tuple[int, str]`, `Optional[float]`, ...). It drives input generation, shrinking and comparison.
7
+ * `RTy`: a Rust type parsed from the generated signature (`i64`, `&str`, `Vec<f64>`,
8
+ `IndexMap<String, V>`, `Result<T, E>`, ...). It drives the generated Rust harness.
9
+
10
+ Anything outside these models raises `Unsupported(reason)`; the caller reports the function as
11
+ `equiv: not-applicable` with that reason. Standard library only (Hypothesis is optional).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import ast
17
+ import math
18
+ import random
19
+ import re
20
+ from collections.abc import Iterator
21
+ from dataclasses import dataclass
22
+ from typing import Any
23
+
24
+ # A Ty is a nested tuple whose first item is the kind:
25
+ # ("int",) ("float",) ("str",) ("bool",) ("none",) ("any",)
26
+ # ("list", T) ("tuple", (T, ...)) ("tuplev", T) ("dict", V) ("opt", T) ("model", name)
27
+ # dict keys are always str (JSON objects). The same tuples travel as JSON lists to the runner.
28
+ Ty = tuple[Any, ...]
29
+
30
+ I64_MIN, I64_MAX = -(2**63), 2**63 - 1
31
+
32
+
33
+ class Unsupported(Exception):
34
+ """The signature is outside what equivalence testing can handle (the message is the reason)."""
35
+
36
+
37
+ # --- Python annotations -------------------------------------------------------------------------
38
+
39
+ _SIMPLE: dict[str, Ty] = {
40
+ "int": ("int",),
41
+ "float": ("float",),
42
+ "str": ("str",),
43
+ "bool": ("bool",),
44
+ "None": ("none",),
45
+ }
46
+ _LISTS = {"list", "List", "Sequence", "MutableSequence"}
47
+ _DICTS = {"dict", "Dict", "Mapping", "MutableMapping"}
48
+ _TUPLES = {"tuple", "Tuple"}
49
+
50
+
51
+ def _base_name(node: ast.expr) -> str | None:
52
+ if isinstance(node, ast.Name):
53
+ return node.id
54
+ if isinstance(node, ast.Attribute):
55
+ return node.attr
56
+ return None
57
+
58
+
59
+ def _union(members: list[Ty], text: str) -> Ty:
60
+ rest = [m for m in members if m != ("none",)]
61
+ if len(rest) == 1 and len(members) == 2:
62
+ return ("opt", rest[0])
63
+ raise Unsupported(f"union type {text} (only Optional[T] is supported)")
64
+
65
+
66
+ def parse_ann(node: ast.expr | None, models: frozenset[str] | set[str] = frozenset()) -> Ty:
67
+ """Python annotation AST -> Ty, or `Unsupported`."""
68
+ if node is None:
69
+ raise Unsupported("missing type annotation")
70
+ text = ast.unparse(node)
71
+ if isinstance(node, ast.Constant):
72
+ if node.value is None:
73
+ return ("none",)
74
+ if isinstance(node.value, str):
75
+ try:
76
+ return parse_ann(ast.parse(node.value, mode="eval").body, models)
77
+ except SyntaxError:
78
+ raise Unsupported(f"annotation {text} is not parseable") from None
79
+ if isinstance(node, ast.Name | ast.Attribute):
80
+ name = _base_name(node)
81
+ if isinstance(node, ast.Name) and name in _SIMPLE:
82
+ return _SIMPLE[name]
83
+ if name in models:
84
+ return ("model", name)
85
+ raise Unsupported(f"type {text} is not JSON-comparable")
86
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
87
+ parts: list[ast.expr] = []
88
+
89
+ def flat(n: ast.expr) -> None:
90
+ if isinstance(n, ast.BinOp) and isinstance(n.op, ast.BitOr):
91
+ flat(n.left)
92
+ flat(n.right)
93
+ else:
94
+ parts.append(n)
95
+
96
+ flat(node)
97
+ return _union([parse_ann(p, models) for p in parts], text)
98
+ if isinstance(node, ast.Subscript):
99
+ base = _base_name(node.value)
100
+ sl = node.slice
101
+ args = list(sl.elts) if isinstance(sl, ast.Tuple) else [sl]
102
+ if base in _LISTS and len(args) == 1:
103
+ return ("list", parse_ann(args[0], models))
104
+ if base in _DICTS and len(args) == 2:
105
+ if parse_ann(args[0], models) != ("str",):
106
+ raise Unsupported(f"{text}: only str keys survive a JSON round trip")
107
+ return ("dict", parse_ann(args[1], models))
108
+ if base in _TUPLES:
109
+ if len(args) == 2 and isinstance(args[1], ast.Constant) and args[1].value is ...:
110
+ return ("tuplev", parse_ann(args[0], models))
111
+ return ("tuple", tuple(parse_ann(a, models) for a in args))
112
+ if base == "Optional" and len(args) == 1:
113
+ return ("opt", parse_ann(args[0], models))
114
+ if base == "Union":
115
+ return _union([parse_ann(a, models) for a in args], text)
116
+ raise Unsupported(f"type {text} is not JSON-comparable")
117
+
118
+
119
+ def has_model(ty: Ty) -> bool:
120
+ if ty[0] == "model":
121
+ return True
122
+ if ty[0] in ("list", "tuplev", "dict", "opt"):
123
+ return has_model(ty[1])
124
+ if ty[0] == "tuple":
125
+ return any(has_model(t) for t in ty[1])
126
+ return False
127
+
128
+
129
+ # --- values: fit, wire format ------------------------------------------------------------------
130
+
131
+
132
+ def fits(ty: Ty, v: Any) -> bool:
133
+ """Is the Python value `v` an instance of `ty`? (bool is not an int; int is a float.)"""
134
+ k = ty[0]
135
+ if k == "int":
136
+ return type(v) is int
137
+ if k == "float":
138
+ return type(v) in (int, float)
139
+ if k == "str":
140
+ return isinstance(v, str)
141
+ if k == "bool":
142
+ return isinstance(v, bool)
143
+ if k == "none":
144
+ return v is None
145
+ if k == "any":
146
+ return True
147
+ if k == "opt":
148
+ return v is None or fits(ty[1], v)
149
+ if k == "list":
150
+ return isinstance(v, list) and all(fits(ty[1], x) for x in v)
151
+ if k == "tuplev":
152
+ return isinstance(v, tuple | list) and all(fits(ty[1], x) for x in v)
153
+ if k == "tuple":
154
+ return isinstance(v, tuple | list) and len(v) == len(ty[1]) and all(
155
+ fits(t, x) for t, x in zip(ty[1], v, strict=True)
156
+ ) # fmt: skip
157
+ if k == "dict":
158
+ return isinstance(v, dict) and all(
159
+ isinstance(a, str) and fits(ty[1], b) for a, b in v.items()
160
+ )
161
+ return False
162
+
163
+
164
+ def to_wire(v: Any) -> Any:
165
+ """Python value -> JSON-able (non-finite floats become {"$f": ...}, tuples become lists)."""
166
+ if isinstance(v, float) and not math.isfinite(v):
167
+ return {"$f": "nan" if v != v else ("inf" if v > 0 else "-inf")}
168
+ if isinstance(v, list | tuple):
169
+ return [to_wire(x) for x in v]
170
+ if isinstance(v, dict):
171
+ return {k: to_wire(x) for k, x in v.items()}
172
+ return v
173
+
174
+
175
+ def has_bigint(v: Any) -> bool:
176
+ """Does the value contain an int that does not fit i64 (Rust would overflow or reject it)?"""
177
+ if type(v) is int:
178
+ return not I64_MIN <= v <= I64_MAX
179
+ if isinstance(v, list | tuple):
180
+ return any(has_bigint(x) for x in v)
181
+ if isinstance(v, dict):
182
+ return any(has_bigint(x) for x in v.values())
183
+ return False
184
+
185
+
186
+ # --- input generation ---------------------------------------------------------------------------
187
+
188
+ EDGE_INTS = [0, 1, -1, 2, -2, 7, 10, 100, -100, 255, 256, 65535, 2**31 - 1, -(2**31), 2**31,
189
+ 10**9, 2**40, I64_MAX, I64_MIN] # fmt: skip
190
+ # Past these a Python int no longer fits Rust's i64: they provoke the overflow-drift finding.
191
+ BOUNDARY_INTS = [I64_MAX, I64_MIN, I64_MAX + 1, I64_MIN - 1, 2**64, 10**30]
192
+ EDGE_FLOATS = [0.0, -0.0, 1.0, -1.0, 0.5, -2.5, 1e-9, 3.14159, 1e9, 1e300, 2.0**53]
193
+ SPECIAL_FLOATS = [math.nan, math.inf, -math.inf]
194
+ EDGE_STRS = ["", "a", " ", "abc", "Hello, World", "ÄÖÜ äöü ß", "naïve café", "日本語", "😀", "a😀b",
195
+ "line\nbreak", "tab\there", 'quote"s', "x" * 40, "0", "-1"] # fmt: skip
196
+ _ALPHABET = "abcxyz XYZ019_-.,:/é日😀"
197
+
198
+
199
+ def _rand_int(rng: random.Random) -> int:
200
+ return rng.choice(
201
+ [rng.randint(-20, 20), rng.randint(-1000, 1000), rng.randint(-(2**40), 2**40)]
202
+ )
203
+
204
+
205
+ def gen_edges(ty: Ty, *, probe: bool = False) -> list[Any]:
206
+ """Deterministic edge values for a type (the first inputs tried)."""
207
+ k = ty[0]
208
+ if k == "int":
209
+ return [*EDGE_INTS, *(BOUNDARY_INTS if probe else [])]
210
+ if k == "float":
211
+ return [*EDGE_FLOATS, *SPECIAL_FLOATS]
212
+ if k == "str":
213
+ return list(EDGE_STRS)
214
+ if k == "bool":
215
+ return [True, False]
216
+ if k == "none":
217
+ return [None]
218
+ if k == "opt":
219
+ return [None, *gen_edges(ty[1])[:4]]
220
+ if k == "list":
221
+ inner = gen_edges(ty[1])
222
+ return [[], inner[:1], inner[:3], [[]] if ty[1][0] == "list" else inner[:2] * 2]
223
+ if k == "tuplev":
224
+ inner = gen_edges(ty[1])
225
+ return [(), tuple(inner[:1]), tuple(inner[:3])]
226
+ if k == "tuple":
227
+ return [tuple(gen_edges(t)[0] for t in ty[1])]
228
+ if k == "dict":
229
+ inner = gen_edges(ty[1])
230
+ return [{}, {"a": inner[0]}, {"a": inner[0], "b": inner[-1], "": inner[0]}]
231
+ return []
232
+
233
+
234
+ def gen_random(ty: Ty, rng: random.Random, depth: int = 0) -> Any:
235
+ k = ty[0]
236
+ if k == "int":
237
+ return _rand_int(rng)
238
+ if k == "float":
239
+ return rng.choice([rng.uniform(-100, 100), rng.uniform(-1e6, 1e6), float(rng.randint(-9, 9)),
240
+ rng.choice(EDGE_FLOATS)]) # fmt: skip
241
+ if k == "str":
242
+ n = rng.choice([0, 1, 2, 5, 12])
243
+ return "".join(rng.choice(_ALPHABET) for _ in range(n))
244
+ if k == "bool":
245
+ return rng.random() < 0.5
246
+ if k == "none":
247
+ return None
248
+ if k == "opt":
249
+ return None if rng.random() < 0.25 else gen_random(ty[1], rng, depth)
250
+ size = 0 if depth >= 3 else rng.choice([0, 1, 2, 3, 5])
251
+ if k == "list":
252
+ return [gen_random(ty[1], rng, depth + 1) for _ in range(size)]
253
+ if k == "tuplev":
254
+ return tuple(gen_random(ty[1], rng, depth + 1) for _ in range(size))
255
+ if k == "tuple":
256
+ return tuple(gen_random(t, rng, depth + 1) for t in ty[1])
257
+ if k == "dict":
258
+ return {
259
+ gen_random(("str",), rng): gen_random(ty[1], rng, depth + 1)
260
+ for _ in range(min(size, 3))
261
+ }
262
+ raise Unsupported(f"cannot generate values of type {ty[0]}")
263
+
264
+
265
+ def finite_only(ty: Ty, v: Any) -> bool:
266
+ """False if the value holds nan/inf (model payloads must stay plain JSON)."""
267
+ if isinstance(v, float):
268
+ return math.isfinite(v)
269
+ if isinstance(v, list | tuple):
270
+ return all(finite_only(ty, x) for x in v)
271
+ if isinstance(v, dict):
272
+ return all(finite_only(ty, x) for x in v.values())
273
+ return True
274
+
275
+
276
+ # --- shrinking ----------------------------------------------------------------------------------
277
+
278
+
279
+ def shrink_candidates(ty: Ty, v: Any) -> Iterator[Any]:
280
+ """Strictly simpler values than `v`, simplest first (ints toward 0, shorter strings/lists...)."""
281
+ k = ty[0]
282
+ if k == "int":
283
+ step = 1 if v > 0 else -1
284
+ seen: set[int] = set()
285
+ for c in (0, abs(v) if v < 0 else 0, v // 2 if v > 0 else -(-v // 2), v - step):
286
+ if c != v and (abs(c) < abs(v) or c == -v) and c not in seen:
287
+ seen.add(c)
288
+ yield c
289
+ elif k == "float":
290
+ if v != 0.0 or math.copysign(1, v) < 0:
291
+ yield 0.0
292
+ if math.isfinite(v) and v != round(v):
293
+ yield float(round(v))
294
+ if math.isfinite(v) and abs(v) > 1:
295
+ yield v / 2
296
+ elif k == "str":
297
+ if v:
298
+ yield ""
299
+ if len(v) > 1:
300
+ yield v[:1]
301
+ yield v[: len(v) // 2]
302
+ yield v[1:]
303
+ yield v[:-1]
304
+ elif k == "bool":
305
+ if v:
306
+ yield False
307
+ elif k == "opt":
308
+ if v is not None:
309
+ yield None
310
+ yield from shrink_candidates(ty[1], v)
311
+ elif k in ("list", "tuplev"):
312
+ make = list if k == "list" else tuple
313
+ if v:
314
+ yield make()
315
+ for i in range(len(v)):
316
+ yield make([*v[:i], *v[i + 1 :]])
317
+ for i, x in enumerate(v):
318
+ for c in shrink_candidates(ty[1], x):
319
+ yield make([*v[:i], c, *v[i + 1 :]])
320
+ elif k == "tuple":
321
+ for i, (t, x) in enumerate(zip(ty[1], v, strict=True)):
322
+ for c in shrink_candidates(t, x):
323
+ yield (*v[:i], c, *v[i + 1 :])
324
+ elif k == "dict":
325
+ if v:
326
+ yield {}
327
+ for key in v:
328
+ yield {a: b for a, b in v.items() if a != key}
329
+ for key, x in v.items():
330
+ for c in shrink_candidates(ty[1], x):
331
+ yield {**v, key: c}
332
+
333
+
334
+ def shrink(tys: list[Ty], args: list[Any], still_fails: Any, budget: int = 150) -> list[Any]:
335
+ """Greedy shrinker: keep replacing one argument by a simpler value while `still_fails`."""
336
+ cur, steps = list(args), 0
337
+ progress = True
338
+ while progress and steps < budget:
339
+ progress = False
340
+ for i, (ty, v) in enumerate(zip(tys, cur, strict=True)):
341
+ for cand in shrink_candidates(ty, v):
342
+ steps += 1
343
+ trial = [*cur[:i], cand, *cur[i + 1 :]]
344
+ if still_fails(trial):
345
+ cur, progress = trial, True
346
+ break
347
+ if steps >= budget:
348
+ return cur
349
+ return cur
350
+
351
+
352
+ def hypothesis_strategy(ty: Ty) -> Any:
353
+ """A Hypothesis strategy built from our Ty (never from the user's module)."""
354
+ from hypothesis import strategies as st
355
+
356
+ k = ty[0]
357
+ if k == "int":
358
+ return st.one_of(
359
+ st.integers(-1000, 1000), st.integers(-(2**40), 2**40), st.sampled_from(EDGE_INTS)
360
+ )
361
+ if k == "float":
362
+ return st.floats()
363
+ if k == "str":
364
+ return st.text(max_size=20)
365
+ if k == "bool":
366
+ return st.booleans()
367
+ if k == "none":
368
+ return st.none()
369
+ if k == "opt":
370
+ return st.none() | hypothesis_strategy(ty[1])
371
+ if k == "list":
372
+ return st.lists(hypothesis_strategy(ty[1]), max_size=5)
373
+ if k == "tuplev":
374
+ return st.lists(hypothesis_strategy(ty[1]), max_size=5).map(tuple)
375
+ if k == "tuple":
376
+ return st.tuples(*(hypothesis_strategy(t) for t in ty[1]))
377
+ if k == "dict":
378
+ return st.dictionaries(st.text(max_size=6), hypothesis_strategy(ty[1]), max_size=3)
379
+ raise Unsupported(f"no strategy for {ty[0]}")
380
+
381
+
382
+ def hypothesis_available() -> bool:
383
+ import importlib.util
384
+
385
+ return importlib.util.find_spec("hypothesis") is not None
386
+
387
+
388
+ # --- Rust types ---------------------------------------------------------------------------------
389
+
390
+
391
+ @dataclass(frozen=True)
392
+ class RTy:
393
+ kind: str # int float bool str unit vec map opt tuple result
394
+ args: tuple[RTy, ...] = ()
395
+ owned: str = "" # Rust type text of an owned value of this type (for `let a0: <owned>`)
396
+ ref: bool = False # the signature takes/returns it behind `&`
397
+ name: str = (
398
+ "" # int/float: i64, f64, ...; map: HashMap | BTreeMap | IndexMap; result: error type
399
+ )
400
+
401
+ @property
402
+ def has_shared(self) -> bool:
403
+ return "python2rust_rt::Shared<" in self.owned or any(t.has_shared for t in self.args)
404
+
405
+
406
+ _INTS = {"i8", "i16", "i32", "i64", "isize", "u8", "u16", "u32", "u64", "usize"}
407
+ _TOKEN = re.compile(r"&|'\w+|\(|\)|\[|\]|<|>|,|::|\w+|\S")
408
+
409
+
410
+ class _RustTypeParser:
411
+ def __init__(self, text: str):
412
+ self.toks = _TOKEN.findall(text)
413
+ self.i = 0
414
+ self.text = text
415
+
416
+ def peek(self) -> str:
417
+ return self.toks[self.i] if self.i < len(self.toks) else ""
418
+
419
+ def next(self) -> str:
420
+ t = self.peek()
421
+ self.i += 1
422
+ return t
423
+
424
+ def expect(self, t: str) -> None:
425
+ if self.next() != t:
426
+ raise Unsupported(f"cannot parse Rust type {self.text!r}")
427
+
428
+ def parse(self, *, top: bool) -> RTy:
429
+ t = self.peek()
430
+ if t == "&":
431
+ self.next()
432
+ if self.peek().startswith("'"):
433
+ self.next()
434
+ if self.peek() == "mut":
435
+ raise Unsupported("&mut parameter")
436
+ if not top:
437
+ raise Unsupported("reference nested inside another type")
438
+ inner = self.parse(top=False)
439
+ if inner.kind not in ("str", "vec", "map", "int", "float", "bool", "opt", "tuple"):
440
+ raise Unsupported(f"reference to {self.text}")
441
+ return RTy(inner.kind, inner.args, inner.owned, True, inner.name)
442
+ if t == "(":
443
+ self.next()
444
+ items: list[RTy] = []
445
+ while self.peek() != ")":
446
+ items.append(self.parse(top=False))
447
+ if self.peek() == ",":
448
+ self.next()
449
+ self.expect(")")
450
+ if not items:
451
+ return RTy("unit", owned="()")
452
+ owned = "(" + ", ".join(i.owned for i in items) + ("," if len(items) == 1 else "") + ")"
453
+ return RTy("tuple", tuple(items), owned)
454
+ if t == "[":
455
+ self.next()
456
+ inner = self.parse(top=False)
457
+ if self.peek() == ";":
458
+ raise Unsupported("fixed-size array")
459
+ self.expect("]")
460
+ return RTy("vec", (inner,), f"Vec<{inner.owned}>", name="slice")
461
+ name = self.next()
462
+ while self.peek() == "::":
463
+ self.next()
464
+ name = self.next()
465
+ if name in _INTS:
466
+ return RTy("int", owned=name, name=name)
467
+ if name in ("f32", "f64"):
468
+ return RTy("float", owned=name, name=name)
469
+ if name == "bool":
470
+ return RTy("bool", owned="bool")
471
+ if name in ("String", "str"):
472
+ return RTy("str", owned="String")
473
+ generics: list[RTy] = []
474
+ raw_generics: list[str] = []
475
+ if self.peek() == "<":
476
+ self.next()
477
+ while self.peek() != ">":
478
+ start = self.i
479
+ if name == "Result" and generics: # the error type is only named, never mapped
480
+ depth = 0
481
+ while self.peek() and (depth or self.peek() not in (",", ">")):
482
+ depth += {"<": 1, ">": -1}.get(self.next(), 0)
483
+ raw_generics.append(" ".join(self.toks[start : self.i]))
484
+ generics.append(RTy("unit"))
485
+ else:
486
+ generics.append(self.parse(top=False))
487
+ raw_generics.append(" ".join(self.toks[start : self.i]))
488
+ if self.peek() == ",":
489
+ self.next()
490
+ self.expect(">")
491
+ if name == "Shared" and len(generics) == 1:
492
+ inner = generics[0]
493
+ return RTy(
494
+ inner.kind, inner.args, f"python2rust_rt::Shared<{inner.owned}>", name=inner.name
495
+ )
496
+ if name == "Vec" and len(generics) == 1:
497
+ return RTy("vec", tuple(generics), f"Vec<{generics[0].owned}>", name="Vec")
498
+ if name in ("HashMap", "BTreeMap", "IndexMap") and len(generics) == 2:
499
+ if generics[0].kind != "str":
500
+ raise Unsupported(f"{name} with non-String keys")
501
+ return RTy("map", (generics[1],), f"{name}<String, {generics[1].owned}>", name=name)
502
+ if name == "Option" and len(generics) == 1:
503
+ return RTy("opt", tuple(generics), f"Option<{generics[0].owned}>")
504
+ if name == "Result" and len(generics) == 2:
505
+ return RTy("result", (generics[0],), name=raw_generics[1])
506
+ if (
507
+ name == "Result" and len(generics) == 1
508
+ ): # a `type Result<T> = ...` alias: error type unknown
509
+ return RTy("result", (generics[0],), name="?")
510
+ raise Unsupported(f"Rust type {self.text.strip()} has no JSON mapping")
511
+
512
+
513
+ def parse_rust_type(text: str, *, top: bool = True) -> RTy:
514
+ p = _RustTypeParser(text)
515
+ out = p.parse(top=top)
516
+ if p.i < len(p.toks):
517
+ raise Unsupported(f"cannot parse Rust type {text!r}")
518
+ return out
519
+
520
+
521
+ def compat(py: Ty, rs: RTy) -> str | None:
522
+ """None when the Rust type can hold the Python type, else the reason it cannot."""
523
+ k = py[0]
524
+ if k == "int" and rs.kind == "int":
525
+ return None
526
+ if k == "float" and rs.kind == "float":
527
+ return None
528
+ if k in ("bool", "str") and rs.kind == k:
529
+ return None
530
+ if k == "none" and rs.kind == "unit":
531
+ return None
532
+ if k == "opt" and rs.kind == "opt":
533
+ return compat(py[1], rs.args[0])
534
+ if k in ("list", "tuplev") and rs.kind == "vec":
535
+ return compat(py[1], rs.args[0])
536
+ if k == "dict" and rs.kind == "map":
537
+ return compat(py[1], rs.args[0])
538
+ if k == "tuple" and rs.kind == "tuple" and len(py[1]) == len(rs.args):
539
+ for p, r in zip(py[1], rs.args, strict=True):
540
+ if (why := compat(p, r)) is not None:
541
+ return why
542
+ return None
543
+ return f"Python {py[0]} does not match Rust {rs.owned or rs.kind}"
@@ -0,0 +1,76 @@
1
+ """A per-machine secret and keyed MACs over it.
2
+
3
+ Records kept inside a project directory (the patch store, the judge cache) carry a plain sha256
4
+ that anyone who can edit the file can recompute. A MAC keyed by a secret that lives outside the
5
+ project cannot be recomputed by an edit to the project, and a store copied from another machine
6
+ does not verify. The secret is 32 random bytes in `$XDG_CACHE_HOME/python2rust/secret` (or
7
+ `~/.cache/python2rust/secret`), mode 0600, created atomically on first use.
8
+ `PYTHON2RUST_SECRET_FILE` names another file (tests, CI).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ import hashlib
15
+ import hmac
16
+ import os
17
+ import secrets
18
+ import threading
19
+ from pathlib import Path
20
+
21
+ _LOCK = threading.Lock()
22
+ _SIZE = 32
23
+
24
+
25
+ def secret_path() -> Path:
26
+ override = os.environ.get("PYTHON2RUST_SECRET_FILE")
27
+ if override:
28
+ return Path(override)
29
+ cache = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache")
30
+ return cache / "python2rust" / "secret"
31
+
32
+
33
+ def _read(path: Path) -> bytes | None:
34
+ try:
35
+ data = path.read_bytes()
36
+ except FileNotFoundError:
37
+ return None
38
+ return data if len(data) >= _SIZE else None
39
+
40
+
41
+ def _secret() -> bytes:
42
+ path = secret_path()
43
+ with _LOCK:
44
+ found = _read(path)
45
+ if found is not None:
46
+ return found
47
+ path.parent.mkdir(parents=True, exist_ok=True)
48
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.{secrets.token_hex(4)}.tmp")
49
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
50
+ try:
51
+ with os.fdopen(fd, "wb") as fh:
52
+ fh.write(secrets.token_bytes(_SIZE))
53
+ if (
54
+ path.exists()
55
+ ): # a truncated secret is not a key: replace it (old tags stop verifying)
56
+ os.replace(tmp, path)
57
+ else:
58
+ with contextlib.suppress(FileExistsError):
59
+ os.link(tmp, path) # fails when another process won the race: keep theirs
60
+ finally:
61
+ tmp.unlink(missing_ok=True)
62
+ found = _read(path)
63
+ if found is None:
64
+ raise OSError(f"could not create the python2rust secret at {path}")
65
+ return found
66
+
67
+
68
+ def mac(purpose: str, data: bytes) -> str:
69
+ """Hex HMAC-SHA256 of `data`, domain-separated by `purpose`, keyed by the machine secret."""
70
+ key = hmac.new(_secret(), b"python2rust/" + purpose.encode(), hashlib.sha256).digest()
71
+ return hmac.new(key, data, hashlib.sha256).hexdigest()
72
+
73
+
74
+ def verify_mac(purpose: str, data: bytes, tag: object) -> bool:
75
+ """True when `tag` is `mac(purpose, data)`; constant-time, False for anything not a str."""
76
+ return isinstance(tag, str) and hmac.compare_digest(mac(purpose, data), tag)