Skip to main content

rust_anything/
harness.rs

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