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