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 std::collections::BTreeMap;
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use anyhow::{Context, Result, bail};
13use serde::{Deserialize, Serialize};
14use serde_json::{Value, json};
15
16use crate::bridge::{Kind, Manifest, RType, param_type};
17use crate::ts::exports::LocalType;
18use crate::ts::shape::{self, Shape};
19
20pub const CASES: &str = "cases.jsonl";
21const WORK_DIR: &str = ".rust-anything";
22
23/// Strings that break naive ports: empty, case, whitespace, non-ASCII, astral, combining.
24const STRINGS: &[&str] = &[
25    "",
26    "a",
27    "ab",
28    "abc",
29    "hello",
30    "hello world",
31    "Hello World",
32    "HELLO",
33    "  padded  ",
34    "a.b.c",
35    "ns:key.path",
36    "a:b:c",
37    ":",
38    ".leading",
39    "trailing.",
40    "a..b",
41    "src/a/b.ts",
42    "./x/**/*.json",
43    "key_name-1",
44    "{name} has {count} items",
45    "line1\nline2",
46    "tab\tseparated",
47    "ünïcödé",
48    "straße",
49    "İstanbul",
50    "ΣΊΣΥΦΟΣ",
51    "日本語のテキスト",
52    "emoji 👍🏽 mix",
53    "😀",
54    "a😀b😀c",
55    "e\u{301}",
56    "\u{FEFF}bom",
57];
58const JSON_VALUES: &str =
59    r#"[null, true, 0, "x", [], {}, {"a": "b"}, {"a": {"b": "c"}}, ["a", 1]]"#;
60
61#[derive(Debug, Serialize)]
62pub struct RecordOutcome {
63    pub path: PathBuf,
64    pub cases: usize,
65    pub errors: usize,
66    /// Cases from the semantic traps (added to the generated ones for every function).
67    pub traps: usize,
68    pub per_function: BTreeMap<String, usize>,
69    /// Functions in files that use regexes: their string parameters also got the regex traps.
70    #[serde(skip_serializing_if = "Vec::is_empty")]
71    pub regex_functions: Vec<String>,
72}
73
74#[derive(Debug, Serialize, Deserialize)]
75pub struct DiffOutcome {
76    pub total: usize,
77    pub passed: usize,
78    pub failed: usize,
79    /// Exports the Rust module does not provide.
80    pub missing: Vec<String>,
81    /// The first mismatches: `{ fn, args, expected, actual }`.
82    pub mismatches: Vec<Value>,
83}
84
85pub struct RecordOptions<'a> {
86    pub crate_dir: &'a Path,
87    /// Generated cases per function.
88    pub count: usize,
89    /// Extra cases, one `{"fn": name, "args": [...]}` JSON object per line.
90    pub inputs: Option<&'a Path>,
91    /// Import the original from this JS module instead of the TS source files.
92    pub module: Option<&'a Path>,
93    /// Resolve npm packages the original imports from this folder's `node_modules`.
94    pub resolve_from: Option<&'a Path>,
95    pub node_args: &'a [String],
96}
97
98pub fn record(opts: &RecordOptions) -> Result<RecordOutcome> {
99    let manifest = Manifest::load(opts.crate_dir)?;
100    let mut cases: Vec<Value> = Vec::new();
101    let module_for = |file: &str| -> Result<String> {
102        let path = match opts.module {
103            Some(m) => m
104                .canonicalize()
105                .with_context(|| format!("resolving {}", m.display()))?,
106            None => manifest.root.join(file),
107        };
108        Ok(path.to_string_lossy().into_owned())
109    };
110    let mut scopes: BTreeMap<String, Vec<LocalType>> = BTreeMap::new();
111    let mut regex_files: BTreeMap<String, bool> = BTreeMap::new();
112    let mut regex_functions = Vec::new();
113    let mut traps = 0;
114    for f in &manifest.exports {
115        let module = module_for(&f.file)?;
116        if !scopes.contains_key(&f.file) {
117            let text = std::fs::read_to_string(manifest.root.join(&f.file)).unwrap_or_default();
118            regex_files.insert(
119                f.file.clone(),
120                crate::risks::uses_regex(manifest.language, &text),
121            );
122            scopes.insert(
123                f.file.clone(),
124                crate::bridge::types_in_scope(&manifest.root, &f.file, &text),
125            );
126        }
127        let regex = regex_files[&f.file];
128        if regex && f.params.iter().any(|p| param_type(p) == RType::Str) {
129            regex_functions.push(f.name.clone());
130        }
131        let types = &scopes[&f.file];
132        let mut all = generate(f, opts.count, types);
133        let mut seen: std::collections::HashSet<String> = all
134            .iter()
135            .map(|a| serde_json::to_string(a).unwrap_or_default())
136            .collect();
137        let base: Vec<Value> = all
138            .first()
139            .and_then(Value::as_array)
140            .cloned()
141            .unwrap_or_default();
142        for args in trap_args(&f.params, &base, regex) {
143            let args = Value::Array(args);
144            if seen.insert(serde_json::to_string(&args).unwrap_or_default()) {
145                all.push(args);
146                traps += 1;
147            }
148        }
149        for (i, mut args) in all.into_iter().enumerate() {
150            // Python callers pass ints where floats are expected, and int-ness can leak into
151            // results: every fourth case passes integral `number` arguments as ints.
152            if manifest.language == crate::lang::Lang::Python && i % 4 == 3 {
153                intify(&f.params, &mut args);
154            }
155            let mut case = json!({ "fn": f.name, "module": module, "args": args });
156            split_keyword_only(&f.params, &mut case);
157            cases.push(case);
158        }
159    }
160    for class in &manifest.classes {
161        let module = module_for(&class.file)?;
162        let text = std::fs::read_to_string(manifest.root.join(&class.file)).unwrap_or_default();
163        let types = crate::bridge::types_in_scope(&manifest.root, &class.file, &text);
164        for mut scenario in scenarios(class, opts.count.max(20), &types) {
165            scenario["module"] = Value::String(module.clone());
166            cases.push(scenario);
167        }
168    }
169    if let Some(path) = opts.inputs {
170        let text =
171            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
172        for (i, line) in text
173            .lines()
174            .enumerate()
175            .filter(|(_, l)| !l.trim().is_empty())
176        {
177            let mut case: Value = serde_json::from_str(line).with_context(|| {
178                format!(
179                    "{}:{} (values use the record codec: {{\"$undefined\": true}}, {{\"$num\": \"NaN\"}}, \
180                     and {{\"$utf16\": [code units]}} for strings with lone surrogates)",
181                    path.display(),
182                    i + 1
183                )
184            })?;
185            if let Some(class) = case["class"].as_str() {
186                let Some(c) = manifest.classes.iter().find(|c| c.name == class) else {
187                    bail!(
188                        "{}:{}: `{class}` is not a ported class of this unit",
189                        path.display(),
190                        i + 1
191                    );
192                };
193                case["module"] = Value::String(module_for(&c.file)?);
194                cases.push(case);
195                continue;
196            }
197            let name = case["fn"].as_str().unwrap_or_default().to_string();
198            let Some(f) = manifest.exports.iter().find(|f| f.name == name) else {
199                bail!(
200                    "{}:{}: `{name}` is not an export of this unit",
201                    path.display(),
202                    i + 1
203                );
204            };
205            case["module"] = Value::String(module_for(&f.file)?);
206            cases.push(case);
207        }
208    }
209
210    let out = if manifest.language == crate::lang::Lang::Python {
211        crate::harness_py::record(opts.crate_dir, &cases)?
212    } else if manifest.kind == Kind::CAbi {
213        crate::harness_c::record(opts.crate_dir, &manifest, &cases)?
214    } else if manifest.language == crate::lang::Lang::Go {
215        crate::harness_go::record(opts.crate_dir, &manifest, &cases)?
216    } else if manifest.language == crate::lang::Lang::Ruby {
217        crate::harness_ruby::record(opts.crate_dir, &manifest, &cases)?
218    } else if manifest.language == crate::lang::Lang::Java {
219        crate::harness_java::record(opts.crate_dir, &manifest, &cases)?
220    } else {
221        record_node(opts, &manifest, &cases)?
222    };
223    let text = std::fs::read_to_string(&out)?;
224    let mut per_function = BTreeMap::new();
225    let mut errors = 0;
226    let mut count = 0;
227    for line in text.lines().filter(|l| !l.is_empty()) {
228        let case: Value = serde_json::from_str(line)?;
229        count += 1;
230        let class_error = case["results"]
231            .as_array()
232            .is_some_and(|r| r.iter().any(|x| x.get("error").is_some()));
233        errors +=
234            usize::from(case.get("error").is_some() || case.get("panic").is_some() || class_error);
235        let name = case["fn"]
236            .as_str()
237            .or_else(|| case["class"].as_str())
238            .unwrap_or_default();
239        *per_function.entry(name.to_string()).or_default() += 1;
240    }
241    Ok(RecordOutcome {
242        path: out,
243        cases: count,
244        errors,
245        traps,
246        per_function,
247        regex_functions,
248    })
249}
250
251/// Runs the recorded inputs through Node: the original TS/JS, with the resolve hook.
252fn record_node(opts: &RecordOptions, manifest: &Manifest, cases: &[Value]) -> Result<PathBuf> {
253    let work = opts.crate_dir.join(WORK_DIR);
254    std::fs::create_dir_all(&work)?;
255    let inputs_path = work.join("inputs.json");
256    std::fs::write(&inputs_path, serde_json::to_string(cases)?)?;
257    let script = work.join("record.mjs");
258    std::fs::write(&script, format!("{CODEC_JS}\n{RECORD_JS}"))?;
259    let out = opts.crate_dir.join(CASES);
260    // TS sources often import the way bundlers resolve (`./errors`, `./types`): a resolve hook
261    // lets Node follow them, so the original runs as it is.
262    std::fs::write(work.join("resolve.mjs"), RESOLVE_JS)?;
263    std::fs::write(work.join("register.mjs"), REGISTER_JS)?;
264    let register = work.canonicalize()?.join("register.mjs");
265    let mut node_args = vec![format!("--import={}", file_url(&register))];
266    node_args.extend(opts.node_args.iter().cloned());
267    let aliases = alias_env(manifest);
268    let mut cmd = Command::new("node");
269    cmd.args(&node_args)
270        .arg(&script)
271        .arg(&inputs_path)
272        .arg(&out)
273        .env("RUST_ANYTHING_PATHS", &aliases)
274        .env("RUST_ANYTHING_WORKSPACE", workspace_env(manifest));
275    if let Some(dir) = opts.resolve_from {
276        let dir = dir
277            .canonicalize()
278            .with_context(|| format!("resolving {}", dir.display()))?;
279        cmd.env("RUST_ANYTHING_RESOLVE_FROM", dir);
280    }
281    if let Err(error) = run(&mut cmd, "node") {
282        // Enums and parameter properties need Node to transform TS, not only strip types.
283        if !format!("{error:#}").contains("ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX") {
284            return Err(error);
285        }
286        let mut retry = Command::new("node");
287        retry
288            .arg("--experimental-transform-types")
289            .arg("--no-warnings=ExperimentalWarning")
290            .args(&node_args)
291            .arg(&script)
292            .arg(&inputs_path)
293            .arg(&out)
294            .env("RUST_ANYTHING_PATHS", &aliases)
295            .env("RUST_ANYTHING_WORKSPACE", workspace_env(manifest));
296        if let Some(dir) = opts.resolve_from {
297            retry.env("RUST_ANYTHING_RESOLVE_FROM", dir.canonicalize()?);
298        }
299        run(&mut retry, "node --experimental-transform-types")?;
300    }
301
302    Ok(out)
303}
304
305pub fn build(crate_dir: &Path) -> Result<PathBuf> {
306    let manifest = Manifest::load(crate_dir)?;
307    match manifest.kind {
308        Kind::Pyo3 => crate::harness_py::build(crate_dir, &manifest),
309        Kind::Ffi if manifest.language == crate::lang::Lang::Ruby => {
310            crate::harness_ruby::build(crate_dir, &manifest)
311        }
312        Kind::CAbi | Kind::Ffi => crate::harness_c::build(crate_dir, &manifest),
313        Kind::Napi => {
314            let target = crate_dir.join("target");
315            run(
316                Command::new("cargo")
317                    .args(["build", "--release", "--manifest-path"])
318                    .arg(crate_dir.join("Cargo.toml"))
319                    .env("CARGO_TARGET_DIR", &target),
320                "cargo build",
321            )?;
322            let lib = manifest.lib_name();
323            let release = target.join("release");
324            let built = [
325                format!("lib{lib}.so"),
326                format!("lib{lib}.dylib"),
327                format!("{lib}.dll"),
328            ]
329            .iter()
330            .map(|name| release.join(name))
331            .find(|p| p.exists())
332            .with_context(|| format!("no native library for `{lib}` in {}", release.display()))?;
333            let artifact = crate_dir.join(format!("{lib}.node"));
334            std::fs::copy(&built, &artifact)?;
335            Ok(artifact)
336        }
337        Kind::Wasm => {
338            let target = crate_dir.join("target");
339            run(
340                Command::new("cargo")
341                    .args([
342                        "build",
343                        "--release",
344                        "--target",
345                        "wasm32-unknown-unknown",
346                        "--manifest-path",
347                    ])
348                    .arg(crate_dir.join("Cargo.toml"))
349                    .env("CARGO_TARGET_DIR", &target),
350                "cargo build --target wasm32-unknown-unknown (needs `rustup target add wasm32-unknown-unknown`)",
351            )?;
352            // wasm-bindgen's CLI must match the crate's wasm-bindgen version exactly.
353            let lock = std::fs::read_to_string(crate_dir.join("Cargo.lock")).unwrap_or_default();
354            let wanted = locked_version(&lock, "wasm-bindgen")
355                .context("wasm-bindgen missing from Cargo.lock")?;
356            let installed = Command::new("wasm-bindgen")
357                .arg("--version")
358                .output()
359                .ok()
360                .map(|o| {
361                    String::from_utf8_lossy(&o.stdout)
362                        .trim()
363                        .rsplit(' ')
364                        .next()
365                        .unwrap_or_default()
366                        .to_string()
367                });
368            if installed.as_deref() != Some(wanted.as_str()) {
369                bail!(
370                    "the crate uses wasm-bindgen {wanted}; the CLI must match:\n  cargo install wasm-bindgen-cli --version {wanted} --locked{}",
371                    installed
372                        .map(|v| format!(" (found {v})"))
373                        .unwrap_or_default()
374                );
375            }
376            let lib = manifest.lib_name();
377            let wasm = target
378                .join("wasm32-unknown-unknown/release")
379                .join(format!("{lib}.wasm"));
380            run(
381                Command::new("wasm-bindgen")
382                    .args(["--target", "nodejs", "--out-dir"])
383                    .arg(crate_dir.join("pkg"))
384                    .arg(&wasm),
385                "wasm-bindgen",
386            )?;
387            Ok(crate_dir.join("pkg").join(format!("{lib}.js")))
388        }
389    }
390}
391
392/// Per-function timing of the original against the Rust module.
393/// What `bench` concludes: the geometric-mean speedup and what to do.
394#[derive(Debug, Serialize)]
395pub struct Verdict {
396    pub speedup: f64,
397    pub faster: Vec<String>,
398    pub slower: Vec<String>,
399    pub advice: String,
400}
401
402/// Faster means at least 1.1x, slower below 0.9x; between is a tie (timing noise).
403pub fn verdict(rows: &[BenchRow], lang: crate::lang::Lang) -> Verdict {
404    let faster: Vec<String> = rows
405        .iter()
406        .filter(|r| r.speedup >= 1.1)
407        .map(|r| r.name.clone())
408        .collect();
409    let slower: Vec<String> = rows
410        .iter()
411        .filter(|r| r.speedup < 0.9)
412        .map(|r| r.name.clone())
413        .collect();
414    let speedup = if rows.is_empty() {
415        1.0
416    } else {
417        (rows.iter().map(|r| r.speedup.max(1e-9).ln()).sum::<f64>() / rows.len() as f64).exp()
418    };
419    let advice = if rows.is_empty() {
420        "Nothing to compare: record cases that do not throw first.".to_string()
421    } else if slower.is_empty() && faster.len() == rows.len() {
422        "Ship it: every function is faster in Rust, call included.".to_string()
423    } else if slower.is_empty() {
424        "Ship it: no function is slower in Rust; some only tie.".to_string()
425    } else if lang == crate::lang::Lang::C {
426        // C links the port directly: there is no crossing to blame.
427        format!(
428            "No call overhead in C: these are slower as Rust code. Profile and optimize them, or keep them in C: {}.",
429            slower.join(", ")
430        )
431    } else if speedup >= 1.1 {
432        format!(
433            "Ship the faster functions. Keep the slower ones in the original (`bridge --keep`) or move their callers to Rust too: {}.",
434            slower.join(", ")
435        )
436    } else {
437        "Do not ship this unit for speed: calling across costs more than the work these functions do. \
438         Port a bigger unit (these functions together with their callers), so one call does more work."
439            .to_string()
440    };
441    Verdict {
442        speedup,
443        faster,
444        slower,
445        advice,
446    }
447}
448
449/// Rows from two `{ name: { cases, ns } }` timing maps: the original's and the port's.
450pub fn bench_rows(
451    m: &Manifest,
452    original: &serde_json::Map<String, Value>,
453    rust: &serde_json::Map<String, Value>,
454) -> Vec<BenchRow> {
455    m.exports
456        .iter()
457        .filter_map(|f| {
458            let (old, new) = (original.get(&f.name)?, rust.get(&f.name)?);
459            let (o, n) = (old["ns"].as_f64()?, new["ns"].as_f64()?);
460            Some(BenchRow {
461                name: f.name.clone(),
462                cases: usize::try_from(old["cases"].as_u64().unwrap_or(0)).unwrap_or(0),
463                original_ns: o,
464                rust_ns: n,
465                speedup: o / n,
466            })
467        })
468        .collect()
469}
470
471#[derive(Debug, Serialize, Deserialize)]
472pub struct BenchRow {
473    #[serde(rename = "fn")]
474    pub name: String,
475    pub cases: usize,
476    /// Nanoseconds per call.
477    pub original_ns: f64,
478    pub rust_ns: f64,
479    /// `original_ns / rust_ns`: above 1 means Rust is faster, bridge included.
480    pub speedup: f64,
481}
482
483pub struct BenchOptions<'a> {
484    pub crate_dir: &'a Path,
485    /// Minimum measured time per function and side, in milliseconds.
486    pub min_ms: u64,
487    pub resolve_from: Option<&'a Path>,
488    pub node_args: &'a [String],
489}
490
491/// Times the recorded cases against the original and the built Rust module, bridge included.
492pub fn bench(opts: &BenchOptions) -> Result<Vec<BenchRow>> {
493    let manifest = Manifest::load(opts.crate_dir)?;
494    if manifest.language == crate::lang::Lang::Python {
495        return crate::harness_py::bench(opts.crate_dir, &manifest, opts.min_ms);
496    }
497    if manifest.kind == Kind::CAbi {
498        return crate::harness_c::bench(opts.crate_dir, &manifest, opts.min_ms);
499    }
500    if manifest.language == crate::lang::Lang::Go {
501        return crate::harness_go::bench(opts.crate_dir, &manifest, opts.min_ms);
502    }
503    if manifest.language == crate::lang::Lang::Ruby {
504        return crate::harness_ruby::bench(opts.crate_dir, &manifest, opts.min_ms);
505    }
506    if manifest.language == crate::lang::Lang::Java {
507        return crate::harness_java::bench(opts.crate_dir, &manifest, opts.min_ms);
508    }
509    let cases = opts.crate_dir.join(CASES);
510    if !cases.exists() {
511        bail!(
512            "no {CASES} in {} (run `rust-anything record` first)",
513            opts.crate_dir.display()
514        );
515    }
516    let modules: BTreeMap<String, String> = manifest
517        .exports
518        .iter()
519        .map(|f| {
520            (
521                f.name.clone(),
522                manifest.root.join(&f.file).to_string_lossy().into_owned(),
523            )
524        })
525        .collect();
526    let work = opts.crate_dir.join(WORK_DIR);
527    std::fs::create_dir_all(&work)?;
528    std::fs::write(work.join("resolve.mjs"), RESOLVE_JS)?;
529    std::fs::write(work.join("register.mjs"), REGISTER_JS)?;
530    let class_modules: BTreeMap<String, String> = manifest
531        .classes
532        .iter()
533        .map(|c| {
534            (
535                c.name.clone(),
536                manifest.root.join(&c.file).to_string_lossy().into_owned(),
537            )
538        })
539        .collect();
540    let modules_path = work.join("bench-modules.json");
541    std::fs::write(
542        &modules_path,
543        serde_json::to_string(&json!({ "functions": modules, "classes": class_modules }))?,
544    )?;
545    let script = work.join("bench.mjs");
546    std::fs::write(&script, format!("{CODEC_JS}\n{BENCH_JS}"))?;
547    let out = work.join("bench.json");
548    let native = opts.crate_dir.join("index.cjs").canonicalize()?;
549    let register = work.canonicalize()?.join("register.mjs");
550    let mut cmd = Command::new("node");
551    cmd.arg("--experimental-transform-types")
552        .arg("--no-warnings")
553        .arg(format!("--import={}", file_url(&register)))
554        .args(opts.node_args)
555        .arg(&script)
556        .arg(&modules_path)
557        .arg(&native)
558        .arg(&cases)
559        .arg(&out)
560        .arg(opts.min_ms.to_string())
561        .env("RUST_ANYTHING_PATHS", alias_env(&manifest))
562        .env("RUST_ANYTHING_WORKSPACE", workspace_env(&manifest));
563    if let Some(dir) = opts.resolve_from {
564        cmd.env("RUST_ANYTHING_RESOLVE_FROM", dir.canonicalize()?);
565    }
566    run(&mut cmd, "node")?;
567    Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
568}
569
570pub struct DiffOptions<'a> {
571    pub crate_dir: &'a Path,
572    /// The module to test; defaults to the crate's `index.cjs`.
573    pub module: Option<&'a Path>,
574    /// Compare objects regardless of key order.
575    pub ignore_key_order: bool,
576    pub node_args: &'a [String],
577    /// Floats match within this tolerance; the one saved by `record` when `None`.
578    pub float_tolerance: Option<f64>,
579}
580
581/// The first mismatches a diff reports.
582const SHOWN_MISMATCHES: usize = 20;
583
584pub fn diff(opts: &DiffOptions) -> Result<DiffOutcome> {
585    let mut outcome = diff_exact(opts)?;
586    let saved = Manifest::load(opts.crate_dir)
587        .ok()
588        .and_then(|m| m.float_tolerance);
589    if let Some(t) = opts.float_tolerance.or(saved) {
590        outcome = crate::tolerance::apply(outcome, crate::tolerance::check(t)?);
591    }
592    outcome.mismatches.truncate(SHOWN_MISMATCHES);
593    Ok(outcome)
594}
595
596fn diff_exact(opts: &DiffOptions) -> Result<DiffOutcome> {
597    if let Ok(manifest) = Manifest::load(opts.crate_dir)
598        && manifest.language == crate::lang::Lang::Python
599        && opts.module.is_none()
600    {
601        return crate::harness_py::diff(opts.crate_dir, &manifest, opts.ignore_key_order);
602    }
603    if let Ok(manifest) = Manifest::load(opts.crate_dir)
604        && manifest.kind == Kind::CAbi
605        && opts.module.is_none()
606    {
607        return crate::harness_c::diff(opts.crate_dir, &manifest);
608    }
609    if let Ok(manifest) = Manifest::load(opts.crate_dir)
610        && manifest.language == crate::lang::Lang::Go
611        && opts.module.is_none()
612    {
613        return crate::harness_go::diff(opts.crate_dir, &manifest);
614    }
615    if let Ok(manifest) = Manifest::load(opts.crate_dir)
616        && manifest.language == crate::lang::Lang::Ruby
617        && opts.module.is_none()
618    {
619        return crate::harness_ruby::diff(opts.crate_dir, &manifest);
620    }
621    if let Ok(manifest) = Manifest::load(opts.crate_dir)
622        && manifest.language == crate::lang::Lang::Java
623        && opts.module.is_none()
624    {
625        return crate::harness_java::diff(opts.crate_dir, &manifest);
626    }
627    let cases = opts.crate_dir.join(CASES);
628    if !cases.exists() {
629        bail!(
630            "no {CASES} in {} (run `rust-anything record` first)",
631            opts.crate_dir.display()
632        );
633    }
634    let module = match opts.module {
635        Some(m) => m.to_path_buf(),
636        None => opts.crate_dir.join("index.cjs"),
637    };
638    let module = module
639        .canonicalize()
640        .with_context(|| format!("resolving {}", module.display()))?;
641    let work = opts.crate_dir.join(WORK_DIR);
642    std::fs::create_dir_all(&work)?;
643    let script = work.join("diff.mjs");
644    std::fs::write(&script, format!("{CODEC_JS}\n{DIFF_JS}"))?;
645    let out = work.join("diff.json");
646    let flag = if opts.ignore_key_order {
647        "sort"
648    } else {
649        "keep"
650    };
651    run_node(
652        opts.node_args,
653        &script,
654        &[
655            module.as_os_str(),
656            cases.as_os_str(),
657            out.as_os_str(),
658            flag.as_ref(),
659        ],
660    )?;
661    let text = std::fs::read_to_string(&out)?;
662    Ok(serde_json::from_str(&text)?)
663}
664
665/// The version of `package` in a Cargo.lock.
666fn locked_version(lock: &str, package: &str) -> Option<String> {
667    let mut lines = lock.lines();
668    while let Some(line) = lines.next() {
669        if line.trim() == format!("name = \"{package}\"") {
670            let version = lines
671                .next()?
672                .trim()
673                .strip_prefix("version = \"")?
674                .strip_suffix('"')?;
675            return Some(version.to_string());
676        }
677    }
678    None
679}
680
681/// Deterministic inputs for one function: edge cases first, then seeded random mixes.
682pub fn generate(
683    f: &crate::ts::exports::ExportedFn,
684    count: usize,
685    types: &[LocalType],
686) -> Vec<Value> {
687    let mut rng = Rng::new(f.name.bytes().fold(0x9E37_79B9_7F4A_7C15, |h, b| {
688        (h ^ u64::from(b)).wrapping_mul(0x100_0000_01B3)
689    }));
690    let mut seen = std::collections::HashSet::new();
691    let mut out = Vec::new();
692    let mut attempts = 0;
693    while out.len() < count && attempts < count * 20 {
694        attempts += 1;
695        let args = args_for(&f.params, types, &mut rng);
696        let key = serde_json::to_string(&args).unwrap_or_default();
697        if seen.insert(key) {
698            out.push(Value::Array(args));
699        }
700    }
701    out
702}
703
704/// The semantic traps for a value of type `t`: what most often behaves differently once ported
705/// (string length and case, signed division and overflow, float printing, map and sort order).
706fn trap_values(t: &RType) -> Vec<Value> {
707    match t {
708        RType::Str => crate::app::STRING_TRAPS
709            .iter()
710            .chain(["ΣΊΣΥΦΟΣ", "a😀b", "\u{FEFF}bom"].iter())
711            .map(|s| json!(s))
712            .collect(),
713        RType::Int => [
714            -7,
715            -1,
716            0,
717            2_147_483_648,
718            -2_147_483_649,
719            9_007_199_254_740_993,
720            i64::MAX,
721            i64::MIN,
722        ]
723        .iter()
724        .map(|n| json!(n))
725        .collect(),
726        RType::F64 => {
727            let mut out: Vec<Value> = [
728                -7.5,
729                0.1,
730                0.30000000000000004,
731                1e21,
732                1e-7,
733                5e-324,
734                1.797_693_134_862_315_7e308,
735                9_007_199_254_740_992.0,
736            ]
737            .iter()
738            .map(|n| json!(n))
739            .collect();
740            out.push(json!({ "$num": "-0" }));
741            out
742        }
743        RType::Vec(inner) => match inner.as_ref() {
744            RType::Str => vec![json!([]), json!(["b", "a", "B", "é", "10", "9", "a"])],
745            RType::Int => vec![json!([]), json!([-7, 3, 0, i64::MAX, -1])],
746            RType::F64 => vec![json!([]), json!([0.1, 0.2, -0.5, 1e21])],
747            _ => vec![json!([])],
748        },
749        RType::Opt(inner) => {
750            let mut out = vec![json!({ "$undefined": true })];
751            out.extend(trap_values(inner));
752            out
753        }
754        RType::Json => crate::app::JSON_TRAPS
755            .iter()
756            .filter_map(|t| serde_json::from_str(t).ok())
757            .chain([json!([3, 1, 2]), json!({})])
758            .collect(),
759        RType::Bool | RType::Unit => Vec::new(),
760    }
761}
762
763/// Every trap value in every parameter, one at a time, the other arguments as in `base`.
764/// Structured parameters (objects with a known shape) are left as generated.
765pub fn trap_args(
766    params: &[crate::ts::exports::Param],
767    base: &[Value],
768    regex: bool,
769) -> Vec<Vec<Value>> {
770    let mut out = Vec::new();
771    if base.len() < params.iter().filter(|p| !p.rest).count() {
772        return out;
773    }
774    for (i, p) in params.iter().enumerate() {
775        if p.rest || i >= base.len() {
776            continue;
777        }
778        let t = param_type(p);
779        let structured = t.contains_json() && !matches!(t, RType::Json);
780        let any = matches!(p.ts_type.trim(), "any" | "unknown" | "object" | "Object");
781        if structured || (matches!(t, RType::Json) && !any) {
782            continue;
783        }
784        let mut values = trap_values(&t);
785        if regex && t == RType::Str {
786            values.extend(crate::risks::REGEX_TRAPS.iter().map(|s| json!(s)));
787        }
788        for v in values {
789            if base[i] != v {
790                let mut args = base.to_vec();
791                args[i] = v;
792                out.push(args);
793            }
794        }
795    }
796    out
797}
798
799/// One argument list for `params`: values that fit, edge cases, and sometimes omitted optionals.
800fn args_for(
801    params: &[crate::ts::exports::Param],
802    types: &[LocalType],
803    rng: &mut Rng,
804) -> Vec<Value> {
805    let mut args: Vec<Value> = Vec::new();
806    for p in params {
807        let t = param_type(p);
808        // Structured parameters: values that fit the TS type, and now and then a value
809        // that does not, so error paths get recorded too.
810        let structured = |rng: &mut Rng| {
811            if rng.below(100) < 15 {
812                value(&RType::Json, rng)
813            } else {
814                shaped(&shape::parse(&p.ts_type), types, rng, 0)
815            }
816        };
817        if p.rest {
818            let inner = match t {
819                RType::Vec(inner) => *inner,
820                other => other,
821            };
822            for _ in 0..rng.below(3) {
823                args.push(value(&inner, rng));
824            }
825        } else if t.contains_json() {
826            let v = structured(rng);
827            args.push(if p.optional && rng.below(5) == 0 {
828                json!({ "$undefined": true })
829            } else {
830                v
831            });
832        } else {
833            args.push(value(&t, rng));
834        }
835    }
836    // Search-like functions rarely hit on random text: often derive one string from another.
837    let strings: Vec<usize> = (0..args.len()).filter(|&i| args[i].is_string()).collect();
838    if strings.len() >= 2 && rng.below(10) < 5 {
839        let from = strings[rng.below(strings.len())];
840        let to = strings[rng.below(strings.len())];
841        if from != to {
842            let source: Vec<char> = args[from].as_str().unwrap_or_default().chars().collect();
843            if !source.is_empty() {
844                let start = rng.below(source.len());
845                let end = start + 1 + rng.below(source.len() - start);
846                let mut piece: String = source[start..end].iter().collect();
847                if rng.below(4) == 0 {
848                    piece = piece.to_uppercase();
849                }
850                args[to] = Value::String(piece);
851            }
852        }
853    }
854    // Trailing optional arguments: sometimes omit them, the way JS callers do.
855    while args.last().is_some_and(|a| a.get("$undefined").is_some()) && rng.below(2) == 0 {
856        args.pop();
857    }
858    args
859}
860
861/// Class scenarios: construct, then call a random sequence of methods.
862pub fn scenarios(
863    class: &crate::ts::exports::ExportedClass,
864    count: usize,
865    types: &[LocalType],
866) -> Vec<Value> {
867    let mut rng = Rng::new(class.name.bytes().fold(0x2545_F491_4F6C_DD1D, |h, b| {
868        (h ^ u64::from(b)).wrapping_mul(0x100_0000_01B3)
869    }));
870    (0..count)
871        .map(|_| {
872            let ctor = args_for(&class.constructor, types, &mut rng);
873            let steps = if class.methods.is_empty() {
874                0
875            } else {
876                1 + rng.below(12)
877            };
878            // Stateful classes need calls that meet again (`set(k)` then `get(k)`): string
879            // arguments often reuse a string seen earlier in the scenario.
880            let mut seen: Vec<Value> = ctor.iter().filter(|v| v.is_string()).cloned().collect();
881            let calls: Vec<Value> = (0..steps)
882                .map(|_| {
883                    let m = &class.methods[rng.below(class.methods.len())];
884                    let mut args = args_for(&m.params, types, &mut rng);
885                    for arg in &mut args {
886                        if arg.is_string() {
887                            if !seen.is_empty() && rng.below(2) == 0 {
888                                *arg = seen[rng.below(seen.len())].clone();
889                            } else {
890                                seen.push(arg.clone());
891                            }
892                        }
893                    }
894                    json!({ "method": m.name, "args": args })
895                })
896                .collect();
897            json!({ "class": class.name, "ctor": ctor, "calls": calls })
898        })
899        .collect()
900}
901
902/// Property names for generated objects: plain, nested-looking, integer-like (JS orders those
903/// first), non-ASCII.
904const KEYS: &[&str] = &[
905    "a", "b", "nav", "home", "title", "2", "10", "ünï", "😀", "a.b",
906];
907
908/// A value that fits a TS shape. Named types resolve against `types`; recursion stops at a depth.
909fn shaped(s: &Shape, types: &[LocalType], rng: &mut Rng, depth: usize) -> Value {
910    match s {
911        Shape::Str => value(&RType::Str, rng),
912        Shape::Num => value(&RType::F64, rng),
913        Shape::Int => value(&RType::Int, rng),
914        Shape::Bool => value(&RType::Bool, rng),
915        Shape::Null => Value::Null,
916        Shape::Undefined => json!({ "$undefined": true }),
917        Shape::LitStr(text) => Value::String(text.clone()),
918        Shape::LitNum(n) => json!(n),
919        Shape::LitBool(b) => Value::Bool(*b),
920        Shape::Union(items) if !items.is_empty() => {
921            shaped(&items[rng.below(items.len())], types, rng, depth)
922        }
923        Shape::Array(item) if depth < 6 => Value::Array(
924            (0..rng.below(4))
925                .map(|_| shaped(item, types, rng, depth + 1))
926                .collect(),
927        ),
928        Shape::Tuple(items) => Value::Array(
929            items
930                .iter()
931                .map(|i| shaped(i, types, rng, depth + 1))
932                .collect(),
933        ),
934        Shape::Object(props, index) if depth < 6 => {
935            let mut out = serde_json::Map::new();
936            for (name, optional, prop) in props {
937                if *optional && rng.below(4) == 0 {
938                    continue;
939                }
940                out.insert(name.clone(), shaped(prop, types, rng, depth + 1));
941            }
942            if let Some(item) = index {
943                for _ in 0..rng.below(4) {
944                    out.insert(
945                        KEYS[rng.below(KEYS.len())].to_string(),
946                        shaped(item, types, rng, depth + 1),
947                    );
948                }
949            }
950            Value::Object(out)
951        }
952        Shape::Ref(name, args) if depth < 6 => {
953            shaped(&shape::resolve(name, args, types), types, rng, depth + 1)
954        }
955        Shape::Any => value(&RType::Json, rng),
956        // Too deep, or empty: a leaf ends the recursion.
957        _ => Value::Null,
958    }
959}
960
961fn value(t: &RType, rng: &mut Rng) -> Value {
962    match t {
963        RType::Str => {
964            let a = STRINGS[rng.below(STRINGS.len())];
965            if rng.below(5) == 0 {
966                Value::String(format!("{a}{}", STRINGS[rng.below(STRINGS.len())]))
967            } else {
968                Value::String(a.into())
969            }
970        }
971        RType::Int => {
972            // Small, signed, and the edges of 32 and 64 bits.
973            let n: [i64; 12] = [
974                0,
975                1,
976                -1,
977                2,
978                7,
979                42,
980                100,
981                -100,
982                255,
983                i64::from(i32::MAX),
984                i64::from(i32::MIN),
985                i64::MAX,
986            ];
987            json!(n[rng.below(n.len())])
988        }
989        RType::F64 => {
990            let n = [
991                0.0,
992                1.0,
993                -1.0,
994                2.0,
995                3.0,
996                10.0,
997                0.5,
998                -2.5,
999                42.0,
1000                100.0,
1001                1000.0,
1002                1e6,
1003                2_147_483_648.0,
1004                9_007_199_254_740_992.0,
1005            ];
1006            match rng.below(n.len() + 4) {
1007                i if i < n.len() => json!(n[i]),
1008                i if i == n.len() => json!({ "$num": "-0" }),
1009                i if i == n.len() + 1 => json!({ "$num": "NaN" }),
1010                i if i == n.len() + 2 => json!({ "$num": "Infinity" }),
1011                _ => json!({ "$num": "-Infinity" }),
1012            }
1013        }
1014        RType::Bool => Value::Bool(rng.below(2) == 0),
1015        RType::Unit => json!({ "$undefined": true }),
1016        RType::Vec(inner) => Value::Array((0..rng.below(4)).map(|_| value(inner, rng)).collect()),
1017        RType::Opt(inner) => {
1018            if rng.below(4) == 0 {
1019                json!({ "$undefined": true })
1020            } else {
1021                value(inner, rng)
1022            }
1023        }
1024        RType::Json => {
1025            let values: Vec<Value> = serde_json::from_str(JSON_VALUES).unwrap_or_default();
1026            values
1027                .get(rng.below(values.len().max(1)))
1028                .cloned()
1029                .unwrap_or(Value::Null)
1030        }
1031    }
1032}
1033
1034/// xorshift64*: deterministic, so a recording is reproducible.
1035struct Rng(u64);
1036
1037impl Rng {
1038    fn new(seed: u64) -> Self {
1039        Self(seed | 1)
1040    }
1041
1042    fn below(&mut self, n: usize) -> usize {
1043        if n == 0 {
1044            return 0;
1045        }
1046        self.0 ^= self.0 >> 12;
1047        self.0 ^= self.0 << 25;
1048        self.0 ^= self.0 >> 27;
1049        let x = self.0.wrapping_mul(0x2545_F491_4F6C_DD1D);
1050        usize::try_from(x >> 33).unwrap_or(0) % n
1051    }
1052}
1053
1054fn run_node(node_args: &[String], script: &Path, args: &[&std::ffi::OsStr]) -> Result<()> {
1055    run(
1056        Command::new("node").args(node_args).arg(script).args(args),
1057        "node",
1058    )
1059}
1060
1061fn run(cmd: &mut Command, what: &str) -> Result<()> {
1062    let output = cmd.output().with_context(|| format!("running {what}"))?;
1063    if !output.status.success() {
1064        let stderr = String::from_utf8_lossy(&output.stderr);
1065        let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
1066        bail!(
1067            "{what} failed ({}):\n{}",
1068            output.status,
1069            tail.into_iter().rev().collect::<Vec<_>>().join("\n")
1070        );
1071    }
1072    Ok(())
1073}
1074
1075/// Python keyword-only parameters (after `*`) are passed by name: they move from `args` into
1076/// `kwargs`, and an omitted (`undefined`) one is left out.
1077/// Integral float arguments of `number` parameters, as ints.
1078fn intify(params: &[crate::ts::exports::Param], args: &mut Value) {
1079    let Some(items) = args.as_array_mut() else {
1080        return;
1081    };
1082    for (p, v) in params.iter().zip(items.iter_mut()) {
1083        if p.ts_type == "number"
1084            && let Some(x) = v.as_f64()
1085            && x.fract() == 0.0
1086            && x.abs() < 1e15
1087            && !(x == 0.0 && x.is_sign_negative())
1088        {
1089            *v = json!(x as i64);
1090        }
1091    }
1092}
1093
1094fn split_keyword_only(params: &[crate::ts::exports::Param], case: &mut Value) {
1095    if !params.iter().any(|p| p.keyword_only) {
1096        return;
1097    }
1098    let Some(args) = case["args"].as_array().cloned() else {
1099        return;
1100    };
1101    let mut positional = Vec::new();
1102    let mut kwargs = serde_json::Map::new();
1103    for (i, value) in args.into_iter().enumerate() {
1104        match params.get(i) {
1105            Some(p) if p.keyword_only => {
1106                if value.get("$undefined").is_none() {
1107                    kwargs.insert(p.name.clone(), value);
1108                }
1109            }
1110            _ => positional.push(value),
1111        }
1112    }
1113    case["args"] = Value::Array(positional);
1114    case["kwargs"] = Value::Object(kwargs);
1115}
1116
1117/// Workspace packages as `{ name: absolute source folder }` for the resolve hook: a monorepo
1118/// imports its own packages by name, and their build output may not exist.
1119fn workspace_env(manifest: &Manifest) -> String {
1120    let packages: BTreeMap<String, String> = crate::ts::discover::discover(&manifest.root)
1121        .map(|ws| {
1122            ws.packages
1123                .into_iter()
1124                .filter(|p| !p.dir.is_empty())
1125                .map(|p| {
1126                    let dir = manifest.root.join(&p.dir);
1127                    let src = if dir.join("src").is_dir() {
1128                        dir.join("src")
1129                    } else {
1130                        dir
1131                    };
1132                    (p.name, src.to_string_lossy().into_owned())
1133                })
1134                .collect()
1135        })
1136        .unwrap_or_default();
1137    serde_json::to_string(&packages).unwrap_or_else(|_| "{}".into())
1138}
1139
1140/// The tsconfig `paths` of the unit's files, as JSON for the resolve hook: `[[pattern, [absolute targets]]]`.
1141fn alias_env(manifest: &Manifest) -> String {
1142    let mut entries: Vec<(String, Vec<String>)> = Vec::new();
1143    let files = manifest
1144        .exports
1145        .iter()
1146        .map(|f| &f.file)
1147        .chain(manifest.classes.iter().map(|c| &c.file));
1148    for file in files {
1149        let dir = file.rsplit_once('/').map_or("", |(d, _)| d);
1150        for (pattern, targets) in
1151            crate::ts::tsconfig::PathAliases::nearest(&manifest.root, dir).entries
1152        {
1153            if entries.iter().all(|(p, _)| *p != pattern) {
1154                let absolute = targets
1155                    .iter()
1156                    .map(|t| manifest.root.join(t).to_string_lossy().into_owned())
1157                    .collect();
1158                entries.push((pattern, absolute));
1159            }
1160        }
1161    }
1162    serde_json::to_string(&entries).unwrap_or_else(|_| "[]".into())
1163}
1164
1165fn file_url(path: &Path) -> String {
1166    let text = path.to_string_lossy().replace('\\', "/");
1167    if text.starts_with('/') {
1168        format!("file://{text}")
1169    } else {
1170        format!("file:///{text}")
1171    }
1172}
1173
1174const REGISTER_JS: &str =
1175    "import { register } from 'node:module'\nregister('./resolve.mjs', import.meta.url)\n";
1176
1177/// Node resolve hook: bundler-style relative imports, and npm packages from
1178/// `RUST_ANYTHING_RESOLVE_FROM` when the source tree has none installed.
1179const RESOLVE_JS: &str = r#"
1180import { existsSync, statSync } from 'node:fs'
1181import { fileURLToPath, pathToFileURL } from 'node:url'
1182
1183const extra = process.env.RUST_ANYTHING_RESOLVE_FROM
1184// tsconfig `paths`: [[pattern, [absolute targets]]], longest prefix first.
1185const aliases = JSON.parse(process.env.RUST_ANYTHING_PATHS || '[]')
1186  .sort(([a], [b]) => b.split('*')[0].length - a.split('*')[0].length)
1187// Workspace packages by name: `@x18n/core` and `@x18n/core/sub` resolve to source.
1188const workspace = JSON.parse(process.env.RUST_ANYTHING_WORKSPACE || '{}')
1189const workspaceTargets = (specifier) => {
1190  for (const [name, src] of Object.entries(workspace)) {
1191    if (specifier === name)
1192      return [`${src}/index`]
1193    if (specifier.startsWith(`${name}/`))
1194      return [`${src}/${specifier.slice(name.length + 1)}`, `${src}/${specifier.slice(name.length + 1)}/index`]
1195  }
1196  return []
1197}
1198const aliasTargets = (specifier) => {
1199  for (const [pattern, targets] of aliases) {
1200    const [prefix, suffix = ''] = pattern.split('*')
1201    const exact = !pattern.includes('*')
1202    if (exact ? specifier === pattern : specifier.startsWith(prefix) && specifier.endsWith(suffix) && specifier.length >= prefix.length + suffix.length) {
1203      const star = exact ? '' : specifier.slice(prefix.length, specifier.length - suffix.length)
1204      return targets.map(t => t.replace('*', star))
1205    }
1206  }
1207  return []
1208}
1209const suffixes = ['.ts', '.tsx', '.mts', '.js', '.mjs', '/index.ts', '/index.mts', '/index.js']
1210const isFile = p => existsSync(p) && statSync(p).isFile()
1211
1212export async function resolve(specifier, context, next) {
1213  // Aliases first: `@/x` is not even a valid package name for Node.
1214  for (const target of [...aliasTargets(specifier), ...workspaceTargets(specifier)]) {
1215    const stem = target.replace(/\.js$/, '')
1216    for (const suffix of ['', ...suffixes]) {
1217      if (isFile(stem + suffix))
1218        return next(pathToFileURL(stem + suffix).href, context)
1219    }
1220  }
1221  try {
1222    return await next(specifier, context)
1223  }
1224  catch (error) {
1225    const missing = error?.code === 'ERR_MODULE_NOT_FOUND' || error?.code === 'ERR_UNSUPPORTED_DIR_IMPORT'
1226    if (!missing || !context.parentURL)
1227      throw error
1228    if (specifier.startsWith('.') || specifier.startsWith('/')) {
1229      const stem = fileURLToPath(new URL(specifier, context.parentURL)).replace(/\.js$/, '')
1230      for (const suffix of suffixes) {
1231        if (isFile(stem + suffix))
1232          return next(pathToFileURL(stem + suffix).href, context)
1233      }
1234    }
1235    else if (extra) {
1236      return next(specifier, { ...context, parentURL: pathToFileURL(`${extra}/`).href })
1237    }
1238    throw error
1239  }
1240}
1241"#;
1242
1243/// Encoding shared by the record, diff and shadow scripts. Lossless for what a JS caller
1244/// can observe: `undefined`, `NaN`, `-0`, BigInt, Map/Set order, key order, lone surrogates.
1245pub const CODEC_JS: &str = r#"
1246const enc = (v, stack = []) => {
1247  if (v === undefined) return { $undefined: true }
1248  if (typeof v === 'number') {
1249    if (Number.isNaN(v)) return { $num: 'NaN' }
1250    if (!Number.isFinite(v)) return { $num: v > 0 ? 'Infinity' : '-Infinity' }
1251    if (Object.is(v, -0)) return { $num: '-0' }
1252    return v
1253  }
1254  // Strings JS split inside a surrogate pair are not valid Unicode: keep their code units.
1255  if (typeof v === 'string' && !v.isWellFormed()) return { $utf16: Array.from({ length: v.length }, (_, i) => v.charCodeAt(i)) }
1256  if (typeof v === 'bigint') return { $bigint: String(v) }
1257  if (typeof v === 'function') return { $function: v.name }
1258  if (typeof v === 'symbol') return { $symbol: String(v.description) }
1259  if (v === null || typeof v !== 'object') return v
1260  if (stack.includes(v)) return { $cycle: true }
1261  const next = [...stack, v]
1262  if (Array.isArray(v)) return v.map(x => enc(x, next))
1263  if (v instanceof Map) return { $map: [...v].map(([k, x]) => [enc(k, next), enc(x, next)]) }
1264  if (v instanceof Set) return { $set: [...v].map(x => enc(x, next)) }
1265  if (v instanceof Date) return { $date: Number.isNaN(v.getTime()) ? 'Invalid' : v.toISOString() }
1266  if (v instanceof RegExp) return { $regexp: String(v) }
1267  if (v instanceof Error) return { $error: v.message }
1268  const out = {}
1269  for (const k of Object.keys(v)) out[k] = enc(v[k], next)
1270  return out
1271}
1272const dec = (v) => {
1273  if (Array.isArray(v)) return v.map(dec)
1274  if (v === null || typeof v !== 'object') return v
1275  if (v.$undefined) return undefined
1276  if ('$num' in v) return Number(v.$num)
1277  if ('$bigint' in v) return BigInt(v.$bigint)
1278  if ('$utf16' in v) return String.fromCharCode(...v.$utf16)
1279  if ('$map' in v) return new Map(v.$map.map(([k, x]) => [dec(k), dec(x)]))
1280  if ('$set' in v) return new Set(v.$set.map(dec))
1281  if ('$date' in v) return new Date(v.$date)
1282  const out = {}
1283  for (const [k, x] of Object.entries(v)) out[k] = dec(x)
1284  return out
1285}
1286const canon = (v, sort) => {
1287  if (Array.isArray(v)) return v.map(x => canon(x, sort))
1288  if (v === null || typeof v !== 'object') return v
1289  const keys = Object.keys(v)
1290  if (sort) keys.sort()
1291  const out = {}
1292  for (const k of keys) out[k] = canon(v[k], sort)
1293  return out
1294}
1295const same = (a, b, sort = false) => JSON.stringify(canon(a, sort)) === JSON.stringify(canon(b, sort))
1296"#;
1297
1298const RECORD_JS: &str = r#"
1299import { readFileSync, writeFileSync } from 'node:fs'
1300import { pathToFileURL } from 'node:url'
1301
1302const [inputsPath, outPath] = process.argv.slice(2)
1303const inputs = JSON.parse(readFileSync(inputsPath, 'utf8'))
1304const modules = new Map()
1305const lines = []
1306// A class scenario: construct, then call each method in turn; every step's result is recorded.
1307const runScenario = async (Class, c) => {
1308  const results = []
1309  let instance
1310  try {
1311    instance = new Class(...c.ctor.map(dec))
1312    results.push({ ok: true })
1313  }
1314  catch (error) {
1315    results.push({ error: String(error?.message ?? error) })
1316    return results
1317  }
1318  for (const call of c.calls) {
1319    try {
1320      results.push({ ok: enc(await instance[call.method](...call.args.map(dec))) })
1321    }
1322    catch (error) {
1323      results.push({ error: String(error?.message ?? error) })
1324    }
1325  }
1326  return results
1327}
1328for (const c of inputs) {
1329  let mod = modules.get(c.module)
1330  if (!mod) {
1331    mod = await import(pathToFileURL(c.module).href)
1332    modules.set(c.module, mod)
1333  }
1334  if (c.class) {
1335    const Class = mod[c.class] ?? mod.default?.[c.class]
1336    if (typeof Class !== 'function') {
1337      console.error(`${c.class} is not a class exported by ${c.module}`)
1338      process.exit(2)
1339    }
1340    lines.push(JSON.stringify({ class: c.class, ctor: c.ctor, calls: c.calls, results: await runScenario(Class, c) }))
1341    continue
1342  }
1343  const fn = mod[c.fn] ?? mod.default?.[c.fn]
1344  if (typeof fn !== 'function') {
1345    console.error(`${c.fn} is not a function exported by ${c.module}`)
1346    process.exit(2)
1347  }
1348  try {
1349    const value = await fn(...c.args.map(dec))
1350    lines.push(JSON.stringify({ fn: c.fn, args: c.args, ok: enc(value) }))
1351  }
1352  catch (error) {
1353    lines.push(JSON.stringify({ fn: c.fn, args: c.args, error: String(error?.message ?? error) }))
1354  }
1355}
1356writeFileSync(outPath, `${lines.join('\n')}\n`)
1357"#;
1358
1359const BENCH_JS: &str = r#"
1360import { readFileSync, writeFileSync } from 'node:fs'
1361import { pathToFileURL } from 'node:url'
1362
1363const [modulesPath, nativePath, casesPath, outPath, minMs] = process.argv.slice(2)
1364const { functions: modules, classes: classModules } = JSON.parse(readFileSync(modulesPath, 'utf8'))
1365const loaded = await import(pathToFileURL(nativePath).href)
1366const native = { ...(loaded.default && typeof loaded.default === 'object' ? loaded.default : {}), ...loaded }
1367const cases = readFileSync(casesPath, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l))
1368const byFn = new Map()
1369const scenarios = new Map()
1370for (const c of cases.filter(c => c.class)) {
1371  if (!scenarios.has(c.class)) scenarios.set(c.class, [])
1372  scenarios.get(c.class).push(c)
1373}
1374for (const c of cases.filter(c => !c.class)) {
1375  if (!byFn.has(c.fn)) byFn.set(c.fn, [])
1376  byFn.get(c.fn).push(c.args.map(dec))
1377}
1378// Time whole passes over the cases until `minMs` has passed; errors count as calls.
1379const time = (fn, argsList) => {
1380  const pass = () => {
1381    for (const args of argsList) {
1382      try { fn(...args) } catch {}
1383    }
1384  }
1385  pass()
1386  let passes = 0
1387  const start = performance.now()
1388  do { pass(); passes++ } while (performance.now() - start < Number(minMs))
1389  return (performance.now() - start) * 1e6 / (passes * argsList.length)
1390}
1391const rows = []
1392for (const [name, argsList] of byFn) {
1393  const original = (await import(pathToFileURL(modules[name]).href))[name]
1394  const rust = native[name]
1395  if (typeof original !== 'function' || typeof rust !== 'function') continue
1396  const originalNs = time(original, argsList)
1397  const rustNs = time(rust, argsList)
1398  rows.push({ fn: name, cases: argsList.length, original_ns: originalNs, rust_ns: rustNs, speedup: originalNs / rustNs })
1399}
1400// Classes: time whole scenarios (construct, then every call).
1401const play = (Class, list) => () => {
1402  for (const c of list) {
1403    try {
1404      const instance = new Class(...c.ctor.map(dec))
1405      for (const call of c.calls) {
1406        try { instance[call.method](...call.args.map(dec)) } catch {}
1407      }
1408    } catch {}
1409  }
1410}
1411for (const [name, list] of scenarios) {
1412  const original = (await import(pathToFileURL(classModules[name]).href))[name]
1413  const rust = native[name]
1414  if (typeof original !== 'function' || typeof rust !== 'function') continue
1415  const timeAll = (fn) => {
1416    fn()
1417    let passes = 0
1418    const start = performance.now()
1419    do { fn(); passes++ } while (performance.now() - start < Number(minMs))
1420    return (performance.now() - start) * 1e6 / (passes * list.length)
1421  }
1422  const originalNs = timeAll(play(original, list))
1423  const rustNs = timeAll(play(rust, list))
1424  rows.push({ fn: `class ${name}`, cases: list.length, original_ns: originalNs, rust_ns: rustNs, speedup: originalNs / rustNs })
1425}
1426writeFileSync(outPath, JSON.stringify(rows))
1427"#;
1428
1429const DIFF_JS: &str = r#"
1430import { readFileSync, writeFileSync } from 'node:fs'
1431import { pathToFileURL } from 'node:url'
1432
1433const [modulePath, casesPath, outPath, keyOrder] = process.argv.slice(2)
1434const loaded = await import(pathToFileURL(modulePath).href)
1435const mod = { ...(loaded.default && typeof loaded.default === 'object' ? loaded.default : {}), ...loaded }
1436const cases = readFileSync(casesPath, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l))
1437const summary = { total: cases.length, passed: 0, failed: 0, missing: [], mismatches: [] }
1438const scenario = async (Class, c) => {
1439  const results = []
1440  let instance
1441  try {
1442    instance = new Class(...c.ctor.map(dec))
1443    results.push({ ok: true })
1444  }
1445  catch (error) {
1446    results.push({ error: String(error?.message ?? error) })
1447    return results
1448  }
1449  for (const call of c.calls) {
1450    try {
1451      results.push({ ok: enc(await instance[call.method](...call.args.map(dec))) })
1452    }
1453    catch (error) {
1454      results.push({ error: String(error?.message ?? error) })
1455    }
1456  }
1457  return results
1458}
1459const stepsMatch = (want, got) => want.length === got.length && want.every((w, i) =>
1460  ('error' in w && 'error' in got[i]) || ('ok' in w && 'ok' in got[i] && same(w.ok, got[i].ok, keyOrder === 'sort')))
1461for (const c of cases) {
1462  if (c.class) {
1463    const Class = mod[c.class]
1464    if (typeof Class !== 'function') {
1465      if (!summary.missing.includes(c.class)) summary.missing.push(c.class)
1466      summary.failed++
1467      continue
1468    }
1469    const got = await scenario(Class, c)
1470    if (stepsMatch(c.results, got)) {
1471      summary.passed++
1472    }
1473    else {
1474      summary.failed++
1475      summary.mismatches.push({ fn: c.class, args: [c.ctor, c.calls], expected: c.results, actual: got })
1476    }
1477    continue
1478  }
1479  const fn = mod[c.fn]
1480  let actual
1481  if (typeof fn !== 'function') {
1482    if (!summary.missing.includes(c.fn)) summary.missing.push(c.fn)
1483    actual = { missing: true }
1484  }
1485  else {
1486    try {
1487      actual = { ok: enc(await fn(...c.args.map(dec))) }
1488    }
1489    catch (error) {
1490      actual = { error: String(error?.message ?? error) }
1491    }
1492  }
1493  const expected = 'error' in c ? { error: c.error } : { ok: c.ok }
1494  // Both sides throwing counts as agreement: error messages are not part of the contract.
1495  const pass = ('error' in expected && 'error' in actual) || ('ok' in expected && 'ok' in actual && same(expected.ok, actual.ok, keyOrder === 'sort'))
1496  if (pass) {
1497    summary.passed++
1498  }
1499  else {
1500    summary.failed++
1501    summary.mismatches.push({ fn: c.fn, args: c.args, expected, actual })
1502  }
1503}
1504writeFileSync(outPath, JSON.stringify(summary, null, 2))
1505"#;
1506
1507#[cfg(test)]
1508mod tests {
1509    use super::*;
1510    use crate::ts::exports::{ExportedFn, Param};
1511
1512    fn f(params: &[(&str, &str)]) -> ExportedFn {
1513        ExportedFn {
1514            name: "f".into(),
1515            file: "a.ts".into(),
1516            line: 1,
1517            params: params
1518                .iter()
1519                .map(|(n, t)| Param {
1520                    name: (*n).into(),
1521                    ts_type: (*t).into(),
1522                    optional: false,
1523                    rest: false,
1524                    ..Default::default()
1525                })
1526                .collect(),
1527            returns: "number".into(),
1528            is_async: false,
1529            is_generator: false,
1530            type_params: Vec::new(),
1531            uses_instanceof: false,
1532            ..Default::default()
1533        }
1534    }
1535
1536    #[test]
1537    fn generates_deterministic_distinct_inputs() {
1538        let a = generate(&f(&[("q", "string"), ("t", "string")]), 50, &[]);
1539        let b = generate(&f(&[("q", "string"), ("t", "string")]), 50, &[]);
1540        assert_eq!(a, b);
1541        assert_eq!(a.len(), 50);
1542        let unique: std::collections::HashSet<String> = a.iter().map(|v| v.to_string()).collect();
1543        assert_eq!(unique.len(), 50);
1544        assert!(
1545            a.iter()
1546                .any(|args| args.to_string().contains('😀') || args.to_string().contains('👍'))
1547        );
1548    }
1549
1550    #[test]
1551    fn generates_values_that_fit_object_types() {
1552        let types = crate::ts::exports::local_types(
1553            "m.ts",
1554            "export interface Edit { readonly range: { start: number, end: number }, readonly text: string }\n",
1555        );
1556        let cases = generate(&f(&[("edits", "readonly Edit[]")]), 60, &types);
1557        let fitting = cases
1558            .iter()
1559            .filter_map(|args| args[0].as_array())
1560            .flatten()
1561            .filter(|e| e["range"]["start"].is_number() || e["range"]["start"].is_object())
1562            .count();
1563        assert!(fitting > 20, "{fitting}");
1564    }
1565
1566    #[test]
1567    fn covers_number_edge_cases() {
1568        let cases = generate(&f(&[("n", "number")]), 18, &[]);
1569        let text = serde_json::to_string(&cases).unwrap();
1570        assert!(text.contains("NaN") && text.contains("-0"));
1571    }
1572}
1573
1574#[cfg(test)]
1575mod verdict_tests {
1576    use super::*;
1577
1578    fn row(name: &str, speedup: f64) -> BenchRow {
1579        BenchRow {
1580            name: name.into(),
1581            cases: 1,
1582            original_ns: speedup,
1583            rust_ns: 1.0,
1584            speedup,
1585        }
1586    }
1587
1588    #[test]
1589    fn advice_follows_the_numbers() {
1590        let ts = crate::lang::Lang::Ts;
1591        assert!(
1592            verdict(&[row("a", 3.0), row("b", 2.0)], ts)
1593                .advice
1594                .starts_with("Ship it: every")
1595        );
1596        assert!(
1597            verdict(&[row("a", 3.0), row("b", 1.0)], ts)
1598                .advice
1599                .starts_with("Ship it: no function")
1600        );
1601        let mixed = verdict(&[row("a", 4.0), row("b", 0.5)], ts);
1602        assert!(mixed.advice.contains("Keep the slower ones") && mixed.advice.ends_with("b."));
1603        assert!(
1604            verdict(&[row("a", 0.2), row("b", 0.3)], ts)
1605                .advice
1606                .starts_with("Do not ship")
1607        );
1608        assert!(
1609            verdict(&[row("a", 0.5)], crate::lang::Lang::C)
1610                .advice
1611                .starts_with("No call overhead")
1612        );
1613    }
1614}