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,505 @@
1
+ """The Rust side of `verify --level equiv`: read signatures, generate a harness binary, build it.
2
+
3
+ The harness lives in the scratch crate next to the generated modules (`m000`, `m001`, ...). It reads
4
+ JSON lines `{"fn": "m000::add", "args": [...]}` and answers `@@P2R {"ok": v}`, `{"err": kind}`
5
+ (an `Err(e)` returned by the function, kind = the variant name), `{"err": "panic"}` (caught with
6
+ `catch_unwind`), or `{"skip": why}` (an argument the Rust types cannot represent). Plain `println!`
7
+ output of the code under test is ignored by the parent because only prefixed lines count.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import re
14
+ import shutil
15
+ import tempfile
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from python2rust.agent.patches import strip_noise
21
+ from python2rust.verify import check as chk
22
+ from python2rust.verify.check import CheckModule
23
+ from python2rust.verify.equiv.types import RTy, Unsupported, parse_rust_type
24
+
25
+ _FN = re.compile(
26
+ r"^(?P<vis>pub(?:\([^)]*\))?\s+)?(?P<mods>(?:(?:async|unsafe|const|extern\s+\"[^\"]*\")\s+)*)"
27
+ r"fn\s+(?:r#)?(?P<name>\w+)\s*(?P<gen><)?",
28
+ re.M,
29
+ )
30
+
31
+
32
+ @dataclass
33
+ class RustSig:
34
+ name: str # as written in the Rust source (without r#)
35
+ params: list[tuple[str, RTy]]
36
+ ret: RTy
37
+ text: str # the function's source, for the judge
38
+ is_pub: bool
39
+ ident: str = "" # the identifier to call (r# prefix when needed)
40
+
41
+
42
+ def _match(text: str, start: int, open_ch: str, close_ch: str) -> int:
43
+ depth = 0
44
+ for i in range(start, len(text)):
45
+ if text[i] == open_ch:
46
+ depth += 1
47
+ elif text[i] == close_ch:
48
+ depth -= 1
49
+ if depth == 0:
50
+ return i
51
+ return -1
52
+
53
+
54
+ def _split_top(text: str) -> list[str]:
55
+ out, depth, cur = [], 0, []
56
+ for ch in text:
57
+ if ch in "([<":
58
+ depth += 1
59
+ elif ch in ")]>":
60
+ depth -= 1
61
+ if ch == "," and depth == 0:
62
+ out.append("".join(cur))
63
+ cur = []
64
+ else:
65
+ cur.append(ch)
66
+ if "".join(cur).strip():
67
+ out.append("".join(cur))
68
+ return [p.strip() for p in out]
69
+
70
+
71
+ def snake(name: str) -> str:
72
+ return re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", name).lower()
73
+
74
+
75
+ def find_rust_fn(rust: str, py_name: str) -> RustSig:
76
+ """The top-level Rust function made from Python function `py_name`; raises `Unsupported`."""
77
+ clean = strip_noise(rust)
78
+ wanted = {py_name, snake(py_name)}
79
+ for m in _FN.finditer(clean):
80
+ if m.group("name") not in wanted:
81
+ continue
82
+ name = m.group("name")
83
+ if m.group("gen"):
84
+ raise Unsupported("generic Rust function")
85
+ if "async" in m.group("mods"):
86
+ raise Unsupported("async Rust function")
87
+ open_at = clean.find("(", m.end())
88
+ close_at = _match(clean, open_at, "(", ")")
89
+ if open_at < 0 or close_at < 0:
90
+ raise Unsupported("cannot read the Rust signature")
91
+ brace = clean.find("{", close_at)
92
+ header = clean[close_at + 1 : brace if brace >= 0 else len(clean)]
93
+ header = header.split(" where ")[0]
94
+ ret_text = header.split("->", 1)[1].strip() if "->" in header else "()"
95
+ params: list[tuple[str, RTy]] = []
96
+ for part in _split_top(clean[open_at + 1 : close_at]):
97
+ if re.fullmatch(r"(?:&\s*(?:mut\s+)?)?(?:mut\s+)?self(?:\s*:.*)?", part):
98
+ raise Unsupported("method (takes self)")
99
+ pname, _, ptype = part.partition(":")
100
+ params.append((pname.replace("mut ", "").strip(), parse_rust_type(ptype)))
101
+ end = _match(clean, brace, "{", "}") if brace >= 0 else -1
102
+ text = rust[m.start() : end + 1] if end > 0 else rust[m.start() : close_at + 1]
103
+ ident = f"r#{name}" if name in _KEYWORDS else name
104
+ return RustSig(name, params, parse_rust_type(ret_text), text, bool(m.group("vis")), ident)
105
+ raise Unsupported(f"no top-level Rust function named {py_name}")
106
+
107
+
108
+ _KEYWORDS = {"as", "async", "await", "dyn", "fn", "impl", "let", "loop", "match", "mod", "move",
109
+ "mut", "ref", "self", "static", "struct", "trait", "type", "use", "where", "box", "do", "final",
110
+ "try", "yield", "in", "for", "if", "else", "while", "return", "break", "continue", "pub", "enum",
111
+ "const", "crate", "extern", "false", "true", "super", "unsafe"} # fmt: skip
112
+
113
+
114
+ def rust_models(rust: str) -> dict[str, bool]:
115
+ """`{struct name: derives both Serialize and Deserialize}` for the module's structs."""
116
+ clean = strip_noise(rust)
117
+ out: dict[str, bool] = {}
118
+ for m in re.finditer(r"^pub\s+struct\s+(\w+)", clean, re.M):
119
+ above = clean[: m.start()].splitlines()
120
+ attrs: list[str] = []
121
+ while above and above[-1].strip().startswith("#["): # the attribute lines right above it
122
+ attrs.append(above.pop())
123
+ derives = " ".join(attrs)
124
+ out[m.group(1)] = "Serialize" in derives and "Deserialize" in derives
125
+ return out
126
+
127
+
128
+ # --- harness source -----------------------------------------------------------------------------
129
+
130
+ PRELUDE = r"""use serde_json::{json, Value};
131
+ use std::collections::{BTreeMap, HashMap};
132
+ use std::io::BufRead;
133
+ use std::panic::{catch_unwind, AssertUnwindSafe};
134
+
135
+ trait FromJ: Sized { fn from_j(v: &Value) -> Result<Self, String>; }
136
+ trait ToJ { fn to_j(&self) -> Value; }
137
+
138
+ macro_rules! int_impl { ($($t:ty),*) => {$(
139
+ impl FromJ for $t {
140
+ fn from_j(v: &Value) -> Result<Self, String> {
141
+ if let Some(i) = v.as_i64() {
142
+ return <$t>::try_from(i).map_err(|_| format!("int {} out of range for {}", i, stringify!($t)));
143
+ }
144
+ if let Some(u) = v.as_u64() {
145
+ return <$t>::try_from(u).map_err(|_| format!("int {} out of range for {}", u, stringify!($t)));
146
+ }
147
+ Err(format!("expected an integer for {}, got {}", stringify!($t), v))
148
+ }
149
+ }
150
+ impl ToJ for $t { fn to_j(&self) -> Value { json!(*self) } }
151
+ )*} }
152
+ int_impl!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
153
+
154
+ fn tag(f: f64) -> Value {
155
+ if f.is_nan() { json!({"$f": "nan"}) }
156
+ else if f.is_infinite() { json!({"$f": if f > 0.0 { "inf" } else { "-inf" }}) }
157
+ else { json!(f) }
158
+ }
159
+ impl FromJ for f64 {
160
+ fn from_j(v: &Value) -> Result<Self, String> {
161
+ if let Some(f) = v.as_f64() { return Ok(f); }
162
+ match v.get("$f").and_then(|x| x.as_str()) {
163
+ Some("nan") => Ok(f64::NAN),
164
+ Some("inf") => Ok(f64::INFINITY),
165
+ Some("-inf") => Ok(f64::NEG_INFINITY),
166
+ _ => Err(format!("expected a float, got {}", v)),
167
+ }
168
+ }
169
+ }
170
+ impl ToJ for f64 { fn to_j(&self) -> Value { tag(*self) } }
171
+ impl FromJ for f32 { fn from_j(v: &Value) -> Result<Self, String> { Ok(f64::from_j(v)? as f32) } }
172
+ impl ToJ for f32 { fn to_j(&self) -> Value { tag(*self as f64) } }
173
+ impl FromJ for bool {
174
+ fn from_j(v: &Value) -> Result<Self, String> { v.as_bool().ok_or_else(|| format!("expected a bool, got {}", v)) }
175
+ }
176
+ impl ToJ for bool { fn to_j(&self) -> Value { json!(*self) } }
177
+ impl FromJ for String {
178
+ fn from_j(v: &Value) -> Result<Self, String> { v.as_str().map(String::from).ok_or_else(|| format!("expected a string, got {}", v)) }
179
+ }
180
+ impl ToJ for String { fn to_j(&self) -> Value { json!(self) } }
181
+ impl ToJ for str { fn to_j(&self) -> Value { json!(self) } }
182
+ impl FromJ for () {
183
+ fn from_j(v: &Value) -> Result<Self, String> { if v.is_null() { Ok(()) } else { Err(format!("expected null, got {}", v)) } }
184
+ }
185
+ impl ToJ for () { fn to_j(&self) -> Value { Value::Null } }
186
+ impl<T: ToJ + ?Sized> ToJ for &T { fn to_j(&self) -> Value { (**self).to_j() } }
187
+ impl<T: FromJ> FromJ for Vec<T> {
188
+ fn from_j(v: &Value) -> Result<Self, String> {
189
+ v.as_array().ok_or_else(|| format!("expected an array, got {}", v))?.iter().map(T::from_j).collect()
190
+ }
191
+ }
192
+ impl<T: ToJ> ToJ for Vec<T> { fn to_j(&self) -> Value { Value::Array(self.iter().map(|x| x.to_j()).collect()) } }
193
+ impl<T: ToJ> ToJ for [T] { fn to_j(&self) -> Value { Value::Array(self.iter().map(|x| x.to_j()).collect()) } }
194
+ impl<T: FromJ> FromJ for Option<T> {
195
+ fn from_j(v: &Value) -> Result<Self, String> { if v.is_null() { Ok(None) } else { Ok(Some(T::from_j(v)?)) } }
196
+ }
197
+ impl<T: ToJ> ToJ for Option<T> {
198
+ fn to_j(&self) -> Value { match self { Some(x) => x.to_j(), None => Value::Null } }
199
+ }
200
+ impl<V: FromJ> FromJ for HashMap<String, V> {
201
+ fn from_j(v: &Value) -> Result<Self, String> {
202
+ let o = v.as_object().ok_or_else(|| format!("expected an object, got {}", v))?;
203
+ let mut m = HashMap::new();
204
+ for (k, x) in o { m.insert(k.clone(), V::from_j(x)?); }
205
+ Ok(m)
206
+ }
207
+ }
208
+ impl<V: ToJ> ToJ for HashMap<String, V> {
209
+ fn to_j(&self) -> Value {
210
+ let mut keys: Vec<&String> = self.keys().collect();
211
+ keys.sort();
212
+ let mut o = serde_json::Map::new();
213
+ for k in keys { o.insert(k.clone(), self[k].to_j()); }
214
+ Value::Object(o)
215
+ }
216
+ }
217
+ impl<V: FromJ> FromJ for BTreeMap<String, V> {
218
+ fn from_j(v: &Value) -> Result<Self, String> {
219
+ let o = v.as_object().ok_or_else(|| format!("expected an object, got {}", v))?;
220
+ let mut m = BTreeMap::new();
221
+ for (k, x) in o { m.insert(k.clone(), V::from_j(x)?); }
222
+ Ok(m)
223
+ }
224
+ }
225
+ impl<V: ToJ> ToJ for BTreeMap<String, V> {
226
+ fn to_j(&self) -> Value {
227
+ let mut o = serde_json::Map::new();
228
+ for (k, x) in self { o.insert(k.clone(), x.to_j()); }
229
+ Value::Object(o)
230
+ }
231
+ }
232
+ macro_rules! tuple_impl { ($($n:tt $t:ident),+; $len:expr) => {
233
+ impl<$($t: FromJ),+> FromJ for ($($t,)+) {
234
+ fn from_j(v: &Value) -> Result<Self, String> {
235
+ let a = v.as_array().ok_or_else(|| format!("expected an array, got {}", v))?;
236
+ if a.len() != $len { return Err("tuple arity".to_string()); }
237
+ Ok(($(<$t as FromJ>::from_j(&a[$n])?,)+))
238
+ }
239
+ }
240
+ impl<$($t: ToJ),+> ToJ for ($($t,)+) {
241
+ fn to_j(&self) -> Value { Value::Array(vec![$(self.$n.to_j()),+]) }
242
+ }
243
+ } }
244
+ tuple_impl!(0 A; 1);
245
+ tuple_impl!(0 A, 1 B; 2);
246
+ tuple_impl!(0 A, 1 B, 2 C; 3);
247
+ tuple_impl!(0 A, 1 B, 2 C, 3 D; 4);
248
+ """
249
+
250
+ SHARED_IMPLS = r"""
251
+ impl<T: FromJ> FromJ for python2rust_rt::Shared<T> {
252
+ fn from_j(v: &Value) -> Result<Self, String> { T::from_j(v).map(Self::new) }
253
+ }
254
+ impl<T: ToJ> ToJ for python2rust_rt::Shared<T> {
255
+ fn to_j(&self) -> Value { self.borrow().to_j() }
256
+ }
257
+ """
258
+
259
+ INDEXMAP_IMPLS = r"""
260
+ use indexmap::IndexMap; // the parameter text `IndexMap<String, V>` names it unqualified
261
+ impl<V: FromJ> FromJ for indexmap::IndexMap<String, V> {
262
+ fn from_j(v: &Value) -> Result<Self, String> {
263
+ let o = v.as_object().ok_or_else(|| format!("expected an object, got {}", v))?;
264
+ let mut m = indexmap::IndexMap::new();
265
+ for (k, x) in o { m.insert(k.clone(), V::from_j(x)?); }
266
+ Ok(m)
267
+ }
268
+ }
269
+ impl<V: ToJ> ToJ for indexmap::IndexMap<String, V> {
270
+ fn to_j(&self) -> Value {
271
+ let mut o = serde_json::Map::new();
272
+ for (k, x) in self { o.insert(k.clone(), x.to_j()); }
273
+ Value::Object(o)
274
+ }
275
+ }
276
+ """
277
+
278
+ MAIN = r"""
279
+ fn kind_of(dbg: &str) -> String {
280
+ if dbg.starts_with('"') { return "Error".to_string(); }
281
+ dbg.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect()
282
+ }
283
+ fn emit(v: Value) { println!("@@P2R {}", v); }
284
+ fn main() {
285
+ std::panic::set_hook(Box::new(|_| {}));
286
+ let init_ok = module_init();
287
+ let stdin = std::io::stdin();
288
+ for line in stdin.lock().lines() {
289
+ let line = match line { Ok(l) => l, Err(_) => break };
290
+ if line.trim().is_empty() { continue; }
291
+ let req: Value = match serde_json::from_str(&line) {
292
+ Ok(v) => v,
293
+ Err(e) => { emit(json!({"skip": format!("bad request: {}", e)})); continue; }
294
+ };
295
+ if !init_ok { emit(json!({"skip": "a module's top-level code panicked when it was initialised"})); continue; }
296
+ let f = req["fn"].as_str().unwrap_or("").to_string();
297
+ let args: Vec<Value> = req["args"].as_array().cloned().unwrap_or_default();
298
+ emit(dispatch(&f, &args));
299
+ }
300
+ }
301
+ """
302
+
303
+
304
+ @dataclass
305
+ class PlanFn:
306
+ key: str # "m000::add"
307
+ module: str # "m000"
308
+ ident: str
309
+ params: list[RTy]
310
+ ret: RTy
311
+
312
+
313
+ @dataclass
314
+ class PlanModel:
315
+ key: str # "model:m000::User"
316
+ path: str # "m000::User"
317
+
318
+
319
+ @dataclass
320
+ class HarnessPlan:
321
+ fns: list[PlanFn] = field(default_factory=list)
322
+ models: list[PlanModel] = field(default_factory=list)
323
+ modules: list[str] = field(default_factory=list)
324
+ # `<module>::py2rs_module_init` of every module that has one: the import-time statements and
325
+ # module values, which Python runs once when the module is imported (idempotent, behind a Once).
326
+ # The harness runs them at startup, in module order. `py2rs_main` (the same plus the
327
+ # `if __name__ == "__main__":` body) is never called: importing a module does not run that body.
328
+ init_calls: list[str] = field(default_factory=list)
329
+
330
+ def uses_indexmap(self) -> bool:
331
+ def walk(t: RTy) -> bool:
332
+ return t.name == "IndexMap" or any(walk(c) for c in t.args)
333
+
334
+ return any(walk(t) for f in self.fns for t in [*f.params, f.ret])
335
+
336
+
337
+ def _fn_arm(f: PlanFn, debug_err: bool) -> str:
338
+ decls, call_args, observed = [], [], []
339
+ for i, p in enumerate(f.params):
340
+ decls.append(f"let a{i}: {p.owned} = FromJ::from_j(&args[{i}])?;")
341
+ call_args.append(f"&a{i}" if p.ref else f"a{i}.clone()" if p.has_shared else f"a{i}")
342
+ if p.has_shared:
343
+ observed.append(f"ToJ::to_j(&a{i})")
344
+ ret = f.ret
345
+ if ret.kind == "result":
346
+ err = (
347
+ 'let d = format!("{:?}", e); json!({"err": kind_of(&d), "msg": d})'
348
+ if debug_err
349
+ else 'json!({"err": "Error"})'
350
+ )
351
+ if ret.name.strip().endswith("PyError"):
352
+ # the core's error type carries the Python exception kind: its Debug output starts with
353
+ # the struct name, which says nothing about which exception it stands for
354
+ err = 'json!({"err": e.kind.name, "msg": e.message.clone()})'
355
+ out = f'match r {{ Ok(v) => json!({{"ok": ToJ::to_j(&v)}}), Err(e) => {{ {err} }} }}'
356
+ else:
357
+ out = 'json!({"ok": ToJ::to_j(&r)})'
358
+ decl_text = "\n ".join(decls)
359
+ mut = "mut " if observed else ""
360
+ post = f'reply["args_after"] = json!([{", ".join(observed)}]);' if observed else ""
361
+ return f""" "{f.key}" => (|| -> Result<Value, String> {{
362
+ if args.len() != {len(f.params)} {{ return Err("arity".to_string()); }}
363
+ {decl_text}
364
+ let {mut}reply = match catch_unwind(AssertUnwindSafe(|| {f.module}::{f.ident}({", ".join(call_args)}))) {{
365
+ Ok(r) => {out},
366
+ Err(_) => json!({{"err": "panic"}}),
367
+ }};
368
+ {post}
369
+ Ok(reply)
370
+ }})().unwrap_or_else(|e| json!({{"skip": e}})),
371
+ """
372
+
373
+
374
+ def _model_arm(m: PlanModel) -> str:
375
+ return f""" "{m.key}" => match args.first().map(|p| serde_json::from_value::<{m.path}>(p.clone())) {{
376
+ Some(Ok(m)) => match serde_json::to_value(&m) {{
377
+ Ok(v) => json!({{"ok": v}}),
378
+ Err(_) => json!({{"err": "serialize"}}),
379
+ }},
380
+ _ => json!({{"err": "reject"}}),
381
+ }},
382
+ """
383
+
384
+
385
+ def harness_source(plan: HarnessPlan, *, debug_err: bool = True) -> str:
386
+ uses = ", ".join(sorted({m.split("::")[0] for m in plan.modules}))
387
+ arms = "".join(_fn_arm(f, debug_err) for f in plan.fns) + "".join(
388
+ _model_arm(m) for m in plan.models
389
+ )
390
+ dispatch = (
391
+ "fn dispatch(f: &str, args: &[Value]) -> Value {\n match f {\n"
392
+ + arms
393
+ + ' _ => json!({"skip": format!("unknown function {}", f)}),\n }\n}\n'
394
+ )
395
+ init = "".join(f" {c}();\n" for c in plan.init_calls)
396
+ module_init = (
397
+ "fn module_init() -> bool {\n"
398
+ " std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {\n"
399
+ + init
400
+ + " })).is_ok()\n}\n"
401
+ )
402
+ return (
403
+ "#![allow(unused, dead_code, unused_imports)]\n"
404
+ f"use python2rust_check::{{{uses}}};\n"
405
+ + PRELUDE
406
+ + (INDEXMAP_IMPLS if plan.uses_indexmap() else "")
407
+ + (SHARED_IMPLS if any(t.has_shared for f in plan.fns for t in [*f.params, f.ret]) else "")
408
+ + module_init
409
+ + dispatch
410
+ + MAIN
411
+ )
412
+
413
+
414
+ # --- build --------------------------------------------------------------------------------------
415
+
416
+ _MIN_DEPS: dict[str, Any] = {
417
+ "serde": {"version": "1", "features": ["derive"]},
418
+ "serde_json": {"version": "1", "features": ["preserve_order", "float_roundtrip"]},
419
+ "indexmap": {"version": "2", "features": ["serde"]},
420
+ }
421
+
422
+
423
+ def harness_dependencies(
424
+ deps_from: str | None, modules: list[chk.CheckModule] | None = None
425
+ ) -> dict[str, Any]:
426
+ """The dependency table: the project's (or the default crate table) plus what the harness needs."""
427
+ if deps_from:
428
+ deps = chk.read_dependencies(deps_from)
429
+ else:
430
+ deps = (
431
+ {} if os.environ.get(chk.NO_DEFAULT_DEPS_ENV) == "1" else chk.default_dependencies()[0]
432
+ )
433
+ deps = chk.with_required_crates(deps, modules or []) # python2rust-rt and its features, ...
434
+ for name, spec in _MIN_DEPS.items():
435
+ have = deps.get(name)
436
+ if have is None:
437
+ deps[name] = spec
438
+ elif name == "serde_json": # key order is observable, floats must round-trip exactly
439
+ base = {"version": have} if isinstance(have, str) else dict(have)
440
+ base["features"] = sorted({*base.get("features", []), *_MIN_DEPS[name]["features"]})
441
+ deps[name] = base
442
+ return deps
443
+
444
+
445
+ @dataclass
446
+ class Build:
447
+ exe: str | None = None
448
+ error: str | None = None
449
+ notes: list[str] = field(default_factory=list)
450
+
451
+
452
+ def build_harness(
453
+ modules: list[CheckModule],
454
+ plan: HarnessPlan,
455
+ work: Path,
456
+ *,
457
+ deps_from: str | None = None,
458
+ offline: bool = False,
459
+ timeout: float = 300,
460
+ target_dir: str | None = None,
461
+ ) -> Build:
462
+ """Write the scratch crate under `work/crate`, `cargo build` it, return the harness binary."""
463
+ cargo = shutil.which("cargo")
464
+ if cargo is None:
465
+ return Build(error="cargo was not found on PATH")
466
+ crate = work / "crate"
467
+ chk.write_scratch_crate(crate, modules, harness_dependencies(deps_from, modules))
468
+ tdir = Path(target_dir) if target_dir else chk._cache_dir()
469
+ tdir.mkdir(parents=True, exist_ok=True)
470
+ build = Build()
471
+ for debug_err in (True, False):
472
+ (crate / "src" / "main.rs").write_text(
473
+ harness_source(plan, debug_err=debug_err), encoding="utf-8"
474
+ )
475
+ for attempt_offline in dict.fromkeys([offline, True]):
476
+ run = chk.run_in_crate(
477
+ crate, "build", offline=attempt_offline, timeout=timeout, target_dir=str(tdir)
478
+ )
479
+ if run.returncode == 0 and run.executables:
480
+ return Build(exe=run.executables[-1], notes=build.notes)
481
+ errors = [
482
+ msg["message"]["message"]
483
+ for msg in run.messages
484
+ if str(msg.get("message", {}).get("level", "")).startswith("error")
485
+ ]
486
+ if errors:
487
+ build.error = "; ".join(errors[:3])
488
+ break
489
+ tail = " ".join(run.stderr.strip().splitlines()[-2:])
490
+ build.error = run.reason or f"cargo build failed: {tail}"
491
+ if not any(f.ret.kind == "result" for f in plan.fns):
492
+ break
493
+ return build
494
+
495
+
496
+ def scratch_env() -> dict[str, str]:
497
+ """The only environment child processes get: no tokens, keys or proxies."""
498
+ env = {"PATH": os.environ.get("PATH", ""), "RUST_BACKTRACE": "0", "PYTHONIOENCODING": "utf-8"}
499
+ if os.name == "nt":
500
+ env["SYSTEMROOT"] = os.environ.get("SYSTEMROOT", "")
501
+ return env
502
+
503
+
504
+ def make_workdir() -> Path:
505
+ return Path(tempfile.mkdtemp(prefix="python2rust-equiv-"))