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