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