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