Skip to main content

rust_anything/
harness.rs

1//! Steps 3 and 5's runtime half: record what the original code does, build the Rust module, and
2//! replay the recorded cases against it.
3//!
4//! Both sides run in Node through small generated scripts, so the comparison sees exactly
5//! what a JS caller sees. Values are encoded so `undefined`, `NaN`, `-0`, `Map`, `Set`,
6//! `BigInt` and key order survive JSON.
7
8use 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";
22pub(crate) const WORK_DIR: &str = ".rust-anything";
23const COVERAGE_DIR: &str = "coverage";
24
25/// Strings that break naive ports: empty, case, whitespace, non-ASCII, astral, combining.
26const 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    /// Cases from the semantic traps (added to the generated ones for every function).
69    pub traps: usize,
70    pub per_function: BTreeMap<String, usize>,
71    /// Functions in files that use regexes: their string parameters also got the regex traps.
72    #[serde(skip_serializing_if = "Vec::is_empty")]
73    pub regex_functions: Vec<String>,
74    /// Inputs left out because the original ran past the per-case time limit on them.
75    #[serde(skip_serializing_if = "Vec::is_empty")]
76    pub timed_out: Vec<Value>,
77    /// Lines of the original the cases ran (TS/JS, from V8's coverage).
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub coverage: Option<Value>,
80    /// The clock and seed the original ran with (`--pin-clock`).
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub pinned: Option<crate::pin::Pin>,
83}
84
85#[derive(Debug, Default, Serialize, Deserialize)]
86pub struct DiffOutcome {
87    pub total: usize,
88    pub passed: usize,
89    pub failed: usize,
90    /// Exports the Rust module does not provide.
91    pub missing: Vec<String>,
92    /// The first mismatches: `{ fn, args, expected, actual }`.
93    pub mismatches: Vec<Value>,
94    /// Mismatches `known-diffs.jsonl` explains, counted in `passed`.
95    #[serde(default, skip_serializing_if = "is_zero")]
96    pub accepted: usize,
97    /// `known-diffs.jsonl` entries no mismatch matched any more.
98    #[serde(default, skip_serializing_if = "Vec::is_empty")]
99    pub stale_known: Vec<Value>,
100    /// Matches across the last changes to `port.rs`, and whether they stopped going up.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub trend: Option<crate::recording::Trend>,
103    /// The distinct differences among all the mismatches (not only the first ones), most cases
104    /// first.
105    #[serde(default, skip_serializing_if = "Vec::is_empty")]
106    pub groups: Vec<crate::mismatch::Group>,
107}
108
109fn is_zero(n: &usize) -> bool {
110    *n == 0
111}
112
113pub struct RecordOptions<'a> {
114    pub crate_dir: &'a Path,
115    /// Generated cases per function.
116    pub count: usize,
117    /// Extra cases, one `{"fn": name, "args": [...]}` JSON object per line, with `"kwargs": {...}`
118    /// for Python and Ruby arguments passed by keyword.
119    pub inputs: Option<&'a Path>,
120    /// Import the original from this JS module instead of the TS source files.
121    pub module: Option<&'a Path>,
122    /// Resolve npm packages the original imports from this folder's `node_modules`.
123    pub resolve_from: Option<&'a Path>,
124    pub node_args: &'a [String],
125}
126
127/// The dataclasses a Python file can take: its own and its package's, so a type imported from
128/// a sibling module (`from .models import Limits`) is found too.
129fn python_types(root: &Path, file: &str) -> Vec<LocalType> {
130    let dir = root.join(file).parent().map(Path::to_path_buf);
131    let mut files = vec![root.join(file)];
132    if let Some(dir) = dir
133        && let Ok(entries) = std::fs::read_dir(dir)
134    {
135        let mut siblings: Vec<PathBuf> = entries
136            .flatten()
137            .map(|e| e.path())
138            .filter(|p| p.extension().is_some_and(|e| e == "py") && !files.contains(p))
139            .collect();
140        siblings.sort();
141        files.extend(siblings);
142    }
143    files
144        .iter()
145        .filter_map(|p| std::fs::read_to_string(p).ok())
146        .flat_map(|text| crate::lang::python::dataclass_types(&text))
147        .collect()
148}
149
150/// Generates the cases a recording runs, shared by the host and on-device drivers.
151fn generate_cases(
152    opts: &RecordOptions,
153    manifest: &Manifest,
154) -> Result<(Vec<Value>, usize, Vec<String>)> {
155    generate_cases_salted(opts, manifest, 0)
156}
157
158/// [`generate_cases`] with the generator's seeds mixed with `salt`. A non-zero salt gives fresh
159/// inputs (`fuzz`): no traps and no `--inputs`, which the recording already has.
160pub(crate) fn generate_cases_salted(
161    opts: &RecordOptions,
162    manifest: &Manifest,
163    salt: u64,
164) -> Result<(Vec<Value>, usize, Vec<String>)> {
165    let mut cases: Vec<Value> = Vec::new();
166    let module_for = |file: &str| -> Result<String> {
167        let path = match opts.module {
168            Some(m) => m
169                .canonical()
170                .with_context(|| format!("resolving {}", m.display()))?,
171            None => manifest.root.join(file),
172        };
173        Ok(path.to_string_lossy().into_owned())
174    };
175    let mut scopes: BTreeMap<String, Vec<LocalType>> = BTreeMap::new();
176    let mut regex_files: BTreeMap<String, bool> = BTreeMap::new();
177    let mut regex_functions = Vec::new();
178    let mut traps = 0;
179    for f in &manifest.exports {
180        let module = module_for(&f.file)?;
181        if !scopes.contains_key(&f.file) {
182            let text = std::fs::read_to_string(manifest.root.join(&f.file)).unwrap_or_default();
183            regex_files.insert(
184                f.file.clone(),
185                crate::risks::uses_regex(manifest.language, &text),
186            );
187            let types = if manifest.language == crate::lang::Lang::Python {
188                python_types(&manifest.root, &f.file)
189            } else {
190                crate::bridge::types_in_scope(&manifest.root, &f.file, &text)
191            };
192            scopes.insert(f.file.clone(), types);
193        }
194        let regex = regex_files[&f.file];
195        if regex && f.params.iter().any(|p| param_type(p) == RType::Str) {
196            regex_functions.push(f.name.clone());
197        }
198        let types = &scopes[&f.file];
199        let mut all = generate_salted(f, opts.count, types, salt);
200        let mut seen: std::collections::HashSet<String> = all
201            .iter()
202            .map(|a| serde_json::to_string(a).unwrap_or_default())
203            .collect();
204        let base: Vec<Value> = all
205            .first()
206            .and_then(Value::as_array)
207            .cloned()
208            .unwrap_or_default();
209        for args in trap_args(&f.params, &base, regex)
210            .into_iter()
211            .filter(|_| salt == 0)
212        {
213            let args = Value::Array(args);
214            if seen.insert(serde_json::to_string(&args).unwrap_or_default()) {
215                all.push(args);
216                traps += 1;
217            }
218        }
219        for (i, mut args) in all.into_iter().enumerate() {
220            // Python callers pass ints where floats are expected, and int-ness can leak into
221            // results: every fourth case passes integral `number` arguments as ints.
222            if manifest.language == crate::lang::Lang::Python && i % 4 == 3 {
223                intify(&f.params, &mut args);
224            }
225            let mut case = json!({ "fn": f.name, "module": module, "args": args });
226            split_keyword_only(&f.params, &mut case);
227            cases.push(case);
228        }
229    }
230    for class in &manifest.classes {
231        let module = module_for(&class.file)?;
232        let text = std::fs::read_to_string(manifest.root.join(&class.file)).unwrap_or_default();
233        let types = crate::bridge::types_in_scope(&manifest.root, &class.file, &text);
234        for mut scenario in scenarios_salted(class, opts.count.max(20), &types, salt) {
235            scenario["module"] = Value::String(module.clone());
236            cases.push(scenario);
237        }
238    }
239    if let Some(path) = opts.inputs.filter(|_| salt == 0) {
240        let text =
241            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
242        for (i, line) in text
243            .lines()
244            .enumerate()
245            .filter(|(_, l)| !l.trim().is_empty())
246        {
247            let mut case: Value = parse_deep(line).with_context(|| {
248                format!(
249                    "{}:{} (values use the record codec: {{\"$undefined\": true}}, {{\"$num\": \"NaN\"}}, \
250                     and {{\"$utf16\": [code units]}} for strings with lone surrogates)",
251                    path.display(),
252                    i + 1
253                )
254            })?;
255            if let Some(class) = case["class"].as_str() {
256                let Some(c) = manifest.classes.iter().find(|c| c.name == class) else {
257                    bail!(
258                        "{}:{}: `{class}` is not a ported class of this unit",
259                        path.display(),
260                        i + 1
261                    );
262                };
263                case["module"] = Value::String(module_for(&c.file)?);
264                cases.push(case);
265                continue;
266            }
267            let Some(name) = case["fn"].as_str().filter(|s| !s.is_empty()) else {
268                bail!("{}:{}: \"fn\" is missing", path.display(), i + 1);
269            };
270            let Some(f) = manifest.exports.iter().find(|f| f.name == name) else {
271                let mut known: Vec<&str> =
272                    manifest.exports.iter().map(|f| f.name.as_str()).collect();
273                known.sort_unstable();
274                known.dedup();
275                bail!(
276                    "{}:{}: `{name}` is not an export of this unit (exports: {})",
277                    path.display(),
278                    i + 1,
279                    known.join(", ")
280                );
281            };
282            if !case["args"].is_array() {
283                bail!(
284                    "{}:{}: \"args\" must be an array of arguments",
285                    path.display(),
286                    i + 1
287                );
288            }
289            case["module"] = Value::String(module_for(&f.file)?);
290            cases.push(case);
291        }
292    }
293
294    Ok((cases, traps, regex_functions))
295}
296
297/// `--count 0` with no `--inputs` (or `--from-tests`) would record nothing and replace
298/// `cases.jsonl` with an empty file, so it is refused before anything is touched.
299fn check_count(opts: &RecordOptions) -> Result<()> {
300    if opts.count == 0 && opts.inputs.is_none() {
301        bail!(
302            "`--count 0` records nothing: pass --count 1 or more, or give cases with --inputs or \
303             --from-tests"
304        );
305    }
306    Ok(())
307}
308
309pub fn record(opts: &RecordOptions) -> Result<RecordOutcome> {
310    check_count(opts)?;
311    let crate_dir = std::path::absolute(opts.crate_dir)?;
312    let opts = &RecordOptions {
313        crate_dir: &crate_dir,
314        ..*opts
315    };
316    let manifest = Manifest::load(opts.crate_dir)?;
317    let (cases, traps, regex_functions) = generate_cases(opts, &manifest)?;
318
319    let timed_out_path = opts.crate_dir.join(WORK_DIR).join(TIMED_OUT);
320    let _ = std::fs::remove_file(&timed_out_path);
321    let coverage_dir = opts.crate_dir.join(WORK_DIR).join(COVERAGE_DIR);
322    let _ = std::fs::remove_dir_all(&coverage_dir);
323    let out = record_with(opts, &manifest, &cases)?;
324    let coverage = crate::recording::node_coverage(&coverage_dir, &manifest);
325    crate::recording::save_fingerprint(opts.crate_dir, &manifest, coverage.as_ref())?;
326    let mut outcome = summarize(opts, &out, traps, regex_functions, coverage)?;
327    outcome.pinned = crate::pin::load(opts.crate_dir)?.filter(|_| crate::pin::supported(&manifest));
328    Ok(outcome)
329}
330
331/// Runs `cases` through the original with the language's driver and writes `cases.jsonl`.
332pub(crate) fn record_with(
333    opts: &RecordOptions,
334    manifest: &Manifest,
335    cases: &[Value],
336) -> Result<PathBuf> {
337    Ok(if manifest.language == crate::lang::Lang::Python {
338        crate::harness_py::record(opts.crate_dir, cases)?
339    } else if manifest.kind == Kind::CAbi {
340        crate::harness_c::record(opts.crate_dir, manifest, cases)?
341    } else if manifest.language == crate::lang::Lang::Go {
342        crate::harness_go::record(opts.crate_dir, manifest, cases)?
343    } else if manifest.language == crate::lang::Lang::Ruby {
344        crate::harness_ruby::record(opts.crate_dir, manifest, cases)?
345    } else if manifest.language == crate::lang::Lang::Php {
346        crate::harness_php::record(opts.crate_dir, manifest, cases)?
347    } else if manifest.language == crate::lang::Lang::Csharp {
348        crate::harness_csharp::record(opts.crate_dir, manifest, cases)?
349    } else if manifest.language == crate::lang::Lang::Powershell {
350        crate::harness_powershell::record(opts.crate_dir, manifest, cases)?
351    } else if manifest.language == crate::lang::Lang::Java {
352        crate::harness_java::record(opts.crate_dir, manifest, cases)?
353    } else if manifest.language == crate::lang::Lang::Kotlin {
354        crate::harness_kotlin::record(opts.crate_dir, manifest, cases)?
355    } else {
356        record_node(opts, manifest, cases)?
357    })
358}
359
360/// Records on a connected Android device: the cases are generated here, the original Kotlin
361/// runs under ART, and the results come back as the same `cases.jsonl`.
362pub fn record_android(opts: &RecordOptions, device: Option<&str>) -> Result<RecordOutcome> {
363    check_count(opts)?;
364    let manifest = Manifest::load(opts.crate_dir)?;
365    let (cases, traps, regex_functions) = generate_cases(opts, &manifest)?;
366    let _ = std::fs::remove_file(opts.crate_dir.join(WORK_DIR).join(TIMED_OUT));
367    let out = crate::android_device::record(opts.crate_dir, &manifest, &cases, device)?;
368    crate::recording::save_fingerprint(opts.crate_dir, &manifest, None)?;
369    summarize(opts, &out, traps, regex_functions, None)
370}
371
372fn summarize(
373    opts: &RecordOptions,
374    out: &Path,
375    traps: usize,
376    regex_functions: Vec<String>,
377    coverage: Option<Value>,
378) -> Result<RecordOutcome> {
379    let text = std::fs::read_to_string(out)?;
380    let mut per_function = BTreeMap::new();
381    let mut errors = 0;
382    let mut count = 0;
383    for line in text.lines().filter(|l| !l.is_empty()) {
384        let case: Value = parse_deep(line)?;
385        count += 1;
386        let class_error = case["results"]
387            .as_array()
388            .is_some_and(|r| r.iter().any(|x| x.get("error").is_some()));
389        errors +=
390            usize::from(case.get("error").is_some() || case.get("panic").is_some() || class_error);
391        let name = case["fn"]
392            .as_str()
393            .or_else(|| case["class"].as_str())
394            .unwrap_or_default();
395        *per_function.entry(name.to_string()).or_default() += 1;
396    }
397    let timed_out_path = opts.crate_dir.join(WORK_DIR).join(TIMED_OUT);
398    let timed_out: Vec<Value> = std::fs::read_to_string(&timed_out_path)
399        .ok()
400        .and_then(|t| serde_json::from_str(&t).ok())
401        .unwrap_or_default();
402    Ok(RecordOutcome {
403        path: out.to_path_buf(),
404        cases: count,
405        errors,
406        traps,
407        per_function,
408        regex_functions,
409        timed_out: timed_out
410            .iter()
411            .map(|c| serde_json::json!({ "fn": c["fn"].clone(), "args": c["args"].clone() }))
412            .collect(),
413        coverage,
414        pinned: None,
415    })
416}
417
418/// Runs the recorded inputs through Node: the original TS/JS, with the resolve hook.
419fn record_node(opts: &RecordOptions, manifest: &Manifest, cases: &[Value]) -> Result<PathBuf> {
420    let work = opts.crate_dir.join(WORK_DIR);
421    std::fs::create_dir_all(&work)?;
422    let script = work.join("record.mjs");
423    std::fs::write(
424        &script,
425        format!("{CODEC_JS}\n{}\n{RECORD_JS}", crate::pin::PIN_JS),
426    )?;
427    let out = opts.crate_dir.join(CASES);
428    // TS sources often import the way bundlers resolve (`./errors`, `./types`): a resolve hook
429    // lets Node follow them, so the original runs as it is.
430    std::fs::write(work.join("resolve.mjs"), RESOLVE_JS)?;
431    std::fs::write(work.join("register.mjs"), REGISTER_JS)?;
432    let register = work.canonical()?.join("register.mjs");
433    let mut node_args: Vec<String> = strip_types_args().iter().map(|a| a.to_string()).collect();
434    node_args.push(format!("--import={}", file_url(&register)));
435    node_args.extend(opts.node_args.iter().cloned());
436    let aliases = alias_env(manifest);
437    let resolve_from = opts
438        .resolve_from
439        .map(|dir| {
440            dir.canonical()
441                .with_context(|| format!("resolving {}", dir.display()))
442        })
443        .transpose()?;
444    let record = |transform: bool| {
445        record_cases(cases, &work, &out, "node", |inputs, part| {
446            let mut cmd = Command::new("node");
447            if transform {
448                // Enums and parameter properties need Node to transform TS, not only strip types.
449                cmd.args(transform_flag())
450                    .arg("--no-warnings=ExperimentalWarning");
451            }
452            cmd.args(&node_args)
453                .arg(&script)
454                .arg(inputs)
455                .arg(part)
456                .env("NODE_V8_COVERAGE", work.join(COVERAGE_DIR))
457                .env("RUST_ANYTHING_PATHS", &aliases)
458                .env("RUST_ANYTHING_WORKSPACE", workspace_env(manifest));
459            if let Some(dir) = &resolve_from {
460                cmd.env("RUST_ANYTHING_RESOLVE_FROM", dir);
461            }
462            crate::pin::apply(&mut cmd, opts.crate_dir)?;
463            crate::enable::original_only(&mut cmd, &Manifest::load(opts.crate_dir)?);
464            Ok(cmd)
465        })
466    };
467    if let Err(error) = record(false) {
468        if !format!("{error:#}").contains("ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX") {
469            return Err(error);
470        }
471        record(true)?;
472    }
473    Ok(out)
474}
475
476/// The flags Node needs to load `.ts` sources: none from 22.18 and 23.6, which strip types by
477/// default, but `--experimental-strip-types` on 22.6 to 22.17 and 23.0 to 23.5.
478fn strip_types_args() -> &'static [&'static str] {
479    static NEEDED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
480    let needed = *NEEDED.get_or_init(|| {
481        let mut cmd = Command::new("node");
482        cmd.arg("--version");
483        crate::process::output(&mut cmd, crate::process::QUICK)
484            .ok()
485            .and_then(|out| crate::doctor::parse_version(&String::from_utf8_lossy(&out.stdout)))
486            .is_some_and(needs_strip_types_flag)
487    });
488    if needed {
489        &[
490            "--experimental-strip-types",
491            "--no-warnings=ExperimentalWarning",
492        ]
493    } else {
494        &[]
495    }
496}
497
498fn needs_strip_types_flag(node: crate::doctor::Version) -> bool {
499    let crate::doctor::Version(major, minor, _) = node;
500    (major == 22 && (6..18).contains(&minor)) || (major == 23 && minor < 6)
501}
502
503fn transform_flag() -> Option<&'static str> {
504    static SUPPORTED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
505    let supported = *SUPPORTED.get_or_init(|| {
506        let mut cmd = Command::new("node");
507        cmd.args(["--experimental-transform-types", "--no-warnings", "-e", "0"])
508            .stdout(std::process::Stdio::null())
509            .stderr(std::process::Stdio::null());
510        crate::process::status(&mut cmd, crate::process::QUICK).is_ok_and(|s| s.success())
511    });
512    supported.then_some("--experimental-transform-types")
513}
514
515/// Copies a freshly built library into place by renaming, so a process that has the old one
516/// loaded keeps a valid file.
517pub(crate) fn install(built: &Path, dest: &Path) -> Result<()> {
518    let tmp = dest.with_extension(format!("tmp-{}", std::process::id()));
519    std::fs::copy(built, &tmp).with_context(|| format!("copying {}", built.display()))?;
520    std::fs::rename(&tmp, dest).with_context(|| format!("installing {}", dest.display()))
521}
522
523/// The library `diff` loads, when it is older than the crate's sources: a forgotten `build`
524/// would otherwise test the previous port.
525fn stale_build(crate_dir: &Path, manifest: &Manifest) -> Option<PathBuf> {
526    let built = match manifest.kind {
527        Kind::Napi => crate_dir.join(format!("{}.node", manifest.lib_name())),
528        Kind::Pyo3 => crate::harness_py::native_file(crate_dir, manifest),
529        Kind::Ffi if manifest.language == crate::lang::Lang::Php => {
530            crate::harness_php::built_file(crate_dir, manifest)?
531        }
532        Kind::Ffi if manifest.language == crate::lang::Lang::Csharp => {
533            crate::harness_csharp::built_file(crate_dir, manifest)?
534        }
535        Kind::Ffi if manifest.language == crate::lang::Lang::Powershell => {
536            crate::harness_powershell::built_file(crate_dir, manifest)?
537        }
538        _ => return None,
539    };
540    sources_newer_than(crate_dir, &built).then_some(built)
541}
542
543/// True when `Cargo.toml` or any `.rs` file under `src/` is newer than `built`.
544pub(crate) fn sources_newer_than(crate_dir: &Path, built: &Path) -> bool {
545    let Ok(built_at) = std::fs::metadata(built).and_then(|m| m.modified()) else {
546        return false;
547    };
548    let mut sources = vec![crate_dir.join("Cargo.toml")];
549    sources.extend(
550        walkdir_rs(&crate_dir.join("src"))
551            .into_iter()
552            .filter(|p| p.extension().is_some_and(|e| e == "rs")),
553    );
554    sources
555        .iter()
556        .filter_map(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok())
557        .any(|changed| changed > built_at)
558}
559
560fn walkdir_rs(dir: &Path) -> Vec<PathBuf> {
561    let mut out = Vec::new();
562    let Ok(entries) = std::fs::read_dir(dir) else {
563        return out;
564    };
565    for entry in entries.flatten() {
566        let path = entry.path();
567        if path.is_dir() {
568            out.extend(walkdir_rs(&path));
569        } else {
570            out.push(path);
571        }
572    }
573    out
574}
575
576/// Builds a JNI crate for Android: one library per ABI, installed into `jniLibs/`.
577pub fn build_android(
578    crate_dir: &Path,
579    opts: &crate::android::Options,
580) -> Result<crate::android::Report> {
581    let manifest = Manifest::load(crate_dir)?;
582    crate::android::build(crate_dir, &manifest, opts)
583}
584
585pub fn build(crate_dir: &Path) -> Result<PathBuf> {
586    let manifest = Manifest::load(crate_dir)?;
587    match manifest.kind {
588        Kind::Pyo3 => crate::harness_py::build(crate_dir, &manifest),
589        Kind::Ffi if manifest.language == crate::lang::Lang::Ruby => {
590            crate::harness_ruby::build(crate_dir, &manifest)
591        }
592        Kind::Ffi if manifest.language == crate::lang::Lang::Php => {
593            crate::harness_php::build(crate_dir, &manifest)
594        }
595        Kind::Ffi if manifest.language == crate::lang::Lang::Csharp => {
596            crate::harness_csharp::build(crate_dir, &manifest)
597        }
598        Kind::Ffi if manifest.language == crate::lang::Lang::Powershell => {
599            crate::harness_powershell::build(crate_dir, &manifest)
600        }
601        Kind::CAbi | Kind::Ffi => crate::harness_c::build(crate_dir, &manifest),
602        Kind::Napi => {
603            let target = crate::cache::target_for(crate_dir)?;
604            run(
605                Command::new("cargo")
606                    .args(["build", "--release", "--manifest-path"])
607                    .arg(crate_dir.join("Cargo.toml"))
608                    .env("CARGO_TARGET_DIR", &target.dir),
609                "cargo build",
610            )?;
611            let lib = manifest.lib_name();
612            let release = target.dir.join("release");
613            let built = [
614                format!("lib{lib}.so"),
615                format!("lib{lib}.dylib"),
616                format!("{lib}.dll"),
617            ]
618            .iter()
619            .map(|name| release.join(name))
620            .find(|p| p.exists())
621            .with_context(|| format!("no native library for `{lib}` in {}", release.display()))?;
622            let artifact = crate_dir.join(format!("{lib}.node"));
623            install(&built, &artifact)?;
624            Ok(artifact)
625        }
626        Kind::Wasm => {
627            let target = crate::cache::target_for(crate_dir)?.dir;
628            run(
629                Command::new("cargo")
630                    .args([
631                        "build",
632                        "--release",
633                        "--target",
634                        "wasm32-unknown-unknown",
635                        "--manifest-path",
636                    ])
637                    .arg(crate_dir.join("Cargo.toml"))
638                    .env("CARGO_TARGET_DIR", &target),
639                "cargo build --target wasm32-unknown-unknown (needs `rustup target add wasm32-unknown-unknown`)",
640            )?;
641            // wasm-bindgen's CLI must match the crate's wasm-bindgen version exactly.
642            let lock = std::fs::read_to_string(crate_dir.join("Cargo.lock")).unwrap_or_default();
643            let wanted = locked_version(&lock, "wasm-bindgen")
644                .context("wasm-bindgen missing from Cargo.lock")?;
645            let installed = Command::new("wasm-bindgen")
646                .arg("--version")
647                .output()
648                .ok()
649                .map(|o| {
650                    String::from_utf8_lossy(&o.stdout)
651                        .trim()
652                        .rsplit(' ')
653                        .next()
654                        .unwrap_or_default()
655                        .to_string()
656                });
657            if installed.as_deref() != Some(wanted.as_str()) {
658                bail!(
659                    "the crate uses wasm-bindgen {wanted}; the CLI must match:\n  cargo install wasm-bindgen-cli --version {wanted} --locked{}",
660                    installed
661                        .map(|v| format!(" (found {v})"))
662                        .unwrap_or_default()
663                );
664            }
665            let lib = manifest.lib_name();
666            let wasm = target
667                .join("wasm32-unknown-unknown/release")
668                .join(format!("{lib}.wasm"));
669            run(
670                Command::new("wasm-bindgen")
671                    .args(["--target", "nodejs", "--out-dir"])
672                    .arg(crate_dir.join("pkg"))
673                    .arg(&wasm),
674                "wasm-bindgen",
675            )?;
676            std::fs::write(
677                crate_dir.join("pkg").join("package.json"),
678                "{\n  \"type\": \"commonjs\"\n}\n",
679            )?;
680            Ok(crate_dir.join("pkg").join(format!("{lib}.js")))
681        }
682    }
683}
684
685/// Per-function timing of the original against the Rust module.
686/// What `bench` concludes: the geometric-mean speedup and what to do.
687#[derive(Debug, Serialize)]
688pub struct Verdict {
689    pub speedup: f64,
690    pub faster: Vec<String>,
691    pub slower: Vec<String>,
692    pub advice: String,
693    /// Functions whose recorded cases do not all match: timed, but not counted (#341).
694    #[serde(skip_serializing_if = "Vec::is_empty")]
695    pub left_out: Vec<String>,
696}
697
698/// Faster means at least 1.1x, slower below 0.9x; between is a tie (timing noise). Functions
699/// whose cases do not all match are left out: their time is the cost of failing (a panic caught
700/// at the bridge), not of the work.
701pub fn verdict(rows: &[BenchRow], lang: crate::lang::Lang) -> Verdict {
702    let left_out: Vec<String> = rows
703        .iter()
704        .filter(|r| r.failing)
705        .map(|r| r.name.clone())
706        .collect();
707    let rows: Vec<&BenchRow> = rows.iter().filter(|r| !r.failing).collect();
708    let faster: Vec<String> = rows
709        .iter()
710        .filter(|r| r.speedup >= 1.1)
711        .map(|r| r.name.clone())
712        .collect();
713    let slower: Vec<String> = rows
714        .iter()
715        .filter(|r| r.speedup < 0.9)
716        .map(|r| r.name.clone())
717        .collect();
718    let speedup = if rows.is_empty() {
719        1.0
720    } else {
721        (rows.iter().map(|r| r.speedup.max(1e-9).ln()).sum::<f64>() / rows.len() as f64).exp()
722    };
723    let advice = if rows.is_empty() && !left_out.is_empty() {
724        "Nothing to compare: no function matches all its recorded cases yet. Run `diff`."
725            .to_string()
726    } else if rows.is_empty() {
727        "Nothing to compare: record cases that do not throw first.".to_string()
728    } else if slower.is_empty() && faster.len() == rows.len() {
729        "Ship it: every function is faster in Rust, call included.".to_string()
730    } else if slower.is_empty() {
731        "Ship it: no function is slower in Rust; some only tie.".to_string()
732    } else if lang == crate::lang::Lang::C {
733        // C links the port directly: there is no crossing to blame.
734        format!(
735            "No call overhead in C: these are slower as Rust code. Profile and optimize them, or keep them in C: {}.",
736            slower.join(", ")
737        )
738    } else if speedup >= 1.1 {
739        format!(
740            "Ship the faster functions. Keep the slower ones in the original (`bridge --keep`) or move their callers to Rust too: {}.",
741            slower.join(", ")
742        )
743    } else {
744        "Do not ship this unit for speed: calling across costs more than the work these functions do. \
745         Port a bigger unit (these functions together with their callers), so one call does more work."
746            .to_string()
747    };
748    Verdict {
749        speedup,
750        faster,
751        slower,
752        advice,
753        left_out,
754    }
755}
756
757/// "Nx faster" at or above parity, "Nx slower" below it.
758pub fn speed_phrase(speedup: f64) -> String {
759    if speedup >= 1.0 {
760        // Same rule on the faster side: `1.04x` is not `1.0x`, which reads as no change at all.
761        if speedup < 1.05 {
762            format!("{speedup:.2}x faster")
763        } else {
764            format!("{speedup:.1}x faster")
765        }
766    } else {
767        let slower = 1.0 / speedup.max(1e-9);
768        // A port a few percent behind reads as "1.0x slower" at one decimal, which says it is not
769        // slower at all: below 1.05 the difference gets a second decimal, as `bench` prints it.
770        if slower < 1.05 {
771            format!("{slower:.2}x slower")
772        } else {
773            format!("{slower:.1}x slower")
774        }
775    }
776}
777
778/// Rows from two `{ name: { cases, ns } }` timing maps: the original's and the port's.
779pub fn bench_rows(
780    m: &Manifest,
781    original: &serde_json::Map<String, Value>,
782    rust: &serde_json::Map<String, Value>,
783) -> Vec<BenchRow> {
784    m.exports
785        .iter()
786        .filter_map(|f| {
787            let (old, new) = (original.get(&f.name)?, rust.get(&f.name)?);
788            let (o, n) = (old["ns"].as_f64()?, new["ns"].as_f64()?);
789            Some(BenchRow {
790                name: f.name.clone(),
791                cases: usize::try_from(old["cases"].as_u64().unwrap_or(0)).unwrap_or(0),
792                original_ns: o,
793                rust_ns: n,
794                speedup: o / n,
795                failing: false,
796            })
797        })
798        .collect()
799}
800
801#[derive(Debug, Serialize, Deserialize)]
802pub struct BenchRow {
803    #[serde(rename = "fn")]
804    pub name: String,
805    pub cases: usize,
806    /// Nanoseconds per call.
807    pub original_ns: f64,
808    pub rust_ns: f64,
809    /// `original_ns / rust_ns`: above 1 means Rust is faster, bridge included.
810    pub speedup: f64,
811    /// Some recorded cases of this function do not match (or the port lacks it), so its time is
812    /// not the port's and `verdict` leaves it out (#341).
813    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
814    pub failing: bool,
815}
816
817pub struct BenchOptions<'a> {
818    pub crate_dir: &'a Path,
819    /// Minimum measured time per function and side, in milliseconds.
820    pub min_ms: u64,
821    pub resolve_from: Option<&'a Path>,
822    pub node_args: &'a [String],
823}
824
825/// Times the recorded cases against the original and the built Rust module, bridge included,
826/// and marks the functions whose recorded cases do not all match.
827pub fn bench(opts: &BenchOptions) -> Result<Vec<BenchRow>> {
828    if opts.min_ms == 0 {
829        bail!("`--min-ms` must be at least 1");
830    }
831    let resolve_from = opts
832        .resolve_from
833        .map(|dir| {
834            dir.canonical()
835                .with_context(|| format!("resolving {}", dir.display()))
836        })
837        .transpose()?;
838    let opts = &BenchOptions {
839        resolve_from: resolve_from.as_deref(),
840        ..*opts
841    };
842    let mut rows = time_functions(opts)?;
843    let crate_dir = std::path::absolute(opts.crate_dir)?;
844    let diff = DiffOptions {
845        crate_dir: &crate_dir,
846        module: None,
847        ignore_key_order: false,
848        node_args: opts.node_args,
849        float_tolerance: None,
850    };
851    let cases_path = crate_dir.join(CASES);
852    let cases = std::fs::read_to_string(&cases_path)
853        .with_context(|| format!("reading {}", cases_path.display()))?;
854    // `diff_exact` and `settle`, not `diff_full`: a bench is not a change to the port, so it adds
855    // nothing to the match trend.
856    let outcome = settle(&diff, diff_exact(&diff)?)?;
857    let counts = counts_from_cases_text(&cases, &outcome)?;
858    for row in &mut rows {
859        row.failing = failing(&row.name, &outcome, &counts);
860    }
861    Ok(rows)
862}
863
864fn failing(row: &str, outcome: &DiffOutcome, counts: &BTreeMap<String, (usize, usize)>) -> bool {
865    let name = row.strip_prefix("class ").unwrap_or(row);
866    outcome.missing.iter().any(|m| m == name)
867        || counts
868            .get(name)
869            .is_some_and(|&(passed, total)| passed < total)
870}
871
872fn time_functions(opts: &BenchOptions) -> Result<Vec<BenchRow>> {
873    let crate_dir = std::path::absolute(opts.crate_dir)?;
874    let opts = &BenchOptions {
875        crate_dir: &crate_dir,
876        ..*opts
877    };
878    let manifest = Manifest::load(opts.crate_dir)?;
879    if manifest.language == crate::lang::Lang::Python {
880        return crate::harness_py::bench(opts.crate_dir, &manifest, opts.min_ms);
881    }
882    if manifest.kind == Kind::CAbi {
883        return crate::harness_c::bench(opts.crate_dir, &manifest, opts.min_ms);
884    }
885    if manifest.language == crate::lang::Lang::Go {
886        return crate::harness_go::bench(opts.crate_dir, &manifest, opts.min_ms);
887    }
888    if manifest.language == crate::lang::Lang::Ruby {
889        return crate::harness_ruby::bench(opts.crate_dir, &manifest, opts.min_ms);
890    }
891    if manifest.language == crate::lang::Lang::Php {
892        return crate::harness_php::bench(opts.crate_dir, &manifest, opts.min_ms);
893    }
894    if manifest.language == crate::lang::Lang::Csharp {
895        return crate::harness_csharp::bench(opts.crate_dir, &manifest, opts.min_ms);
896    }
897    if manifest.language == crate::lang::Lang::Powershell {
898        return crate::harness_powershell::bench(opts.crate_dir, &manifest, opts.min_ms);
899    }
900    if manifest.language == crate::lang::Lang::Java {
901        return crate::harness_java::bench(opts.crate_dir, &manifest, opts.min_ms);
902    }
903    if manifest.language == crate::lang::Lang::Kotlin {
904        return crate::harness_kotlin::bench(opts.crate_dir, &manifest, opts.min_ms);
905    }
906    let cases = opts.crate_dir.join(CASES);
907    if !cases.exists() {
908        bail!(
909            "no {CASES} in {} (run `rust-anything record` first)",
910            opts.crate_dir.display()
911        );
912    }
913    let modules: BTreeMap<String, String> = manifest
914        .exports
915        .iter()
916        .map(|f| {
917            (
918                f.name.clone(),
919                manifest.root.join(&f.file).to_string_lossy().into_owned(),
920            )
921        })
922        .collect();
923    let work = opts.crate_dir.join(WORK_DIR);
924    std::fs::create_dir_all(&work)?;
925    std::fs::write(work.join("resolve.mjs"), RESOLVE_JS)?;
926    std::fs::write(work.join("register.mjs"), REGISTER_JS)?;
927    let class_modules: BTreeMap<String, String> = manifest
928        .classes
929        .iter()
930        .map(|c| {
931            (
932                c.name.clone(),
933                manifest.root.join(&c.file).to_string_lossy().into_owned(),
934            )
935        })
936        .collect();
937    let async_functions: Vec<&str> = manifest
938        .exports
939        .iter()
940        .filter(|f| f.is_async)
941        .map(|f| f.name.as_str())
942        .collect();
943    let modules_path = work.join("bench-modules.json");
944    std::fs::write(
945        &modules_path,
946        serde_json::to_string(&json!({
947            "functions": modules,
948            "classes": class_modules,
949            "asyncFunctions": async_functions,
950        }))?,
951    )?;
952    let script = work.join("bench.mjs");
953    std::fs::write(&script, format!("{CODEC_JS}\n{BENCH_JS}"))?;
954    let out = work.join("bench.json");
955    let native = opts.crate_dir.join("index.cjs").canonical()?;
956    let register = work.canonical()?.join("register.mjs");
957    let mut cmd = Command::new("node");
958    crate::enable::original_only(&mut cmd, &manifest);
959    cmd.args(strip_types_args())
960        .args(transform_flag())
961        .arg("--no-warnings")
962        .arg(format!("--import={}", file_url(&register)))
963        .args(opts.node_args)
964        .arg(&script)
965        .arg(&modules_path)
966        .arg(&native)
967        .arg(&cases)
968        .arg(&out)
969        .arg(opts.min_ms.to_string())
970        .env("RUST_ANYTHING_PATHS", alias_env(&manifest))
971        .env("RUST_ANYTHING_WORKSPACE", workspace_env(&manifest));
972    if let Some(dir) = opts.resolve_from {
973        cmd.env("RUST_ANYTHING_RESOLVE_FROM", dir);
974    }
975    run(&mut cmd, "node")?;
976    Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
977}
978
979pub struct DiffOptions<'a> {
980    pub crate_dir: &'a Path,
981    /// The module to test; defaults to the crate's `index.cjs`.
982    pub module: Option<&'a Path>,
983    /// Compare objects regardless of key order.
984    pub ignore_key_order: bool,
985    pub node_args: &'a [String],
986    /// Floats match within this tolerance; the one saved by `record` when `None`.
987    pub float_tolerance: Option<f64>,
988}
989
990/// Whether objects compare regardless of key order: the flag for this run, or the choice
991/// `record --ignore-key-order` saved with the crate, which `gate`, `enable`, `report` and `go` read
992/// because they have no flag of their own.
993fn ignores_key_order(opts: &DiffOptions) -> bool {
994    opts.ignore_key_order || Manifest::load(opts.crate_dir).is_ok_and(|m| m.ignore_key_order)
995}
996
997/// The first mismatches a diff reports.
998const SHOWN_MISMATCHES: usize = 20;
999
1000pub fn diff(opts: &DiffOptions) -> Result<DiffOutcome> {
1001    let mut outcome = diff_full(opts)?;
1002    outcome.mismatches.truncate(SHOWN_MISMATCHES);
1003    Ok(outcome)
1004}
1005
1006/// Like `diff`, without truncating `mismatches`, so callers can inspect per-function results.
1007pub fn diff_full(opts: &DiffOptions) -> Result<DiffOutcome> {
1008    let mut outcome = located(settle(opts, diff_exact(opts)?)?);
1009    anyhow::ensure!(
1010        outcome.total > 0,
1011        "no recorded cases to compare; run `rust-anything record` first"
1012    );
1013    if opts.module.is_none() {
1014        outcome.trend = crate::recording::track(opts.crate_dir, outcome.passed, outcome.total);
1015    }
1016    Ok(outcome)
1017}
1018
1019/// `(passed, total)` recorded cases per function name.
1020pub type FunctionCounts = BTreeMap<String, (usize, usize)>;
1021
1022/// `(passed, total)` recorded cases for each function in `cases.jsonl`, using the full
1023/// (untruncated) mismatches in `outcome`.
1024pub fn per_function_counts(crate_dir: &Path, outcome: &DiffOutcome) -> Result<FunctionCounts> {
1025    let cases_path = crate_dir.join(CASES);
1026    let text = std::fs::read_to_string(&cases_path)
1027        .with_context(|| format!("reading {}", cases_path.display()))?;
1028    counts_from_cases_text(&text, outcome)
1029}
1030
1031/// Runs `diff_full` and computes [`per_function_counts`] from the exact `cases.jsonl` snapshot
1032/// that `diff_full` verified, failing if `cases.jsonl` was modified concurrently.
1033pub fn diff_full_with_counts(opts: &DiffOptions) -> Result<(DiffOutcome, FunctionCounts)> {
1034    let cases_path = opts.crate_dir.join(CASES);
1035    if !cases_path.exists() {
1036        bail!(
1037            "no {CASES} in {} (run `rust-anything record` first)",
1038            opts.crate_dir.display()
1039        );
1040    }
1041    let snapshot = std::fs::read_to_string(&cases_path)
1042        .with_context(|| format!("reading {}", cases_path.display()))?;
1043    let outcome = diff_full(opts)?;
1044    let current = std::fs::read_to_string(&cases_path)
1045        .with_context(|| format!("reading {}", cases_path.display()))?;
1046    anyhow::ensure!(
1047        current == snapshot,
1048        "{CASES} changed while diff was running; rerun `enable`"
1049    );
1050    let counts = counts_from_cases_text(&snapshot, &outcome)?;
1051    Ok((outcome, counts))
1052}
1053
1054fn counts_from_cases_text(
1055    text: &str,
1056    outcome: &DiffOutcome,
1057) -> Result<BTreeMap<String, (usize, usize)>> {
1058    let mut totals: BTreeMap<String, usize> = BTreeMap::new();
1059    for line in text.lines().filter(|l| !l.is_empty()) {
1060        let case: Value = parse_deep(line)?;
1061        if let Some(name) = case["fn"].as_str().or_else(|| case["class"].as_str()) {
1062            *totals.entry(name.to_string()).or_default() += 1;
1063        }
1064    }
1065    let mut failed: BTreeMap<String, usize> = BTreeMap::new();
1066    for m in &outcome.mismatches {
1067        if let Some(name) = m["fn"].as_str().or_else(|| m["class"].as_str()) {
1068            *failed.entry(name.to_string()).or_default() += 1;
1069        }
1070    }
1071    Ok(totals
1072        .into_iter()
1073        .map(|(name, total)| {
1074            let passed = if outcome.missing.contains(&name) {
1075                0
1076            } else {
1077                total.saturating_sub(failed.get(&name).copied().unwrap_or(0))
1078            };
1079            (name, (passed, total))
1080        })
1081        .collect())
1082}
1083
1084/// Diffs on a connected Android device, using the port built for the device's ABI.
1085pub fn diff_android(
1086    opts: &DiffOptions,
1087    device: Option<&str>,
1088    jni_libs: Option<&Path>,
1089) -> Result<DiffOutcome> {
1090    let manifest = Manifest::load(opts.crate_dir)?;
1091    diff_after(
1092        opts,
1093        crate::android_device::diff(opts.crate_dir, &manifest, device, jni_libs)?,
1094    )
1095}
1096
1097fn diff_after(opts: &DiffOptions, exact: DiffOutcome) -> Result<DiffOutcome> {
1098    let mut outcome = located(settle(opts, exact)?);
1099    outcome.mismatches.truncate(SHOWN_MISMATCHES);
1100    anyhow::ensure!(
1101        outcome.total > 0,
1102        "no recorded cases to compare; run `rust-anything record` first"
1103    );
1104    if opts.module.is_none() {
1105        outcome.trend = crate::recording::track(opts.crate_dir, outcome.passed, outcome.total);
1106    }
1107    Ok(outcome)
1108}
1109
1110/// Each mismatch with where it starts, and the distinct differences among them.
1111fn located(mut outcome: DiffOutcome) -> DiffOutcome {
1112    crate::mismatch::annotate(&mut outcome);
1113    outcome.groups = crate::mismatch::group_mismatches(&outcome.mismatches);
1114    outcome
1115}
1116
1117/// Applies the float tolerance and `known-diffs.jsonl` to a driver's outcome, keeping every
1118/// mismatch.
1119pub(crate) fn settle(opts: &DiffOptions, exact: DiffOutcome) -> Result<DiffOutcome> {
1120    let mut outcome = exact;
1121    let manifest = Manifest::load(opts.crate_dir).ok();
1122    let saved = manifest.as_ref().and_then(|m| m.float_tolerance);
1123    if let Some(t) = opts.float_tolerance.or(saved) {
1124        let preserve_key_order = opts.module.is_some()
1125            || manifest.as_ref().is_none_or(|m| {
1126                matches!(
1127                    m.language,
1128                    crate::lang::Lang::Ts | crate::lang::Lang::Python
1129                )
1130            });
1131        outcome = crate::tolerance::apply(
1132            outcome,
1133            crate::tolerance::check(t)?,
1134            ignores_key_order(opts) || !preserve_key_order,
1135        );
1136    }
1137    Ok(crate::recording::apply_known(
1138        outcome,
1139        &crate::recording::known_diffs(opts.crate_dir)?,
1140    ))
1141}
1142
1143pub(crate) fn diff_exact(opts: &DiffOptions) -> Result<DiffOutcome> {
1144    let crate_dir = std::path::absolute(opts.crate_dir)?;
1145    let opts = &DiffOptions {
1146        crate_dir: &crate_dir,
1147        ..*opts
1148    };
1149    if opts.module.is_none()
1150        && let Ok(manifest) = Manifest::load(opts.crate_dir)
1151        && let Some(built) = stale_build(opts.crate_dir, &manifest)
1152    {
1153        bail!(
1154            "{} is older than the crate's sources, so diff would test the previous port; run \
1155             `rust-anything build {}` first",
1156            built.display(),
1157            opts.crate_dir.display()
1158        );
1159    }
1160    if let Ok(manifest) = Manifest::load(opts.crate_dir)
1161        && manifest.language == crate::lang::Lang::Python
1162        && opts.module.is_none()
1163    {
1164        return crate::harness_py::diff(opts.crate_dir, &manifest, ignores_key_order(opts));
1165    }
1166    if let Ok(manifest) = Manifest::load(opts.crate_dir)
1167        && manifest.kind == Kind::CAbi
1168        && opts.module.is_none()
1169    {
1170        return crate::harness_c::diff(opts.crate_dir, &manifest);
1171    }
1172    if let Ok(manifest) = Manifest::load(opts.crate_dir)
1173        && manifest.language == crate::lang::Lang::Go
1174        && opts.module.is_none()
1175    {
1176        return crate::harness_go::diff(opts.crate_dir, &manifest);
1177    }
1178    if let Ok(manifest) = Manifest::load(opts.crate_dir)
1179        && manifest.language == crate::lang::Lang::Csharp
1180        && opts.module.is_none()
1181    {
1182        return crate::harness_csharp::diff(opts.crate_dir, &manifest);
1183    }
1184    if let Ok(manifest) = Manifest::load(opts.crate_dir)
1185        && manifest.language == crate::lang::Lang::Ruby
1186        && opts.module.is_none()
1187    {
1188        return crate::harness_ruby::diff(opts.crate_dir, &manifest);
1189    }
1190    if let Ok(manifest) = Manifest::load(opts.crate_dir)
1191        && manifest.language == crate::lang::Lang::Php
1192        && opts.module.is_none()
1193    {
1194        return crate::harness_php::diff(opts.crate_dir, &manifest);
1195    }
1196    if let Ok(manifest) = Manifest::load(opts.crate_dir)
1197        && manifest.language == crate::lang::Lang::Powershell
1198        && opts.module.is_none()
1199    {
1200        return crate::harness_powershell::diff(opts.crate_dir, &manifest);
1201    }
1202    if let Ok(manifest) = Manifest::load(opts.crate_dir)
1203        && manifest.language == crate::lang::Lang::Java
1204        && opts.module.is_none()
1205    {
1206        return crate::harness_java::diff(opts.crate_dir, &manifest);
1207    }
1208    if let Ok(manifest) = Manifest::load(opts.crate_dir)
1209        && manifest.language == crate::lang::Lang::Kotlin
1210        && opts.module.is_none()
1211    {
1212        return crate::harness_kotlin::diff(opts.crate_dir, &manifest);
1213    }
1214    let cases = opts.crate_dir.join(CASES);
1215    if !cases.exists() {
1216        bail!(
1217            "no {CASES} in {} (run `rust-anything record` first)",
1218            opts.crate_dir.display()
1219        );
1220    }
1221    let module = match opts.module {
1222        Some(m) => m.to_path_buf(),
1223        None => opts.crate_dir.join("index.cjs"),
1224    };
1225    let module = module
1226        .canonical()
1227        .with_context(|| format!("resolving {}", module.display()))?;
1228    let work = opts.crate_dir.join(WORK_DIR);
1229    std::fs::create_dir_all(&work)?;
1230    let script = work.join("diff.mjs");
1231    std::fs::write(
1232        &script,
1233        format!("{CODEC_JS}\n{}\n{DIFF_JS}", crate::pin::PIN_JS),
1234    )?;
1235    let out = work.join("diff.json");
1236    let flag = if ignores_key_order(opts) {
1237        "sort"
1238    } else {
1239        "keep"
1240    };
1241    let mut cmd = Command::new("node");
1242    cmd.args(strip_types_args())
1243        .args(opts.node_args)
1244        .arg(&script)
1245        .args([&module, &cases, &out])
1246        .arg(flag);
1247    crate::pin::apply(&mut cmd, opts.crate_dir)?;
1248    crate::enable::original_only(&mut cmd, &Manifest::load(opts.crate_dir)?);
1249    run(&mut cmd, "node")?;
1250    let text = std::fs::read_to_string(&out)?;
1251    Ok(serde_json::from_str(&text)?)
1252}
1253
1254/// The version of `package` in a Cargo.lock.
1255fn locked_version(lock: &str, package: &str) -> Option<String> {
1256    let mut lines = lock.lines();
1257    while let Some(line) = lines.next() {
1258        if line.trim() == format!("name = \"{package}\"") {
1259            let version = lines
1260                .next()?
1261                .trim()
1262                .strip_prefix("version = \"")?
1263                .strip_suffix('"')?;
1264            return Some(version.to_string());
1265        }
1266    }
1267    None
1268}
1269
1270/// Deterministic inputs for one function: edge cases first, then seeded random mixes.
1271pub fn generate(
1272    f: &crate::ts::exports::ExportedFn,
1273    count: usize,
1274    types: &[LocalType],
1275) -> Vec<Value> {
1276    generate_salted(f, count, types, 0)
1277}
1278
1279/// [`generate`] from another seed: `salt` 0 gives the recorded inputs, any other value fresh ones.
1280pub fn generate_salted(
1281    f: &crate::ts::exports::ExportedFn,
1282    count: usize,
1283    types: &[LocalType],
1284    salt: u64,
1285) -> Vec<Value> {
1286    let mut rng = Rng::new(
1287        f.name.bytes().fold(0x9E37_79B9_7F4A_7C15, |h, b| {
1288            (h ^ u64::from(b)).wrapping_mul(0x100_0000_01B3)
1289        }) ^ salt,
1290    );
1291    let mut seen = std::collections::HashSet::new();
1292    let mut out = Vec::new();
1293    let mut attempts = 0;
1294    while out.len() < count && attempts < count * 20 {
1295        attempts += 1;
1296        let args = args_for(&f.params, types, &mut rng);
1297        let key = serde_json::to_string(&args).unwrap_or_default();
1298        if seen.insert(key) {
1299            out.push(Value::Array(args));
1300        }
1301    }
1302    out
1303}
1304
1305/// The semantic traps for a value of type `t`: what most often behaves differently once ported
1306/// (string length and case, signed division and overflow, float printing, map and sort order).
1307fn trap_values(t: &RType) -> Vec<Value> {
1308    match t {
1309        RType::Str => crate::app::STRING_TRAPS
1310            .iter()
1311            .chain(
1312                [
1313                    "ΣΊΣΥΦΟΣ",
1314                    "a😀b",
1315                    "\u{FEFF}bom",
1316                    "a²b x½ y①",
1317                    "aⅠb Ⅻ",
1318                    "a𐐀b 𝐀bc",
1319                    "कि ٣٤",
1320                ]
1321                .iter(),
1322            )
1323            .map(|s| json!(s))
1324            .collect(),
1325        RType::Int => [
1326            -7,
1327            -1,
1328            0,
1329            2_147_483_648,
1330            -2_147_483_649,
1331            9_007_199_254_740_993,
1332            i64::MAX,
1333            i64::MIN,
1334        ]
1335        .iter()
1336        .map(|n| json!(n))
1337        .collect(),
1338        RType::F64 => {
1339            let mut out: Vec<Value> = [
1340                -7.5,
1341                0.1,
1342                0.30000000000000004,
1343                1e21,
1344                1e-7,
1345                5e-324,
1346                1.797_693_134_862_315_7e308,
1347                9_007_199_254_740_992.0,
1348            ]
1349            .iter()
1350            .map(|n| json!(n))
1351            .collect();
1352            out.push(json!({ "$num": "-0" }));
1353            out
1354        }
1355        RType::Vec(inner) => match inner.as_ref() {
1356            RType::Str => vec![json!([]), json!(["b", "a", "B", "é", "10", "9", "a"])],
1357            RType::Int => vec![json!([]), json!([-7, 3, 0, i64::MAX, -1])],
1358            RType::F64 => vec![json!([]), json!([0.1, 0.2, -0.5, 1e21])],
1359            _ => vec![json!([])],
1360        },
1361        RType::Opt(inner) => {
1362            let mut out = vec![json!({ "$undefined": true })];
1363            out.extend(trap_values(inner));
1364            out
1365        }
1366        RType::Json => crate::app::JSON_TRAPS
1367            .iter()
1368            .filter_map(|t| serde_json::from_str(t).ok())
1369            .chain([json!([3, 1, 2]), json!({})])
1370            .collect(),
1371        RType::Bytes => vec![
1372            json!({ "$bytes": [] }),
1373            json!({ "$bytes": [0] }),
1374            json!({ "$bytes": [0, 1, 255] }),
1375            json!({ "$bytes": [104, 101, 108, 108, 111] }),
1376        ],
1377        RType::Bool | RType::Unit => Vec::new(),
1378    }
1379}
1380
1381/// Every trap value in every parameter, one at a time, the other arguments as in `base`.
1382/// Structured parameters (objects with a known shape) are left as generated.
1383pub fn trap_args(
1384    params: &[crate::ts::exports::Param],
1385    base: &[Value],
1386    regex: bool,
1387) -> Vec<Vec<Value>> {
1388    let mut out = Vec::new();
1389    let params: Vec<&crate::ts::exports::Param> = params
1390        .iter()
1391        .filter(|p| !p.ts_type.starts_with("len:"))
1392        .collect();
1393    if base.len() < params.iter().filter(|p| !p.rest).count() {
1394        return out;
1395    }
1396    for (i, p) in params.iter().enumerate() {
1397        if p.rest || i >= base.len() {
1398            continue;
1399        }
1400        if let Some(values) = c_pointer_traps(&p.ts_type) {
1401            for v in values {
1402                if base[i] != v {
1403                    let mut args = base.to_vec();
1404                    args[i] = v;
1405                    out.push(args);
1406                }
1407            }
1408            continue;
1409        }
1410        let t = param_type(p);
1411        let structured = t.contains_json() && !matches!(t, RType::Json);
1412        let any = matches!(p.ts_type.trim(), "any" | "unknown" | "object" | "Object");
1413        if structured || (matches!(t, RType::Json) && !any) {
1414            continue;
1415        }
1416        let mut values = trap_values(&t);
1417        if regex && t == RType::Str {
1418            values.extend(crate::risks::REGEX_TRAPS.iter().map(|s| json!(s)));
1419        }
1420        for v in values {
1421            if base[i] != v {
1422                let mut args = base.to_vec();
1423                args[i] = v;
1424                out.push(args);
1425            }
1426        }
1427    }
1428    out
1429}
1430
1431/// Edge cases for C pointer parameters: buffers as hex text (`bytes`, `buffer`) or a size of
1432/// zeroed bytes (`buffer`), the starting value behind an `out` pointer, a `char **` that starts
1433/// NULL, unwritten or at offset 0 (`outptr`), and structs of zeros, ones, minus ones, minimums
1434/// and maximums, plus each field zero with the others one (a zero denominator).
1435fn c_pointer_traps(ts_type: &str) -> Option<Vec<Value>> {
1436    Some(match ts_type {
1437        "bytes" => vec![
1438            json!(""),
1439            json!("00"),
1440            json!("ff"),
1441            json!("616263"),
1442            json!((0..=255u8).map(|b| format!("{b:02x}")).collect::<String>()),
1443            json!("ff".repeat(64)),
1444        ],
1445        "buffer" => vec![
1446            json!(0),
1447            json!(1),
1448            json!(3),
1449            json!(64),
1450            json!("ff".repeat(16)),
1451        ],
1452        "out" => vec![json!(0), json!(-1), json!(2_147_483_647)],
1453        t if t.starts_with("outptr:") => vec![json!(true), Value::Null, json!(0)],
1454        t => {
1455            let s = crate::codegen_c::c_struct(t)?;
1456            let field = |pick: &dyn Fn(&[Value]) -> Value, zero: Option<usize>| {
1457                let fields = s.fields.iter().enumerate().map(|(i, (ty, name))| {
1458                    let edges = c_field_edges(ty);
1459                    let v = if zero == Some(i) {
1460                        edges[0].clone()
1461                    } else {
1462                        pick(&edges)
1463                    };
1464                    (name.clone(), v)
1465                });
1466                Value::Object(fields.collect())
1467            };
1468            let mut out: Vec<Value> = (0..5)
1469                .map(|k| field(&|e: &[Value]| e[k.min(e.len() - 1)].clone(), None))
1470                .collect();
1471            out.extend((0..s.fields.len()).map(|i| field(&|e: &[Value]| e[1].clone(), Some(i))));
1472            out.dedup();
1473            out
1474        }
1475    })
1476}
1477
1478/// Edge values for a C scalar struct field: zero, one, then minus one, the minimum and the
1479/// maximum where the type has them (non-finite values for floating point).
1480fn c_field_edges(ty: &str) -> Vec<Value> {
1481    let ty = ty.trim();
1482    if ty.contains("float") || ty.contains("double") {
1483        return vec![
1484            json!(0.0),
1485            json!(1.0),
1486            json!(-1.0),
1487            json!({ "$num": "NaN" }),
1488            json!({ "$num": "Infinity" }),
1489            json!({ "$num": "-Infinity" }),
1490            json!(0.5),
1491            json!(1e300),
1492        ];
1493    }
1494    if ty == "bool" || ty == "_Bool" {
1495        return vec![json!(false), json!(true)];
1496    }
1497    let unsigned = ty.starts_with('u') || ty.starts_with("unsigned") || ty == "size_t";
1498    let bits = if ty.contains('8') || ty.ends_with("char") {
1499        8
1500    } else if ty.contains("16") || ty.contains("short") {
1501        16
1502    } else if ty.contains("64") || ty.contains("long") || ty.contains("size") || ty.contains("ptr")
1503    {
1504        64
1505    } else {
1506        32
1507    };
1508    if unsigned {
1509        let max = if bits == 64 {
1510            u64::MAX
1511        } else {
1512            (1u64 << bits) - 1
1513        };
1514        vec![json!(0), json!(1), json!(max), json!(max - 1), json!(2)]
1515    } else {
1516        let max = i64::MAX >> (64 - bits);
1517        vec![json!(0), json!(1), json!(-1), json!(-max - 1), json!(max)]
1518    }
1519}
1520
1521/// A random value for a C pointer parameter (see `c_pointer_traps`).
1522fn c_pointer_value(ts_type: &str, rng: &mut Rng) -> Value {
1523    const SIZES: [usize; 12] = [0, 1, 2, 3, 4, 5, 8, 16, 17, 64, 100, 1024];
1524    match ts_type {
1525        "bytes" => {
1526            let n = SIZES[rng.below(SIZES.len())];
1527            let text = rng.below(2) == 0;
1528            json!(
1529                (0..n)
1530                    .map(|_| {
1531                        let b = if text {
1532                            0x20 + rng.below(0x5f)
1533                        } else {
1534                            rng.below(256)
1535                        };
1536                        format!("{b:02x}")
1537                    })
1538                    .collect::<String>()
1539            )
1540        }
1541        "buffer" => json!(SIZES[rng.below(SIZES.len())]),
1542        t if t.starts_with("outptr:") => [json!(true), Value::Null, json!(0)][rng.below(3)].clone(),
1543        t if let Some(s) = crate::codegen_c::c_struct(t) => Value::Object(
1544            s.fields
1545                .iter()
1546                .map(|(ty, name)| {
1547                    let edges = c_field_edges(ty);
1548                    let small: [i32; 14] =
1549                        [0, 1, -1, 2, 3, 7, 12, 25, 30, 1000, 1001, 90000, -5, -48000];
1550                    let v = match rng.below(10) {
1551                        0..=2 => edges[rng.below(edges.len())].clone(),
1552                        _ if edges.len() == 2 => edges[rng.below(2)].clone(),
1553                        _ if ty.contains("float") || ty.contains("double") => {
1554                            json!(f64::from(small[rng.below(small.len())]) / 4.0)
1555                        }
1556                        _ if edges[2] != json!(-1) => {
1557                            json!(small[rng.below(small.len())].unsigned_abs())
1558                        }
1559                        _ => json!(small[rng.below(small.len())]),
1560                    };
1561                    (name.clone(), v)
1562                })
1563                .collect(),
1564        ),
1565        _ => json!([0, 1, -1, 7, 1000, 65536][rng.below(6)]),
1566    }
1567}
1568
1569/// One argument list for `params`: values that fit, edge cases, and sometimes omitted optionals.
1570fn args_for(
1571    params: &[crate::ts::exports::Param],
1572    types: &[LocalType],
1573    rng: &mut Rng,
1574) -> Vec<Value> {
1575    let mut args: Vec<Value> = Vec::new();
1576    for p in params {
1577        match p.ts_type.as_str() {
1578            t if t.starts_with("len:") => continue,
1579            t if matches!(t, "bytes" | "buffer" | "out")
1580                || t.starts_with("outptr:")
1581                || t.starts_with("struct:") =>
1582            {
1583                args.push(c_pointer_value(&p.ts_type, rng));
1584                continue;
1585            }
1586            _ => {}
1587        }
1588        let t = param_type(p);
1589        // Structured parameters: values that fit the TS type, and now and then a value
1590        // that does not, so error paths get recorded too.
1591        let structured = |rng: &mut Rng| {
1592            if rng.below(100) < 15 {
1593                value(&RType::Json, rng)
1594            } else {
1595                shaped(&shape::parse(&p.ts_type), types, rng, 0)
1596            }
1597        };
1598        if p.rest {
1599            let inner = match t {
1600                RType::Vec(inner) => *inner,
1601                other => other,
1602            };
1603            for _ in 0..rng.below(3) {
1604                args.push(value(&inner, rng));
1605            }
1606        } else if t.contains_json() {
1607            let v = structured(rng);
1608            args.push(if p.optional && rng.below(5) == 0 {
1609                json!({ "$undefined": true })
1610            } else {
1611                v
1612            });
1613        } else {
1614            args.push(value(&t, rng));
1615        }
1616    }
1617    // Search-like functions rarely hit on random text: often derive one string from another.
1618    let strings: Vec<usize> = (0..args.len()).filter(|&i| args[i].is_string()).collect();
1619    if strings.len() >= 2 && rng.below(10) < 5 {
1620        let from = strings[rng.below(strings.len())];
1621        let to = strings[rng.below(strings.len())];
1622        if from != to {
1623            let source: Vec<char> = args[from].as_str().unwrap_or_default().chars().collect();
1624            if !source.is_empty() {
1625                let start = rng.below(source.len());
1626                let end = start + 1 + rng.below(source.len() - start);
1627                let mut piece: String = source[start..end].iter().collect();
1628                if rng.below(4) == 0 {
1629                    piece = piece.to_uppercase();
1630                }
1631                args[to] = Value::String(piece);
1632            }
1633        }
1634    }
1635    // Trailing optional arguments: sometimes omit them, the way JS callers do.
1636    while args.last().is_some_and(|a| a.get("$undefined").is_some()) && rng.below(2) == 0 {
1637        args.pop();
1638    }
1639    args
1640}
1641
1642/// Class scenarios: construct, then call a random sequence of methods.
1643pub fn scenarios(
1644    class: &crate::ts::exports::ExportedClass,
1645    count: usize,
1646    types: &[LocalType],
1647) -> Vec<Value> {
1648    scenarios_salted(class, count, types, 0)
1649}
1650
1651/// [`scenarios`] from another seed, as [`generate_salted`].
1652pub fn scenarios_salted(
1653    class: &crate::ts::exports::ExportedClass,
1654    count: usize,
1655    types: &[LocalType],
1656    salt: u64,
1657) -> Vec<Value> {
1658    let mut rng = Rng::new(
1659        class.name.bytes().fold(0x2545_F491_4F6C_DD1D, |h, b| {
1660            (h ^ u64::from(b)).wrapping_mul(0x100_0000_01B3)
1661        }) ^ salt,
1662    );
1663    (0..count)
1664        .map(|_| {
1665            let ctor = args_for(&class.constructor, types, &mut rng);
1666            let steps = if class.methods.is_empty() {
1667                0
1668            } else {
1669                1 + rng.below(12)
1670            };
1671            // Stateful classes need calls that meet again (`set(k)` then `get(k)`): string
1672            // arguments often reuse a string seen earlier in the scenario.
1673            let mut seen: Vec<Value> = ctor.iter().filter(|v| v.is_string()).cloned().collect();
1674            let calls: Vec<Value> = (0..steps)
1675                .map(|_| {
1676                    let m = &class.methods[rng.below(class.methods.len())];
1677                    let mut args = args_for(&m.params, types, &mut rng);
1678                    for arg in &mut args {
1679                        if arg.is_string() {
1680                            if !seen.is_empty() && rng.below(2) == 0 {
1681                                *arg = seen[rng.below(seen.len())].clone();
1682                            } else {
1683                                seen.push(arg.clone());
1684                            }
1685                        }
1686                    }
1687                    json!({ "method": m.name, "args": args })
1688                })
1689                .collect();
1690            json!({ "class": class.name, "ctor": ctor, "calls": calls })
1691        })
1692        .collect()
1693}
1694
1695/// Property names for generated objects: plain, nested-looking, integer-like (JS orders those
1696/// first), non-ASCII.
1697const KEYS: &[&str] = &[
1698    "a", "b", "nav", "home", "title", "2", "10", "ünï", "😀", "a.b",
1699];
1700
1701/// A value that fits a TS shape. Named types resolve against `types`; recursion stops at a depth.
1702fn shaped(s: &Shape, types: &[LocalType], rng: &mut Rng, depth: usize) -> Value {
1703    match s {
1704        Shape::Str => value(&RType::Str, rng),
1705        Shape::Num => value(&RType::F64, rng),
1706        Shape::Int => value(&RType::Int, rng),
1707        Shape::Bool => value(&RType::Bool, rng),
1708        Shape::Bytes => value(&RType::Bytes, rng),
1709        Shape::Null => Value::Null,
1710        Shape::Undefined => json!({ "$undefined": true }),
1711        Shape::LitStr(text) => Value::String(text.clone()),
1712        Shape::LitNum(n) => json!(n),
1713        Shape::LitBool(b) => Value::Bool(*b),
1714        Shape::Union(items) if !items.is_empty() => {
1715            shaped(&items[rng.below(items.len())], types, rng, depth)
1716        }
1717        Shape::Array(item) if depth < 6 => Value::Array(
1718            (0..rng.below(4))
1719                .map(|_| shaped(item, types, rng, depth + 1))
1720                .collect(),
1721        ),
1722        Shape::Tuple(items) => Value::Array(
1723            items
1724                .iter()
1725                .map(|i| shaped(i, types, rng, depth + 1))
1726                .collect(),
1727        ),
1728        Shape::Object(props, index) if depth < 6 => {
1729            let mut out = serde_json::Map::new();
1730            for (name, optional, prop) in props {
1731                if *optional && rng.below(4) == 0 {
1732                    continue;
1733                }
1734                out.insert(name.clone(), shaped(prop, types, rng, depth + 1));
1735            }
1736            if let Some(item) = index {
1737                for _ in 0..rng.below(4) {
1738                    out.insert(
1739                        KEYS[rng.below(KEYS.len())].to_string(),
1740                        shaped(item, types, rng, depth + 1),
1741                    );
1742                }
1743            }
1744            Value::Object(out)
1745        }
1746        Shape::Ref(name, args) if depth < 6 => {
1747            shaped(&shape::resolve(name, args, types), types, rng, depth + 1)
1748        }
1749        Shape::Any => value(&RType::Json, rng),
1750        // Too deep, or empty: a leaf ends the recursion.
1751        _ => Value::Null,
1752    }
1753}
1754
1755fn value(t: &RType, rng: &mut Rng) -> Value {
1756    match t {
1757        RType::Str => {
1758            let a = STRINGS[rng.below(STRINGS.len())];
1759            if rng.below(5) == 0 {
1760                Value::String(format!("{a}{}", STRINGS[rng.below(STRINGS.len())]))
1761            } else {
1762                Value::String(a.into())
1763            }
1764        }
1765        RType::Int => {
1766            // Small, signed, and the edges of 32 and 64 bits.
1767            let n: [i64; 12] = [
1768                0,
1769                1,
1770                -1,
1771                2,
1772                7,
1773                42,
1774                100,
1775                -100,
1776                255,
1777                i64::from(i32::MAX),
1778                i64::from(i32::MIN),
1779                i64::MAX,
1780            ];
1781            json!(n[rng.below(n.len())])
1782        }
1783        RType::F64 => {
1784            let n = [
1785                0.0,
1786                1.0,
1787                -1.0,
1788                2.0,
1789                3.0,
1790                10.0,
1791                0.5,
1792                -2.5,
1793                42.0,
1794                100.0,
1795                1000.0,
1796                1e6,
1797                2_147_483_648.0,
1798                9_007_199_254_740_992.0,
1799            ];
1800            match rng.below(n.len() + 4) {
1801                i if i < n.len() => json!(n[i]),
1802                i if i == n.len() => json!({ "$num": "-0" }),
1803                i if i == n.len() + 1 => json!({ "$num": "NaN" }),
1804                i if i == n.len() + 2 => json!({ "$num": "Infinity" }),
1805                _ => json!({ "$num": "-Infinity" }),
1806            }
1807        }
1808        RType::Bool => Value::Bool(rng.below(2) == 0),
1809        RType::Bytes => {
1810            let len = rng.below(6);
1811            let bytes: Vec<u64> = (0..len).map(|_| rng.below(256) as u64).collect();
1812            json!({ "$bytes": bytes })
1813        }
1814        RType::Unit => json!({ "$undefined": true }),
1815        RType::Vec(inner) => Value::Array((0..rng.below(4)).map(|_| value(inner, rng)).collect()),
1816        RType::Opt(inner) => {
1817            if rng.below(4) == 0 {
1818                json!({ "$undefined": true })
1819            } else {
1820                value(inner, rng)
1821            }
1822        }
1823        RType::Json => {
1824            let values: Vec<Value> = serde_json::from_str(JSON_VALUES).unwrap_or_default();
1825            values
1826                .get(rng.below(values.len().max(1)))
1827                .cloned()
1828                .unwrap_or(Value::Null)
1829        }
1830    }
1831}
1832
1833/// xorshift64*: deterministic, so a recording is reproducible.
1834struct Rng(u64);
1835
1836impl Rng {
1837    fn new(seed: u64) -> Self {
1838        Self(seed | 1)
1839    }
1840
1841    fn below(&mut self, n: usize) -> usize {
1842        if n == 0 {
1843            return 0;
1844        }
1845        self.0 ^= self.0 >> 12;
1846        self.0 ^= self.0 << 25;
1847        self.0 ^= self.0 >> 27;
1848        let x = self.0.wrapping_mul(0x2545_F491_4F6C_DD1D);
1849        usize::try_from(x >> 33).unwrap_or(0) % n
1850    }
1851}
1852
1853/// How long one recorded case may run before the original is stopped on it:
1854/// `RUST_ANYTHING_CASE_TIMEOUT` seconds, 10 by default.
1855fn case_timeout() -> std::time::Duration {
1856    std::env::var("RUST_ANYTHING_CASE_TIMEOUT")
1857        .ok()
1858        .and_then(|v| v.parse::<f64>().ok())
1859        .and_then(crate::process::seconds)
1860        .unwrap_or(std::time::Duration::from_secs(10))
1861}
1862
1863/// Runs a record driver over `cases` with a watchdog. The driver appends the index of each case
1864/// it starts to `RUST_ANYTHING_PROGRESS` and flushes each recorded line. A case that runs past
1865/// the time limit (an input that makes the original allocate or loop for ever) stops the driver;
1866/// the lines recorded so far are kept, that input is left out, and the driver goes on with the
1867/// rest. Returns the inputs left out.
1868pub(crate) fn record_cases(
1869    cases: &[Value],
1870    work: &Path,
1871    out: &Path,
1872    what: &str,
1873    mut command: impl FnMut(&Path, &Path) -> Result<Command>,
1874) -> Result<Vec<Value>> {
1875    use std::process::Stdio;
1876    use std::time::Instant;
1877    std::fs::create_dir_all(work)?;
1878    let timeout = case_timeout();
1879    let inputs = work.join("record-inputs.json");
1880    let part = work.join("record-part.jsonl");
1881    let progress = work.join("record-progress");
1882    let stderr_path = work.join("record-stderr");
1883    let mut recorded = String::new();
1884    let mut timed_out = Vec::new();
1885    let mut start = 0;
1886    while start < cases.len() {
1887        std::fs::write(&inputs, serde_json::to_string(&cases[start..])?)?;
1888        std::fs::write(&progress, "")?;
1889        let _ = std::fs::remove_file(&part);
1890        let mut cmd = command(&inputs, &part)?;
1891        cmd.env("RUST_ANYTHING_PROGRESS", &progress)
1892            .stdin(Stdio::null())
1893            .stdout(Stdio::null())
1894            .stderr(std::fs::File::create(&stderr_path)?);
1895        #[cfg(unix)]
1896        {
1897            use std::os::unix::process::CommandExt as _;
1898            cmd.process_group(0);
1899        }
1900        let _scratch = scratch_cwd(&mut cmd)?;
1901        let mut child = cmd
1902            .spawn()
1903            .map_err(|e| crate::process::spawn_error(&cmd, what, e))?;
1904        let mut current: Option<(usize, Instant)> = None;
1905        let status = loop {
1906            if let Some(status) = child.try_wait()? {
1907                break Some(status);
1908            }
1909            let started = std::fs::read_to_string(&progress).ok().and_then(|p| {
1910                p.lines()
1911                    .last()
1912                    .and_then(|l| l.trim().parse::<usize>().ok())
1913            });
1914            match (started, current) {
1915                (Some(i), Some((j, _))) if i == j => {}
1916                (Some(i), _) => current = Some((i, Instant::now())),
1917                (None, _) => {}
1918            }
1919            if let Some((_, since)) = current
1920                && since.elapsed() > timeout
1921            {
1922                #[cfg(unix)]
1923                {
1924                    let _ = Command::new("/bin/kill")
1925                        .args(["-KILL", "--", &format!("-{}", child.id())])
1926                        .stderr(Stdio::null())
1927                        .status();
1928                }
1929                let _ = child.kill();
1930                let _ = child.wait();
1931                break None;
1932            }
1933            std::thread::sleep(std::time::Duration::from_millis(20));
1934        };
1935        let written = std::fs::read_to_string(&part).unwrap_or_default();
1936        let complete = written.rfind('\n').map_or("", |end| &written[..=end]);
1937        recorded.push_str(complete);
1938        match (status, current) {
1939            (Some(status), _) if status.success() => break,
1940            (Some(status), _) => {
1941                let stderr = std::fs::read_to_string(&stderr_path).unwrap_or_default();
1942                let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
1943                bail!(
1944                    "{what} failed ({status}):\n{}",
1945                    tail.into_iter().rev().collect::<Vec<_>>().join("\n")
1946                );
1947            }
1948            (None, Some((i, _))) => {
1949                timed_out.push(cases[start + i].clone());
1950                start += i + 1;
1951            }
1952            (None, None) => unreachable!("the watchdog only stops a driver inside a case"),
1953        }
1954    }
1955    std::fs::write(out, recorded)?;
1956    std::fs::write(work.join(TIMED_OUT), serde_json::to_string(&timed_out)?)?;
1957    Ok(timed_out)
1958}
1959
1960/// Inputs the last `record` left out because the original ran past the time limit on them.
1961pub(crate) const TIMED_OUT: &str = "timed-out.json";
1962
1963pub(crate) struct Scratch(PathBuf);
1964
1965impl Drop for Scratch {
1966    fn drop(&mut self) {
1967        let _ = std::fs::remove_dir_all(&self.0);
1968    }
1969}
1970
1971pub(crate) fn scratch_cwd(cmd: &mut Command) -> Result<Option<Scratch>> {
1972    if cmd.get_current_dir().is_some() {
1973        return Ok(None);
1974    }
1975    let dir = crate::app::temp_dir("unit")?;
1976    cmd.current_dir(&dir);
1977    Ok(Some(Scratch(dir)))
1978}
1979
1980fn run(cmd: &mut Command, what: &str) -> Result<()> {
1981    let _scratch = scratch_cwd(cmd)?;
1982    let output = cmd
1983        .output()
1984        .map_err(|e| crate::process::spawn_error(cmd, what, e))?;
1985    if !output.status.success() {
1986        let stderr = String::from_utf8_lossy(&output.stderr);
1987        let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
1988        bail!(
1989            "{what} failed ({}):\n{}",
1990            output.status,
1991            tail.into_iter().rev().collect::<Vec<_>>().join("\n")
1992        );
1993    }
1994    Ok(())
1995}
1996
1997/// Python keyword-only parameters (after `*`) are passed by name: they move from `args` into
1998/// `kwargs`, and an omitted (`undefined`) one is left out.
1999/// Integral float arguments of `number` parameters, as ints.
2000fn intify(params: &[crate::ts::exports::Param], args: &mut Value) {
2001    let Some(items) = args.as_array_mut() else {
2002        return;
2003    };
2004    for (p, v) in params.iter().zip(items.iter_mut()) {
2005        if p.ts_type == "number"
2006            && let Some(x) = v.as_f64()
2007            && x.fract() == 0.0
2008            && x.abs() < 1e15
2009            && !(x == 0.0 && x.is_sign_negative())
2010        {
2011            *v = json!(x as i64);
2012        }
2013    }
2014}
2015
2016fn split_keyword_only(params: &[crate::ts::exports::Param], case: &mut Value) {
2017    if !params.iter().any(|p| p.keyword_only) {
2018        return;
2019    }
2020    let Some(args) = case["args"].as_array().cloned() else {
2021        return;
2022    };
2023    let mut positional = Vec::new();
2024    let mut kwargs = serde_json::Map::new();
2025    for (i, value) in args.into_iter().enumerate() {
2026        match params.get(i) {
2027            Some(p) if p.keyword_only => {
2028                if value.get("$undefined").is_none() {
2029                    kwargs.insert(p.name.clone(), value);
2030                }
2031            }
2032            _ => positional.push(value),
2033        }
2034    }
2035    case["args"] = Value::Array(positional);
2036    case["kwargs"] = Value::Object(kwargs);
2037}
2038
2039/// Workspace packages as `{ name: absolute source folder }` for the resolve hook: a monorepo
2040/// imports its own packages by name, and their build output may not exist.
2041fn workspace_env(manifest: &Manifest) -> String {
2042    let packages: BTreeMap<String, String> = crate::ts::discover::discover(&manifest.root)
2043        .map(|ws| {
2044            ws.packages
2045                .into_iter()
2046                .filter(|p| !p.dir.is_empty())
2047                .map(|p| {
2048                    let dir = manifest.root.join(&p.dir);
2049                    let src = if dir.join("src").is_dir() {
2050                        dir.join("src")
2051                    } else {
2052                        dir
2053                    };
2054                    (p.name, src.to_string_lossy().into_owned())
2055                })
2056                .collect()
2057        })
2058        .unwrap_or_default();
2059    serde_json::to_string(&packages).unwrap_or_else(|_| "{}".into())
2060}
2061
2062/// The tsconfig `paths` of the unit's files, as JSON for the resolve hook: `[[pattern, [absolute targets]]]`.
2063fn alias_env(manifest: &Manifest) -> String {
2064    let mut entries: Vec<(String, Vec<String>)> = Vec::new();
2065    let files = manifest
2066        .exports
2067        .iter()
2068        .map(|f| &f.file)
2069        .chain(manifest.classes.iter().map(|c| &c.file));
2070    for file in files {
2071        let dir = file.rsplit_once('/').map_or("", |(d, _)| d);
2072        for (pattern, targets) in
2073            crate::ts::tsconfig::PathAliases::nearest(&manifest.root, dir).entries
2074        {
2075            if entries.iter().all(|(p, _)| *p != pattern) {
2076                let absolute = targets
2077                    .iter()
2078                    .map(|t| manifest.root.join(t).to_string_lossy().into_owned())
2079                    .collect();
2080                entries.push((pattern, absolute));
2081            }
2082        }
2083    }
2084    serde_json::to_string(&entries).unwrap_or_else(|_| "[]".into())
2085}
2086
2087fn file_url(path: &Path) -> String {
2088    use std::fmt::Write as _;
2089
2090    let text = path.to_string_lossy();
2091    #[cfg(windows)]
2092    let text = text.replace('\\', "/");
2093    let mut url = if text.starts_with('/') {
2094        String::from("file://")
2095    } else {
2096        String::from("file:///")
2097    };
2098    for byte in text.bytes() {
2099        if byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b':' | b'-' | b'_' | b'.' | b'~') {
2100            url.push(char::from(byte));
2101        } else {
2102            let _ = write!(url, "%{byte:02X}");
2103        }
2104    }
2105    url
2106}
2107
2108const REGISTER_JS: &str =
2109    "import { register } from 'node:module'\nregister('./resolve.mjs', import.meta.url)\n";
2110
2111/// Node resolve hook: bundler-style relative imports, and npm packages from
2112/// `RUST_ANYTHING_RESOLVE_FROM` when the source tree has none installed.
2113const RESOLVE_JS: &str = r#"
2114import { existsSync, statSync } from 'node:fs'
2115import { fileURLToPath, pathToFileURL } from 'node:url'
2116
2117const extra = process.env.RUST_ANYTHING_RESOLVE_FROM
2118// tsconfig `paths`: exact keys first, then wildcard keys by longest prefix.
2119const aliasPriority = pattern => pattern.includes('*') ? pattern.indexOf('*') : Number.POSITIVE_INFINITY
2120const aliases = JSON.parse(process.env.RUST_ANYTHING_PATHS || '[]')
2121  .sort(([a], [b]) => aliasPriority(b) - aliasPriority(a))
2122// Workspace packages by name: `@x18n/core` and `@x18n/core/sub` resolve to source.
2123const workspace = JSON.parse(process.env.RUST_ANYTHING_WORKSPACE || '{}')
2124const workspaceTargets = (specifier) => {
2125  for (const [name, src] of Object.entries(workspace)) {
2126    if (specifier === name)
2127      return [`${src}/index`]
2128    if (specifier.startsWith(`${name}/`))
2129      return [`${src}/${specifier.slice(name.length + 1)}`, `${src}/${specifier.slice(name.length + 1)}/index`]
2130  }
2131  return []
2132}
2133const aliasTargets = (specifier) => {
2134  for (const [pattern, targets] of aliases) {
2135    const [prefix, suffix = ''] = pattern.split('*')
2136    const exact = !pattern.includes('*')
2137    if (exact ? specifier === pattern : specifier.startsWith(prefix) && specifier.endsWith(suffix) && specifier.length >= prefix.length + suffix.length) {
2138      const star = exact ? '' : specifier.slice(prefix.length, specifier.length - suffix.length)
2139      return targets.map(t => t.replace('*', () => star))
2140    }
2141  }
2142  return []
2143}
2144const suffixes = ['.ts', '.tsx', '.mts', '.js', '.mjs', '/index.ts', '/index.mts', '/index.js']
2145const sourceCandidates = path => {
2146  const exact = path.match(/\.(mjs|cjs|jsx)$/)
2147  if (exact) {
2148    const replacement = { mjs: 'mts', cjs: 'cts', jsx: 'tsx' }[exact[1]]
2149    return [path, path.slice(0, -exact[1].length) + replacement]
2150  }
2151  const stem = path.replace(/\.js$/, '')
2152  return [stem, ...suffixes.map(suffix => stem + suffix)]
2153}
2154const isFile = p => existsSync(p) && statSync(p).isFile()
2155
2156export async function resolve(specifier, context, next) {
2157  // Aliases first: `@/x` is not even a valid package name for Node.
2158  for (const target of [...aliasTargets(specifier), ...workspaceTargets(specifier)]) {
2159    for (const candidate of sourceCandidates(target)) {
2160      if (isFile(candidate))
2161        return next(pathToFileURL(candidate).href, context)
2162    }
2163  }
2164  try {
2165    return await next(specifier, context)
2166  }
2167  catch (error) {
2168    const missing = error?.code === 'ERR_MODULE_NOT_FOUND' || error?.code === 'ERR_UNSUPPORTED_DIR_IMPORT'
2169    if (!missing || !context.parentURL)
2170      throw error
2171    if (specifier.startsWith('.') || specifier.startsWith('/')) {
2172      const path = fileURLToPath(new URL(specifier, context.parentURL))
2173      for (const candidate of sourceCandidates(path)) {
2174        if (isFile(candidate))
2175          return next(pathToFileURL(candidate).href, context)
2176      }
2177    }
2178    else if (extra) {
2179      return next(specifier, { ...context, parentURL: pathToFileURL(`${extra}/`).href })
2180    }
2181    throw error
2182  }
2183}
2184"#;
2185
2186/// Encoding shared by the record, diff and shadow scripts. Lossless for what a JS caller
2187/// can observe: `undefined`, `NaN`, `-0`, BigInt, Map/Set order, key order, lone surrogates.
2188pub const CODEC_JS: &str = r#"
2189const enc = (v, stack = []) => {
2190  if (v === undefined) return { $undefined: true }
2191  if (typeof v === 'number') {
2192    if (Number.isNaN(v)) return { $num: 'NaN' }
2193    if (!Number.isFinite(v)) return { $num: v > 0 ? 'Infinity' : '-Infinity' }
2194    if (Object.is(v, -0)) return { $num: '-0' }
2195    return v
2196  }
2197  // Strings JS split inside a surrogate pair are not valid Unicode: keep their code units.
2198  if (typeof v === 'string' && !v.isWellFormed()) return { $utf16: Array.from({ length: v.length }, (_, i) => v.charCodeAt(i)) }
2199  if (typeof v === 'bigint') return { $bigint: String(v) }
2200  if (typeof v === 'function') return { $function: v.name }
2201  if (typeof v === 'symbol') return { $symbol: String(v.description) }
2202  if (v === null || typeof v !== 'object') return v
2203  if (stack.includes(v)) return { $cycle: true }
2204  const next = [...stack, v]
2205  if (Array.isArray(v)) return v.map(x => enc(x, next))
2206  if (typeof Buffer !== 'undefined' && Buffer.isBuffer(v)) return { $buffer: [...v] }
2207  if (v instanceof Uint8Array) return { $bytes: [...v] }
2208  if (ArrayBuffer.isView(v) && !(v instanceof DataView)) return { $typed: { kind: v.constructor.name, values: [...v].map(x => enc(x, next)) } }
2209  if (v instanceof Map) return { $map: [...v].map(([k, x]) => [enc(k, next), enc(x, next)]) }
2210  if (v instanceof Set) return { $set: [...v].map(x => enc(x, next)) }
2211  if (v instanceof Date) return { $date: Number.isNaN(v.getTime()) ? 'Invalid' : v.toISOString() }
2212  if (v instanceof RegExp) return { $regexp: String(v) }
2213  if (v instanceof Error) return { $error: v.message }
2214  const plain = Object.fromEntries(Object.keys(v).map(k => [k, enc(v[k], next)]))
2215  return looksLikeMarker(plain) ? { $object: plain } : plain
2216}
2217const MARKERS = ['$undefined', '$num', '$bigint', '$utf16', '$map', '$set', '$date', '$bytes', '$buffer', '$typed', '$object']
2218const looksLikeMarker = (v) => {
2219  const keys = Object.keys(v)
2220  return keys.length === 1 && MARKERS.includes(keys[0])
2221}
2222const dec = (v) => {
2223  if (Array.isArray(v)) return v.map(dec)
2224  if (v === null || typeof v !== 'object') return v
2225  if (!looksLikeMarker(v)) return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, dec(x)]))
2226  if ('$object' in v) return Object.fromEntries(Object.entries(v.$object).map(([k, x]) => [k, dec(x)]))
2227  if ('$undefined' in v) return undefined
2228  if ('$num' in v) return Number(v.$num)
2229  if ('$bigint' in v) return BigInt(v.$bigint)
2230  if ('$utf16' in v) {
2231    let text = ''
2232    for (let i = 0; i < v.$utf16.length; i += 8192)
2233      text += String.fromCharCode(...v.$utf16.slice(i, i + 8192))
2234    return text
2235  }
2236  if ('$map' in v) return new Map(v.$map.map(([k, x]) => [dec(k), dec(x)]))
2237  if ('$set' in v) return new Set(v.$set.map(dec))
2238  if ('$date' in v) return new Date(v.$date)
2239  if ('$bytes' in v) return Uint8Array.from(v.$bytes)
2240  if ('$typed' in v) return globalThis[v.$typed.kind].from(v.$typed.values.map(dec))
2241  return Buffer.from(v.$buffer)
2242}
2243const canon = (v, sort) => {
2244  if (Array.isArray(v)) return v.map(x => canon(x, sort))
2245  if (v === null || typeof v !== 'object') return v
2246  const keys = Object.keys(v)
2247  if (sort) keys.sort()
2248  return Object.fromEntries(keys.map(k => [k, canon(v[k], sort)]))
2249}
2250const same = (a, b, sort = false) => JSON.stringify(canon(a, sort)) === JSON.stringify(canon(b, sort))
2251"#;
2252
2253const RECORD_JS: &str = r#"
2254import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
2255import { pathToFileURL } from 'node:url'
2256
2257const [inputsPath, outPath] = process.argv.slice(2)
2258const inputs = JSON.parse(readFileSync(inputsPath, 'utf8'))
2259const modules = new Map()
2260const progress = process.env.RUST_ANYTHING_PROGRESS
2261writeFileSync(outPath, '')
2262const lines = { push: line => appendFileSync(outPath, `${line}\n`) }
2263// A class scenario: construct, then call each method in turn; every step's result is recorded.
2264const runScenario = async (Class, c) => {
2265  const results = []
2266  let instance
2267  try {
2268    instance = new Class(...c.ctor.map(dec))
2269    results.push({ ok: true })
2270  }
2271  catch (error) {
2272    results.push({ error: String(error?.message ?? error) })
2273    return results
2274  }
2275  for (const call of c.calls) {
2276    try {
2277      results.push({ ok: enc(await instance[call.method](...call.args.map(dec))) })
2278    }
2279    catch (error) {
2280      results.push({ error: String(error?.message ?? error) })
2281    }
2282  }
2283  return results
2284}
2285for (const [index, c] of inputs.entries()) {
2286  if (progress) appendFileSync(progress, `${index}\n`)
2287  let mod = modules.get(c.module)
2288  if (!mod) {
2289    mod = await import(pathToFileURL(c.module).href)
2290    modules.set(c.module, mod)
2291  }
2292  if (c.class) {
2293    const Class = mod[c.class] ?? mod.default?.[c.class]
2294    if (typeof Class !== 'function') {
2295      console.error(`${c.class} is not a class exported by ${c.module}`)
2296      process.exit(2)
2297    }
2298    pinCase(index)
2299    lines.push(JSON.stringify({ class: c.class, ctor: c.ctor, calls: c.calls, results: await runScenario(Class, c) }))
2300    continue
2301  }
2302  const fn = mod[c.fn] ?? mod.default?.[c.fn]
2303  if (typeof fn !== 'function') {
2304    console.error(`${c.fn} is not a function exported by ${c.module}`)
2305    process.exit(2)
2306  }
2307  pinCase(index)
2308  try {
2309    const value = await fn(...c.args.map(dec))
2310    lines.push(JSON.stringify({ fn: c.fn, args: c.args, ok: enc(value) }))
2311  }
2312  catch (error) {
2313    lines.push(JSON.stringify({ fn: c.fn, args: c.args, error: String(error?.message ?? error) }))
2314  }
2315}
2316"#;
2317
2318const BENCH_JS: &str = r#"
2319import { readFileSync, writeFileSync } from 'node:fs'
2320import { pathToFileURL } from 'node:url'
2321
2322const [modulesPath, nativePath, casesPath, outPath, minMs] = process.argv.slice(2)
2323const { functions: modules, classes: classModules, asyncFunctions } = JSON.parse(readFileSync(modulesPath, 'utf8'))
2324const loaded = await import(pathToFileURL(nativePath).href)
2325const native = { ...(loaded.default && typeof loaded.default === 'object' ? loaded.default : {}), ...loaded }
2326const cases = readFileSync(casesPath, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l))
2327const byFn = new Map()
2328const scenarios = new Map()
2329for (const c of cases.filter(c => c.class)) {
2330  if (!scenarios.has(c.class)) scenarios.set(c.class, [])
2331  scenarios.get(c.class).push(c)
2332}
2333for (const c of cases.filter(c => !c.class)) {
2334  if (!byFn.has(c.fn)) byFn.set(c.fn, [])
2335  byFn.get(c.fn).push(c.args.map(dec))
2336}
2337// Time whole passes over the cases until `minMs` has passed; errors count as calls.
2338const time = (fn, argsList) => {
2339  const pass = () => {
2340    for (const args of argsList) {
2341      try { fn(...args) } catch {}
2342    }
2343  }
2344  pass()
2345  let passes = 0
2346  const start = performance.now()
2347  do { pass(); passes++ } while (performance.now() - start < Number(minMs))
2348  return (performance.now() - start) * 1e6 / (passes * argsList.length)
2349}
2350const timeAsync = async (fn, argsList) => {
2351  const pass = async () => {
2352    for (const args of argsList) {
2353      try { await fn(...args) } catch {}
2354    }
2355  }
2356  await pass()
2357  let passes = 0
2358  const start = performance.now()
2359  do { await pass(); passes++ } while (performance.now() - start < Number(minMs))
2360  return (performance.now() - start) * 1e6 / (passes * argsList.length)
2361}
2362const rows = []
2363for (const [name, argsList] of byFn) {
2364  const original = (await import(pathToFileURL(modules[name]).href))[name]
2365  const rust = native[name]
2366  if (typeof original !== 'function' || typeof rust !== 'function') continue
2367  const timer = asyncFunctions.includes(name) ? timeAsync : time
2368  const originalNs = await timer(original, argsList)
2369  const rustNs = await timer(rust, argsList)
2370  rows.push({ fn: name, cases: argsList.length, original_ns: originalNs, rust_ns: rustNs, speedup: originalNs / rustNs })
2371}
2372// Classes: time whole scenarios (construct, then every call).
2373const play = (Class, list) => () => {
2374  for (const c of list) {
2375    try {
2376      const instance = new Class(...c.ctor.map(dec))
2377      for (const call of c.calls) {
2378        try { instance[call.method](...call.args.map(dec)) } catch {}
2379      }
2380    } catch {}
2381  }
2382}
2383for (const [name, list] of scenarios) {
2384  const original = (await import(pathToFileURL(classModules[name]).href))[name]
2385  const rust = native[name]
2386  if (typeof original !== 'function' || typeof rust !== 'function') continue
2387  const timeAll = (fn) => {
2388    fn()
2389    let passes = 0
2390    const start = performance.now()
2391    do { fn(); passes++ } while (performance.now() - start < Number(minMs))
2392    return (performance.now() - start) * 1e6 / (passes * list.length)
2393  }
2394  const originalNs = timeAll(play(original, list))
2395  const rustNs = timeAll(play(rust, list))
2396  rows.push({ fn: `class ${name}`, cases: list.length, original_ns: originalNs, rust_ns: rustNs, speedup: originalNs / rustNs })
2397}
2398writeFileSync(outPath, JSON.stringify(rows))
2399"#;
2400
2401const DIFF_JS: &str = r#"
2402import { readFileSync, writeFileSync } from 'node:fs'
2403import { pathToFileURL } from 'node:url'
2404
2405const [modulePath, casesPath, outPath, keyOrder] = process.argv.slice(2)
2406const loaded = await import(pathToFileURL(modulePath).href)
2407const mod = { ...(loaded.default && typeof loaded.default === 'object' ? loaded.default : {}), ...loaded }
2408const cases = readFileSync(casesPath, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l))
2409const summary = { total: cases.length, passed: 0, failed: 0, missing: [], mismatches: [] }
2410const scenario = async (Class, c) => {
2411  const results = []
2412  let instance
2413  try {
2414    instance = new Class(...c.ctor.map(dec))
2415    results.push({ ok: true })
2416  }
2417  catch (error) {
2418    results.push({ error: String(error?.message ?? error) })
2419    return results
2420  }
2421  for (const call of c.calls) {
2422    try {
2423      results.push({ ok: enc(await instance[call.method](...call.args.map(dec))) })
2424    }
2425    catch (error) {
2426      results.push({ error: String(error?.message ?? error) })
2427    }
2428  }
2429  return results
2430}
2431const stepsMatch = (want, got) => want.length === got.length && want.every((w, i) =>
2432  ('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')))
2433for (const [index, c] of cases.entries()) {
2434  pinCase(index)
2435  if (c.class) {
2436    const Class = mod[c.class]
2437    if (typeof Class !== 'function') {
2438      if (!summary.missing.includes(c.class)) summary.missing.push(c.class)
2439      summary.failed++
2440      continue
2441    }
2442    const got = await scenario(Class, c)
2443    if (stepsMatch(c.results, got)) {
2444      summary.passed++
2445    }
2446    else {
2447      summary.failed++
2448      summary.mismatches.push({ fn: c.class, args: [c.ctor, c.calls], expected: c.results, actual: got })
2449    }
2450    continue
2451  }
2452  const fn = mod[c.fn]
2453  let actual
2454  if (typeof fn !== 'function') {
2455    if (!summary.missing.includes(c.fn)) summary.missing.push(c.fn)
2456    actual = { missing: true }
2457  }
2458  else {
2459    try {
2460      actual = { ok: enc(await fn(...c.args.map(dec))) }
2461    }
2462    catch (error) {
2463      actual = { error: String(error?.message ?? error) }
2464    }
2465  }
2466  const expected = 'error' in c ? { error: c.error } : { ok: c.ok }
2467  // Both sides throwing counts as agreement: error messages are not part of the contract.
2468  const panicked = 'error' in actual && actual.error.startsWith('Rust panic:')
2469  const pass = !panicked && ('error' in expected && 'error' in actual) || ('ok' in expected && 'ok' in actual && same(expected.ok, actual.ok, keyOrder === 'sort'))
2470  if (pass) {
2471    summary.passed++
2472  }
2473  else {
2474    summary.failed++
2475    summary.mismatches.push({ fn: c.fn, args: c.args, expected, actual })
2476  }
2477}
2478writeFileSync(outPath, JSON.stringify(summary, null, 2))
2479"#;
2480
2481#[cfg(test)]
2482mod tests {
2483    #[test]
2484    fn a_class_bench_row_is_failing_when_its_cases_do_not_match() {
2485        let outcome = DiffOutcome {
2486            missing: vec!["Gone".into()],
2487            ..Default::default()
2488        };
2489        let counts = BTreeMap::from([("Counter".to_string(), (1, 2)), ("add".to_string(), (2, 2))]);
2490        assert!(super::failing("class Counter", &outcome, &counts));
2491        assert!(super::failing("class Gone", &outcome, &counts));
2492        assert!(!super::failing("add", &outcome, &counts));
2493    }
2494
2495    use super::*;
2496    use crate::ts::exports::{ExportedFn, Param};
2497
2498    #[test]
2499    fn a_saved_key_order_choice_is_read_by_diffs_without_the_flag() {
2500        // `record --ignore-key-order` writes it; `gate`, `enable`, `report` and `go` have no flag of
2501        // their own, so they inherit it from here.
2502        let dir = std::env::temp_dir().join(format!("ra-key-order-{}", std::process::id()));
2503        let _ = std::fs::remove_dir_all(&dir);
2504        std::fs::create_dir_all(&dir).unwrap();
2505        let opts = |flag: bool| DiffOptions {
2506            crate_dir: &dir,
2507            module: None,
2508            ignore_key_order: flag,
2509            node_args: &[],
2510            float_tolerance: None,
2511        };
2512        // No crate at all: the flag alone decides, and nothing panics.
2513        assert!(!ignores_key_order(&opts(false)));
2514        assert!(ignores_key_order(&opts(true)));
2515        // What `record` saves is what `gate`, `enable` and `report` read without the flag.
2516        let manifest: Manifest = serde_json::from_value(serde_json::json!({
2517            "schema": crate::bridge::SCHEMA,
2518            "root": ".",
2519            "unit": "src/util.ts",
2520            "kind": "napi",
2521            "crate_name": "util-rs",
2522            "exports": [],
2523        }))
2524        .unwrap();
2525        manifest.save(&dir).unwrap();
2526        assert!(!ignores_key_order(&opts(false)));
2527        let mut saved = Manifest::load(&dir).unwrap();
2528        saved.ignore_key_order = true;
2529        saved.save(&dir).unwrap();
2530        assert!(ignores_key_order(&opts(false)));
2531        saved.ignore_key_order = false;
2532        saved.save(&dir).unwrap();
2533        assert!(!ignores_key_order(&opts(false)));
2534        assert!(ignores_key_order(&opts(true)));
2535        std::fs::remove_dir_all(&dir).unwrap();
2536    }
2537
2538    #[test]
2539    fn node_gets_the_strip_types_flag_only_where_it_needs_it() {
2540        use crate::doctor::Version;
2541        for (major, minor, patch) in [(22, 6, 0), (22, 14, 0), (22, 17, 1), (23, 0, 0), (23, 5, 9)]
2542        {
2543            assert!(
2544                needs_strip_types_flag(Version(major, minor, patch)),
2545                "{major}.{minor}.{patch}"
2546            );
2547        }
2548        // Before 22.6 the flag does not exist (doctor asks for 22.6); from 22.18 and 23.6 Node
2549        // strips types by default.
2550        for (major, minor, patch) in [
2551            (22, 5, 9),
2552            (22, 18, 0),
2553            (22, 20, 0),
2554            (23, 6, 0),
2555            (24, 13, 1),
2556            (25, 0, 0),
2557        ] {
2558            assert!(
2559                !needs_strip_types_flag(Version(major, minor, patch)),
2560                "{major}.{minor}.{patch}"
2561            );
2562        }
2563    }
2564
2565    #[test]
2566    fn the_js_codec_keeps_marker_shaped_data_and_typed_arrays() {
2567        let script = format!(
2568            "{CODEC_JS}\n{}",
2569            r#"
2570const assert = (ok, what) => { if (!ok) { console.error(what); process.exit(1) } }
2571const round = v => dec(JSON.parse(JSON.stringify(enc(v))))
2572const plain = [{ $date: '2024-01-01T00:00:00.000Z' }, { $undefined: true }, { $bigint: '7' }, { $object: 1 }]
2573for (const v of plain) assert(JSON.stringify(round(v)) === JSON.stringify(v), 'plain ' + JSON.stringify(v))
2574const wide = dec({ $date: '2024-01-01T00:00:00.000Z', tz: 'UTC' })
2575assert(wide.tz === 'UTC' && typeof wide.$date === 'string', 'sibling keys are data')
2576assert(round(new Date(0)) instanceof Date, 'dates still decode')
2577for (const T of [Float64Array, Float32Array, Int32Array, Uint8ClampedArray, BigInt64Array]) {
2578  const v = T === BigInt64Array ? new T([1n, -2n]) : new T([1, 2])
2579  const back = round(v)
2580  assert(back instanceof T && back.length === 2 && back[1] === v[1], 'typed ' + T.name)
2581}
2582assert(JSON.stringify(enc(new Float64Array([1, 2]))) !== JSON.stringify(enc(new Int32Array([1, 2]))), 'kinds differ')
2583assert(round(new Uint8Array([1])) instanceof Uint8Array, 'bytes stay bytes')
2584"#
2585        );
2586        let Ok(out) = Command::new("node")
2587            .args(["--input-type=module", "-e", &script])
2588            .output()
2589        else {
2590            return;
2591        };
2592        assert!(
2593            out.status.success(),
2594            "{}",
2595            String::from_utf8_lossy(&out.stderr)
2596        );
2597    }
2598
2599    fn f(params: &[(&str, &str)]) -> ExportedFn {
2600        ExportedFn {
2601            name: "f".into(),
2602            file: "a.ts".into(),
2603            line: 1,
2604            params: params
2605                .iter()
2606                .map(|(n, t)| Param {
2607                    name: (*n).into(),
2608                    ts_type: (*t).into(),
2609                    optional: false,
2610                    rest: false,
2611                    ..Default::default()
2612                })
2613                .collect(),
2614            returns: "number".into(),
2615            is_async: false,
2616            is_generator: false,
2617            type_params: Vec::new(),
2618            uses_instanceof: false,
2619            ..Default::default()
2620        }
2621    }
2622
2623    #[test]
2624    fn reads_case_lines_deeper_than_128() {
2625        let deep = format!("{}1{}", "[".repeat(300), "]".repeat(300));
2626        assert!(serde_json::from_str::<Value>(&deep).is_err());
2627        assert!(parse_deep(&deep).is_ok());
2628        assert!(parse_deep("[1] x").is_err());
2629    }
2630
2631    #[test]
2632    fn generates_deterministic_distinct_inputs() {
2633        let a = generate(&f(&[("q", "string"), ("t", "string")]), 50, &[]);
2634        let b = generate(&f(&[("q", "string"), ("t", "string")]), 50, &[]);
2635        assert_eq!(a, b);
2636        assert_eq!(a.len(), 50);
2637        let unique: std::collections::HashSet<String> = a.iter().map(|v| v.to_string()).collect();
2638        assert_eq!(unique.len(), 50);
2639        assert!(
2640            a.iter()
2641                .any(|args| args.to_string().contains('😀') || args.to_string().contains('👍'))
2642        );
2643    }
2644
2645    #[test]
2646    fn generates_values_that_fit_object_types() {
2647        let types = crate::ts::exports::local_types(
2648            "m.ts",
2649            "export interface Edit { readonly range: { start: number, end: number }, readonly text: string }\n",
2650        );
2651        let cases = generate(&f(&[("edits", "readonly Edit[]")]), 60, &types);
2652        let fitting = cases
2653            .iter()
2654            .filter_map(|args| args[0].as_array())
2655            .flatten()
2656            .filter(|e| e["range"]["start"].is_number() || e["range"]["start"].is_object())
2657            .count();
2658        assert!(fitting > 20, "{fitting}");
2659    }
2660
2661    #[test]
2662    fn covers_number_edge_cases() {
2663        let cases = generate(&f(&[("n", "number")]), 18, &[]);
2664        let text = serde_json::to_string(&cases).unwrap();
2665        assert!(text.contains("NaN") && text.contains("-0"));
2666    }
2667
2668    #[test]
2669    fn run_reports_missing_program_clearly() {
2670        let program = "rust-anything-nonexistent-build-tool-498";
2671        let err = run(&mut Command::new(program), "cargo build").unwrap_err();
2672        let msg = format!("{err:#}");
2673        assert!(
2674            msg.contains(&format!("`{program}` not found on PATH")),
2675            "{msg}"
2676        );
2677        assert!(msg.contains("rust-anything doctor"), "{msg}");
2678        assert!(!msg.contains("os error"), "{msg}");
2679    }
2680}
2681
2682#[cfg(test)]
2683mod verdict_tests {
2684    use super::*;
2685
2686    fn row(name: &str, speedup: f64) -> BenchRow {
2687        BenchRow {
2688            name: name.into(),
2689            cases: 1,
2690            original_ns: speedup,
2691            rust_ns: 1.0,
2692            speedup,
2693            failing: false,
2694        }
2695    }
2696
2697    #[test]
2698    fn functions_that_do_not_match_are_left_out_of_the_verdict() {
2699        // The numbers in #341: `count` is ported, `rangeOf` and `words` still panic.
2700        let failing = |name, speedup| BenchRow {
2701            failing: true,
2702            ..row(name, speedup)
2703        };
2704        let v = verdict(
2705            &[
2706                failing("rangeOf", 0.0012),
2707                failing("words", 0.0058),
2708                row("count", 0.11),
2709            ],
2710            crate::lang::Lang::Ts,
2711        );
2712        assert_eq!(v.left_out, ["rangeOf", "words"]);
2713        assert!((v.speedup - 0.11).abs() < 1e-9, "{v:?}");
2714        assert_eq!(v.slower, ["count"]);
2715
2716        let none = verdict(&[failing("words", 0.0058)], crate::lang::Lang::Ts);
2717        assert!(
2718            none.advice
2719                .starts_with("Nothing to compare: no function matches")
2720        );
2721        assert!((none.speedup - 1.0).abs() < 1e-9);
2722    }
2723
2724    #[test]
2725    fn advice_follows_the_numbers() {
2726        let ts = crate::lang::Lang::Ts;
2727        assert!(
2728            verdict(&[row("a", 3.0), row("b", 2.0)], ts)
2729                .advice
2730                .starts_with("Ship it: every")
2731        );
2732        assert!(
2733            verdict(&[row("a", 3.0), row("b", 1.0)], ts)
2734                .advice
2735                .starts_with("Ship it: no function")
2736        );
2737        let mixed = verdict(&[row("a", 4.0), row("b", 0.5)], ts);
2738        assert!(mixed.advice.contains("Keep the slower ones") && mixed.advice.ends_with("b."));
2739        assert!(
2740            verdict(&[row("a", 0.2), row("b", 0.3)], ts)
2741                .advice
2742                .starts_with("Do not ship")
2743        );
2744        assert!(
2745            verdict(&[row("a", 0.5)], crate::lang::Lang::C)
2746                .advice
2747                .starts_with("No call overhead")
2748        );
2749    }
2750
2751    #[test]
2752    fn speed_phrase_formats_faster_and_slower() {
2753        assert_eq!(speed_phrase(31.42), "31.4x faster");
2754        assert_eq!(speed_phrase(1.2), "1.2x faster");
2755        assert_eq!(speed_phrase(1.04), "1.04x faster");
2756        assert_eq!(speed_phrase(0.97), "1.03x slower");
2757        assert_eq!(speed_phrase(0.96), "1.04x slower");
2758        assert_eq!(speed_phrase(0.9), "1.1x slower");
2759        assert_eq!(speed_phrase(0.5), "2.0x slower");
2760        assert_eq!(speed_phrase(0.15), "6.7x slower");
2761        assert_eq!(speed_phrase(0.12), "8.3x slower");
2762    }
2763}
2764
2765/// Parses one case line: recorded values (a pretty-printer's document trees) nest deeper than
2766/// serde_json's default limit of 128.
2767pub(crate) fn parse_deep(text: &str) -> serde_json::Result<Value> {
2768    let mut de = serde_json::Deserializer::from_str(text);
2769    de.disable_recursion_limit();
2770    let value = Value::deserialize(&mut de)?;
2771    de.end()?;
2772    Ok(value)
2773}