1use std::path::{Path, PathBuf};
5use std::process::Command;
6
7use anyhow::{Context, Result, bail};
8use serde_json::Value;
9
10use crate::bridge::Manifest;
11use crate::harness::{BenchRow, CASES, DiffOutcome};
12
13const WORK_DIR: &str = ".rust-anything";
14
15fn python() -> &'static str {
16 if Command::new("python3")
17 .arg("--version")
18 .output()
19 .is_ok_and(|output| output.status.success())
20 {
21 "python3"
22 } else {
23 "python"
24 }
25}
26
27fn run(cmd: &mut Command) -> Result<()> {
28 let output = cmd.output().context("running python")?;
29 if !output.status.success() {
30 let stderr = String::from_utf8_lossy(&output.stderr);
31 let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
32 bail!(
33 "python failed ({}):\n{}",
34 output.status,
35 tail.into_iter().rev().collect::<Vec<_>>().join("\n")
36 );
37 }
38 Ok(())
39}
40
41fn driver(crate_dir: &Path) -> Result<PathBuf> {
42 let work = crate_dir.join(WORK_DIR);
43 std::fs::create_dir_all(&work)?;
44 let path = work.join("driver.py");
45 std::fs::write(&path, DRIVER_PY)?;
46 Ok(path)
47}
48
49pub fn package(crate_dir: &Path, manifest: &Manifest) -> (PathBuf, String) {
51 (crate_dir.join("python"), manifest.lib_name())
52}
53
54pub fn record(crate_dir: &Path, cases: &[Value]) -> Result<PathBuf> {
55 let driver = driver(crate_dir)?;
56 let out = crate_dir.join(CASES);
57 crate::harness::record_cases(
58 cases,
59 &crate_dir.join(WORK_DIR),
60 &out,
61 "python",
62 |inputs, part| {
63 let mut cmd = Command::new(python());
64 cmd.arg(&driver)
65 .arg("record")
66 .arg(inputs)
67 .arg(part)
68 .env("PYTHONHASHSEED", "0")
69 .env("PYTHONDONTWRITEBYTECODE", "1");
71 Ok(cmd)
72 },
73 )?;
74 Ok(out)
75}
76
77pub fn build(crate_dir: &Path, manifest: &Manifest) -> Result<PathBuf> {
78 let target = crate_dir.join("target");
79 let output = Command::new("cargo")
80 .args(["build", "--release", "--manifest-path"])
81 .arg(crate_dir.join("Cargo.toml"))
82 .env("CARGO_TARGET_DIR", &target)
83 .output()
84 .context("running cargo build")?;
85 if !output.status.success() {
86 bail!(
87 "cargo build failed:\n{}",
88 String::from_utf8_lossy(&output.stderr)
89 );
90 }
91 let lib = manifest.lib_name();
92 let release = target.join("release");
93 let built = [
94 format!("lib{lib}.so"),
95 format!("lib{lib}.dylib"),
96 format!("{lib}.dll"),
97 ]
98 .iter()
99 .map(|n| release.join(n))
100 .find(|p| p.exists())
101 .with_context(|| format!("no extension module for `{lib}` in {}", release.display()))?;
102 let (dir, name) = package(crate_dir, manifest);
103 let package_dir = dir.join(&name);
104 std::fs::create_dir_all(&package_dir)?;
105 crate::harness::install(&built, &native_file(crate_dir, manifest))?;
106 Ok(package_dir)
107}
108
109pub(crate) fn native_file(crate_dir: &Path, manifest: &Manifest) -> PathBuf {
111 let (dir, name) = package(crate_dir, manifest);
112 dir.join(name).join(if cfg!(windows) {
113 "_native.pyd"
114 } else {
115 "_native.abi3.so"
116 })
117}
118
119pub fn diff(crate_dir: &Path, manifest: &Manifest, ignore_key_order: bool) -> Result<DiffOutcome> {
120 let cases = crate_dir.join(CASES);
121 if !cases.exists() {
122 bail!(
123 "no {CASES} in {} (run `rust-anything record` first)",
124 crate_dir.display()
125 );
126 }
127 let driver = driver(crate_dir)?;
128 let (dir, name) = package(crate_dir, manifest);
129 let out = crate_dir.join(WORK_DIR).join("diff.json");
130 run(Command::new(python())
131 .arg(&driver)
132 .arg("diff")
133 .arg(&cases)
134 .arg(&out)
135 .arg(dir)
136 .arg(name)
137 .arg(if ignore_key_order { "sort" } else { "keep" })
138 .env("PYTHONHASHSEED", "0")
139 .env("PYTHONDONTWRITEBYTECODE", "1"))?;
141 Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
142}
143
144pub fn bench(crate_dir: &Path, manifest: &Manifest, min_ms: u64) -> Result<Vec<BenchRow>> {
145 let cases = crate_dir.join(CASES);
146 if !cases.exists() {
147 bail!(
148 "no {CASES} in {} (run `rust-anything record` first)",
149 crate_dir.display()
150 );
151 }
152 let driver = driver(crate_dir)?;
153 let (dir, name) = package(crate_dir, manifest);
154 let modules: serde_json::Map<String, Value> = manifest
155 .exports
156 .iter()
157 .map(|f| {
158 (
159 f.name.clone(),
160 Value::String(manifest.root.join(&f.file).to_string_lossy().into_owned()),
161 )
162 })
163 .chain(manifest.classes.iter().map(|c| {
164 (
165 c.name.clone(),
166 Value::String(manifest.root.join(&c.file).to_string_lossy().into_owned()),
167 )
168 }))
169 .collect();
170 let modules_path = crate_dir.join(WORK_DIR).join("bench-modules.json");
171 std::fs::write(&modules_path, serde_json::to_string(&modules)?)?;
172 let out = crate_dir.join(WORK_DIR).join("bench.json");
173 run(Command::new(python())
174 .arg(&driver)
175 .arg("bench")
176 .arg(&cases)
177 .arg(&out)
178 .arg(dir)
179 .arg(name)
180 .arg(&modules_path)
181 .arg(min_ms.to_string())
182 .env("PYTHONHASHSEED", "0")
183 .env("PYTHONDONTWRITEBYTECODE", "1"))?;
185 Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
186}
187
188pub const DRIVER_PY: &str = r#"
190import dataclasses
191import importlib
192import json
193import math
194import os
195import sys
196import time
197
198BIG = 2 ** 53
199
200
201def enc(v, stack=()):
202 if v is None or isinstance(v, (bool, str)):
203 return v
204 if isinstance(v, int):
205 return v if -BIG <= v <= BIG else {"$int": str(v)}
206 if isinstance(v, float):
207 if math.isnan(v):
208 return {"$num": "NaN"}
209 if math.isinf(v):
210 return {"$num": "Infinity" if v > 0 else "-Infinity"}
211 if v == 0 and math.copysign(1, v) < 0:
212 return {"$num": "-0"}
213 # 1.0 and 1 are different Python values: keep floats distinguishable.
214 return {"$float": repr(v)} if v.is_integer() else v
215 if any(v is s for s in stack):
216 return {"$cycle": True}
217 stack = stack + (v,)
218 if isinstance(v, list):
219 return [enc(x, stack) for x in v]
220 if isinstance(v, tuple):
221 return {"$tuple": [enc(x, stack) for x in v]}
222 if isinstance(v, (set, frozenset)):
223 return {"$set": sorted((enc(x, stack) for x in v), key=json.dumps)}
224 if isinstance(v, (bytes, bytearray)):
225 return {"$bytes": list(v)}
226 if isinstance(v, dict):
227 if all(isinstance(k, str) for k in v):
228 return {k: enc(x, stack) for k, x in v.items()}
229 return {"$dict": [[enc(k, stack), enc(x, stack)] for k, x in v.items()]}
230 if hasattr(v, "__dict__"):
231 return {"$object": type(v).__name__, "attrs": enc(vars(v), stack)}
232 return {"$repr": type(v).__name__}
233
234
235def dec(v):
236 if isinstance(v, list):
237 return [dec(x) for x in v]
238 if not isinstance(v, dict):
239 return v
240 if len(v) == 1:
241 (key, inner), = v.items()
242 if key == "$undefined":
243 return None
244 if key == "$num":
245 return {"NaN": math.nan, "Infinity": math.inf, "-Infinity": -math.inf, "-0": -0.0}[inner]
246 if key == "$float":
247 return float(inner)
248 if key == "$int":
249 return int(inner)
250 if key == "$tuple":
251 return tuple(dec(x) for x in inner)
252 if key == "$set":
253 return {dec(x) for x in inner}
254 if key == "$bytes":
255 return bytes(inner)
256 if key == "$dict":
257 return {dec(k): dec(x) for k, x in inner}
258 if set(v) == {"$object", "attrs"} and isinstance(v["attrs"], dict):
259 cls = dataclass_named(v["$object"])
260 if cls is not None:
261 return cls(**{k: dec(x) for k, x in v["attrs"].items()})
262 return {k: dec(x) for k, x in v.items()}
263
264
265def dataclass_named(name):
266 """A dataclass the loaded modules define, for building a recorded `$object` argument."""
267 for module in list(sys.modules.values()):
268 cls = getattr(module, name, None)
269 if isinstance(cls, type) and dataclasses.is_dataclass(cls):
270 return cls
271 return None
272
273
274def canon(v, sort):
275 return json.dumps(v, sort_keys=sort, ensure_ascii=False)
276
277
278def load(path):
279 """Imports a source file with its package context, so relative imports work."""
280 path = os.path.abspath(path)
281 directory, filename = os.path.split(path)
282 parts = [os.path.splitext(filename)[0]]
283 while os.path.exists(os.path.join(directory, "__init__.py")):
284 directory, package = os.path.split(directory)
285 parts.insert(0, package)
286 if parts[-1] == "__init__":
287 parts.pop()
288 if directory not in sys.path:
289 sys.path.insert(0, directory)
290 return importlib.import_module(".".join(parts))
291
292
293def error_text(e):
294 return f"{type(e).__name__}: {e}"
295
296
297def call_args(args):
298 """Trailing `undefined` arguments are omitted, so Python defaults apply."""
299 args = list(args)
300 while args and args[-1] == {"$undefined": True}:
301 args.pop()
302 return [dec(a) for a in args]
303
304
305def run_case(mod, c):
306 if c.get("class"):
307 cls = getattr(mod, c["class"])
308 results = []
309 try:
310 instance = cls(*call_args(c["ctor"]))
311 results.append({"ok": True})
312 except (KeyboardInterrupt, SystemExit):
313 raise
314 except BaseException as e: # noqa: BLE001
315 results.append({"error": error_text(e)})
316 return {"results": results}
317 for call in c["calls"]:
318 try:
319 results.append({"ok": enc(getattr(instance, call["method"])(*call_args(call["args"])))})
320 except (KeyboardInterrupt, SystemExit):
321 raise
322 except BaseException as e: # noqa: BLE001
323 results.append({"error": error_text(e)})
324 return {"results": results}
325 kwargs = {k: dec(v) for k, v in c.get("kwargs", {}).items()}
326 try:
327 return {"ok": enc(getattr(mod, c["fn"])(*call_args(c["args"]), **kwargs))}
328 except (KeyboardInterrupt, SystemExit):
329 raise
330 except BaseException as e: # noqa: BLE001
331 return {"error": error_text(e)}
332
333
334def record(inputs_path, out_path):
335 cases = json.load(open(inputs_path, encoding="utf-8"))
336 modules = {}
337 progress = os.environ.get("RUST_ANYTHING_PROGRESS")
338 with open(out_path, "w", encoding="utf-8") as out:
339 for index, c in enumerate(cases):
340 if progress:
341 with open(progress, "a", encoding="utf-8") as p:
342 p.write("%d\n" % index)
343 if c["module"] not in modules:
344 modules[c["module"]] = load(c["module"])
345 result = run_case(modules[c["module"]], c)
346 line = {k: c[k] for k in ("fn", "class", "ctor", "calls", "args", "kwargs") if k in c}
347 line.update(result)
348 out.write(json.dumps(line, ensure_ascii=False) + "\n")
349 out.flush()
350
351
352def native(package_dir, name):
353 sys.path.insert(0, package_dir)
354 return importlib.import_module(name)
355
356
357def error_type(text):
358 return text.split(":", 1)[0]
359
360
361def same(expected, actual, sort):
362 """Exception types are part of a Python contract and must match; a Rust `TypeError` means
363 the bindings rejected the arguments, which agrees with any error from the original."""
364 if "error" in expected or "error" in actual:
365 if not ("error" in expected and "error" in actual):
366 return False
367 return error_type(actual["error"]) in (error_type(expected["error"]), "TypeError")
368 return canon(expected.get("ok"), sort) == canon(actual.get("ok"), sort)
369
370
371def diff(cases_path, out_path, package_dir, name, key_order):
372 mod = native(package_dir, name)
373 sort = key_order == "sort"
374 summary = {"total": 0, "passed": 0, "failed": 0, "missing": [], "mismatches": []}
375 for line in open(cases_path, encoding="utf-8"):
376 if not line.strip():
377 continue
378 c = json.loads(line)
379 summary["total"] += 1
380 name_ = c.get("class") or c["fn"]
381 if not hasattr(mod, name_):
382 if name_ not in summary["missing"]:
383 summary["missing"].append(name_)
384 summary["failed"] += 1
385 continue
386 got = run_case(mod, c)
387 if c.get("class"):
388 want, have = c["results"], got["results"]
389 ok = len(want) == len(have) and all(same(w, h, sort) for w, h in zip(want, have))
390 expected, actual = want, have
391 else:
392 expected = {"error": c["error"]} if "error" in c else {"ok": c.get("ok")}
393 ok = same(expected, got, sort)
394 actual = got
395 if ok:
396 summary["passed"] += 1
397 else:
398 summary["failed"] += 1
399 summary["mismatches"].append({"fn": name_, "args": c.get("args", [c.get("ctor"), c.get("calls")]), "expected": expected, "actual": actual})
400 json.dump(summary, open(out_path, "w", encoding="utf-8"), ensure_ascii=False)
401
402
403def bench(cases_path, out_path, package_dir, name, modules_path, min_ms):
404 new = native(package_dir, name)
405 sources = json.load(open(modules_path, encoding="utf-8"))
406 groups = {}
407 for line in open(cases_path, encoding="utf-8"):
408 if line.strip():
409 c = json.loads(line)
410 groups.setdefault(c.get("class") or c["fn"], []).append(c)
411 rows = []
412 for key, cases in groups.items():
413 if key not in sources or not hasattr(new, key):
414 continue
415 old = load(sources[key])
416
417 def timed(mod):
418 if cases[0].get("class"):
419 def once():
420 for c in cases:
421 run_case(mod, c)
422 else:
423 # Arguments are decoded once: only the calls are timed.
424 fn = getattr(mod, key)
425 prepared = [(call_args(c["args"]), {k: dec(v) for k, v in c.get("kwargs", {}).items()}) for c in cases]
426
427 def once():
428 for args, kwargs in prepared:
429 try:
430 fn(*args, **kwargs)
431 except (KeyboardInterrupt, SystemExit):
432 raise
433 except BaseException: # noqa: BLE001
434 pass
435 once()
436 passes, start = 0, time.perf_counter()
437 while True:
438 once()
439 passes += 1
440 elapsed = time.perf_counter() - start
441 if elapsed * 1000 >= min_ms:
442 return elapsed * 1e9 / (passes * len(cases))
443 original_ns, rust_ns = timed(old), timed(new)
444 label = f"class {key}" if cases[0].get("class") else key
445 rows.append({"fn": label, "cases": len(cases), "original_ns": original_ns, "rust_ns": rust_ns, "speedup": original_ns / rust_ns})
446 json.dump(rows, open(out_path, "w", encoding="utf-8"))
447
448
449if __name__ == "__main__":
450 mode, *rest = sys.argv[1:]
451 if mode == "record":
452 record(*rest)
453 elif mode == "diff":
454 diff(*rest)
455 elif mode == "bench":
456 bench(rest[0], rest[1], rest[2], rest[3], rest[4], int(rest[5]))
457"#;