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