1use crate::walk::Canonical;
5use std::path::{Path, PathBuf};
6use std::process::Command;
7
8use anyhow::{Context, Result, bail};
9use serde_json::{Value, json};
10
11use crate::bridge::Manifest;
12use crate::harness::{BenchRow, CASES, DiffOutcome};
13use crate::lang::c::{defines_main, scalar};
14
15const WORK_DIR: &str = ".rust-anything";
16
17fn run(cmd: &mut Command, what: &str) -> Result<()> {
18 let output = cmd.output().with_context(|| format!("running {what}"))?;
19 if !output.status.success() {
20 let stderr = String::from_utf8_lossy(&output.stderr);
21 let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
22 bail!(
23 "{what} failed ({}):\n{}",
24 output.status,
25 tail.into_iter().rev().collect::<Vec<_>>().join("\n")
26 );
27 }
28 Ok(())
29}
30
31fn compiler() -> &'static str {
32 if Command::new("cc").arg("--version").output().is_ok() {
33 "cc"
34 } else {
35 "gcc"
36 }
37}
38
39fn signatures(manifest: &Manifest) -> Value {
41 let ctypes = |c: &str, ts: &str| -> String {
42 if ts == "string" {
43 "c_char_p".into()
44 } else {
45 scalar(c).map_or("c_int", |(_, _, _, ct)| ct).to_string()
46 }
47 };
48 let map: serde_json::Map<String, Value> = manifest
49 .exports
50 .iter()
51 .map(|f| {
52 let args: Vec<String> = f
53 .params
54 .iter()
55 .map(|p| ctypes(p.native_type.as_deref().unwrap_or("int"), &p.ts_type))
56 .collect();
57 let ret = ctypes(f.native_return.as_deref().unwrap_or("void"), &f.returns);
58 (f.name.clone(), json!({ "args": args, "ret": ret }))
59 })
60 .collect();
61 Value::Object(map)
62}
63
64fn build_original(crate_dir: &Path, manifest: &Manifest) -> Result<PathBuf> {
66 let ws = crate::lang::c::discover(&manifest.root)?;
67 let mut sources = Vec::new();
68 let mut include_dirs = std::collections::BTreeSet::new();
69 include_dirs.insert(manifest.root.clone());
70 for file in ws
71 .files
72 .iter()
73 .filter(|f| f.kind == crate::ts::discover::FileKind::Source)
74 {
75 let path = manifest.root.join(&file.path);
76 if let Some(dir) = path.parent() {
77 include_dirs.insert(dir.to_path_buf());
78 }
79 if file.path.ends_with(".c")
80 && !defines_main(&std::fs::read_to_string(&path).unwrap_or_default())
81 {
82 sources.push(path);
83 }
84 }
85 for entry in crate::walk::builder(&manifest.root)
88 .require_git(false)
89 .build()
90 .flatten()
91 {
92 if entry.path().extension().is_some_and(|e| e == "h")
93 && let Some(dir) = entry.path().parent()
94 {
95 include_dirs.insert(dir.to_path_buf());
96 }
97 }
98 let out = crate_dir.join(WORK_DIR).join("original.so");
99 std::fs::create_dir_all(crate_dir.join(WORK_DIR))?;
100 let mut cmd = Command::new(compiler());
101 cmd.args(["-shared", "-fPIC", "-O1", "-w", "-o"]).arg(&out);
102 for dir in &include_dirs {
103 cmd.arg(format!("-I{}", dir.display()));
104 }
105 cmd.args(&sources).arg("-lm");
106 run(&mut cmd, "cc (original sources)")?;
107 Ok(out)
108}
109
110fn driver(crate_dir: &Path, manifest: &Manifest) -> Result<(PathBuf, PathBuf)> {
111 let work = crate_dir.join(WORK_DIR);
112 std::fs::create_dir_all(&work)?;
113 let path = work.join("driver_c.py");
114 std::fs::write(&path, DRIVER_C_PY)?;
115 let sigs = work.join("signatures.json");
116 std::fs::write(&sigs, serde_json::to_string(&signatures(manifest))?)?;
117 Ok((path, sigs))
118}
119
120fn python() -> Command {
121 let mut cmd = Command::new("python3");
122 cmd.env("PYTHONDONTWRITEBYTECODE", "1");
123 cmd
124}
125
126pub fn record(crate_dir: &Path, manifest: &Manifest, cases: &[Value]) -> Result<PathBuf> {
127 let original = build_original(crate_dir, manifest)?;
128 let (driver, sigs) = driver(crate_dir, manifest)?;
129 let out = crate_dir.join(CASES);
130 crate::harness::record_cases(
131 cases,
132 &crate_dir.join(WORK_DIR),
133 &out,
134 "python (ctypes)",
135 |inputs, part| {
136 let mut cmd = python();
137 cmd.arg(&driver)
138 .arg("record")
139 .arg(&original)
140 .arg(&sigs)
141 .arg(inputs)
142 .arg(part);
143 Ok(cmd)
144 },
145 )?;
146 Ok(out)
147}
148
149pub fn build(crate_dir: &Path, manifest: &Manifest) -> Result<PathBuf> {
151 let target = crate_dir.join("target");
152 run(
153 Command::new("cargo")
154 .args(["build", "--release", "--manifest-path"])
155 .arg(crate_dir.join("Cargo.toml"))
156 .env("CARGO_TARGET_DIR", &target),
157 "cargo build",
158 )?;
159 let lib = manifest.lib_name();
160 let release = target.join("release");
161 [
162 format!("lib{lib}.so"),
163 format!("lib{lib}.dylib"),
164 format!("{lib}.dll"),
165 ]
166 .iter()
167 .map(|n| release.join(n))
168 .find(|p| p.exists())
169 .with_context(|| format!("no shared library for `{lib}` in {}", release.display()))
170}
171
172pub fn built_library(crate_dir: &Path, manifest: &Manifest) -> Result<PathBuf> {
174 let lib = manifest.lib_name();
175 let release = crate_dir.join("target/release");
176 [
177 format!("lib{lib}.so"),
178 format!("lib{lib}.dylib"),
179 format!("{lib}.dll"),
180 ]
181 .iter()
182 .map(|n| release.join(n))
183 .find(|p| p.exists())
184 .with_context(|| {
185 format!(
186 "no built library in {} (run `rust-anything build` first)",
187 release.display()
188 )
189 })
190}
191
192pub fn diff(crate_dir: &Path, manifest: &Manifest) -> Result<DiffOutcome> {
193 let cases = crate_dir.join(CASES);
194 if !cases.exists() {
195 bail!(
196 "no {CASES} in {} (run `rust-anything record` first)",
197 crate_dir.display()
198 );
199 }
200 let rust = built_library(crate_dir, manifest)?;
201 let (driver, sigs) = driver(crate_dir, manifest)?;
202 let out = crate_dir.join(WORK_DIR).join("diff.json");
203 run(
204 python()
205 .arg(&driver)
206 .arg("diff")
207 .arg(&rust)
208 .arg(&sigs)
209 .arg(&cases)
210 .arg(&out),
211 "python (ctypes)",
212 )?;
213 Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
214}
215
216pub fn bench(crate_dir: &Path, manifest: &Manifest, min_ms: u64) -> Result<Vec<BenchRow>> {
217 let cases_path = crate_dir.join(CASES);
218 if !cases_path.exists() {
219 bail!(
220 "no {CASES} in {} (run `rust-anything record` first)",
221 crate_dir.display()
222 );
223 }
224 let rust = built_library(crate_dir, manifest)?.canonical()?;
225 let work = crate_dir.canonical()?.join(WORK_DIR);
226 std::fs::create_dir_all(&work)?;
227 let cases: Vec<Value> = std::fs::read_to_string(&cases_path)?
228 .lines()
229 .filter(|l| !l.trim().is_empty())
230 .map(serde_json::from_str)
231 .collect::<Result<_, _>>()?;
232 let source = work.join("bench.c");
233 std::fs::write(&source, bench_c(manifest, &cases, min_ms))?;
234 let (sources, include_dirs) = original_sources(manifest)?;
237 let bin = work.join("bench");
238 let mut cmd = Command::new(compiler());
239 cmd.args(["-O2", "-w", "-o"]).arg(&bin).arg(&source);
240 for f in crate::codegen_c::shadow_flags(manifest).split_whitespace() {
241 cmd.arg(f);
242 }
243 for dir in &include_dirs {
244 cmd.arg(format!("-I{}", dir.display()));
245 }
246 cmd.args(&sources)
247 .arg(&rust)
248 .arg(format!(
249 "-Wl,-rpath,{}",
250 rust.parent()
251 .map_or_else(String::new, |p| p.display().to_string())
252 ))
253 .arg("-lm");
254 run(&mut cmd, "cc (bench)")?;
255 let out = work.join("bench.json");
256 run(Command::new(&bin).arg(&out), "bench")?;
257 let timings: serde_json::Map<String, Value> =
258 serde_json::from_str(&std::fs::read_to_string(&out)?)?;
259 Ok(manifest
260 .exports
261 .iter()
262 .filter_map(|f| {
263 let t = timings.get(&f.name)?;
264 let (o, n) = (t["original_ns"].as_f64()?, t["rust_ns"].as_f64()?);
265 Some(BenchRow {
266 name: f.name.clone(),
267 cases: usize::try_from(t["cases"].as_u64().unwrap_or(0)).unwrap_or(0),
268 original_ns: o,
269 rust_ns: n,
270 speedup: o / n,
271 })
272 })
273 .collect())
274}
275
276fn original_sources(
278 manifest: &Manifest,
279) -> Result<(Vec<PathBuf>, std::collections::BTreeSet<PathBuf>)> {
280 let ws = crate::lang::c::discover(&manifest.root)?;
281 let mut sources = Vec::new();
282 let mut include_dirs = std::collections::BTreeSet::new();
283 include_dirs.insert(manifest.root.clone());
284 for file in ws
285 .files
286 .iter()
287 .filter(|f| f.kind == crate::ts::discover::FileKind::Source)
288 {
289 let path = manifest.root.join(&file.path);
290 if let Some(dir) = path.parent() {
291 include_dirs.insert(dir.to_path_buf());
292 }
293 if file.path.ends_with(".c")
294 && !defines_main(&std::fs::read_to_string(&path).unwrap_or_default())
295 {
296 sources.push(path);
297 }
298 }
299 for entry in crate::walk::builder(&manifest.root)
300 .require_git(false)
301 .build()
302 .flatten()
303 {
304 if entry.path().extension().is_some_and(|e| e == "h")
305 && let Some(dir) = entry.path().parent()
306 {
307 include_dirs.insert(dir.to_path_buf());
308 }
309 }
310 Ok((sources, include_dirs))
311}
312
313fn c_literal(s: &str) -> String {
315 let mut out = String::from("\"");
316 for b in s.bytes() {
317 match b {
318 b'"' => out.push_str("\\\""),
319 b'\\' => out.push_str("\\\\"),
320 0x20..=0x7e if b != b'?' => out.push(b as char),
321 _ => out.push_str(&format!("\\{b:03o}")),
322 }
323 }
324 out.push('"');
325 out
326}
327
328fn c_arg(v: &Value, c_type: &str, is_string: bool) -> Option<String> {
330 if is_string {
331 return match v {
332 Value::String(s) => Some(c_literal(s)),
333 Value::Null => Some("NULL".into()),
334 _ => None,
335 };
336 }
337 let float = matches!(
338 c_type.trim_start_matches("const ").trim(),
339 "double" | "float" | "long double"
340 );
341 match v {
342 Value::Number(n) if float => n
343 .as_f64()
344 .map(|x| format!("({c_type})rust_anything_f({}ULL)", x.to_bits())),
345 Value::Object(o) if float => {
346 let x = match o.get("$num")?.as_str()? {
347 "NaN" => f64::NAN,
348 "Infinity" => f64::INFINITY,
349 "-Infinity" => f64::NEG_INFINITY,
350 _ => -0.0,
351 };
352 Some(format!("({c_type})rust_anything_f({}ULL)", x.to_bits()))
353 }
354 Value::Number(n) => n
355 .as_i64()
356 .map(|i| format!("({c_type}){i}LL"))
357 .or_else(|| n.as_u64().map(|u| format!("({c_type}){u}ULL"))),
358 Value::Bool(b) => Some(format!("({c_type}){}", i32::from(*b))),
359 _ => None,
360 }
361}
362
363fn bench_c(m: &Manifest, cases: &[Value], min_ms: u64) -> String {
365 use std::fmt::Write as _;
366 let mut out = String::from(
367 "#include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n\
368 #include <sys/types.h>\n#include <time.h>\n\n\
369 static double rust_anything_f(uint64_t bits) { double d; memcpy(&d, &bits, sizeof d); return d; }\n\
370 static double now_ns(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e9 + t.tv_nsec; }\n\
371 static volatile uint64_t sink;\n\n",
372 );
373 let mut rows = Vec::new();
374 for f in &m.exports {
375 let prototype = f.prototype.as_deref().unwrap_or(&f.name);
376 let original = prototype.replacen(
377 &format!("{}(", f.name),
378 &format!("{}__original(", f.name),
379 1,
380 );
381 let rust = prototype.replacen(
382 &format!("{}(", f.name),
383 &format!("rust_anything_{}(", f.name),
384 1,
385 );
386 let _ = writeln!(out, "{original};\n{rust};");
387 let mut calls = Vec::new();
388 for c in cases
389 .iter()
390 .filter(|c| c["fn"] == f.name.as_str() && c.get("error").is_none())
391 {
392 let args = c["args"].as_array().cloned().unwrap_or_default();
393 let exprs: Option<Vec<String>> = f
394 .params
395 .iter()
396 .enumerate()
397 .map(|(i, p)| {
398 c_arg(
399 args.get(i).unwrap_or(&Value::Null),
400 p.native_type.as_deref().unwrap_or("int"),
401 p.ts_type == "string",
402 )
403 })
404 .collect();
405 if let Some(exprs) = exprs {
406 calls.push(exprs.join(", "));
407 }
408 }
409 if calls.is_empty() {
410 continue;
411 }
412 let void = f.native_return.as_deref() == Some("void");
413 let body = |target: &str| -> String {
414 calls
415 .iter()
416 .map(|a| {
417 if void {
418 format!(" {target}({a});\n")
419 } else {
420 format!(" sink += (uint64_t){target}({a});\n")
421 }
422 })
423 .collect()
424 };
425 let _ = writeln!(
426 out,
427 "static void pass_{n}_original(void) {{\n{}}}\nstatic void pass_{n}_rust(void) {{\n{}}}\n",
428 body(&format!("{}__original", f.name)),
429 body(&format!("rust_anything_{}", f.name)),
430 n = f.name
431 );
432 rows.push((f.name.clone(), calls.len()));
433 }
434 let _ = writeln!(
435 out,
436 "static double timed(void (*pass)(void), int calls) {{\n pass();\n double start = now_ns(), elapsed;\n long passes = 0;\n\
437 \x20 do {{ pass(); passes++; elapsed = now_ns() - start; }} while (elapsed < {min_ms} * 1e6);\n return elapsed / ((double)passes * calls);\n}}\n\n\
438 int main(int argc, char **argv) {{\n FILE *out = fopen(argv[1], \"w\");\n fputs(\"{{\", out);"
439 );
440 for (i, (name, n)) in rows.iter().enumerate() {
441 let _ = writeln!(
442 out,
443 " fprintf(out, \"{}\\\"{name}\\\": {{\\\"cases\\\": {n}, \\\"original_ns\\\": %f, \\\"rust_ns\\\": %f}}\", \
444 timed(pass_{name}_original, {n}), timed(pass_{name}_rust, {n}));",
445 if i == 0 { "" } else { "," }
446 );
447 }
448 out.push_str(" fputs(\"}\", out);\n fclose(out);\n return 0;\n}\n");
449 out
450}
451
452const DRIVER_C_PY: &str = r#"
453import ctypes
454import json
455import locale
456import math
457import os
458import signal
459import sys
460import time
461
462# Python switches C's locale to the user's at startup; a C program stays in "C" unless it calls
463# setlocale, so the library must see "C" here (isspace, toupper, strtod depend on it).
464locale.setlocale(locale.LC_ALL, "C")
465
466
467def enc(v):
468 if isinstance(v, float):
469 if math.isnan(v):
470 return {"$num": "NaN"}
471 if math.isinf(v):
472 return {"$num": "Infinity" if v > 0 else "-Infinity"}
473 if v == 0 and math.copysign(1, v) < 0:
474 return {"$num": "-0"}
475 if isinstance(v, bytes):
476 return {"$bytes": list(v)}
477 return v
478
479
480def dec(v):
481 if isinstance(v, dict) and len(v) == 1:
482 (key, inner), = v.items()
483 if key == "$undefined":
484 return None
485 if key == "$num":
486 return {"NaN": math.nan, "Infinity": math.inf, "-Infinity": -math.inf, "-0": -0.0}[inner]
487 return v
488
489
490def bind(path, signatures):
491 lib = ctypes.CDLL(path)
492 functions = {}
493 for name, sig in signatures.items():
494 try:
495 fn = getattr(lib, name)
496 except AttributeError:
497 continue
498 fn.argtypes = [getattr(ctypes, t) for t in sig["args"]]
499 fn.restype = None if sig["ret"] == "None" else getattr(ctypes, sig["ret"])
500 functions[name] = (fn, sig)
501 return functions
502
503
504def call(functions, c):
505 fn, sig = functions[c["fn"]]
506 args = []
507 for value, kind in zip([dec(a) for a in c["args"]], sig["args"]):
508 if kind == "c_char_p":
509 args.append(None if value is None else str(value).encode("utf-8"))
510 elif kind in ("c_float", "c_double"):
511 args.append(float(value) if isinstance(value, (int, float)) else 0.0)
512 elif kind == "c_bool":
513 args.append(bool(value))
514 else:
515 args.append(int(value) if isinstance(value, (int, float)) and math.isfinite(value) else 0)
516 while len(args) < len(sig["args"]):
517 args.append(None if sig["args"][len(args)] == "c_char_p" else 0)
518 return {"ok": enc(fn(*args))}
519
520
521def isolated(functions, c):
522 """Runs one case in a forked child: undefined behavior in C can crash the process."""
523 read_end, write_end = os.pipe()
524 pid = os.fork()
525 if pid == 0:
526 os.close(read_end)
527 try:
528 result = call(functions, c)
529 except Exception as e: # ctypes conversion errors
530 result = {"error": "%s: %s" % (type(e).__name__, e)}
531 os.write(write_end, json.dumps(result).encode())
532 os._exit(0)
533 os.close(write_end)
534 data = b""
535 while True:
536 chunk = os.read(read_end, 65536)
537 if not chunk:
538 break
539 data += chunk
540 os.close(read_end)
541 _, status = os.waitpid(pid, 0)
542 if os.WIFSIGNALED(status):
543 return {"error": "crash: " + signal.Signals(os.WTERMSIG(status)).name}
544 return json.loads(data) if data else {"error": "crash: no result"}
545
546
547def cases_of(path):
548 return [json.loads(line) for line in open(path, encoding="utf-8") if line.strip()]
549
550
551def record(lib, sigs, inputs, out_path):
552 functions = bind(lib, json.load(open(sigs)))
553 progress = os.environ.get("RUST_ANYTHING_PROGRESS")
554 with open(out_path, "w", encoding="utf-8") as out:
555 for index, c in enumerate(json.load(open(inputs, encoding="utf-8"))):
556 if progress:
557 with open(progress, "a", encoding="utf-8") as p:
558 p.write("%d\n" % index)
559 line = {"fn": c["fn"], "args": c["args"]}
560 line.update(isolated(functions, c))
561 out.write(json.dumps(line, ensure_ascii=False) + "\n")
562 out.flush()
563
564
565def diff(lib, sigs, cases_path, out_path):
566 functions = bind(lib, json.load(open(sigs)))
567 summary = {"total": 0, "passed": 0, "failed": 0, "missing": [], "mismatches": []}
568 for c in cases_of(cases_path):
569 summary["total"] += 1
570 if c["fn"] not in functions:
571 if c["fn"] not in summary["missing"]:
572 summary["missing"].append(c["fn"])
573 summary["failed"] += 1
574 continue
575 if str(c.get("error", "")).startswith("crash:"):
576 # The original's behavior is undefined there: any answer of the port passes.
577 summary["passed"] += 1
578 continue
579 got = isolated(functions, c)
580 expected = {"ok": c.get("ok")}
581 if json.dumps(got) == json.dumps(expected):
582 summary["passed"] += 1
583 else:
584 summary["failed"] += 1
585 summary["mismatches"].append({"fn": c["fn"], "args": c["args"], "expected": expected, "actual": got})
586 json.dump(summary, open(out_path, "w", encoding="utf-8"), ensure_ascii=False)
587
588
589def bench(original, rust, sigs, cases_path, out_path, min_ms):
590 signatures = json.load(open(sigs))
591 old, new = bind(original, signatures), bind(rust, signatures)
592 groups = {}
593 for c in cases_of(cases_path):
594 if "error" not in c:
595 groups.setdefault(c["fn"], []).append(c)
596 rows = []
597 for name, cases in groups.items():
598 if name not in old or name not in new:
599 continue
600
601 def timed(functions):
602 def once():
603 for c in cases:
604 call(functions, c)
605 once()
606 passes, start = 0, time.perf_counter()
607 while True:
608 once()
609 passes += 1
610 elapsed = time.perf_counter() - start
611 if elapsed * 1000 >= min_ms:
612 return elapsed * 1e9 / (passes * len(cases))
613 original_ns, rust_ns = timed(old), timed(new)
614 rows.append({"fn": name, "cases": len(cases), "original_ns": original_ns, "rust_ns": rust_ns, "speedup": original_ns / rust_ns})
615 json.dump(rows, open(out_path, "w"))
616
617
618if __name__ == "__main__":
619 mode, *rest = sys.argv[1:]
620 if mode == "record":
621 record(*rest)
622 elif mode == "diff":
623 diff(*rest)
624 elif mode == "bench":
625 bench(rest[0], rest[1], rest[2], rest[3], rest[4], int(rest[5]))
626"#;