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