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 _scratch = crate::harness::scratch_cwd(cmd)?;
29 let output = cmd.output().context("running python")?;
30 if !output.status.success() {
31 let stderr = String::from_utf8_lossy(&output.stderr);
32 let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
33 bail!(
34 "python failed ({}):\n{}",
35 output.status,
36 tail.into_iter().rev().collect::<Vec<_>>().join("\n")
37 );
38 }
39 Ok(())
40}
41
42fn driver(crate_dir: &Path) -> Result<PathBuf> {
43 let work = crate_dir.join(WORK_DIR);
44 std::fs::create_dir_all(&work)?;
45 let path = work.join("driver.py");
46 std::fs::write(&path, DRIVER_PY)?;
47 Ok(path)
48}
49
50fn source_files(crate_dir: &Path, manifest: &Manifest) -> Result<PathBuf> {
54 let files: std::collections::BTreeSet<&str> = manifest
55 .exports
56 .iter()
57 .map(|f| f.file.as_str())
58 .chain(manifest.classes.iter().map(|c| c.file.as_str()))
59 .collect();
60 let paths: Vec<String> = files
61 .into_iter()
62 .map(|f| manifest.root.join(f).to_string_lossy().into_owned())
63 .collect();
64 let path = crate_dir.join(WORK_DIR).join("diff-sources.json");
65 std::fs::write(&path, serde_json::to_string(&paths)?)?;
66 Ok(path)
67}
68
69pub fn package(crate_dir: &Path, manifest: &Manifest) -> (PathBuf, String) {
71 (crate_dir.join("python"), manifest.lib_name())
72}
73
74pub fn record(crate_dir: &Path, cases: &[Value]) -> Result<PathBuf> {
75 let driver = driver(crate_dir)?;
76 let out = crate_dir.join(CASES);
77 crate::harness::record_cases(
78 cases,
79 &crate_dir.join(WORK_DIR),
80 &out,
81 "python",
82 |inputs, part| {
83 let mut cmd = Command::new(python());
84 cmd.arg(&driver)
85 .arg("record")
86 .arg(inputs)
87 .arg(part)
88 .env("PYTHONHASHSEED", "0")
89 .env("PYTHONDONTWRITEBYTECODE", "1");
91 crate::pin::apply(&mut cmd, crate_dir)?;
92 crate::enable::original_only(&mut cmd, &Manifest::load(crate_dir)?);
93 Ok(cmd)
94 },
95 )?;
96 Ok(out)
97}
98
99pub fn build(crate_dir: &Path, manifest: &Manifest) -> Result<PathBuf> {
100 let target = crate::cache::target_for(crate_dir)?.dir;
101 let mut cmd = Command::new("cargo");
102 cmd.args(["build", "--release", "--manifest-path"])
103 .arg(crate_dir.join("Cargo.toml"))
104 .env("CARGO_TARGET_DIR", &target);
105 let output = cmd
106 .output()
107 .map_err(|e| crate::process::spawn_error(&cmd, "cargo build", e))?;
108 if !output.status.success() {
109 bail!(
110 "cargo build failed:\n{}",
111 String::from_utf8_lossy(&output.stderr)
112 );
113 }
114 let lib = manifest.lib_name();
115 let release = target.join("release");
116 let built = [
117 format!("lib{lib}.so"),
118 format!("lib{lib}.dylib"),
119 format!("{lib}.dll"),
120 ]
121 .iter()
122 .map(|n| release.join(n))
123 .find(|p| p.exists())
124 .with_context(|| format!("no extension module for `{lib}` in {}", release.display()))?;
125 let (dir, name) = package(crate_dir, manifest);
126 let package_dir = dir.join(&name);
127 std::fs::create_dir_all(&package_dir)?;
128 crate::harness::install(&built, &native_file(crate_dir, manifest))?;
129 Ok(package_dir)
130}
131
132pub(crate) fn native_file(crate_dir: &Path, manifest: &Manifest) -> PathBuf {
134 let (dir, name) = package(crate_dir, manifest);
135 dir.join(name).join(if cfg!(windows) {
136 "_native.pyd"
137 } else {
138 "_native.abi3.so"
139 })
140}
141
142pub fn diff(crate_dir: &Path, manifest: &Manifest, ignore_key_order: bool) -> Result<DiffOutcome> {
143 let cases = crate_dir.join(CASES);
144 if !cases.exists() {
145 bail!(
146 "no {CASES} in {} (run `rust-anything record` first)",
147 crate_dir.display()
148 );
149 }
150 let native = native_file(crate_dir, manifest);
151 if !native.exists() {
152 let dir = native.parent().unwrap_or(crate_dir);
153 bail!(
154 "no built library in {} (run `rust-anything build {}` first)",
155 dir.display(),
156 crate_dir.display()
157 );
158 }
159 let driver = driver(crate_dir)?;
160 let (dir, name) = package(crate_dir, manifest);
161 let out = crate_dir.join(WORK_DIR).join("diff.json");
162 let mut cmd = Command::new(python());
163 cmd.arg(&driver)
164 .arg("diff")
165 .arg(&cases)
166 .arg(&out)
167 .arg(dir)
168 .arg(name)
169 .arg(if ignore_key_order { "sort" } else { "keep" })
170 .arg(source_files(crate_dir, manifest)?)
171 .env("PYTHONHASHSEED", "0")
172 .env("PYTHONDONTWRITEBYTECODE", "1");
174 crate::pin::apply(&mut cmd, crate_dir)?;
175 crate::enable::original_only(&mut cmd, &Manifest::load(crate_dir)?);
176 run(&mut cmd)?;
177 Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
178}
179
180pub fn bench(crate_dir: &Path, manifest: &Manifest, min_ms: u64) -> Result<Vec<BenchRow>> {
181 let cases = crate_dir.join(CASES);
182 if !cases.exists() {
183 bail!(
184 "no {CASES} in {} (run `rust-anything record` first)",
185 crate_dir.display()
186 );
187 }
188 let native = native_file(crate_dir, manifest);
189 if !native.exists() {
190 let dir = native.parent().unwrap_or(crate_dir);
191 bail!(
192 "no built library in {} (run `rust-anything build {}` first)",
193 dir.display(),
194 crate_dir.display()
195 );
196 }
197 let driver = driver(crate_dir)?;
198 let (dir, name) = package(crate_dir, manifest);
199 let modules: serde_json::Map<String, Value> = manifest
200 .exports
201 .iter()
202 .map(|f| {
203 (
204 f.name.clone(),
205 Value::String(manifest.root.join(&f.file).to_string_lossy().into_owned()),
206 )
207 })
208 .chain(manifest.classes.iter().map(|c| {
209 (
210 c.name.clone(),
211 Value::String(manifest.root.join(&c.file).to_string_lossy().into_owned()),
212 )
213 }))
214 .collect();
215 let modules_path = crate_dir.join(WORK_DIR).join("bench-modules.json");
216 std::fs::write(&modules_path, serde_json::to_string(&modules)?)?;
217 let out = crate_dir.join(WORK_DIR).join("bench.json");
218 let mut cmd = Command::new(python());
219 crate::enable::original_only(&mut cmd, manifest);
220 run(cmd
221 .arg(&driver)
222 .arg("bench")
223 .arg(&cases)
224 .arg(&out)
225 .arg(dir)
226 .arg(name)
227 .arg(&modules_path)
228 .arg(min_ms.to_string())
229 .env("PYTHONHASHSEED", "0")
230 .env("PYTHONDONTWRITEBYTECODE", "1"))?;
232 Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
233}
234
235pub const DRIVER_PY: &str = r#"
237import dataclasses
238import importlib
239import json
240import math
241import os
242import sys
243import time
244
245BIG = 2 ** 53
246
247
248def enc(v, stack=()):
249 if v is None or isinstance(v, (bool, str)):
250 return v
251 if isinstance(v, int):
252 return v if -BIG <= v <= BIG else {"$int": str(v)}
253 if isinstance(v, float):
254 if math.isnan(v):
255 return {"$num": "NaN"}
256 if math.isinf(v):
257 return {"$num": "Infinity" if v > 0 else "-Infinity"}
258 if v == 0 and math.copysign(1, v) < 0:
259 return {"$num": "-0"}
260 # 1.0 and 1 are different Python values: keep floats distinguishable. Through float.__repr__:
261 # a subclass (numpy.float64 under NumPy 2) has its own repr, "np.float64(0.0)", and float()
262 # would call its __float__.
263 return {"$float": float.__repr__(v)} if v.is_integer() else v
264 if any(v is s for s in stack):
265 return {"$cycle": True}
266 stack = stack + (v,)
267 if isinstance(v, list):
268 return [enc(x, stack) for x in v]
269 if isinstance(v, tuple):
270 return {"$tuple": [enc(x, stack) for x in v]}
271 if isinstance(v, (set, frozenset)):
272 return {"$set": sorted((enc(x, stack) for x in v), key=json.dumps)}
273 if isinstance(v, (bytes, bytearray, memoryview)):
274 return {"$bytes": list(bytes(v))}
275 if isinstance(v, dict):
276 if all(isinstance(k, str) for k in v):
277 return {k: enc(x, stack) for k, x in v.items()}
278 return {"$dict": [[enc(k, stack), enc(x, stack)] for k, x in v.items()]}
279 if hasattr(v, "__dict__"):
280 return {"$object": type(v).__name__, "attrs": enc(vars(v), stack)}
281 return {"$repr": type(v).__name__}
282
283
284def dec(v):
285 if isinstance(v, list):
286 return [dec(x) for x in v]
287 if not isinstance(v, dict):
288 return v
289 if len(v) == 1:
290 (key, inner), = v.items()
291 if key == "$undefined":
292 return None
293 if key == "$num":
294 return {"NaN": math.nan, "Infinity": math.inf, "-Infinity": -math.inf, "-0": -0.0}[inner]
295 if key == "$float":
296 return float(inner)
297 if key == "$int":
298 return int(inner)
299 if key == "$tuple":
300 return tuple(dec(x) for x in inner)
301 if key == "$set":
302 return {dec(x) for x in inner}
303 if key == "$bytes":
304 return bytes(inner)
305 if key == "$dict":
306 return {dec(k): dec(x) for k, x in inner}
307 if set(v) == {"$object", "attrs"} and isinstance(v["attrs"], dict):
308 cls = dataclass_named(v["$object"])
309 if cls is not None:
310 return cls(**{k: dec(x) for k, x in v["attrs"].items()})
311 return {k: dec(x) for k, x in v.items()}
312
313
314def dataclass_named(name):
315 """A dataclass the loaded modules define, for building a recorded `$object` argument."""
316 for module in list(sys.modules.values()):
317 cls = getattr(module, name, None)
318 if isinstance(cls, type) and dataclasses.is_dataclass(cls):
319 return cls
320 return None
321
322
323PIN_CASE = None
324
325
326def pin_clock():
327 """With RUST_ANYTHING_NOW_MS set: a fixed clock and mulberry32 behind `random`, restarted
328 from RUST_ANYTHING_SEED by PIN_CASE before each case (see rust-anything's `pinned.rs`)."""
329 global PIN_CASE
330 now = os.environ.get("RUST_ANYTHING_NOW_MS")
331 if now is None:
332 return
333 import datetime as dt
334 import random as rnd
335 now_ms = int(now)
336 seconds = now_ms / 1000
337 seed = int(os.environ.get("RUST_ANYTHING_SEED", "0")) & 0xFFFFFFFF
338 time.time = lambda: seconds
339 time.time_ns = lambda: now_ms * 1_000_000
340 base_datetime, base_date = dt.datetime, dt.date
341
342 def pinned_type(base, methods):
343 class Meta(type):
344 def __instancecheck__(cls, obj):
345 return isinstance(obj, base)
346
347 def __subclasscheck__(cls, sub):
348 return issubclass(sub, base)
349
350 pinned = Meta(base.__name__, (base,), {k: classmethod(f) for k, f in methods.items()})
351 pinned.__module__ = base.__module__
352 return pinned
353
354 dt.datetime = pinned_type(base_datetime, {
355 "now": lambda cls, tz=None: base_datetime.fromtimestamp(seconds, tz),
356 "utcnow": lambda cls: base_datetime.fromtimestamp(seconds, dt.timezone.utc).replace(tzinfo=None),
357 "today": lambda cls: base_datetime.fromtimestamp(seconds),
358 })
359 dt.date = pinned_type(base_date, {"today": lambda cls: base_date.fromtimestamp(seconds)})
360 state = [seed]
361
362 def next_u32():
363 s = (state[0] + 0x6D2B79F5) & 0xFFFFFFFF
364 state[0] = s
365 t = ((s ^ (s >> 15)) * (s | 1)) & 0xFFFFFFFF
366 t ^= (t + ((t ^ (t >> 7)) * (t | 61))) & 0xFFFFFFFF
367 return t ^ (t >> 14)
368
369 class Pinned(rnd.Random):
370 def seed(self, *args, **kwargs):
371 self.gauss_next = None
372
373 def random(self):
374 return next_u32() / 4294967296
375
376 def getrandbits(self, k):
377 if k < 0:
378 raise ValueError("number of bits must be non-negative")
379 out, shift = 0, 0
380 while k > 0:
381 r = next_u32()
382 if k < 32:
383 r >>= 32 - k
384 out |= r << shift
385 shift += 32
386 k -= 32
387 return out
388
389 inst = Pinned()
390 for name in rnd.__all__:
391 if not isinstance(getattr(rnd, name, None), type) and callable(getattr(inst, name, None)):
392 setattr(rnd, name, getattr(inst, name))
393
394 def pin_case(index):
395 state[0] = seed
396 inst.gauss_next = None
397 os.environ["RUST_ANYTHING_CASE"] = str(index)
398
399 PIN_CASE = pin_case
400
401
402def canon(v, sort):
403 return json.dumps(v, sort_keys=sort, ensure_ascii=False)
404
405
406def import_root(path):
407 """The folder a source file is imported from, with its package context, and its module name."""
408 path = os.path.abspath(path)
409 directory, filename = os.path.split(path)
410 parts = [os.path.splitext(filename)[0]]
411 while os.path.exists(os.path.join(directory, "__init__.py")):
412 directory, package = os.path.split(directory)
413 parts.insert(0, package)
414 if parts[-1] == "__init__":
415 parts.pop()
416 return directory, ".".join(parts)
417
418
419def load(path):
420 """Imports a source file with its package context, so relative imports work."""
421 directory, module = import_root(path)
422 if directory not in sys.path:
423 sys.path.insert(0, directory)
424 return importlib.import_module(module)
425
426
427def error_text(e):
428 return f"{type(e).__name__}: {e}"
429
430
431def call_args(args):
432 """Trailing `undefined` arguments are omitted, so Python defaults apply."""
433 args = list(args)
434 while args and args[-1] == {"$undefined": True}:
435 args.pop()
436 return [dec(a) for a in args]
437
438
439def binding_name(name):
440 """The name the Rust bindings give a parameter: `bridge::snake_case`, without `r#`."""
441 out = []
442 for i, ch in enumerate(name):
443 if ch.isupper():
444 prev = name[i - 1] if i else ""
445 nxt = name[i + 1:i + 2]
446 if prev and (prev.islower() or "0" <= prev <= "9") or (prev.isupper() and nxt.islower()):
447 out.append("_")
448 out.append(ch.lower())
449 else:
450 out.append(ch if ch.isalnum() else "_")
451 return "".join(out)
452
453
454def call_kwargs(c, rename=None):
455 """Keyword arguments by their names in the original, or in the bindings with `rename`."""
456 return {(rename(k) if rename else k): dec(v) for k, v in c.get("kwargs", {}).items()}
457
458
459def shown_args(c):
460 """A case's arguments as mismatches show them: keyword arguments appended, as Ruby does."""
461 if c.get("class"):
462 return [c.get("ctor"), c.get("calls")]
463 return c["args"] + [c["kwargs"]] if c.get("kwargs") else c["args"]
464
465
466def run_case(mod, c, rename=None):
467 if c.get("class"):
468 cls = getattr(mod, c["class"])
469 results = []
470 try:
471 instance = cls(*call_args(c["ctor"]))
472 results.append({"ok": True})
473 except (KeyboardInterrupt, SystemExit):
474 raise
475 except BaseException as e: # noqa: BLE001
476 results.append({"error": error_text(e)})
477 return {"results": results}
478 for call in c["calls"]:
479 try:
480 results.append({"ok": enc(getattr(instance, call["method"])(*call_args(call["args"])))})
481 except (KeyboardInterrupt, SystemExit):
482 raise
483 except BaseException as e: # noqa: BLE001
484 results.append({"error": error_text(e)})
485 return {"results": results}
486 kwargs = call_kwargs(c, rename)
487 try:
488 return {"ok": enc(getattr(mod, c["fn"])(*call_args(c["args"]), **kwargs))}
489 except (KeyboardInterrupt, SystemExit):
490 raise
491 except BaseException as e: # noqa: BLE001
492 return {"error": error_text(e)}
493
494
495def record(inputs_path, out_path):
496 cases = json.load(open(inputs_path, encoding="utf-8"))
497 modules = {}
498 progress = os.environ.get("RUST_ANYTHING_PROGRESS")
499 with open(out_path, "w", encoding="utf-8") as out:
500 for index, c in enumerate(cases):
501 if progress:
502 with open(progress, "a", encoding="utf-8") as p:
503 p.write("%d\n" % index)
504 if c["module"] not in modules:
505 modules[c["module"]] = load(c["module"])
506 if PIN_CASE:
507 PIN_CASE(index)
508 result = run_case(modules[c["module"]], c)
509 line = {k: c[k] for k in ("fn", "class", "ctor", "calls", "args", "kwargs") if k in c}
510 line.update(result)
511 out.write(json.dumps(line, ensure_ascii=False) + "\n")
512 out.flush()
513
514
515def native(package_dir, name):
516 sys.path.insert(0, package_dir)
517 return importlib.import_module(name)
518
519
520def error_type(text):
521 return text.split(":", 1)[0]
522
523
524def same(expected, actual, sort):
525 """Exception types are part of a Python contract and must match; a Rust `TypeError` means
526 the bindings rejected the arguments, which agrees with any error from the original."""
527 if "error" in expected or "error" in actual:
528 if not ("error" in expected and "error" in actual):
529 return False
530 return error_type(actual["error"]) in (error_type(expected["error"]), "TypeError")
531 return canon(expected.get("ok"), sort) == canon(actual.get("ok"), sort)
532
533
534def diff(cases_path, out_path, package_dir, name, key_order, sources_path=None):
535 mod = native(package_dir, name)
536 # The original's packages stay importable, as they are in the app: a port raises the
537 # original's own exception classes by importing them (`Err("pkg.errors.Bad: ...")`).
538 sources = json.load(open(sources_path, encoding="utf-8")) if sources_path else []
539 for source in sources:
540 directory = import_root(source)[0]
541 if directory not in sys.path:
542 sys.path.insert(0, directory)
543 sort = key_order == "sort"
544 summary = {"total": 0, "passed": 0, "failed": 0, "missing": [], "mismatches": []}
545 for index, line in enumerate(open(cases_path, encoding="utf-8")):
546 if not line.strip():
547 continue
548 c = json.loads(line)
549 summary["total"] += 1
550 name_ = c.get("class") or c["fn"]
551 if not hasattr(mod, name_):
552 if name_ not in summary["missing"]:
553 summary["missing"].append(name_)
554 summary["failed"] += 1
555 continue
556 if PIN_CASE:
557 PIN_CASE(index)
558 got = run_case(mod, c, binding_name)
559 if c.get("class"):
560 want, have = c["results"], got["results"]
561 ok = len(want) == len(have) and all(same(w, h, sort) for w, h in zip(want, have))
562 expected, actual = want, have
563 else:
564 expected = {"error": c["error"]} if "error" in c else {"ok": c.get("ok")}
565 ok = same(expected, got, sort)
566 actual = got
567 if ok:
568 summary["passed"] += 1
569 else:
570 summary["failed"] += 1
571 summary["mismatches"].append({"fn": name_, "args": shown_args(c), "expected": expected, "actual": actual})
572 json.dump(summary, open(out_path, "w", encoding="utf-8"), ensure_ascii=False)
573
574
575def bench(cases_path, out_path, package_dir, name, modules_path, min_ms):
576 new = native(package_dir, name)
577 sources = json.load(open(modules_path, encoding="utf-8"))
578 groups = {}
579 for line in open(cases_path, encoding="utf-8"):
580 if line.strip():
581 c = json.loads(line)
582 groups.setdefault(c.get("class") or c["fn"], []).append(c)
583 rows = []
584 for key, cases in groups.items():
585 if key not in sources or not hasattr(new, key):
586 continue
587 old = load(sources[key])
588
589 def timed(mod, rename=None):
590 if cases[0].get("class"):
591 def once():
592 for c in cases:
593 run_case(mod, c, rename)
594 else:
595 # Arguments are decoded once: only the calls are timed.
596 fn = getattr(mod, key)
597 prepared = [(call_args(c["args"]), call_kwargs(c, rename)) for c in cases]
598
599 def once():
600 for args, kwargs in prepared:
601 try:
602 fn(*args, **kwargs)
603 except (KeyboardInterrupt, SystemExit):
604 raise
605 except BaseException: # noqa: BLE001
606 pass
607 once()
608 passes, start = 0, time.perf_counter()
609 while True:
610 once()
611 passes += 1
612 elapsed = time.perf_counter() - start
613 if elapsed * 1000 >= min_ms:
614 return elapsed * 1e9 / (passes * len(cases))
615 original_ns, rust_ns = timed(old), timed(new, binding_name)
616 label = f"class {key}" if cases[0].get("class") else key
617 rows.append({"fn": label, "cases": len(cases), "original_ns": original_ns, "rust_ns": rust_ns, "speedup": original_ns / rust_ns})
618 json.dump(rows, open(out_path, "w", encoding="utf-8"))
619
620
621if __name__ == "__main__":
622 mode, *rest = sys.argv[1:]
623 pin_clock()
624 if mode == "record":
625 record(*rest)
626 elif mode == "diff":
627 diff(*rest)
628 elif mode == "bench":
629 bench(rest[0], rest[1], rest[2], rest[3], rest[4], int(rest[5]))
630"#;