Skip to main content

rust_anything/
harness.rs

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