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 async_functions: Vec<&str> = manifest
613        .exports
614        .iter()
615        .filter(|f| f.is_async)
616        .map(|f| f.name.as_str())
617        .collect();
618    let modules_path = work.join("bench-modules.json");
619    std::fs::write(
620        &modules_path,
621        serde_json::to_string(&json!({
622            "functions": modules,
623            "classes": class_modules,
624            "asyncFunctions": async_functions,
625        }))?,
626    )?;
627    let script = work.join("bench.mjs");
628    std::fs::write(&script, format!("{CODEC_JS}\n{BENCH_JS}"))?;
629    let out = work.join("bench.json");
630    let native = opts.crate_dir.join("index.cjs").canonical()?;
631    let register = work.canonical()?.join("register.mjs");
632    let mut cmd = Command::new("node");
633    cmd.arg("--experimental-transform-types")
634        .arg("--no-warnings")
635        .arg(format!("--import={}", file_url(&register)))
636        .args(opts.node_args)
637        .arg(&script)
638        .arg(&modules_path)
639        .arg(&native)
640        .arg(&cases)
641        .arg(&out)
642        .arg(opts.min_ms.to_string())
643        .env("RUST_ANYTHING_PATHS", alias_env(&manifest))
644        .env("RUST_ANYTHING_WORKSPACE", workspace_env(&manifest));
645    if let Some(dir) = opts.resolve_from {
646        cmd.env("RUST_ANYTHING_RESOLVE_FROM", dir.canonical()?);
647    }
648    run(&mut cmd, "node")?;
649    Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
650}
651
652pub struct DiffOptions<'a> {
653    pub crate_dir: &'a Path,
654    /// The module to test; defaults to the crate's `index.cjs`.
655    pub module: Option<&'a Path>,
656    /// Compare objects regardless of key order.
657    pub ignore_key_order: bool,
658    pub node_args: &'a [String],
659    /// Floats match within this tolerance; the one saved by `record` when `None`.
660    pub float_tolerance: Option<f64>,
661}
662
663/// The first mismatches a diff reports.
664const SHOWN_MISMATCHES: usize = 20;
665
666pub fn diff(opts: &DiffOptions) -> Result<DiffOutcome> {
667    let mut outcome = diff_exact(opts)?;
668    let manifest = Manifest::load(opts.crate_dir).ok();
669    let saved = manifest.as_ref().and_then(|m| m.float_tolerance);
670    if let Some(t) = opts.float_tolerance.or(saved) {
671        let preserve_key_order = opts.module.is_some()
672            || manifest.as_ref().is_none_or(|m| {
673                matches!(
674                    m.language,
675                    crate::lang::Lang::Ts | crate::lang::Lang::Python
676                )
677            });
678        outcome = crate::tolerance::apply(
679            outcome,
680            crate::tolerance::check(t)?,
681            opts.ignore_key_order || !preserve_key_order,
682        );
683    }
684    outcome.mismatches.truncate(SHOWN_MISMATCHES);
685    anyhow::ensure!(
686        outcome.total > 0,
687        "no recorded cases to compare; run `rust-anything record` first"
688    );
689    Ok(outcome)
690}
691
692fn diff_exact(opts: &DiffOptions) -> Result<DiffOutcome> {
693    if opts.module.is_none()
694        && let Ok(manifest) = Manifest::load(opts.crate_dir)
695        && let Some(built) = stale_build(opts.crate_dir, &manifest)
696    {
697        bail!(
698            "{} is older than the crate's sources, so diff would test the previous port; run \
699             `rust-anything build {}` first",
700            built.display(),
701            opts.crate_dir.display()
702        );
703    }
704    if let Ok(manifest) = Manifest::load(opts.crate_dir)
705        && manifest.language == crate::lang::Lang::Python
706        && opts.module.is_none()
707    {
708        return crate::harness_py::diff(opts.crate_dir, &manifest, opts.ignore_key_order);
709    }
710    if let Ok(manifest) = Manifest::load(opts.crate_dir)
711        && manifest.kind == Kind::CAbi
712        && opts.module.is_none()
713    {
714        return crate::harness_c::diff(opts.crate_dir, &manifest);
715    }
716    if let Ok(manifest) = Manifest::load(opts.crate_dir)
717        && manifest.language == crate::lang::Lang::Go
718        && opts.module.is_none()
719    {
720        return crate::harness_go::diff(opts.crate_dir, &manifest);
721    }
722    if let Ok(manifest) = Manifest::load(opts.crate_dir)
723        && manifest.language == crate::lang::Lang::Ruby
724        && opts.module.is_none()
725    {
726        return crate::harness_ruby::diff(opts.crate_dir, &manifest);
727    }
728    if let Ok(manifest) = Manifest::load(opts.crate_dir)
729        && manifest.language == crate::lang::Lang::Java
730        && opts.module.is_none()
731    {
732        return crate::harness_java::diff(opts.crate_dir, &manifest);
733    }
734    let cases = opts.crate_dir.join(CASES);
735    if !cases.exists() {
736        bail!(
737            "no {CASES} in {} (run `rust-anything record` first)",
738            opts.crate_dir.display()
739        );
740    }
741    let module = match opts.module {
742        Some(m) => m.to_path_buf(),
743        None => opts.crate_dir.join("index.cjs"),
744    };
745    let module = module
746        .canonical()
747        .with_context(|| format!("resolving {}", module.display()))?;
748    let work = opts.crate_dir.join(WORK_DIR);
749    std::fs::create_dir_all(&work)?;
750    let script = work.join("diff.mjs");
751    std::fs::write(&script, format!("{CODEC_JS}\n{DIFF_JS}"))?;
752    let out = work.join("diff.json");
753    let flag = if opts.ignore_key_order {
754        "sort"
755    } else {
756        "keep"
757    };
758    run_node(
759        opts.node_args,
760        &script,
761        &[
762            module.as_os_str(),
763            cases.as_os_str(),
764            out.as_os_str(),
765            flag.as_ref(),
766        ],
767    )?;
768    let text = std::fs::read_to_string(&out)?;
769    Ok(serde_json::from_str(&text)?)
770}
771
772/// The version of `package` in a Cargo.lock.
773fn locked_version(lock: &str, package: &str) -> Option<String> {
774    let mut lines = lock.lines();
775    while let Some(line) = lines.next() {
776        if line.trim() == format!("name = \"{package}\"") {
777            let version = lines
778                .next()?
779                .trim()
780                .strip_prefix("version = \"")?
781                .strip_suffix('"')?;
782            return Some(version.to_string());
783        }
784    }
785    None
786}
787
788/// Deterministic inputs for one function: edge cases first, then seeded random mixes.
789pub fn generate(
790    f: &crate::ts::exports::ExportedFn,
791    count: usize,
792    types: &[LocalType],
793) -> Vec<Value> {
794    let mut rng = Rng::new(f.name.bytes().fold(0x9E37_79B9_7F4A_7C15, |h, b| {
795        (h ^ u64::from(b)).wrapping_mul(0x100_0000_01B3)
796    }));
797    let mut seen = std::collections::HashSet::new();
798    let mut out = Vec::new();
799    let mut attempts = 0;
800    while out.len() < count && attempts < count * 20 {
801        attempts += 1;
802        let args = args_for(&f.params, types, &mut rng);
803        let key = serde_json::to_string(&args).unwrap_or_default();
804        if seen.insert(key) {
805            out.push(Value::Array(args));
806        }
807    }
808    out
809}
810
811/// The semantic traps for a value of type `t`: what most often behaves differently once ported
812/// (string length and case, signed division and overflow, float printing, map and sort order).
813fn trap_values(t: &RType) -> Vec<Value> {
814    match t {
815        RType::Str => crate::app::STRING_TRAPS
816            .iter()
817            .chain(["ΣΊΣΥΦΟΣ", "a😀b", "\u{FEFF}bom"].iter())
818            .map(|s| json!(s))
819            .collect(),
820        RType::Int => [
821            -7,
822            -1,
823            0,
824            2_147_483_648,
825            -2_147_483_649,
826            9_007_199_254_740_993,
827            i64::MAX,
828            i64::MIN,
829        ]
830        .iter()
831        .map(|n| json!(n))
832        .collect(),
833        RType::F64 => {
834            let mut out: Vec<Value> = [
835                -7.5,
836                0.1,
837                0.30000000000000004,
838                1e21,
839                1e-7,
840                5e-324,
841                1.797_693_134_862_315_7e308,
842                9_007_199_254_740_992.0,
843            ]
844            .iter()
845            .map(|n| json!(n))
846            .collect();
847            out.push(json!({ "$num": "-0" }));
848            out
849        }
850        RType::Vec(inner) => match inner.as_ref() {
851            RType::Str => vec![json!([]), json!(["b", "a", "B", "é", "10", "9", "a"])],
852            RType::Int => vec![json!([]), json!([-7, 3, 0, i64::MAX, -1])],
853            RType::F64 => vec![json!([]), json!([0.1, 0.2, -0.5, 1e21])],
854            _ => vec![json!([])],
855        },
856        RType::Opt(inner) => {
857            let mut out = vec![json!({ "$undefined": true })];
858            out.extend(trap_values(inner));
859            out
860        }
861        RType::Json => crate::app::JSON_TRAPS
862            .iter()
863            .filter_map(|t| serde_json::from_str(t).ok())
864            .chain([json!([3, 1, 2]), json!({})])
865            .collect(),
866        RType::Bool | RType::Unit => Vec::new(),
867    }
868}
869
870/// Every trap value in every parameter, one at a time, the other arguments as in `base`.
871/// Structured parameters (objects with a known shape) are left as generated.
872pub fn trap_args(
873    params: &[crate::ts::exports::Param],
874    base: &[Value],
875    regex: bool,
876) -> Vec<Vec<Value>> {
877    let mut out = Vec::new();
878    if base.len() < params.iter().filter(|p| !p.rest).count() {
879        return out;
880    }
881    for (i, p) in params.iter().enumerate() {
882        if p.rest || i >= base.len() {
883            continue;
884        }
885        let t = param_type(p);
886        let structured = t.contains_json() && !matches!(t, RType::Json);
887        let any = matches!(p.ts_type.trim(), "any" | "unknown" | "object" | "Object");
888        if structured || (matches!(t, RType::Json) && !any) {
889            continue;
890        }
891        let mut values = trap_values(&t);
892        if regex && t == RType::Str {
893            values.extend(crate::risks::REGEX_TRAPS.iter().map(|s| json!(s)));
894        }
895        for v in values {
896            if base[i] != v {
897                let mut args = base.to_vec();
898                args[i] = v;
899                out.push(args);
900            }
901        }
902    }
903    out
904}
905
906/// One argument list for `params`: values that fit, edge cases, and sometimes omitted optionals.
907fn args_for(
908    params: &[crate::ts::exports::Param],
909    types: &[LocalType],
910    rng: &mut Rng,
911) -> Vec<Value> {
912    let mut args: Vec<Value> = Vec::new();
913    for p in params {
914        let t = param_type(p);
915        // Structured parameters: values that fit the TS type, and now and then a value
916        // that does not, so error paths get recorded too.
917        let structured = |rng: &mut Rng| {
918            if rng.below(100) < 15 {
919                value(&RType::Json, rng)
920            } else {
921                shaped(&shape::parse(&p.ts_type), types, rng, 0)
922            }
923        };
924        if p.rest {
925            let inner = match t {
926                RType::Vec(inner) => *inner,
927                other => other,
928            };
929            for _ in 0..rng.below(3) {
930                args.push(value(&inner, rng));
931            }
932        } else if t.contains_json() {
933            let v = structured(rng);
934            args.push(if p.optional && rng.below(5) == 0 {
935                json!({ "$undefined": true })
936            } else {
937                v
938            });
939        } else {
940            args.push(value(&t, rng));
941        }
942    }
943    // Search-like functions rarely hit on random text: often derive one string from another.
944    let strings: Vec<usize> = (0..args.len()).filter(|&i| args[i].is_string()).collect();
945    if strings.len() >= 2 && rng.below(10) < 5 {
946        let from = strings[rng.below(strings.len())];
947        let to = strings[rng.below(strings.len())];
948        if from != to {
949            let source: Vec<char> = args[from].as_str().unwrap_or_default().chars().collect();
950            if !source.is_empty() {
951                let start = rng.below(source.len());
952                let end = start + 1 + rng.below(source.len() - start);
953                let mut piece: String = source[start..end].iter().collect();
954                if rng.below(4) == 0 {
955                    piece = piece.to_uppercase();
956                }
957                args[to] = Value::String(piece);
958            }
959        }
960    }
961    // Trailing optional arguments: sometimes omit them, the way JS callers do.
962    while args.last().is_some_and(|a| a.get("$undefined").is_some()) && rng.below(2) == 0 {
963        args.pop();
964    }
965    args
966}
967
968/// Class scenarios: construct, then call a random sequence of methods.
969pub fn scenarios(
970    class: &crate::ts::exports::ExportedClass,
971    count: usize,
972    types: &[LocalType],
973) -> Vec<Value> {
974    let mut rng = Rng::new(class.name.bytes().fold(0x2545_F491_4F6C_DD1D, |h, b| {
975        (h ^ u64::from(b)).wrapping_mul(0x100_0000_01B3)
976    }));
977    (0..count)
978        .map(|_| {
979            let ctor = args_for(&class.constructor, types, &mut rng);
980            let steps = if class.methods.is_empty() {
981                0
982            } else {
983                1 + rng.below(12)
984            };
985            // Stateful classes need calls that meet again (`set(k)` then `get(k)`): string
986            // arguments often reuse a string seen earlier in the scenario.
987            let mut seen: Vec<Value> = ctor.iter().filter(|v| v.is_string()).cloned().collect();
988            let calls: Vec<Value> = (0..steps)
989                .map(|_| {
990                    let m = &class.methods[rng.below(class.methods.len())];
991                    let mut args = args_for(&m.params, types, &mut rng);
992                    for arg in &mut args {
993                        if arg.is_string() {
994                            if !seen.is_empty() && rng.below(2) == 0 {
995                                *arg = seen[rng.below(seen.len())].clone();
996                            } else {
997                                seen.push(arg.clone());
998                            }
999                        }
1000                    }
1001                    json!({ "method": m.name, "args": args })
1002                })
1003                .collect();
1004            json!({ "class": class.name, "ctor": ctor, "calls": calls })
1005        })
1006        .collect()
1007}
1008
1009/// Property names for generated objects: plain, nested-looking, integer-like (JS orders those
1010/// first), non-ASCII.
1011const KEYS: &[&str] = &[
1012    "a", "b", "nav", "home", "title", "2", "10", "ünï", "😀", "a.b",
1013];
1014
1015/// A value that fits a TS shape. Named types resolve against `types`; recursion stops at a depth.
1016fn shaped(s: &Shape, types: &[LocalType], rng: &mut Rng, depth: usize) -> Value {
1017    match s {
1018        Shape::Str => value(&RType::Str, rng),
1019        Shape::Num => value(&RType::F64, rng),
1020        Shape::Int => value(&RType::Int, rng),
1021        Shape::Bool => value(&RType::Bool, rng),
1022        Shape::Null => Value::Null,
1023        Shape::Undefined => json!({ "$undefined": true }),
1024        Shape::LitStr(text) => Value::String(text.clone()),
1025        Shape::LitNum(n) => json!(n),
1026        Shape::LitBool(b) => Value::Bool(*b),
1027        Shape::Union(items) if !items.is_empty() => {
1028            shaped(&items[rng.below(items.len())], types, rng, depth)
1029        }
1030        Shape::Array(item) if depth < 6 => Value::Array(
1031            (0..rng.below(4))
1032                .map(|_| shaped(item, types, rng, depth + 1))
1033                .collect(),
1034        ),
1035        Shape::Tuple(items) => Value::Array(
1036            items
1037                .iter()
1038                .map(|i| shaped(i, types, rng, depth + 1))
1039                .collect(),
1040        ),
1041        Shape::Object(props, index) if depth < 6 => {
1042            let mut out = serde_json::Map::new();
1043            for (name, optional, prop) in props {
1044                if *optional && rng.below(4) == 0 {
1045                    continue;
1046                }
1047                out.insert(name.clone(), shaped(prop, types, rng, depth + 1));
1048            }
1049            if let Some(item) = index {
1050                for _ in 0..rng.below(4) {
1051                    out.insert(
1052                        KEYS[rng.below(KEYS.len())].to_string(),
1053                        shaped(item, types, rng, depth + 1),
1054                    );
1055                }
1056            }
1057            Value::Object(out)
1058        }
1059        Shape::Ref(name, args) if depth < 6 => {
1060            shaped(&shape::resolve(name, args, types), types, rng, depth + 1)
1061        }
1062        Shape::Any => value(&RType::Json, rng),
1063        // Too deep, or empty: a leaf ends the recursion.
1064        _ => Value::Null,
1065    }
1066}
1067
1068fn value(t: &RType, rng: &mut Rng) -> Value {
1069    match t {
1070        RType::Str => {
1071            let a = STRINGS[rng.below(STRINGS.len())];
1072            if rng.below(5) == 0 {
1073                Value::String(format!("{a}{}", STRINGS[rng.below(STRINGS.len())]))
1074            } else {
1075                Value::String(a.into())
1076            }
1077        }
1078        RType::Int => {
1079            // Small, signed, and the edges of 32 and 64 bits.
1080            let n: [i64; 12] = [
1081                0,
1082                1,
1083                -1,
1084                2,
1085                7,
1086                42,
1087                100,
1088                -100,
1089                255,
1090                i64::from(i32::MAX),
1091                i64::from(i32::MIN),
1092                i64::MAX,
1093            ];
1094            json!(n[rng.below(n.len())])
1095        }
1096        RType::F64 => {
1097            let n = [
1098                0.0,
1099                1.0,
1100                -1.0,
1101                2.0,
1102                3.0,
1103                10.0,
1104                0.5,
1105                -2.5,
1106                42.0,
1107                100.0,
1108                1000.0,
1109                1e6,
1110                2_147_483_648.0,
1111                9_007_199_254_740_992.0,
1112            ];
1113            match rng.below(n.len() + 4) {
1114                i if i < n.len() => json!(n[i]),
1115                i if i == n.len() => json!({ "$num": "-0" }),
1116                i if i == n.len() + 1 => json!({ "$num": "NaN" }),
1117                i if i == n.len() + 2 => json!({ "$num": "Infinity" }),
1118                _ => json!({ "$num": "-Infinity" }),
1119            }
1120        }
1121        RType::Bool => Value::Bool(rng.below(2) == 0),
1122        RType::Unit => json!({ "$undefined": true }),
1123        RType::Vec(inner) => Value::Array((0..rng.below(4)).map(|_| value(inner, rng)).collect()),
1124        RType::Opt(inner) => {
1125            if rng.below(4) == 0 {
1126                json!({ "$undefined": true })
1127            } else {
1128                value(inner, rng)
1129            }
1130        }
1131        RType::Json => {
1132            let values: Vec<Value> = serde_json::from_str(JSON_VALUES).unwrap_or_default();
1133            values
1134                .get(rng.below(values.len().max(1)))
1135                .cloned()
1136                .unwrap_or(Value::Null)
1137        }
1138    }
1139}
1140
1141/// xorshift64*: deterministic, so a recording is reproducible.
1142struct Rng(u64);
1143
1144impl Rng {
1145    fn new(seed: u64) -> Self {
1146        Self(seed | 1)
1147    }
1148
1149    fn below(&mut self, n: usize) -> usize {
1150        if n == 0 {
1151            return 0;
1152        }
1153        self.0 ^= self.0 >> 12;
1154        self.0 ^= self.0 << 25;
1155        self.0 ^= self.0 >> 27;
1156        let x = self.0.wrapping_mul(0x2545_F491_4F6C_DD1D);
1157        usize::try_from(x >> 33).unwrap_or(0) % n
1158    }
1159}
1160
1161fn run_node(node_args: &[String], script: &Path, args: &[&std::ffi::OsStr]) -> Result<()> {
1162    run(
1163        Command::new("node").args(node_args).arg(script).args(args),
1164        "node",
1165    )
1166}
1167
1168fn run(cmd: &mut Command, what: &str) -> Result<()> {
1169    let output = cmd.output().with_context(|| format!("running {what}"))?;
1170    if !output.status.success() {
1171        let stderr = String::from_utf8_lossy(&output.stderr);
1172        let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
1173        bail!(
1174            "{what} failed ({}):\n{}",
1175            output.status,
1176            tail.into_iter().rev().collect::<Vec<_>>().join("\n")
1177        );
1178    }
1179    Ok(())
1180}
1181
1182/// Python keyword-only parameters (after `*`) are passed by name: they move from `args` into
1183/// `kwargs`, and an omitted (`undefined`) one is left out.
1184/// Integral float arguments of `number` parameters, as ints.
1185fn intify(params: &[crate::ts::exports::Param], args: &mut Value) {
1186    let Some(items) = args.as_array_mut() else {
1187        return;
1188    };
1189    for (p, v) in params.iter().zip(items.iter_mut()) {
1190        if p.ts_type == "number"
1191            && let Some(x) = v.as_f64()
1192            && x.fract() == 0.0
1193            && x.abs() < 1e15
1194            && !(x == 0.0 && x.is_sign_negative())
1195        {
1196            *v = json!(x as i64);
1197        }
1198    }
1199}
1200
1201fn split_keyword_only(params: &[crate::ts::exports::Param], case: &mut Value) {
1202    if !params.iter().any(|p| p.keyword_only) {
1203        return;
1204    }
1205    let Some(args) = case["args"].as_array().cloned() else {
1206        return;
1207    };
1208    let mut positional = Vec::new();
1209    let mut kwargs = serde_json::Map::new();
1210    for (i, value) in args.into_iter().enumerate() {
1211        match params.get(i) {
1212            Some(p) if p.keyword_only => {
1213                if value.get("$undefined").is_none() {
1214                    kwargs.insert(p.name.clone(), value);
1215                }
1216            }
1217            _ => positional.push(value),
1218        }
1219    }
1220    case["args"] = Value::Array(positional);
1221    case["kwargs"] = Value::Object(kwargs);
1222}
1223
1224/// Workspace packages as `{ name: absolute source folder }` for the resolve hook: a monorepo
1225/// imports its own packages by name, and their build output may not exist.
1226fn workspace_env(manifest: &Manifest) -> String {
1227    let packages: BTreeMap<String, String> = crate::ts::discover::discover(&manifest.root)
1228        .map(|ws| {
1229            ws.packages
1230                .into_iter()
1231                .filter(|p| !p.dir.is_empty())
1232                .map(|p| {
1233                    let dir = manifest.root.join(&p.dir);
1234                    let src = if dir.join("src").is_dir() {
1235                        dir.join("src")
1236                    } else {
1237                        dir
1238                    };
1239                    (p.name, src.to_string_lossy().into_owned())
1240                })
1241                .collect()
1242        })
1243        .unwrap_or_default();
1244    serde_json::to_string(&packages).unwrap_or_else(|_| "{}".into())
1245}
1246
1247/// The tsconfig `paths` of the unit's files, as JSON for the resolve hook: `[[pattern, [absolute targets]]]`.
1248fn alias_env(manifest: &Manifest) -> String {
1249    let mut entries: Vec<(String, Vec<String>)> = Vec::new();
1250    let files = manifest
1251        .exports
1252        .iter()
1253        .map(|f| &f.file)
1254        .chain(manifest.classes.iter().map(|c| &c.file));
1255    for file in files {
1256        let dir = file.rsplit_once('/').map_or("", |(d, _)| d);
1257        for (pattern, targets) in
1258            crate::ts::tsconfig::PathAliases::nearest(&manifest.root, dir).entries
1259        {
1260            if entries.iter().all(|(p, _)| *p != pattern) {
1261                let absolute = targets
1262                    .iter()
1263                    .map(|t| manifest.root.join(t).to_string_lossy().into_owned())
1264                    .collect();
1265                entries.push((pattern, absolute));
1266            }
1267        }
1268    }
1269    serde_json::to_string(&entries).unwrap_or_else(|_| "[]".into())
1270}
1271
1272fn file_url(path: &Path) -> String {
1273    use std::fmt::Write as _;
1274
1275    let text = path.to_string_lossy();
1276    #[cfg(windows)]
1277    let text = text.replace('\\', "/");
1278    let mut url = if text.starts_with('/') {
1279        String::from("file://")
1280    } else {
1281        String::from("file:///")
1282    };
1283    for byte in text.bytes() {
1284        if byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b':' | b'-' | b'_' | b'.' | b'~') {
1285            url.push(char::from(byte));
1286        } else {
1287            let _ = write!(url, "%{byte:02X}");
1288        }
1289    }
1290    url
1291}
1292
1293const REGISTER_JS: &str =
1294    "import { register } from 'node:module'\nregister('./resolve.mjs', import.meta.url)\n";
1295
1296/// Node resolve hook: bundler-style relative imports, and npm packages from
1297/// `RUST_ANYTHING_RESOLVE_FROM` when the source tree has none installed.
1298const RESOLVE_JS: &str = r#"
1299import { existsSync, statSync } from 'node:fs'
1300import { fileURLToPath, pathToFileURL } from 'node:url'
1301
1302const extra = process.env.RUST_ANYTHING_RESOLVE_FROM
1303// tsconfig `paths`: exact keys first, then wildcard keys by longest prefix.
1304const aliasPriority = pattern => pattern.includes('*') ? pattern.indexOf('*') : Number.POSITIVE_INFINITY
1305const aliases = JSON.parse(process.env.RUST_ANYTHING_PATHS || '[]')
1306  .sort(([a], [b]) => aliasPriority(b) - aliasPriority(a))
1307// Workspace packages by name: `@x18n/core` and `@x18n/core/sub` resolve to source.
1308const workspace = JSON.parse(process.env.RUST_ANYTHING_WORKSPACE || '{}')
1309const workspaceTargets = (specifier) => {
1310  for (const [name, src] of Object.entries(workspace)) {
1311    if (specifier === name)
1312      return [`${src}/index`]
1313    if (specifier.startsWith(`${name}/`))
1314      return [`${src}/${specifier.slice(name.length + 1)}`, `${src}/${specifier.slice(name.length + 1)}/index`]
1315  }
1316  return []
1317}
1318const aliasTargets = (specifier) => {
1319  for (const [pattern, targets] of aliases) {
1320    const [prefix, suffix = ''] = pattern.split('*')
1321    const exact = !pattern.includes('*')
1322    if (exact ? specifier === pattern : specifier.startsWith(prefix) && specifier.endsWith(suffix) && specifier.length >= prefix.length + suffix.length) {
1323      const star = exact ? '' : specifier.slice(prefix.length, specifier.length - suffix.length)
1324      return targets.map(t => t.replace('*', () => star))
1325    }
1326  }
1327  return []
1328}
1329const suffixes = ['.ts', '.tsx', '.mts', '.js', '.mjs', '/index.ts', '/index.mts', '/index.js']
1330const sourceCandidates = path => {
1331  const exact = path.match(/\.(mjs|cjs|jsx)$/)
1332  if (exact) {
1333    const replacement = { mjs: 'mts', cjs: 'cts', jsx: 'tsx' }[exact[1]]
1334    return [path, path.slice(0, -exact[1].length) + replacement]
1335  }
1336  const stem = path.replace(/\.js$/, '')
1337  return [stem, ...suffixes.map(suffix => stem + suffix)]
1338}
1339const isFile = p => existsSync(p) && statSync(p).isFile()
1340
1341export async function resolve(specifier, context, next) {
1342  // Aliases first: `@/x` is not even a valid package name for Node.
1343  for (const target of [...aliasTargets(specifier), ...workspaceTargets(specifier)]) {
1344    for (const candidate of sourceCandidates(target)) {
1345      if (isFile(candidate))
1346        return next(pathToFileURL(candidate).href, context)
1347    }
1348  }
1349  try {
1350    return await next(specifier, context)
1351  }
1352  catch (error) {
1353    const missing = error?.code === 'ERR_MODULE_NOT_FOUND' || error?.code === 'ERR_UNSUPPORTED_DIR_IMPORT'
1354    if (!missing || !context.parentURL)
1355      throw error
1356    if (specifier.startsWith('.') || specifier.startsWith('/')) {
1357      const path = fileURLToPath(new URL(specifier, context.parentURL))
1358      for (const candidate of sourceCandidates(path)) {
1359        if (isFile(candidate))
1360          return next(pathToFileURL(candidate).href, context)
1361      }
1362    }
1363    else if (extra) {
1364      return next(specifier, { ...context, parentURL: pathToFileURL(`${extra}/`).href })
1365    }
1366    throw error
1367  }
1368}
1369"#;
1370
1371/// Encoding shared by the record, diff and shadow scripts. Lossless for what a JS caller
1372/// can observe: `undefined`, `NaN`, `-0`, BigInt, Map/Set order, key order, lone surrogates.
1373pub const CODEC_JS: &str = r#"
1374const enc = (v, stack = []) => {
1375  if (v === undefined) return { $undefined: true }
1376  if (typeof v === 'number') {
1377    if (Number.isNaN(v)) return { $num: 'NaN' }
1378    if (!Number.isFinite(v)) return { $num: v > 0 ? 'Infinity' : '-Infinity' }
1379    if (Object.is(v, -0)) return { $num: '-0' }
1380    return v
1381  }
1382  // Strings JS split inside a surrogate pair are not valid Unicode: keep their code units.
1383  if (typeof v === 'string' && !v.isWellFormed()) return { $utf16: Array.from({ length: v.length }, (_, i) => v.charCodeAt(i)) }
1384  if (typeof v === 'bigint') return { $bigint: String(v) }
1385  if (typeof v === 'function') return { $function: v.name }
1386  if (typeof v === 'symbol') return { $symbol: String(v.description) }
1387  if (v === null || typeof v !== 'object') return v
1388  if (stack.includes(v)) return { $cycle: true }
1389  const next = [...stack, v]
1390  if (Array.isArray(v)) return v.map(x => enc(x, next))
1391  if (typeof Buffer !== 'undefined' && Buffer.isBuffer(v)) return { $buffer: [...v] }
1392  if (v instanceof Uint8Array) return { $bytes: [...v] }
1393  if (v instanceof Map) return { $map: [...v].map(([k, x]) => [enc(k, next), enc(x, next)]) }
1394  if (v instanceof Set) return { $set: [...v].map(x => enc(x, next)) }
1395  if (v instanceof Date) return { $date: Number.isNaN(v.getTime()) ? 'Invalid' : v.toISOString() }
1396  if (v instanceof RegExp) return { $regexp: String(v) }
1397  if (v instanceof Error) return { $error: v.message }
1398  return Object.fromEntries(Object.keys(v).map(k => [k, enc(v[k], next)]))
1399}
1400const dec = (v) => {
1401  if (Array.isArray(v)) return v.map(dec)
1402  if (v === null || typeof v !== 'object') return v
1403  if (v.$undefined) return undefined
1404  if ('$num' in v) return Number(v.$num)
1405  if ('$bigint' in v) return BigInt(v.$bigint)
1406  if ('$utf16' in v) {
1407    let text = ''
1408    for (let i = 0; i < v.$utf16.length; i += 8192)
1409      text += String.fromCharCode(...v.$utf16.slice(i, i + 8192))
1410    return text
1411  }
1412  if ('$map' in v) return new Map(v.$map.map(([k, x]) => [dec(k), dec(x)]))
1413  if ('$set' in v) return new Set(v.$set.map(dec))
1414  if ('$date' in v) return new Date(v.$date)
1415  if ('$bytes' in v) return Uint8Array.from(v.$bytes)
1416  if ('$buffer' in v) return Buffer.from(v.$buffer)
1417  return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, dec(x)]))
1418}
1419const canon = (v, sort) => {
1420  if (Array.isArray(v)) return v.map(x => canon(x, sort))
1421  if (v === null || typeof v !== 'object') return v
1422  const keys = Object.keys(v)
1423  if (sort) keys.sort()
1424  return Object.fromEntries(keys.map(k => [k, canon(v[k], sort)]))
1425}
1426const same = (a, b, sort = false) => JSON.stringify(canon(a, sort)) === JSON.stringify(canon(b, sort))
1427"#;
1428
1429const RECORD_JS: &str = r#"
1430import { readFileSync, writeFileSync } from 'node:fs'
1431import { pathToFileURL } from 'node:url'
1432
1433const [inputsPath, outPath] = process.argv.slice(2)
1434const inputs = JSON.parse(readFileSync(inputsPath, 'utf8'))
1435const modules = new Map()
1436const lines = []
1437// A class scenario: construct, then call each method in turn; every step's result is recorded.
1438const runScenario = async (Class, c) => {
1439  const results = []
1440  let instance
1441  try {
1442    instance = new Class(...c.ctor.map(dec))
1443    results.push({ ok: true })
1444  }
1445  catch (error) {
1446    results.push({ error: String(error?.message ?? error) })
1447    return results
1448  }
1449  for (const call of c.calls) {
1450    try {
1451      results.push({ ok: enc(await instance[call.method](...call.args.map(dec))) })
1452    }
1453    catch (error) {
1454      results.push({ error: String(error?.message ?? error) })
1455    }
1456  }
1457  return results
1458}
1459for (const c of inputs) {
1460  let mod = modules.get(c.module)
1461  if (!mod) {
1462    mod = await import(pathToFileURL(c.module).href)
1463    modules.set(c.module, mod)
1464  }
1465  if (c.class) {
1466    const Class = mod[c.class] ?? mod.default?.[c.class]
1467    if (typeof Class !== 'function') {
1468      console.error(`${c.class} is not a class exported by ${c.module}`)
1469      process.exit(2)
1470    }
1471    lines.push(JSON.stringify({ class: c.class, ctor: c.ctor, calls: c.calls, results: await runScenario(Class, c) }))
1472    continue
1473  }
1474  const fn = mod[c.fn] ?? mod.default?.[c.fn]
1475  if (typeof fn !== 'function') {
1476    console.error(`${c.fn} is not a function exported by ${c.module}`)
1477    process.exit(2)
1478  }
1479  try {
1480    const value = await fn(...c.args.map(dec))
1481    lines.push(JSON.stringify({ fn: c.fn, args: c.args, ok: enc(value) }))
1482  }
1483  catch (error) {
1484    lines.push(JSON.stringify({ fn: c.fn, args: c.args, error: String(error?.message ?? error) }))
1485  }
1486}
1487writeFileSync(outPath, `${lines.join('\n')}\n`)
1488"#;
1489
1490const BENCH_JS: &str = r#"
1491import { readFileSync, writeFileSync } from 'node:fs'
1492import { pathToFileURL } from 'node:url'
1493
1494const [modulesPath, nativePath, casesPath, outPath, minMs] = process.argv.slice(2)
1495const { functions: modules, classes: classModules, asyncFunctions } = JSON.parse(readFileSync(modulesPath, 'utf8'))
1496const loaded = await import(pathToFileURL(nativePath).href)
1497const native = { ...(loaded.default && typeof loaded.default === 'object' ? loaded.default : {}), ...loaded }
1498const cases = readFileSync(casesPath, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l))
1499const byFn = new Map()
1500const scenarios = new Map()
1501for (const c of cases.filter(c => c.class)) {
1502  if (!scenarios.has(c.class)) scenarios.set(c.class, [])
1503  scenarios.get(c.class).push(c)
1504}
1505for (const c of cases.filter(c => !c.class)) {
1506  if (!byFn.has(c.fn)) byFn.set(c.fn, [])
1507  byFn.get(c.fn).push(c.args.map(dec))
1508}
1509// Time whole passes over the cases until `minMs` has passed; errors count as calls.
1510const time = (fn, argsList) => {
1511  const pass = () => {
1512    for (const args of argsList) {
1513      try { fn(...args) } catch {}
1514    }
1515  }
1516  pass()
1517  let passes = 0
1518  const start = performance.now()
1519  do { pass(); passes++ } while (performance.now() - start < Number(minMs))
1520  return (performance.now() - start) * 1e6 / (passes * argsList.length)
1521}
1522const timeAsync = async (fn, argsList) => {
1523  const pass = async () => {
1524    for (const args of argsList) {
1525      try { await fn(...args) } catch {}
1526    }
1527  }
1528  await pass()
1529  let passes = 0
1530  const start = performance.now()
1531  do { await pass(); passes++ } while (performance.now() - start < Number(minMs))
1532  return (performance.now() - start) * 1e6 / (passes * argsList.length)
1533}
1534const rows = []
1535for (const [name, argsList] of byFn) {
1536  const original = (await import(pathToFileURL(modules[name]).href))[name]
1537  const rust = native[name]
1538  if (typeof original !== 'function' || typeof rust !== 'function') continue
1539  const timer = asyncFunctions.includes(name) ? timeAsync : time
1540  const originalNs = await timer(original, argsList)
1541  const rustNs = await timer(rust, argsList)
1542  rows.push({ fn: name, cases: argsList.length, original_ns: originalNs, rust_ns: rustNs, speedup: originalNs / rustNs })
1543}
1544// Classes: time whole scenarios (construct, then every call).
1545const play = (Class, list) => () => {
1546  for (const c of list) {
1547    try {
1548      const instance = new Class(...c.ctor.map(dec))
1549      for (const call of c.calls) {
1550        try { instance[call.method](...call.args.map(dec)) } catch {}
1551      }
1552    } catch {}
1553  }
1554}
1555for (const [name, list] of scenarios) {
1556  const original = (await import(pathToFileURL(classModules[name]).href))[name]
1557  const rust = native[name]
1558  if (typeof original !== 'function' || typeof rust !== 'function') continue
1559  const timeAll = (fn) => {
1560    fn()
1561    let passes = 0
1562    const start = performance.now()
1563    do { fn(); passes++ } while (performance.now() - start < Number(minMs))
1564    return (performance.now() - start) * 1e6 / (passes * list.length)
1565  }
1566  const originalNs = timeAll(play(original, list))
1567  const rustNs = timeAll(play(rust, list))
1568  rows.push({ fn: `class ${name}`, cases: list.length, original_ns: originalNs, rust_ns: rustNs, speedup: originalNs / rustNs })
1569}
1570writeFileSync(outPath, JSON.stringify(rows))
1571"#;
1572
1573const DIFF_JS: &str = r#"
1574import { readFileSync, writeFileSync } from 'node:fs'
1575import { pathToFileURL } from 'node:url'
1576
1577const [modulePath, casesPath, outPath, keyOrder] = process.argv.slice(2)
1578const loaded = await import(pathToFileURL(modulePath).href)
1579const mod = { ...(loaded.default && typeof loaded.default === 'object' ? loaded.default : {}), ...loaded }
1580const cases = readFileSync(casesPath, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l))
1581const summary = { total: cases.length, passed: 0, failed: 0, missing: [], mismatches: [] }
1582const scenario = async (Class, c) => {
1583  const results = []
1584  let instance
1585  try {
1586    instance = new Class(...c.ctor.map(dec))
1587    results.push({ ok: true })
1588  }
1589  catch (error) {
1590    results.push({ error: String(error?.message ?? error) })
1591    return results
1592  }
1593  for (const call of c.calls) {
1594    try {
1595      results.push({ ok: enc(await instance[call.method](...call.args.map(dec))) })
1596    }
1597    catch (error) {
1598      results.push({ error: String(error?.message ?? error) })
1599    }
1600  }
1601  return results
1602}
1603const stepsMatch = (want, got) => want.length === got.length && want.every((w, i) =>
1604  ('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')))
1605for (const c of cases) {
1606  if (c.class) {
1607    const Class = mod[c.class]
1608    if (typeof Class !== 'function') {
1609      if (!summary.missing.includes(c.class)) summary.missing.push(c.class)
1610      summary.failed++
1611      continue
1612    }
1613    const got = await scenario(Class, c)
1614    if (stepsMatch(c.results, got)) {
1615      summary.passed++
1616    }
1617    else {
1618      summary.failed++
1619      summary.mismatches.push({ fn: c.class, args: [c.ctor, c.calls], expected: c.results, actual: got })
1620    }
1621    continue
1622  }
1623  const fn = mod[c.fn]
1624  let actual
1625  if (typeof fn !== 'function') {
1626    if (!summary.missing.includes(c.fn)) summary.missing.push(c.fn)
1627    actual = { missing: true }
1628  }
1629  else {
1630    try {
1631      actual = { ok: enc(await fn(...c.args.map(dec))) }
1632    }
1633    catch (error) {
1634      actual = { error: String(error?.message ?? error) }
1635    }
1636  }
1637  const expected = 'error' in c ? { error: c.error } : { ok: c.ok }
1638  // Both sides throwing counts as agreement: error messages are not part of the contract.
1639  const panicked = 'error' in actual && actual.error.startsWith('Rust panic:')
1640  const pass = !panicked && ('error' in expected && 'error' in actual) || ('ok' in expected && 'ok' in actual && same(expected.ok, actual.ok, keyOrder === 'sort'))
1641  if (pass) {
1642    summary.passed++
1643  }
1644  else {
1645    summary.failed++
1646    summary.mismatches.push({ fn: c.fn, args: c.args, expected, actual })
1647  }
1648}
1649writeFileSync(outPath, JSON.stringify(summary, null, 2))
1650"#;
1651
1652#[cfg(test)]
1653mod tests {
1654    use super::*;
1655    use crate::ts::exports::{ExportedFn, Param};
1656
1657    fn f(params: &[(&str, &str)]) -> ExportedFn {
1658        ExportedFn {
1659            name: "f".into(),
1660            file: "a.ts".into(),
1661            line: 1,
1662            params: params
1663                .iter()
1664                .map(|(n, t)| Param {
1665                    name: (*n).into(),
1666                    ts_type: (*t).into(),
1667                    optional: false,
1668                    rest: false,
1669                    ..Default::default()
1670                })
1671                .collect(),
1672            returns: "number".into(),
1673            is_async: false,
1674            is_generator: false,
1675            type_params: Vec::new(),
1676            uses_instanceof: false,
1677            ..Default::default()
1678        }
1679    }
1680
1681    #[test]
1682    fn generates_deterministic_distinct_inputs() {
1683        let a = generate(&f(&[("q", "string"), ("t", "string")]), 50, &[]);
1684        let b = generate(&f(&[("q", "string"), ("t", "string")]), 50, &[]);
1685        assert_eq!(a, b);
1686        assert_eq!(a.len(), 50);
1687        let unique: std::collections::HashSet<String> = a.iter().map(|v| v.to_string()).collect();
1688        assert_eq!(unique.len(), 50);
1689        assert!(
1690            a.iter()
1691                .any(|args| args.to_string().contains('😀') || args.to_string().contains('👍'))
1692        );
1693    }
1694
1695    #[test]
1696    fn generates_values_that_fit_object_types() {
1697        let types = crate::ts::exports::local_types(
1698            "m.ts",
1699            "export interface Edit { readonly range: { start: number, end: number }, readonly text: string }\n",
1700        );
1701        let cases = generate(&f(&[("edits", "readonly Edit[]")]), 60, &types);
1702        let fitting = cases
1703            .iter()
1704            .filter_map(|args| args[0].as_array())
1705            .flatten()
1706            .filter(|e| e["range"]["start"].is_number() || e["range"]["start"].is_object())
1707            .count();
1708        assert!(fitting > 20, "{fitting}");
1709    }
1710
1711    #[test]
1712    fn covers_number_edge_cases() {
1713        let cases = generate(&f(&[("n", "number")]), 18, &[]);
1714        let text = serde_json::to_string(&cases).unwrap();
1715        assert!(text.contains("NaN") && text.contains("-0"));
1716    }
1717}
1718
1719#[cfg(test)]
1720mod verdict_tests {
1721    use super::*;
1722
1723    fn row(name: &str, speedup: f64) -> BenchRow {
1724        BenchRow {
1725            name: name.into(),
1726            cases: 1,
1727            original_ns: speedup,
1728            rust_ns: 1.0,
1729            speedup,
1730        }
1731    }
1732
1733    #[test]
1734    fn advice_follows_the_numbers() {
1735        let ts = crate::lang::Lang::Ts;
1736        assert!(
1737            verdict(&[row("a", 3.0), row("b", 2.0)], ts)
1738                .advice
1739                .starts_with("Ship it: every")
1740        );
1741        assert!(
1742            verdict(&[row("a", 3.0), row("b", 1.0)], ts)
1743                .advice
1744                .starts_with("Ship it: no function")
1745        );
1746        let mixed = verdict(&[row("a", 4.0), row("b", 0.5)], ts);
1747        assert!(mixed.advice.contains("Keep the slower ones") && mixed.advice.ends_with("b."));
1748        assert!(
1749            verdict(&[row("a", 0.2), row("b", 0.3)], ts)
1750                .advice
1751                .starts_with("Do not ship")
1752        );
1753        assert!(
1754            verdict(&[row("a", 0.5)], crate::lang::Lang::C)
1755                .advice
1756                .starts_with("No call overhead")
1757        );
1758    }
1759}