Skip to main content

rust_anything/
harness.rs

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