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