1use crate::walk::Canonical;
9use std::collections::BTreeMap;
10use std::path::{Path, PathBuf};
11use std::process::Command;
12
13use anyhow::{Context, Result, bail};
14use serde::{Deserialize, Serialize};
15use serde_json::{Value, json};
16
17use crate::bridge::{Kind, Manifest, RType, param_type};
18use crate::ts::exports::LocalType;
19use crate::ts::shape::{self, Shape};
20
21pub const CASES: &str = "cases.jsonl";
22const WORK_DIR: &str = ".rust-anything";
23const COVERAGE_DIR: &str = "coverage";
24
25const STRINGS: &[&str] = &[
27 "",
28 "a",
29 "ab",
30 "abc",
31 "hello",
32 "hello world",
33 "Hello World",
34 "HELLO",
35 " padded ",
36 "a.b.c",
37 "ns:key.path",
38 "a:b:c",
39 ":",
40 ".leading",
41 "trailing.",
42 "a..b",
43 "src/a/b.ts",
44 "./x/**/*.json",
45 "key_name-1",
46 "{name} has {count} items",
47 "line1\nline2",
48 "tab\tseparated",
49 "ünïcödé",
50 "straße",
51 "İstanbul",
52 "ΣΊΣΥΦΟΣ",
53 "日本語のテキスト",
54 "emoji 👍🏽 mix",
55 "😀",
56 "a😀b😀c",
57 "e\u{301}",
58 "\u{FEFF}bom",
59];
60const JSON_VALUES: &str =
61 r#"[null, true, 0, "x", [], {}, {"a": "b"}, {"a": {"b": "c"}}, ["a", 1]]"#;
62
63#[derive(Debug, Serialize)]
64pub struct RecordOutcome {
65 pub path: PathBuf,
66 pub cases: usize,
67 pub errors: usize,
68 pub traps: usize,
70 pub per_function: BTreeMap<String, usize>,
71 #[serde(skip_serializing_if = "Vec::is_empty")]
73 pub regex_functions: Vec<String>,
74 #[serde(skip_serializing_if = "Vec::is_empty")]
76 pub timed_out: Vec<Value>,
77 #[serde(skip_serializing_if = "Option::is_none")]
79 pub coverage: Option<Value>,
80}
81
82#[derive(Debug, Default, Serialize, Deserialize)]
83pub struct DiffOutcome {
84 pub total: usize,
85 pub passed: usize,
86 pub failed: usize,
87 pub missing: Vec<String>,
89 pub mismatches: Vec<Value>,
91 #[serde(default, skip_serializing_if = "is_zero")]
93 pub accepted: usize,
94 #[serde(default, skip_serializing_if = "Vec::is_empty")]
96 pub stale_known: Vec<Value>,
97 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub trend: Option<crate::recording::Trend>,
100}
101
102fn is_zero(n: &usize) -> bool {
103 *n == 0
104}
105
106pub struct RecordOptions<'a> {
107 pub crate_dir: &'a Path,
108 pub count: usize,
110 pub inputs: Option<&'a Path>,
112 pub module: Option<&'a Path>,
114 pub resolve_from: Option<&'a Path>,
116 pub node_args: &'a [String],
117}
118
119fn python_types(root: &Path, file: &str) -> Vec<LocalType> {
122 let dir = root.join(file).parent().map(Path::to_path_buf);
123 let mut files = vec![root.join(file)];
124 if let Some(dir) = dir
125 && let Ok(entries) = std::fs::read_dir(dir)
126 {
127 let mut siblings: Vec<PathBuf> = entries
128 .flatten()
129 .map(|e| e.path())
130 .filter(|p| p.extension().is_some_and(|e| e == "py") && !files.contains(p))
131 .collect();
132 siblings.sort();
133 files.extend(siblings);
134 }
135 files
136 .iter()
137 .filter_map(|p| std::fs::read_to_string(p).ok())
138 .flat_map(|text| crate::lang::python::dataclass_types(&text))
139 .collect()
140}
141
142pub fn record(opts: &RecordOptions) -> Result<RecordOutcome> {
143 let manifest = Manifest::load(opts.crate_dir)?;
144 let mut cases: Vec<Value> = Vec::new();
145 let module_for = |file: &str| -> Result<String> {
146 let path = match opts.module {
147 Some(m) => m
148 .canonical()
149 .with_context(|| format!("resolving {}", m.display()))?,
150 None => manifest.root.join(file),
151 };
152 Ok(path.to_string_lossy().into_owned())
153 };
154 let mut scopes: BTreeMap<String, Vec<LocalType>> = BTreeMap::new();
155 let mut regex_files: BTreeMap<String, bool> = BTreeMap::new();
156 let mut regex_functions = Vec::new();
157 let mut traps = 0;
158 for f in &manifest.exports {
159 let module = module_for(&f.file)?;
160 if !scopes.contains_key(&f.file) {
161 let text = std::fs::read_to_string(manifest.root.join(&f.file)).unwrap_or_default();
162 regex_files.insert(
163 f.file.clone(),
164 crate::risks::uses_regex(manifest.language, &text),
165 );
166 let types = if manifest.language == crate::lang::Lang::Python {
167 python_types(&manifest.root, &f.file)
168 } else {
169 crate::bridge::types_in_scope(&manifest.root, &f.file, &text)
170 };
171 scopes.insert(f.file.clone(), types);
172 }
173 let regex = regex_files[&f.file];
174 if regex && f.params.iter().any(|p| param_type(p) == RType::Str) {
175 regex_functions.push(f.name.clone());
176 }
177 let types = &scopes[&f.file];
178 let mut all = generate(f, opts.count, types);
179 let mut seen: std::collections::HashSet<String> = all
180 .iter()
181 .map(|a| serde_json::to_string(a).unwrap_or_default())
182 .collect();
183 let base: Vec<Value> = all
184 .first()
185 .and_then(Value::as_array)
186 .cloned()
187 .unwrap_or_default();
188 for args in trap_args(&f.params, &base, regex) {
189 let args = Value::Array(args);
190 if seen.insert(serde_json::to_string(&args).unwrap_or_default()) {
191 all.push(args);
192 traps += 1;
193 }
194 }
195 for (i, mut args) in all.into_iter().enumerate() {
196 if manifest.language == crate::lang::Lang::Python && i % 4 == 3 {
199 intify(&f.params, &mut args);
200 }
201 let mut case = json!({ "fn": f.name, "module": module, "args": args });
202 split_keyword_only(&f.params, &mut case);
203 cases.push(case);
204 }
205 }
206 for class in &manifest.classes {
207 let module = module_for(&class.file)?;
208 let text = std::fs::read_to_string(manifest.root.join(&class.file)).unwrap_or_default();
209 let types = crate::bridge::types_in_scope(&manifest.root, &class.file, &text);
210 for mut scenario in scenarios(class, opts.count.max(20), &types) {
211 scenario["module"] = Value::String(module.clone());
212 cases.push(scenario);
213 }
214 }
215 if let Some(path) = opts.inputs {
216 let text =
217 std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
218 for (i, line) in text
219 .lines()
220 .enumerate()
221 .filter(|(_, l)| !l.trim().is_empty())
222 {
223 let mut case: Value = parse_deep(line).with_context(|| {
224 format!(
225 "{}:{} (values use the record codec: {{\"$undefined\": true}}, {{\"$num\": \"NaN\"}}, \
226 and {{\"$utf16\": [code units]}} for strings with lone surrogates)",
227 path.display(),
228 i + 1
229 )
230 })?;
231 if let Some(class) = case["class"].as_str() {
232 let Some(c) = manifest.classes.iter().find(|c| c.name == class) else {
233 bail!(
234 "{}:{}: `{class}` is not a ported class of this unit",
235 path.display(),
236 i + 1
237 );
238 };
239 case["module"] = Value::String(module_for(&c.file)?);
240 cases.push(case);
241 continue;
242 }
243 let name = case["fn"].as_str().unwrap_or_default().to_string();
244 let Some(f) = manifest.exports.iter().find(|f| f.name == name) else {
245 bail!(
246 "{}:{}: `{name}` is not an export of this unit",
247 path.display(),
248 i + 1
249 );
250 };
251 case["module"] = Value::String(module_for(&f.file)?);
252 cases.push(case);
253 }
254 }
255
256 let timed_out_path = opts.crate_dir.join(WORK_DIR).join(TIMED_OUT);
257 let _ = std::fs::remove_file(&timed_out_path);
258 let coverage_dir = opts.crate_dir.join(WORK_DIR).join(COVERAGE_DIR);
259 let _ = std::fs::remove_dir_all(&coverage_dir);
260 let out = if manifest.language == crate::lang::Lang::Python {
261 crate::harness_py::record(opts.crate_dir, &cases)?
262 } else if manifest.kind == Kind::CAbi {
263 crate::harness_c::record(opts.crate_dir, &manifest, &cases)?
264 } else if manifest.language == crate::lang::Lang::Go {
265 crate::harness_go::record(opts.crate_dir, &manifest, &cases)?
266 } else if manifest.language == crate::lang::Lang::Ruby {
267 crate::harness_ruby::record(opts.crate_dir, &manifest, &cases)?
268 } else if manifest.language == crate::lang::Lang::Java {
269 crate::harness_java::record(opts.crate_dir, &manifest, &cases)?
270 } else {
271 record_node(opts, &manifest, &cases)?
272 };
273 let coverage = crate::recording::node_coverage(&coverage_dir, &manifest);
274 crate::recording::save_fingerprint(opts.crate_dir, &manifest, coverage.as_ref())?;
275 let text = std::fs::read_to_string(&out)?;
276 let mut per_function = BTreeMap::new();
277 let mut errors = 0;
278 let mut count = 0;
279 for line in text.lines().filter(|l| !l.is_empty()) {
280 let case: Value = parse_deep(line)?;
281 count += 1;
282 let class_error = case["results"]
283 .as_array()
284 .is_some_and(|r| r.iter().any(|x| x.get("error").is_some()));
285 errors +=
286 usize::from(case.get("error").is_some() || case.get("panic").is_some() || class_error);
287 let name = case["fn"]
288 .as_str()
289 .or_else(|| case["class"].as_str())
290 .unwrap_or_default();
291 *per_function.entry(name.to_string()).or_default() += 1;
292 }
293 let timed_out: Vec<Value> = std::fs::read_to_string(&timed_out_path)
294 .ok()
295 .and_then(|t| serde_json::from_str(&t).ok())
296 .unwrap_or_default();
297 Ok(RecordOutcome {
298 path: out,
299 cases: count,
300 errors,
301 traps,
302 per_function,
303 regex_functions,
304 timed_out: timed_out
305 .iter()
306 .map(|c| serde_json::json!({ "fn": c["fn"].clone(), "args": c["args"].clone() }))
307 .collect(),
308 coverage,
309 })
310}
311
312fn record_node(opts: &RecordOptions, manifest: &Manifest, cases: &[Value]) -> Result<PathBuf> {
314 let work = opts.crate_dir.join(WORK_DIR);
315 std::fs::create_dir_all(&work)?;
316 let script = work.join("record.mjs");
317 std::fs::write(&script, format!("{CODEC_JS}\n{RECORD_JS}"))?;
318 let out = opts.crate_dir.join(CASES);
319 std::fs::write(work.join("resolve.mjs"), RESOLVE_JS)?;
322 std::fs::write(work.join("register.mjs"), REGISTER_JS)?;
323 let register = work.canonical()?.join("register.mjs");
324 let mut node_args = vec![format!("--import={}", file_url(®ister))];
325 node_args.extend(opts.node_args.iter().cloned());
326 let aliases = alias_env(manifest);
327 let resolve_from = opts
328 .resolve_from
329 .map(|dir| {
330 dir.canonical()
331 .with_context(|| format!("resolving {}", dir.display()))
332 })
333 .transpose()?;
334 let record = |transform: bool| {
335 record_cases(cases, &work, &out, "node", |inputs, part| {
336 let mut cmd = Command::new("node");
337 if transform {
338 cmd.args(transform_flag())
340 .arg("--no-warnings=ExperimentalWarning");
341 }
342 cmd.args(&node_args)
343 .arg(&script)
344 .arg(inputs)
345 .arg(part)
346 .env("NODE_V8_COVERAGE", work.join(COVERAGE_DIR))
347 .env("RUST_ANYTHING_PATHS", &aliases)
348 .env("RUST_ANYTHING_WORKSPACE", workspace_env(manifest));
349 if let Some(dir) = &resolve_from {
350 cmd.env("RUST_ANYTHING_RESOLVE_FROM", dir);
351 }
352 Ok(cmd)
353 })
354 };
355 if let Err(error) = record(false) {
356 if !format!("{error:#}").contains("ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX") {
357 return Err(error);
358 }
359 record(true)?;
360 }
361 Ok(out)
362}
363
364fn transform_flag() -> Option<&'static str> {
365 static SUPPORTED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
366 let supported = *SUPPORTED.get_or_init(|| {
367 let mut cmd = Command::new("node");
368 cmd.args(["--experimental-transform-types", "--no-warnings", "-e", "0"])
369 .stdout(std::process::Stdio::null())
370 .stderr(std::process::Stdio::null());
371 crate::process::status(&mut cmd, crate::process::QUICK).is_ok_and(|s| s.success())
372 });
373 supported.then_some("--experimental-transform-types")
374}
375
376pub(crate) fn install(built: &Path, dest: &Path) -> Result<()> {
379 let tmp = dest.with_extension(format!("tmp-{}", std::process::id()));
380 std::fs::copy(built, &tmp).with_context(|| format!("copying {}", built.display()))?;
381 std::fs::rename(&tmp, dest).with_context(|| format!("installing {}", dest.display()))
382}
383
384fn stale_build(crate_dir: &Path, manifest: &Manifest) -> Option<PathBuf> {
387 let built = match manifest.kind {
388 Kind::Napi => crate_dir.join(format!("{}.node", manifest.lib_name())),
389 Kind::Pyo3 => crate::harness_py::native_file(crate_dir, manifest),
390 _ => return None,
391 };
392 let built_at = std::fs::metadata(&built).and_then(|m| m.modified()).ok()?;
393 let mut sources = vec![crate_dir.join("Cargo.toml")];
394 sources.extend(
395 walkdir_rs(&crate_dir.join("src"))
396 .into_iter()
397 .filter(|p| p.extension().is_some_and(|e| e == "rs")),
398 );
399 sources
400 .iter()
401 .filter_map(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok())
402 .any(|changed| changed > built_at)
403 .then_some(built)
404}
405
406fn walkdir_rs(dir: &Path) -> Vec<PathBuf> {
407 let mut out = Vec::new();
408 let Ok(entries) = std::fs::read_dir(dir) else {
409 return out;
410 };
411 for entry in entries.flatten() {
412 let path = entry.path();
413 if path.is_dir() {
414 out.extend(walkdir_rs(&path));
415 } else {
416 out.push(path);
417 }
418 }
419 out
420}
421
422pub fn build(crate_dir: &Path) -> Result<PathBuf> {
423 let manifest = Manifest::load(crate_dir)?;
424 match manifest.kind {
425 Kind::Pyo3 => crate::harness_py::build(crate_dir, &manifest),
426 Kind::Ffi if manifest.language == crate::lang::Lang::Ruby => {
427 crate::harness_ruby::build(crate_dir, &manifest)
428 }
429 Kind::CAbi | Kind::Ffi => crate::harness_c::build(crate_dir, &manifest),
430 Kind::Napi => {
431 let target = crate_dir.join("target");
432 run(
433 Command::new("cargo")
434 .args(["build", "--release", "--manifest-path"])
435 .arg(crate_dir.join("Cargo.toml"))
436 .env("CARGO_TARGET_DIR", &target),
437 "cargo build",
438 )?;
439 let lib = manifest.lib_name();
440 let release = target.join("release");
441 let built = [
442 format!("lib{lib}.so"),
443 format!("lib{lib}.dylib"),
444 format!("{lib}.dll"),
445 ]
446 .iter()
447 .map(|name| release.join(name))
448 .find(|p| p.exists())
449 .with_context(|| format!("no native library for `{lib}` in {}", release.display()))?;
450 let artifact = crate_dir.join(format!("{lib}.node"));
451 install(&built, &artifact)?;
452 Ok(artifact)
453 }
454 Kind::Wasm => {
455 let target = crate_dir.join("target");
456 run(
457 Command::new("cargo")
458 .args([
459 "build",
460 "--release",
461 "--target",
462 "wasm32-unknown-unknown",
463 "--manifest-path",
464 ])
465 .arg(crate_dir.join("Cargo.toml"))
466 .env("CARGO_TARGET_DIR", &target),
467 "cargo build --target wasm32-unknown-unknown (needs `rustup target add wasm32-unknown-unknown`)",
468 )?;
469 let lock = std::fs::read_to_string(crate_dir.join("Cargo.lock")).unwrap_or_default();
471 let wanted = locked_version(&lock, "wasm-bindgen")
472 .context("wasm-bindgen missing from Cargo.lock")?;
473 let installed = Command::new("wasm-bindgen")
474 .arg("--version")
475 .output()
476 .ok()
477 .map(|o| {
478 String::from_utf8_lossy(&o.stdout)
479 .trim()
480 .rsplit(' ')
481 .next()
482 .unwrap_or_default()
483 .to_string()
484 });
485 if installed.as_deref() != Some(wanted.as_str()) {
486 bail!(
487 "the crate uses wasm-bindgen {wanted}; the CLI must match:\n cargo install wasm-bindgen-cli --version {wanted} --locked{}",
488 installed
489 .map(|v| format!(" (found {v})"))
490 .unwrap_or_default()
491 );
492 }
493 let lib = manifest.lib_name();
494 let wasm = target
495 .join("wasm32-unknown-unknown/release")
496 .join(format!("{lib}.wasm"));
497 run(
498 Command::new("wasm-bindgen")
499 .args(["--target", "nodejs", "--out-dir"])
500 .arg(crate_dir.join("pkg"))
501 .arg(&wasm),
502 "wasm-bindgen",
503 )?;
504 Ok(crate_dir.join("pkg").join(format!("{lib}.js")))
505 }
506 }
507}
508
509#[derive(Debug, Serialize)]
512pub struct Verdict {
513 pub speedup: f64,
514 pub faster: Vec<String>,
515 pub slower: Vec<String>,
516 pub advice: String,
517}
518
519pub fn verdict(rows: &[BenchRow], lang: crate::lang::Lang) -> Verdict {
521 let faster: Vec<String> = rows
522 .iter()
523 .filter(|r| r.speedup >= 1.1)
524 .map(|r| r.name.clone())
525 .collect();
526 let slower: Vec<String> = rows
527 .iter()
528 .filter(|r| r.speedup < 0.9)
529 .map(|r| r.name.clone())
530 .collect();
531 let speedup = if rows.is_empty() {
532 1.0
533 } else {
534 (rows.iter().map(|r| r.speedup.max(1e-9).ln()).sum::<f64>() / rows.len() as f64).exp()
535 };
536 let advice = if rows.is_empty() {
537 "Nothing to compare: record cases that do not throw first.".to_string()
538 } else if slower.is_empty() && faster.len() == rows.len() {
539 "Ship it: every function is faster in Rust, call included.".to_string()
540 } else if slower.is_empty() {
541 "Ship it: no function is slower in Rust; some only tie.".to_string()
542 } else if lang == crate::lang::Lang::C {
543 format!(
545 "No call overhead in C: these are slower as Rust code. Profile and optimize them, or keep them in C: {}.",
546 slower.join(", ")
547 )
548 } else if speedup >= 1.1 {
549 format!(
550 "Ship the faster functions. Keep the slower ones in the original (`bridge --keep`) or move their callers to Rust too: {}.",
551 slower.join(", ")
552 )
553 } else {
554 "Do not ship this unit for speed: calling across costs more than the work these functions do. \
555 Port a bigger unit (these functions together with their callers), so one call does more work."
556 .to_string()
557 };
558 Verdict {
559 speedup,
560 faster,
561 slower,
562 advice,
563 }
564}
565
566pub fn bench_rows(
568 m: &Manifest,
569 original: &serde_json::Map<String, Value>,
570 rust: &serde_json::Map<String, Value>,
571) -> Vec<BenchRow> {
572 m.exports
573 .iter()
574 .filter_map(|f| {
575 let (old, new) = (original.get(&f.name)?, rust.get(&f.name)?);
576 let (o, n) = (old["ns"].as_f64()?, new["ns"].as_f64()?);
577 Some(BenchRow {
578 name: f.name.clone(),
579 cases: usize::try_from(old["cases"].as_u64().unwrap_or(0)).unwrap_or(0),
580 original_ns: o,
581 rust_ns: n,
582 speedup: o / n,
583 })
584 })
585 .collect()
586}
587
588#[derive(Debug, Serialize, Deserialize)]
589pub struct BenchRow {
590 #[serde(rename = "fn")]
591 pub name: String,
592 pub cases: usize,
593 pub original_ns: f64,
595 pub rust_ns: f64,
596 pub speedup: f64,
598}
599
600pub struct BenchOptions<'a> {
601 pub crate_dir: &'a Path,
602 pub min_ms: u64,
604 pub resolve_from: Option<&'a Path>,
605 pub node_args: &'a [String],
606}
607
608pub fn bench(opts: &BenchOptions) -> Result<Vec<BenchRow>> {
610 let manifest = Manifest::load(opts.crate_dir)?;
611 if manifest.language == crate::lang::Lang::Python {
612 return crate::harness_py::bench(opts.crate_dir, &manifest, opts.min_ms);
613 }
614 if manifest.kind == Kind::CAbi {
615 return crate::harness_c::bench(opts.crate_dir, &manifest, opts.min_ms);
616 }
617 if manifest.language == crate::lang::Lang::Go {
618 return crate::harness_go::bench(opts.crate_dir, &manifest, opts.min_ms);
619 }
620 if manifest.language == crate::lang::Lang::Ruby {
621 return crate::harness_ruby::bench(opts.crate_dir, &manifest, opts.min_ms);
622 }
623 if manifest.language == crate::lang::Lang::Java {
624 return crate::harness_java::bench(opts.crate_dir, &manifest, opts.min_ms);
625 }
626 let cases = opts.crate_dir.join(CASES);
627 if !cases.exists() {
628 bail!(
629 "no {CASES} in {} (run `rust-anything record` first)",
630 opts.crate_dir.display()
631 );
632 }
633 let modules: BTreeMap<String, String> = manifest
634 .exports
635 .iter()
636 .map(|f| {
637 (
638 f.name.clone(),
639 manifest.root.join(&f.file).to_string_lossy().into_owned(),
640 )
641 })
642 .collect();
643 let work = opts.crate_dir.join(WORK_DIR);
644 std::fs::create_dir_all(&work)?;
645 std::fs::write(work.join("resolve.mjs"), RESOLVE_JS)?;
646 std::fs::write(work.join("register.mjs"), REGISTER_JS)?;
647 let class_modules: BTreeMap<String, String> = manifest
648 .classes
649 .iter()
650 .map(|c| {
651 (
652 c.name.clone(),
653 manifest.root.join(&c.file).to_string_lossy().into_owned(),
654 )
655 })
656 .collect();
657 let async_functions: Vec<&str> = manifest
658 .exports
659 .iter()
660 .filter(|f| f.is_async)
661 .map(|f| f.name.as_str())
662 .collect();
663 let modules_path = work.join("bench-modules.json");
664 std::fs::write(
665 &modules_path,
666 serde_json::to_string(&json!({
667 "functions": modules,
668 "classes": class_modules,
669 "asyncFunctions": async_functions,
670 }))?,
671 )?;
672 let script = work.join("bench.mjs");
673 std::fs::write(&script, format!("{CODEC_JS}\n{BENCH_JS}"))?;
674 let out = work.join("bench.json");
675 let native = opts.crate_dir.join("index.cjs").canonical()?;
676 let register = work.canonical()?.join("register.mjs");
677 let mut cmd = Command::new("node");
678 cmd.args(transform_flag())
679 .arg("--no-warnings")
680 .arg(format!("--import={}", file_url(®ister)))
681 .args(opts.node_args)
682 .arg(&script)
683 .arg(&modules_path)
684 .arg(&native)
685 .arg(&cases)
686 .arg(&out)
687 .arg(opts.min_ms.to_string())
688 .env("RUST_ANYTHING_PATHS", alias_env(&manifest))
689 .env("RUST_ANYTHING_WORKSPACE", workspace_env(&manifest));
690 if let Some(dir) = opts.resolve_from {
691 cmd.env("RUST_ANYTHING_RESOLVE_FROM", dir.canonical()?);
692 }
693 run(&mut cmd, "node")?;
694 Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
695}
696
697pub struct DiffOptions<'a> {
698 pub crate_dir: &'a Path,
699 pub module: Option<&'a Path>,
701 pub ignore_key_order: bool,
703 pub node_args: &'a [String],
704 pub float_tolerance: Option<f64>,
706}
707
708const SHOWN_MISMATCHES: usize = 20;
710
711pub fn diff(opts: &DiffOptions) -> Result<DiffOutcome> {
712 let mut outcome = diff_exact(opts)?;
713 let manifest = Manifest::load(opts.crate_dir).ok();
714 let saved = manifest.as_ref().and_then(|m| m.float_tolerance);
715 if let Some(t) = opts.float_tolerance.or(saved) {
716 let preserve_key_order = opts.module.is_some()
717 || manifest.as_ref().is_none_or(|m| {
718 matches!(
719 m.language,
720 crate::lang::Lang::Ts | crate::lang::Lang::Python
721 )
722 });
723 outcome = crate::tolerance::apply(
724 outcome,
725 crate::tolerance::check(t)?,
726 opts.ignore_key_order || !preserve_key_order,
727 );
728 }
729 outcome =
730 crate::recording::apply_known(outcome, &crate::recording::known_diffs(opts.crate_dir)?);
731 outcome.mismatches.truncate(SHOWN_MISMATCHES);
732 anyhow::ensure!(
733 outcome.total > 0,
734 "no recorded cases to compare; run `rust-anything record` first"
735 );
736 if opts.module.is_none() {
737 outcome.trend = crate::recording::track(opts.crate_dir, outcome.passed, outcome.total);
738 }
739 Ok(outcome)
740}
741
742fn diff_exact(opts: &DiffOptions) -> Result<DiffOutcome> {
743 if opts.module.is_none()
744 && let Ok(manifest) = Manifest::load(opts.crate_dir)
745 && let Some(built) = stale_build(opts.crate_dir, &manifest)
746 {
747 bail!(
748 "{} is older than the crate's sources, so diff would test the previous port; run \
749 `rust-anything build {}` first",
750 built.display(),
751 opts.crate_dir.display()
752 );
753 }
754 if let Ok(manifest) = Manifest::load(opts.crate_dir)
755 && manifest.language == crate::lang::Lang::Python
756 && opts.module.is_none()
757 {
758 return crate::harness_py::diff(opts.crate_dir, &manifest, opts.ignore_key_order);
759 }
760 if let Ok(manifest) = Manifest::load(opts.crate_dir)
761 && manifest.kind == Kind::CAbi
762 && opts.module.is_none()
763 {
764 return crate::harness_c::diff(opts.crate_dir, &manifest);
765 }
766 if let Ok(manifest) = Manifest::load(opts.crate_dir)
767 && manifest.language == crate::lang::Lang::Go
768 && opts.module.is_none()
769 {
770 return crate::harness_go::diff(opts.crate_dir, &manifest);
771 }
772 if let Ok(manifest) = Manifest::load(opts.crate_dir)
773 && manifest.language == crate::lang::Lang::Ruby
774 && opts.module.is_none()
775 {
776 return crate::harness_ruby::diff(opts.crate_dir, &manifest);
777 }
778 if let Ok(manifest) = Manifest::load(opts.crate_dir)
779 && manifest.language == crate::lang::Lang::Java
780 && opts.module.is_none()
781 {
782 return crate::harness_java::diff(opts.crate_dir, &manifest);
783 }
784 let cases = opts.crate_dir.join(CASES);
785 if !cases.exists() {
786 bail!(
787 "no {CASES} in {} (run `rust-anything record` first)",
788 opts.crate_dir.display()
789 );
790 }
791 let module = match opts.module {
792 Some(m) => m.to_path_buf(),
793 None => opts.crate_dir.join("index.cjs"),
794 };
795 let module = module
796 .canonical()
797 .with_context(|| format!("resolving {}", module.display()))?;
798 let work = opts.crate_dir.join(WORK_DIR);
799 std::fs::create_dir_all(&work)?;
800 let script = work.join("diff.mjs");
801 std::fs::write(&script, format!("{CODEC_JS}\n{DIFF_JS}"))?;
802 let out = work.join("diff.json");
803 let flag = if opts.ignore_key_order {
804 "sort"
805 } else {
806 "keep"
807 };
808 run_node(
809 opts.node_args,
810 &script,
811 &[
812 module.as_os_str(),
813 cases.as_os_str(),
814 out.as_os_str(),
815 flag.as_ref(),
816 ],
817 )?;
818 let text = std::fs::read_to_string(&out)?;
819 Ok(serde_json::from_str(&text)?)
820}
821
822fn locked_version(lock: &str, package: &str) -> Option<String> {
824 let mut lines = lock.lines();
825 while let Some(line) = lines.next() {
826 if line.trim() == format!("name = \"{package}\"") {
827 let version = lines
828 .next()?
829 .trim()
830 .strip_prefix("version = \"")?
831 .strip_suffix('"')?;
832 return Some(version.to_string());
833 }
834 }
835 None
836}
837
838pub fn generate(
840 f: &crate::ts::exports::ExportedFn,
841 count: usize,
842 types: &[LocalType],
843) -> Vec<Value> {
844 let mut rng = Rng::new(f.name.bytes().fold(0x9E37_79B9_7F4A_7C15, |h, b| {
845 (h ^ u64::from(b)).wrapping_mul(0x100_0000_01B3)
846 }));
847 let mut seen = std::collections::HashSet::new();
848 let mut out = Vec::new();
849 let mut attempts = 0;
850 while out.len() < count && attempts < count * 20 {
851 attempts += 1;
852 let args = args_for(&f.params, types, &mut rng);
853 let key = serde_json::to_string(&args).unwrap_or_default();
854 if seen.insert(key) {
855 out.push(Value::Array(args));
856 }
857 }
858 out
859}
860
861fn trap_values(t: &RType) -> Vec<Value> {
864 match t {
865 RType::Str => crate::app::STRING_TRAPS
866 .iter()
867 .chain(["ΣΊΣΥΦΟΣ", "a😀b", "\u{FEFF}bom"].iter())
868 .map(|s| json!(s))
869 .collect(),
870 RType::Int => [
871 -7,
872 -1,
873 0,
874 2_147_483_648,
875 -2_147_483_649,
876 9_007_199_254_740_993,
877 i64::MAX,
878 i64::MIN,
879 ]
880 .iter()
881 .map(|n| json!(n))
882 .collect(),
883 RType::F64 => {
884 let mut out: Vec<Value> = [
885 -7.5,
886 0.1,
887 0.30000000000000004,
888 1e21,
889 1e-7,
890 5e-324,
891 1.797_693_134_862_315_7e308,
892 9_007_199_254_740_992.0,
893 ]
894 .iter()
895 .map(|n| json!(n))
896 .collect();
897 out.push(json!({ "$num": "-0" }));
898 out
899 }
900 RType::Vec(inner) => match inner.as_ref() {
901 RType::Str => vec![json!([]), json!(["b", "a", "B", "é", "10", "9", "a"])],
902 RType::Int => vec![json!([]), json!([-7, 3, 0, i64::MAX, -1])],
903 RType::F64 => vec![json!([]), json!([0.1, 0.2, -0.5, 1e21])],
904 _ => vec![json!([])],
905 },
906 RType::Opt(inner) => {
907 let mut out = vec![json!({ "$undefined": true })];
908 out.extend(trap_values(inner));
909 out
910 }
911 RType::Json => crate::app::JSON_TRAPS
912 .iter()
913 .filter_map(|t| serde_json::from_str(t).ok())
914 .chain([json!([3, 1, 2]), json!({})])
915 .collect(),
916 RType::Bool | RType::Unit => Vec::new(),
917 }
918}
919
920pub fn trap_args(
923 params: &[crate::ts::exports::Param],
924 base: &[Value],
925 regex: bool,
926) -> Vec<Vec<Value>> {
927 let mut out = Vec::new();
928 if base.len() < params.iter().filter(|p| !p.rest).count() {
929 return out;
930 }
931 for (i, p) in params.iter().enumerate() {
932 if p.rest || i >= base.len() {
933 continue;
934 }
935 let t = param_type(p);
936 let structured = t.contains_json() && !matches!(t, RType::Json);
937 let any = matches!(p.ts_type.trim(), "any" | "unknown" | "object" | "Object");
938 if structured || (matches!(t, RType::Json) && !any) {
939 continue;
940 }
941 let mut values = trap_values(&t);
942 if regex && t == RType::Str {
943 values.extend(crate::risks::REGEX_TRAPS.iter().map(|s| json!(s)));
944 }
945 for v in values {
946 if base[i] != v {
947 let mut args = base.to_vec();
948 args[i] = v;
949 out.push(args);
950 }
951 }
952 }
953 out
954}
955
956fn args_for(
958 params: &[crate::ts::exports::Param],
959 types: &[LocalType],
960 rng: &mut Rng,
961) -> Vec<Value> {
962 let mut args: Vec<Value> = Vec::new();
963 for p in params {
964 let t = param_type(p);
965 let structured = |rng: &mut Rng| {
968 if rng.below(100) < 15 {
969 value(&RType::Json, rng)
970 } else {
971 shaped(&shape::parse(&p.ts_type), types, rng, 0)
972 }
973 };
974 if p.rest {
975 let inner = match t {
976 RType::Vec(inner) => *inner,
977 other => other,
978 };
979 for _ in 0..rng.below(3) {
980 args.push(value(&inner, rng));
981 }
982 } else if t.contains_json() {
983 let v = structured(rng);
984 args.push(if p.optional && rng.below(5) == 0 {
985 json!({ "$undefined": true })
986 } else {
987 v
988 });
989 } else {
990 args.push(value(&t, rng));
991 }
992 }
993 let strings: Vec<usize> = (0..args.len()).filter(|&i| args[i].is_string()).collect();
995 if strings.len() >= 2 && rng.below(10) < 5 {
996 let from = strings[rng.below(strings.len())];
997 let to = strings[rng.below(strings.len())];
998 if from != to {
999 let source: Vec<char> = args[from].as_str().unwrap_or_default().chars().collect();
1000 if !source.is_empty() {
1001 let start = rng.below(source.len());
1002 let end = start + 1 + rng.below(source.len() - start);
1003 let mut piece: String = source[start..end].iter().collect();
1004 if rng.below(4) == 0 {
1005 piece = piece.to_uppercase();
1006 }
1007 args[to] = Value::String(piece);
1008 }
1009 }
1010 }
1011 while args.last().is_some_and(|a| a.get("$undefined").is_some()) && rng.below(2) == 0 {
1013 args.pop();
1014 }
1015 args
1016}
1017
1018pub fn scenarios(
1020 class: &crate::ts::exports::ExportedClass,
1021 count: usize,
1022 types: &[LocalType],
1023) -> Vec<Value> {
1024 let mut rng = Rng::new(class.name.bytes().fold(0x2545_F491_4F6C_DD1D, |h, b| {
1025 (h ^ u64::from(b)).wrapping_mul(0x100_0000_01B3)
1026 }));
1027 (0..count)
1028 .map(|_| {
1029 let ctor = args_for(&class.constructor, types, &mut rng);
1030 let steps = if class.methods.is_empty() {
1031 0
1032 } else {
1033 1 + rng.below(12)
1034 };
1035 let mut seen: Vec<Value> = ctor.iter().filter(|v| v.is_string()).cloned().collect();
1038 let calls: Vec<Value> = (0..steps)
1039 .map(|_| {
1040 let m = &class.methods[rng.below(class.methods.len())];
1041 let mut args = args_for(&m.params, types, &mut rng);
1042 for arg in &mut args {
1043 if arg.is_string() {
1044 if !seen.is_empty() && rng.below(2) == 0 {
1045 *arg = seen[rng.below(seen.len())].clone();
1046 } else {
1047 seen.push(arg.clone());
1048 }
1049 }
1050 }
1051 json!({ "method": m.name, "args": args })
1052 })
1053 .collect();
1054 json!({ "class": class.name, "ctor": ctor, "calls": calls })
1055 })
1056 .collect()
1057}
1058
1059const KEYS: &[&str] = &[
1062 "a", "b", "nav", "home", "title", "2", "10", "ünï", "😀", "a.b",
1063];
1064
1065fn shaped(s: &Shape, types: &[LocalType], rng: &mut Rng, depth: usize) -> Value {
1067 match s {
1068 Shape::Str => value(&RType::Str, rng),
1069 Shape::Num => value(&RType::F64, rng),
1070 Shape::Int => value(&RType::Int, rng),
1071 Shape::Bool => value(&RType::Bool, rng),
1072 Shape::Null => Value::Null,
1073 Shape::Undefined => json!({ "$undefined": true }),
1074 Shape::LitStr(text) => Value::String(text.clone()),
1075 Shape::LitNum(n) => json!(n),
1076 Shape::LitBool(b) => Value::Bool(*b),
1077 Shape::Union(items) if !items.is_empty() => {
1078 shaped(&items[rng.below(items.len())], types, rng, depth)
1079 }
1080 Shape::Array(item) if depth < 6 => Value::Array(
1081 (0..rng.below(4))
1082 .map(|_| shaped(item, types, rng, depth + 1))
1083 .collect(),
1084 ),
1085 Shape::Tuple(items) => Value::Array(
1086 items
1087 .iter()
1088 .map(|i| shaped(i, types, rng, depth + 1))
1089 .collect(),
1090 ),
1091 Shape::Object(props, index) if depth < 6 => {
1092 let mut out = serde_json::Map::new();
1093 for (name, optional, prop) in props {
1094 if *optional && rng.below(4) == 0 {
1095 continue;
1096 }
1097 out.insert(name.clone(), shaped(prop, types, rng, depth + 1));
1098 }
1099 if let Some(item) = index {
1100 for _ in 0..rng.below(4) {
1101 out.insert(
1102 KEYS[rng.below(KEYS.len())].to_string(),
1103 shaped(item, types, rng, depth + 1),
1104 );
1105 }
1106 }
1107 Value::Object(out)
1108 }
1109 Shape::Ref(name, args) if depth < 6 => {
1110 shaped(&shape::resolve(name, args, types), types, rng, depth + 1)
1111 }
1112 Shape::Any => value(&RType::Json, rng),
1113 _ => Value::Null,
1115 }
1116}
1117
1118fn value(t: &RType, rng: &mut Rng) -> Value {
1119 match t {
1120 RType::Str => {
1121 let a = STRINGS[rng.below(STRINGS.len())];
1122 if rng.below(5) == 0 {
1123 Value::String(format!("{a}{}", STRINGS[rng.below(STRINGS.len())]))
1124 } else {
1125 Value::String(a.into())
1126 }
1127 }
1128 RType::Int => {
1129 let n: [i64; 12] = [
1131 0,
1132 1,
1133 -1,
1134 2,
1135 7,
1136 42,
1137 100,
1138 -100,
1139 255,
1140 i64::from(i32::MAX),
1141 i64::from(i32::MIN),
1142 i64::MAX,
1143 ];
1144 json!(n[rng.below(n.len())])
1145 }
1146 RType::F64 => {
1147 let n = [
1148 0.0,
1149 1.0,
1150 -1.0,
1151 2.0,
1152 3.0,
1153 10.0,
1154 0.5,
1155 -2.5,
1156 42.0,
1157 100.0,
1158 1000.0,
1159 1e6,
1160 2_147_483_648.0,
1161 9_007_199_254_740_992.0,
1162 ];
1163 match rng.below(n.len() + 4) {
1164 i if i < n.len() => json!(n[i]),
1165 i if i == n.len() => json!({ "$num": "-0" }),
1166 i if i == n.len() + 1 => json!({ "$num": "NaN" }),
1167 i if i == n.len() + 2 => json!({ "$num": "Infinity" }),
1168 _ => json!({ "$num": "-Infinity" }),
1169 }
1170 }
1171 RType::Bool => Value::Bool(rng.below(2) == 0),
1172 RType::Unit => json!({ "$undefined": true }),
1173 RType::Vec(inner) => Value::Array((0..rng.below(4)).map(|_| value(inner, rng)).collect()),
1174 RType::Opt(inner) => {
1175 if rng.below(4) == 0 {
1176 json!({ "$undefined": true })
1177 } else {
1178 value(inner, rng)
1179 }
1180 }
1181 RType::Json => {
1182 let values: Vec<Value> = serde_json::from_str(JSON_VALUES).unwrap_or_default();
1183 values
1184 .get(rng.below(values.len().max(1)))
1185 .cloned()
1186 .unwrap_or(Value::Null)
1187 }
1188 }
1189}
1190
1191struct Rng(u64);
1193
1194impl Rng {
1195 fn new(seed: u64) -> Self {
1196 Self(seed | 1)
1197 }
1198
1199 fn below(&mut self, n: usize) -> usize {
1200 if n == 0 {
1201 return 0;
1202 }
1203 self.0 ^= self.0 >> 12;
1204 self.0 ^= self.0 << 25;
1205 self.0 ^= self.0 >> 27;
1206 let x = self.0.wrapping_mul(0x2545_F491_4F6C_DD1D);
1207 usize::try_from(x >> 33).unwrap_or(0) % n
1208 }
1209}
1210
1211fn run_node(node_args: &[String], script: &Path, args: &[&std::ffi::OsStr]) -> Result<()> {
1212 run(
1213 Command::new("node").args(node_args).arg(script).args(args),
1214 "node",
1215 )
1216}
1217
1218fn case_timeout() -> std::time::Duration {
1221 let secs = std::env::var("RUST_ANYTHING_CASE_TIMEOUT")
1222 .ok()
1223 .and_then(|v| v.parse::<f64>().ok())
1224 .filter(|s| s.is_finite() && *s > 0.0)
1225 .unwrap_or(10.0);
1226 std::time::Duration::from_secs_f64(secs)
1227}
1228
1229pub(crate) fn record_cases(
1235 cases: &[Value],
1236 work: &Path,
1237 out: &Path,
1238 what: &str,
1239 mut command: impl FnMut(&Path, &Path) -> Result<Command>,
1240) -> Result<Vec<Value>> {
1241 use std::process::Stdio;
1242 use std::time::Instant;
1243 std::fs::create_dir_all(work)?;
1244 let timeout = case_timeout();
1245 let inputs = work.join("record-inputs.json");
1246 let part = work.join("record-part.jsonl");
1247 let progress = work.join("record-progress");
1248 let stderr_path = work.join("record-stderr");
1249 let mut recorded = String::new();
1250 let mut timed_out = Vec::new();
1251 let mut start = 0;
1252 while start < cases.len() {
1253 std::fs::write(&inputs, serde_json::to_string(&cases[start..])?)?;
1254 std::fs::write(&progress, "")?;
1255 let _ = std::fs::remove_file(&part);
1256 let mut cmd = command(&inputs, &part)?;
1257 cmd.env("RUST_ANYTHING_PROGRESS", &progress)
1258 .stdin(Stdio::null())
1259 .stdout(Stdio::null())
1260 .stderr(std::fs::File::create(&stderr_path)?);
1261 #[cfg(unix)]
1262 {
1263 use std::os::unix::process::CommandExt as _;
1264 cmd.process_group(0);
1265 }
1266 let mut child = cmd.spawn().with_context(|| format!("running {what}"))?;
1267 let mut current: Option<(usize, Instant)> = None;
1268 let status = loop {
1269 if let Some(status) = child.try_wait()? {
1270 break Some(status);
1271 }
1272 let started = std::fs::read_to_string(&progress).ok().and_then(|p| {
1273 p.lines()
1274 .last()
1275 .and_then(|l| l.trim().parse::<usize>().ok())
1276 });
1277 match (started, current) {
1278 (Some(i), Some((j, _))) if i == j => {}
1279 (Some(i), _) => current = Some((i, Instant::now())),
1280 (None, _) => {}
1281 }
1282 if let Some((_, since)) = current
1283 && since.elapsed() > timeout
1284 {
1285 #[cfg(unix)]
1286 {
1287 let _ = Command::new("/bin/kill")
1288 .args(["-KILL", "--", &format!("-{}", child.id())])
1289 .stderr(Stdio::null())
1290 .status();
1291 }
1292 let _ = child.kill();
1293 let _ = child.wait();
1294 break None;
1295 }
1296 std::thread::sleep(std::time::Duration::from_millis(20));
1297 };
1298 let written = std::fs::read_to_string(&part).unwrap_or_default();
1299 let complete = written.rfind('\n').map_or("", |end| &written[..=end]);
1300 recorded.push_str(complete);
1301 match (status, current) {
1302 (Some(status), _) if status.success() => break,
1303 (Some(status), _) => {
1304 let stderr = std::fs::read_to_string(&stderr_path).unwrap_or_default();
1305 let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
1306 bail!(
1307 "{what} failed ({status}):\n{}",
1308 tail.into_iter().rev().collect::<Vec<_>>().join("\n")
1309 );
1310 }
1311 (None, Some((i, _))) => {
1312 timed_out.push(cases[start + i].clone());
1313 start += i + 1;
1314 }
1315 (None, None) => unreachable!("the watchdog only stops a driver inside a case"),
1316 }
1317 }
1318 std::fs::write(out, recorded)?;
1319 std::fs::write(work.join(TIMED_OUT), serde_json::to_string(&timed_out)?)?;
1320 Ok(timed_out)
1321}
1322
1323pub(crate) const TIMED_OUT: &str = "timed-out.json";
1325
1326fn run(cmd: &mut Command, what: &str) -> Result<()> {
1327 let output = cmd.output().with_context(|| format!("running {what}"))?;
1328 if !output.status.success() {
1329 let stderr = String::from_utf8_lossy(&output.stderr);
1330 let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
1331 bail!(
1332 "{what} failed ({}):\n{}",
1333 output.status,
1334 tail.into_iter().rev().collect::<Vec<_>>().join("\n")
1335 );
1336 }
1337 Ok(())
1338}
1339
1340fn intify(params: &[crate::ts::exports::Param], args: &mut Value) {
1344 let Some(items) = args.as_array_mut() else {
1345 return;
1346 };
1347 for (p, v) in params.iter().zip(items.iter_mut()) {
1348 if p.ts_type == "number"
1349 && let Some(x) = v.as_f64()
1350 && x.fract() == 0.0
1351 && x.abs() < 1e15
1352 && !(x == 0.0 && x.is_sign_negative())
1353 {
1354 *v = json!(x as i64);
1355 }
1356 }
1357}
1358
1359fn split_keyword_only(params: &[crate::ts::exports::Param], case: &mut Value) {
1360 if !params.iter().any(|p| p.keyword_only) {
1361 return;
1362 }
1363 let Some(args) = case["args"].as_array().cloned() else {
1364 return;
1365 };
1366 let mut positional = Vec::new();
1367 let mut kwargs = serde_json::Map::new();
1368 for (i, value) in args.into_iter().enumerate() {
1369 match params.get(i) {
1370 Some(p) if p.keyword_only => {
1371 if value.get("$undefined").is_none() {
1372 kwargs.insert(p.name.clone(), value);
1373 }
1374 }
1375 _ => positional.push(value),
1376 }
1377 }
1378 case["args"] = Value::Array(positional);
1379 case["kwargs"] = Value::Object(kwargs);
1380}
1381
1382fn workspace_env(manifest: &Manifest) -> String {
1385 let packages: BTreeMap<String, String> = crate::ts::discover::discover(&manifest.root)
1386 .map(|ws| {
1387 ws.packages
1388 .into_iter()
1389 .filter(|p| !p.dir.is_empty())
1390 .map(|p| {
1391 let dir = manifest.root.join(&p.dir);
1392 let src = if dir.join("src").is_dir() {
1393 dir.join("src")
1394 } else {
1395 dir
1396 };
1397 (p.name, src.to_string_lossy().into_owned())
1398 })
1399 .collect()
1400 })
1401 .unwrap_or_default();
1402 serde_json::to_string(&packages).unwrap_or_else(|_| "{}".into())
1403}
1404
1405fn alias_env(manifest: &Manifest) -> String {
1407 let mut entries: Vec<(String, Vec<String>)> = Vec::new();
1408 let files = manifest
1409 .exports
1410 .iter()
1411 .map(|f| &f.file)
1412 .chain(manifest.classes.iter().map(|c| &c.file));
1413 for file in files {
1414 let dir = file.rsplit_once('/').map_or("", |(d, _)| d);
1415 for (pattern, targets) in
1416 crate::ts::tsconfig::PathAliases::nearest(&manifest.root, dir).entries
1417 {
1418 if entries.iter().all(|(p, _)| *p != pattern) {
1419 let absolute = targets
1420 .iter()
1421 .map(|t| manifest.root.join(t).to_string_lossy().into_owned())
1422 .collect();
1423 entries.push((pattern, absolute));
1424 }
1425 }
1426 }
1427 serde_json::to_string(&entries).unwrap_or_else(|_| "[]".into())
1428}
1429
1430fn file_url(path: &Path) -> String {
1431 use std::fmt::Write as _;
1432
1433 let text = path.to_string_lossy();
1434 #[cfg(windows)]
1435 let text = text.replace('\\', "/");
1436 let mut url = if text.starts_with('/') {
1437 String::from("file://")
1438 } else {
1439 String::from("file:///")
1440 };
1441 for byte in text.bytes() {
1442 if byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b':' | b'-' | b'_' | b'.' | b'~') {
1443 url.push(char::from(byte));
1444 } else {
1445 let _ = write!(url, "%{byte:02X}");
1446 }
1447 }
1448 url
1449}
1450
1451const REGISTER_JS: &str =
1452 "import { register } from 'node:module'\nregister('./resolve.mjs', import.meta.url)\n";
1453
1454const RESOLVE_JS: &str = r#"
1457import { existsSync, statSync } from 'node:fs'
1458import { fileURLToPath, pathToFileURL } from 'node:url'
1459
1460const extra = process.env.RUST_ANYTHING_RESOLVE_FROM
1461// tsconfig `paths`: exact keys first, then wildcard keys by longest prefix.
1462const aliasPriority = pattern => pattern.includes('*') ? pattern.indexOf('*') : Number.POSITIVE_INFINITY
1463const aliases = JSON.parse(process.env.RUST_ANYTHING_PATHS || '[]')
1464 .sort(([a], [b]) => aliasPriority(b) - aliasPriority(a))
1465// Workspace packages by name: `@x18n/core` and `@x18n/core/sub` resolve to source.
1466const workspace = JSON.parse(process.env.RUST_ANYTHING_WORKSPACE || '{}')
1467const workspaceTargets = (specifier) => {
1468 for (const [name, src] of Object.entries(workspace)) {
1469 if (specifier === name)
1470 return [`${src}/index`]
1471 if (specifier.startsWith(`${name}/`))
1472 return [`${src}/${specifier.slice(name.length + 1)}`, `${src}/${specifier.slice(name.length + 1)}/index`]
1473 }
1474 return []
1475}
1476const aliasTargets = (specifier) => {
1477 for (const [pattern, targets] of aliases) {
1478 const [prefix, suffix = ''] = pattern.split('*')
1479 const exact = !pattern.includes('*')
1480 if (exact ? specifier === pattern : specifier.startsWith(prefix) && specifier.endsWith(suffix) && specifier.length >= prefix.length + suffix.length) {
1481 const star = exact ? '' : specifier.slice(prefix.length, specifier.length - suffix.length)
1482 return targets.map(t => t.replace('*', () => star))
1483 }
1484 }
1485 return []
1486}
1487const suffixes = ['.ts', '.tsx', '.mts', '.js', '.mjs', '/index.ts', '/index.mts', '/index.js']
1488const sourceCandidates = path => {
1489 const exact = path.match(/\.(mjs|cjs|jsx)$/)
1490 if (exact) {
1491 const replacement = { mjs: 'mts', cjs: 'cts', jsx: 'tsx' }[exact[1]]
1492 return [path, path.slice(0, -exact[1].length) + replacement]
1493 }
1494 const stem = path.replace(/\.js$/, '')
1495 return [stem, ...suffixes.map(suffix => stem + suffix)]
1496}
1497const isFile = p => existsSync(p) && statSync(p).isFile()
1498
1499export async function resolve(specifier, context, next) {
1500 // Aliases first: `@/x` is not even a valid package name for Node.
1501 for (const target of [...aliasTargets(specifier), ...workspaceTargets(specifier)]) {
1502 for (const candidate of sourceCandidates(target)) {
1503 if (isFile(candidate))
1504 return next(pathToFileURL(candidate).href, context)
1505 }
1506 }
1507 try {
1508 return await next(specifier, context)
1509 }
1510 catch (error) {
1511 const missing = error?.code === 'ERR_MODULE_NOT_FOUND' || error?.code === 'ERR_UNSUPPORTED_DIR_IMPORT'
1512 if (!missing || !context.parentURL)
1513 throw error
1514 if (specifier.startsWith('.') || specifier.startsWith('/')) {
1515 const path = fileURLToPath(new URL(specifier, context.parentURL))
1516 for (const candidate of sourceCandidates(path)) {
1517 if (isFile(candidate))
1518 return next(pathToFileURL(candidate).href, context)
1519 }
1520 }
1521 else if (extra) {
1522 return next(specifier, { ...context, parentURL: pathToFileURL(`${extra}/`).href })
1523 }
1524 throw error
1525 }
1526}
1527"#;
1528
1529pub const CODEC_JS: &str = r#"
1532const enc = (v, stack = []) => {
1533 if (v === undefined) return { $undefined: true }
1534 if (typeof v === 'number') {
1535 if (Number.isNaN(v)) return { $num: 'NaN' }
1536 if (!Number.isFinite(v)) return { $num: v > 0 ? 'Infinity' : '-Infinity' }
1537 if (Object.is(v, -0)) return { $num: '-0' }
1538 return v
1539 }
1540 // Strings JS split inside a surrogate pair are not valid Unicode: keep their code units.
1541 if (typeof v === 'string' && !v.isWellFormed()) return { $utf16: Array.from({ length: v.length }, (_, i) => v.charCodeAt(i)) }
1542 if (typeof v === 'bigint') return { $bigint: String(v) }
1543 if (typeof v === 'function') return { $function: v.name }
1544 if (typeof v === 'symbol') return { $symbol: String(v.description) }
1545 if (v === null || typeof v !== 'object') return v
1546 if (stack.includes(v)) return { $cycle: true }
1547 const next = [...stack, v]
1548 if (Array.isArray(v)) return v.map(x => enc(x, next))
1549 if (typeof Buffer !== 'undefined' && Buffer.isBuffer(v)) return { $buffer: [...v] }
1550 if (v instanceof Uint8Array) return { $bytes: [...v] }
1551 if (v instanceof Map) return { $map: [...v].map(([k, x]) => [enc(k, next), enc(x, next)]) }
1552 if (v instanceof Set) return { $set: [...v].map(x => enc(x, next)) }
1553 if (v instanceof Date) return { $date: Number.isNaN(v.getTime()) ? 'Invalid' : v.toISOString() }
1554 if (v instanceof RegExp) return { $regexp: String(v) }
1555 if (v instanceof Error) return { $error: v.message }
1556 return Object.fromEntries(Object.keys(v).map(k => [k, enc(v[k], next)]))
1557}
1558const dec = (v) => {
1559 if (Array.isArray(v)) return v.map(dec)
1560 if (v === null || typeof v !== 'object') return v
1561 if (v.$undefined) return undefined
1562 if ('$num' in v) return Number(v.$num)
1563 if ('$bigint' in v) return BigInt(v.$bigint)
1564 if ('$utf16' in v) {
1565 let text = ''
1566 for (let i = 0; i < v.$utf16.length; i += 8192)
1567 text += String.fromCharCode(...v.$utf16.slice(i, i + 8192))
1568 return text
1569 }
1570 if ('$map' in v) return new Map(v.$map.map(([k, x]) => [dec(k), dec(x)]))
1571 if ('$set' in v) return new Set(v.$set.map(dec))
1572 if ('$date' in v) return new Date(v.$date)
1573 if ('$bytes' in v) return Uint8Array.from(v.$bytes)
1574 if ('$buffer' in v) return Buffer.from(v.$buffer)
1575 return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, dec(x)]))
1576}
1577const canon = (v, sort) => {
1578 if (Array.isArray(v)) return v.map(x => canon(x, sort))
1579 if (v === null || typeof v !== 'object') return v
1580 const keys = Object.keys(v)
1581 if (sort) keys.sort()
1582 return Object.fromEntries(keys.map(k => [k, canon(v[k], sort)]))
1583}
1584const same = (a, b, sort = false) => JSON.stringify(canon(a, sort)) === JSON.stringify(canon(b, sort))
1585"#;
1586
1587const RECORD_JS: &str = r#"
1588import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
1589import { pathToFileURL } from 'node:url'
1590
1591const [inputsPath, outPath] = process.argv.slice(2)
1592const inputs = JSON.parse(readFileSync(inputsPath, 'utf8'))
1593const modules = new Map()
1594const progress = process.env.RUST_ANYTHING_PROGRESS
1595writeFileSync(outPath, '')
1596const lines = { push: line => appendFileSync(outPath, `${line}\n`) }
1597// A class scenario: construct, then call each method in turn; every step's result is recorded.
1598const runScenario = async (Class, c) => {
1599 const results = []
1600 let instance
1601 try {
1602 instance = new Class(...c.ctor.map(dec))
1603 results.push({ ok: true })
1604 }
1605 catch (error) {
1606 results.push({ error: String(error?.message ?? error) })
1607 return results
1608 }
1609 for (const call of c.calls) {
1610 try {
1611 results.push({ ok: enc(await instance[call.method](...call.args.map(dec))) })
1612 }
1613 catch (error) {
1614 results.push({ error: String(error?.message ?? error) })
1615 }
1616 }
1617 return results
1618}
1619for (const [index, c] of inputs.entries()) {
1620 if (progress) appendFileSync(progress, `${index}\n`)
1621 let mod = modules.get(c.module)
1622 if (!mod) {
1623 mod = await import(pathToFileURL(c.module).href)
1624 modules.set(c.module, mod)
1625 }
1626 if (c.class) {
1627 const Class = mod[c.class] ?? mod.default?.[c.class]
1628 if (typeof Class !== 'function') {
1629 console.error(`${c.class} is not a class exported by ${c.module}`)
1630 process.exit(2)
1631 }
1632 lines.push(JSON.stringify({ class: c.class, ctor: c.ctor, calls: c.calls, results: await runScenario(Class, c) }))
1633 continue
1634 }
1635 const fn = mod[c.fn] ?? mod.default?.[c.fn]
1636 if (typeof fn !== 'function') {
1637 console.error(`${c.fn} is not a function exported by ${c.module}`)
1638 process.exit(2)
1639 }
1640 try {
1641 const value = await fn(...c.args.map(dec))
1642 lines.push(JSON.stringify({ fn: c.fn, args: c.args, ok: enc(value) }))
1643 }
1644 catch (error) {
1645 lines.push(JSON.stringify({ fn: c.fn, args: c.args, error: String(error?.message ?? error) }))
1646 }
1647}
1648"#;
1649
1650const BENCH_JS: &str = r#"
1651import { readFileSync, writeFileSync } from 'node:fs'
1652import { pathToFileURL } from 'node:url'
1653
1654const [modulesPath, nativePath, casesPath, outPath, minMs] = process.argv.slice(2)
1655const { functions: modules, classes: classModules, asyncFunctions } = JSON.parse(readFileSync(modulesPath, 'utf8'))
1656const loaded = await import(pathToFileURL(nativePath).href)
1657const native = { ...(loaded.default && typeof loaded.default === 'object' ? loaded.default : {}), ...loaded }
1658const cases = readFileSync(casesPath, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l))
1659const byFn = new Map()
1660const scenarios = new Map()
1661for (const c of cases.filter(c => c.class)) {
1662 if (!scenarios.has(c.class)) scenarios.set(c.class, [])
1663 scenarios.get(c.class).push(c)
1664}
1665for (const c of cases.filter(c => !c.class)) {
1666 if (!byFn.has(c.fn)) byFn.set(c.fn, [])
1667 byFn.get(c.fn).push(c.args.map(dec))
1668}
1669// Time whole passes over the cases until `minMs` has passed; errors count as calls.
1670const time = (fn, argsList) => {
1671 const pass = () => {
1672 for (const args of argsList) {
1673 try { fn(...args) } catch {}
1674 }
1675 }
1676 pass()
1677 let passes = 0
1678 const start = performance.now()
1679 do { pass(); passes++ } while (performance.now() - start < Number(minMs))
1680 return (performance.now() - start) * 1e6 / (passes * argsList.length)
1681}
1682const timeAsync = async (fn, argsList) => {
1683 const pass = async () => {
1684 for (const args of argsList) {
1685 try { await fn(...args) } catch {}
1686 }
1687 }
1688 await pass()
1689 let passes = 0
1690 const start = performance.now()
1691 do { await pass(); passes++ } while (performance.now() - start < Number(minMs))
1692 return (performance.now() - start) * 1e6 / (passes * argsList.length)
1693}
1694const rows = []
1695for (const [name, argsList] of byFn) {
1696 const original = (await import(pathToFileURL(modules[name]).href))[name]
1697 const rust = native[name]
1698 if (typeof original !== 'function' || typeof rust !== 'function') continue
1699 const timer = asyncFunctions.includes(name) ? timeAsync : time
1700 const originalNs = await timer(original, argsList)
1701 const rustNs = await timer(rust, argsList)
1702 rows.push({ fn: name, cases: argsList.length, original_ns: originalNs, rust_ns: rustNs, speedup: originalNs / rustNs })
1703}
1704// Classes: time whole scenarios (construct, then every call).
1705const play = (Class, list) => () => {
1706 for (const c of list) {
1707 try {
1708 const instance = new Class(...c.ctor.map(dec))
1709 for (const call of c.calls) {
1710 try { instance[call.method](...call.args.map(dec)) } catch {}
1711 }
1712 } catch {}
1713 }
1714}
1715for (const [name, list] of scenarios) {
1716 const original = (await import(pathToFileURL(classModules[name]).href))[name]
1717 const rust = native[name]
1718 if (typeof original !== 'function' || typeof rust !== 'function') continue
1719 const timeAll = (fn) => {
1720 fn()
1721 let passes = 0
1722 const start = performance.now()
1723 do { fn(); passes++ } while (performance.now() - start < Number(minMs))
1724 return (performance.now() - start) * 1e6 / (passes * list.length)
1725 }
1726 const originalNs = timeAll(play(original, list))
1727 const rustNs = timeAll(play(rust, list))
1728 rows.push({ fn: `class ${name}`, cases: list.length, original_ns: originalNs, rust_ns: rustNs, speedup: originalNs / rustNs })
1729}
1730writeFileSync(outPath, JSON.stringify(rows))
1731"#;
1732
1733const DIFF_JS: &str = r#"
1734import { readFileSync, writeFileSync } from 'node:fs'
1735import { pathToFileURL } from 'node:url'
1736
1737const [modulePath, casesPath, outPath, keyOrder] = process.argv.slice(2)
1738const loaded = await import(pathToFileURL(modulePath).href)
1739const mod = { ...(loaded.default && typeof loaded.default === 'object' ? loaded.default : {}), ...loaded }
1740const cases = readFileSync(casesPath, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l))
1741const summary = { total: cases.length, passed: 0, failed: 0, missing: [], mismatches: [] }
1742const scenario = async (Class, c) => {
1743 const results = []
1744 let instance
1745 try {
1746 instance = new Class(...c.ctor.map(dec))
1747 results.push({ ok: true })
1748 }
1749 catch (error) {
1750 results.push({ error: String(error?.message ?? error) })
1751 return results
1752 }
1753 for (const call of c.calls) {
1754 try {
1755 results.push({ ok: enc(await instance[call.method](...call.args.map(dec))) })
1756 }
1757 catch (error) {
1758 results.push({ error: String(error?.message ?? error) })
1759 }
1760 }
1761 return results
1762}
1763const stepsMatch = (want, got) => want.length === got.length && want.every((w, i) =>
1764 ('error' in w && 'error' in got[i] && !got[i].error.startsWith('Rust panic:')) || ('ok' in w && 'ok' in got[i] && same(w.ok, got[i].ok, keyOrder === 'sort')))
1765for (const c of cases) {
1766 if (c.class) {
1767 const Class = mod[c.class]
1768 if (typeof Class !== 'function') {
1769 if (!summary.missing.includes(c.class)) summary.missing.push(c.class)
1770 summary.failed++
1771 continue
1772 }
1773 const got = await scenario(Class, c)
1774 if (stepsMatch(c.results, got)) {
1775 summary.passed++
1776 }
1777 else {
1778 summary.failed++
1779 summary.mismatches.push({ fn: c.class, args: [c.ctor, c.calls], expected: c.results, actual: got })
1780 }
1781 continue
1782 }
1783 const fn = mod[c.fn]
1784 let actual
1785 if (typeof fn !== 'function') {
1786 if (!summary.missing.includes(c.fn)) summary.missing.push(c.fn)
1787 actual = { missing: true }
1788 }
1789 else {
1790 try {
1791 actual = { ok: enc(await fn(...c.args.map(dec))) }
1792 }
1793 catch (error) {
1794 actual = { error: String(error?.message ?? error) }
1795 }
1796 }
1797 const expected = 'error' in c ? { error: c.error } : { ok: c.ok }
1798 // Both sides throwing counts as agreement: error messages are not part of the contract.
1799 const panicked = 'error' in actual && actual.error.startsWith('Rust panic:')
1800 const pass = !panicked && ('error' in expected && 'error' in actual) || ('ok' in expected && 'ok' in actual && same(expected.ok, actual.ok, keyOrder === 'sort'))
1801 if (pass) {
1802 summary.passed++
1803 }
1804 else {
1805 summary.failed++
1806 summary.mismatches.push({ fn: c.fn, args: c.args, expected, actual })
1807 }
1808}
1809writeFileSync(outPath, JSON.stringify(summary, null, 2))
1810"#;
1811
1812#[cfg(test)]
1813mod tests {
1814 use super::*;
1815 use crate::ts::exports::{ExportedFn, Param};
1816
1817 fn f(params: &[(&str, &str)]) -> ExportedFn {
1818 ExportedFn {
1819 name: "f".into(),
1820 file: "a.ts".into(),
1821 line: 1,
1822 params: params
1823 .iter()
1824 .map(|(n, t)| Param {
1825 name: (*n).into(),
1826 ts_type: (*t).into(),
1827 optional: false,
1828 rest: false,
1829 ..Default::default()
1830 })
1831 .collect(),
1832 returns: "number".into(),
1833 is_async: false,
1834 is_generator: false,
1835 type_params: Vec::new(),
1836 uses_instanceof: false,
1837 ..Default::default()
1838 }
1839 }
1840
1841 #[test]
1842 fn reads_case_lines_deeper_than_128() {
1843 let deep = format!("{}1{}", "[".repeat(300), "]".repeat(300));
1844 assert!(serde_json::from_str::<Value>(&deep).is_err());
1845 assert!(parse_deep(&deep).is_ok());
1846 assert!(parse_deep("[1] x").is_err());
1847 }
1848
1849 #[test]
1850 fn generates_deterministic_distinct_inputs() {
1851 let a = generate(&f(&[("q", "string"), ("t", "string")]), 50, &[]);
1852 let b = generate(&f(&[("q", "string"), ("t", "string")]), 50, &[]);
1853 assert_eq!(a, b);
1854 assert_eq!(a.len(), 50);
1855 let unique: std::collections::HashSet<String> = a.iter().map(|v| v.to_string()).collect();
1856 assert_eq!(unique.len(), 50);
1857 assert!(
1858 a.iter()
1859 .any(|args| args.to_string().contains('😀') || args.to_string().contains('👍'))
1860 );
1861 }
1862
1863 #[test]
1864 fn generates_values_that_fit_object_types() {
1865 let types = crate::ts::exports::local_types(
1866 "m.ts",
1867 "export interface Edit { readonly range: { start: number, end: number }, readonly text: string }\n",
1868 );
1869 let cases = generate(&f(&[("edits", "readonly Edit[]")]), 60, &types);
1870 let fitting = cases
1871 .iter()
1872 .filter_map(|args| args[0].as_array())
1873 .flatten()
1874 .filter(|e| e["range"]["start"].is_number() || e["range"]["start"].is_object())
1875 .count();
1876 assert!(fitting > 20, "{fitting}");
1877 }
1878
1879 #[test]
1880 fn covers_number_edge_cases() {
1881 let cases = generate(&f(&[("n", "number")]), 18, &[]);
1882 let text = serde_json::to_string(&cases).unwrap();
1883 assert!(text.contains("NaN") && text.contains("-0"));
1884 }
1885}
1886
1887#[cfg(test)]
1888mod verdict_tests {
1889 use super::*;
1890
1891 fn row(name: &str, speedup: f64) -> BenchRow {
1892 BenchRow {
1893 name: name.into(),
1894 cases: 1,
1895 original_ns: speedup,
1896 rust_ns: 1.0,
1897 speedup,
1898 }
1899 }
1900
1901 #[test]
1902 fn advice_follows_the_numbers() {
1903 let ts = crate::lang::Lang::Ts;
1904 assert!(
1905 verdict(&[row("a", 3.0), row("b", 2.0)], ts)
1906 .advice
1907 .starts_with("Ship it: every")
1908 );
1909 assert!(
1910 verdict(&[row("a", 3.0), row("b", 1.0)], ts)
1911 .advice
1912 .starts_with("Ship it: no function")
1913 );
1914 let mixed = verdict(&[row("a", 4.0), row("b", 0.5)], ts);
1915 assert!(mixed.advice.contains("Keep the slower ones") && mixed.advice.ends_with("b."));
1916 assert!(
1917 verdict(&[row("a", 0.2), row("b", 0.3)], ts)
1918 .advice
1919 .starts_with("Do not ship")
1920 );
1921 assert!(
1922 verdict(&[row("a", 0.5)], crate::lang::Lang::C)
1923 .advice
1924 .starts_with("No call overhead")
1925 );
1926 }
1927}
1928
1929pub(crate) fn parse_deep(text: &str) -> serde_json::Result<Value> {
1932 let mut de = serde_json::Deserializer::from_str(text);
1933 de.disable_recursion_limit();
1934 let value = Value::deserialize(&mut de)?;
1935 de.end()?;
1936 Ok(value)
1937}