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