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