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::Bool | RType::Unit => Vec::new(),
1129    }
1130}
1131
1132/// Every trap value in every parameter, one at a time, the other arguments as in `base`.
1133/// Structured parameters (objects with a known shape) are left as generated.
1134pub fn trap_args(
1135    params: &[crate::ts::exports::Param],
1136    base: &[Value],
1137    regex: bool,
1138) -> Vec<Vec<Value>> {
1139    let mut out = Vec::new();
1140    let params: Vec<&crate::ts::exports::Param> = params
1141        .iter()
1142        .filter(|p| !p.ts_type.starts_with("len:"))
1143        .collect();
1144    if base.len() < params.iter().filter(|p| !p.rest).count() {
1145        return out;
1146    }
1147    for (i, p) in params.iter().enumerate() {
1148        if p.rest || i >= base.len() {
1149            continue;
1150        }
1151        if let Some(values) = c_pointer_traps(&p.ts_type) {
1152            for v in values {
1153                if base[i] != v {
1154                    let mut args = base.to_vec();
1155                    args[i] = v;
1156                    out.push(args);
1157                }
1158            }
1159            continue;
1160        }
1161        let t = param_type(p);
1162        let structured = t.contains_json() && !matches!(t, RType::Json);
1163        let any = matches!(p.ts_type.trim(), "any" | "unknown" | "object" | "Object");
1164        if structured || (matches!(t, RType::Json) && !any) {
1165            continue;
1166        }
1167        let mut values = trap_values(&t);
1168        if regex && t == RType::Str {
1169            values.extend(crate::risks::REGEX_TRAPS.iter().map(|s| json!(s)));
1170        }
1171        for v in values {
1172            if base[i] != v {
1173                let mut args = base.to_vec();
1174                args[i] = v;
1175                out.push(args);
1176            }
1177        }
1178    }
1179    out
1180}
1181
1182/// Edge cases for C pointer parameters: buffers as hex text (`bytes`, `buffer`) or a size of
1183/// zeroed bytes (`buffer`), the starting value behind an `out` pointer, a `char **` that starts
1184/// NULL, unwritten or at offset 0 (`outptr`), and structs of zeros, ones, minus ones, minimums
1185/// and maximums, plus each field zero with the others one (a zero denominator).
1186fn c_pointer_traps(ts_type: &str) -> Option<Vec<Value>> {
1187    Some(match ts_type {
1188        "bytes" => vec![
1189            json!(""),
1190            json!("00"),
1191            json!("ff"),
1192            json!("616263"),
1193            json!((0..=255u8).map(|b| format!("{b:02x}")).collect::<String>()),
1194            json!("ff".repeat(64)),
1195        ],
1196        "buffer" => vec![
1197            json!(0),
1198            json!(1),
1199            json!(3),
1200            json!(64),
1201            json!("ff".repeat(16)),
1202        ],
1203        "out" => vec![json!(0), json!(-1), json!(2_147_483_647)],
1204        t if t.starts_with("outptr:") => vec![json!(true), Value::Null, json!(0)],
1205        t => {
1206            let s = crate::codegen_c::c_struct(t)?;
1207            let field = |pick: &dyn Fn(&[Value]) -> Value, zero: Option<usize>| {
1208                let fields = s.fields.iter().enumerate().map(|(i, (ty, name))| {
1209                    let edges = c_field_edges(ty);
1210                    let v = if zero == Some(i) {
1211                        edges[0].clone()
1212                    } else {
1213                        pick(&edges)
1214                    };
1215                    (name.clone(), v)
1216                });
1217                Value::Object(fields.collect())
1218            };
1219            let mut out: Vec<Value> = (0..5)
1220                .map(|k| field(&|e: &[Value]| e[k.min(e.len() - 1)].clone(), None))
1221                .collect();
1222            out.extend((0..s.fields.len()).map(|i| field(&|e: &[Value]| e[1].clone(), Some(i))));
1223            out.dedup();
1224            out
1225        }
1226    })
1227}
1228
1229/// Edge values for a C scalar struct field: zero, one, then minus one, the minimum and the
1230/// maximum where the type has them (non-finite values for floating point).
1231fn c_field_edges(ty: &str) -> Vec<Value> {
1232    let ty = ty.trim();
1233    if ty.contains("float") || ty.contains("double") {
1234        return vec![
1235            json!(0.0),
1236            json!(1.0),
1237            json!(-1.0),
1238            json!({ "$num": "NaN" }),
1239            json!({ "$num": "Infinity" }),
1240            json!({ "$num": "-Infinity" }),
1241            json!(0.5),
1242            json!(1e300),
1243        ];
1244    }
1245    if ty == "bool" || ty == "_Bool" {
1246        return vec![json!(false), json!(true)];
1247    }
1248    let unsigned = ty.starts_with('u') || ty.starts_with("unsigned") || ty == "size_t";
1249    let bits = if ty.contains('8') || ty.ends_with("char") {
1250        8
1251    } else if ty.contains("16") || ty.contains("short") {
1252        16
1253    } else if ty.contains("64") || ty.contains("long") || ty.contains("size") || ty.contains("ptr")
1254    {
1255        64
1256    } else {
1257        32
1258    };
1259    if unsigned {
1260        let max = if bits == 64 {
1261            u64::MAX
1262        } else {
1263            (1u64 << bits) - 1
1264        };
1265        vec![json!(0), json!(1), json!(max), json!(max - 1), json!(2)]
1266    } else {
1267        let max = i64::MAX >> (64 - bits);
1268        vec![json!(0), json!(1), json!(-1), json!(-max - 1), json!(max)]
1269    }
1270}
1271
1272/// A random value for a C pointer parameter (see `c_pointer_traps`).
1273fn c_pointer_value(ts_type: &str, rng: &mut Rng) -> Value {
1274    const SIZES: [usize; 12] = [0, 1, 2, 3, 4, 5, 8, 16, 17, 64, 100, 1024];
1275    match ts_type {
1276        "bytes" => {
1277            let n = SIZES[rng.below(SIZES.len())];
1278            let text = rng.below(2) == 0;
1279            json!(
1280                (0..n)
1281                    .map(|_| {
1282                        let b = if text {
1283                            0x20 + rng.below(0x5f)
1284                        } else {
1285                            rng.below(256)
1286                        };
1287                        format!("{b:02x}")
1288                    })
1289                    .collect::<String>()
1290            )
1291        }
1292        "buffer" => json!(SIZES[rng.below(SIZES.len())]),
1293        t if t.starts_with("outptr:") => [json!(true), Value::Null, json!(0)][rng.below(3)].clone(),
1294        t if let Some(s) = crate::codegen_c::c_struct(t) => Value::Object(
1295            s.fields
1296                .iter()
1297                .map(|(ty, name)| {
1298                    let edges = c_field_edges(ty);
1299                    let small: [i32; 14] =
1300                        [0, 1, -1, 2, 3, 7, 12, 25, 30, 1000, 1001, 90000, -5, -48000];
1301                    let v = match rng.below(10) {
1302                        0..=2 => edges[rng.below(edges.len())].clone(),
1303                        _ if edges.len() == 2 => edges[rng.below(2)].clone(),
1304                        _ if ty.contains("float") || ty.contains("double") => {
1305                            json!(f64::from(small[rng.below(small.len())]) / 4.0)
1306                        }
1307                        _ if edges[2] != json!(-1) => {
1308                            json!(small[rng.below(small.len())].unsigned_abs())
1309                        }
1310                        _ => json!(small[rng.below(small.len())]),
1311                    };
1312                    (name.clone(), v)
1313                })
1314                .collect(),
1315        ),
1316        _ => json!([0, 1, -1, 7, 1000, 65536][rng.below(6)]),
1317    }
1318}
1319
1320/// One argument list for `params`: values that fit, edge cases, and sometimes omitted optionals.
1321fn args_for(
1322    params: &[crate::ts::exports::Param],
1323    types: &[LocalType],
1324    rng: &mut Rng,
1325) -> Vec<Value> {
1326    let mut args: Vec<Value> = Vec::new();
1327    for p in params {
1328        match p.ts_type.as_str() {
1329            t if t.starts_with("len:") => continue,
1330            t if matches!(t, "bytes" | "buffer" | "out")
1331                || t.starts_with("outptr:")
1332                || t.starts_with("struct:") =>
1333            {
1334                args.push(c_pointer_value(&p.ts_type, rng));
1335                continue;
1336            }
1337            _ => {}
1338        }
1339        let t = param_type(p);
1340        // Structured parameters: values that fit the TS type, and now and then a value
1341        // that does not, so error paths get recorded too.
1342        let structured = |rng: &mut Rng| {
1343            if rng.below(100) < 15 {
1344                value(&RType::Json, rng)
1345            } else {
1346                shaped(&shape::parse(&p.ts_type), types, rng, 0)
1347            }
1348        };
1349        if p.rest {
1350            let inner = match t {
1351                RType::Vec(inner) => *inner,
1352                other => other,
1353            };
1354            for _ in 0..rng.below(3) {
1355                args.push(value(&inner, rng));
1356            }
1357        } else if t.contains_json() {
1358            let v = structured(rng);
1359            args.push(if p.optional && rng.below(5) == 0 {
1360                json!({ "$undefined": true })
1361            } else {
1362                v
1363            });
1364        } else {
1365            args.push(value(&t, rng));
1366        }
1367    }
1368    // Search-like functions rarely hit on random text: often derive one string from another.
1369    let strings: Vec<usize> = (0..args.len()).filter(|&i| args[i].is_string()).collect();
1370    if strings.len() >= 2 && rng.below(10) < 5 {
1371        let from = strings[rng.below(strings.len())];
1372        let to = strings[rng.below(strings.len())];
1373        if from != to {
1374            let source: Vec<char> = args[from].as_str().unwrap_or_default().chars().collect();
1375            if !source.is_empty() {
1376                let start = rng.below(source.len());
1377                let end = start + 1 + rng.below(source.len() - start);
1378                let mut piece: String = source[start..end].iter().collect();
1379                if rng.below(4) == 0 {
1380                    piece = piece.to_uppercase();
1381                }
1382                args[to] = Value::String(piece);
1383            }
1384        }
1385    }
1386    // Trailing optional arguments: sometimes omit them, the way JS callers do.
1387    while args.last().is_some_and(|a| a.get("$undefined").is_some()) && rng.below(2) == 0 {
1388        args.pop();
1389    }
1390    args
1391}
1392
1393/// Class scenarios: construct, then call a random sequence of methods.
1394pub fn scenarios(
1395    class: &crate::ts::exports::ExportedClass,
1396    count: usize,
1397    types: &[LocalType],
1398) -> Vec<Value> {
1399    scenarios_salted(class, count, types, 0)
1400}
1401
1402/// [`scenarios`] from another seed, as [`generate_salted`].
1403pub fn scenarios_salted(
1404    class: &crate::ts::exports::ExportedClass,
1405    count: usize,
1406    types: &[LocalType],
1407    salt: u64,
1408) -> Vec<Value> {
1409    let mut rng = Rng::new(
1410        class.name.bytes().fold(0x2545_F491_4F6C_DD1D, |h, b| {
1411            (h ^ u64::from(b)).wrapping_mul(0x100_0000_01B3)
1412        }) ^ salt,
1413    );
1414    (0..count)
1415        .map(|_| {
1416            let ctor = args_for(&class.constructor, types, &mut rng);
1417            let steps = if class.methods.is_empty() {
1418                0
1419            } else {
1420                1 + rng.below(12)
1421            };
1422            // Stateful classes need calls that meet again (`set(k)` then `get(k)`): string
1423            // arguments often reuse a string seen earlier in the scenario.
1424            let mut seen: Vec<Value> = ctor.iter().filter(|v| v.is_string()).cloned().collect();
1425            let calls: Vec<Value> = (0..steps)
1426                .map(|_| {
1427                    let m = &class.methods[rng.below(class.methods.len())];
1428                    let mut args = args_for(&m.params, types, &mut rng);
1429                    for arg in &mut args {
1430                        if arg.is_string() {
1431                            if !seen.is_empty() && rng.below(2) == 0 {
1432                                *arg = seen[rng.below(seen.len())].clone();
1433                            } else {
1434                                seen.push(arg.clone());
1435                            }
1436                        }
1437                    }
1438                    json!({ "method": m.name, "args": args })
1439                })
1440                .collect();
1441            json!({ "class": class.name, "ctor": ctor, "calls": calls })
1442        })
1443        .collect()
1444}
1445
1446/// Property names for generated objects: plain, nested-looking, integer-like (JS orders those
1447/// first), non-ASCII.
1448const KEYS: &[&str] = &[
1449    "a", "b", "nav", "home", "title", "2", "10", "ünï", "😀", "a.b",
1450];
1451
1452/// A value that fits a TS shape. Named types resolve against `types`; recursion stops at a depth.
1453fn shaped(s: &Shape, types: &[LocalType], rng: &mut Rng, depth: usize) -> Value {
1454    match s {
1455        Shape::Str => value(&RType::Str, rng),
1456        Shape::Num => value(&RType::F64, rng),
1457        Shape::Int => value(&RType::Int, rng),
1458        Shape::Bool => value(&RType::Bool, rng),
1459        Shape::Null => Value::Null,
1460        Shape::Undefined => json!({ "$undefined": true }),
1461        Shape::LitStr(text) => Value::String(text.clone()),
1462        Shape::LitNum(n) => json!(n),
1463        Shape::LitBool(b) => Value::Bool(*b),
1464        Shape::Union(items) if !items.is_empty() => {
1465            shaped(&items[rng.below(items.len())], types, rng, depth)
1466        }
1467        Shape::Array(item) if depth < 6 => Value::Array(
1468            (0..rng.below(4))
1469                .map(|_| shaped(item, types, rng, depth + 1))
1470                .collect(),
1471        ),
1472        Shape::Tuple(items) => Value::Array(
1473            items
1474                .iter()
1475                .map(|i| shaped(i, types, rng, depth + 1))
1476                .collect(),
1477        ),
1478        Shape::Object(props, index) if depth < 6 => {
1479            let mut out = serde_json::Map::new();
1480            for (name, optional, prop) in props {
1481                if *optional && rng.below(4) == 0 {
1482                    continue;
1483                }
1484                out.insert(name.clone(), shaped(prop, types, rng, depth + 1));
1485            }
1486            if let Some(item) = index {
1487                for _ in 0..rng.below(4) {
1488                    out.insert(
1489                        KEYS[rng.below(KEYS.len())].to_string(),
1490                        shaped(item, types, rng, depth + 1),
1491                    );
1492                }
1493            }
1494            Value::Object(out)
1495        }
1496        Shape::Ref(name, args) if depth < 6 => {
1497            shaped(&shape::resolve(name, args, types), types, rng, depth + 1)
1498        }
1499        Shape::Any => value(&RType::Json, rng),
1500        // Too deep, or empty: a leaf ends the recursion.
1501        _ => Value::Null,
1502    }
1503}
1504
1505fn value(t: &RType, rng: &mut Rng) -> Value {
1506    match t {
1507        RType::Str => {
1508            let a = STRINGS[rng.below(STRINGS.len())];
1509            if rng.below(5) == 0 {
1510                Value::String(format!("{a}{}", STRINGS[rng.below(STRINGS.len())]))
1511            } else {
1512                Value::String(a.into())
1513            }
1514        }
1515        RType::Int => {
1516            // Small, signed, and the edges of 32 and 64 bits.
1517            let n: [i64; 12] = [
1518                0,
1519                1,
1520                -1,
1521                2,
1522                7,
1523                42,
1524                100,
1525                -100,
1526                255,
1527                i64::from(i32::MAX),
1528                i64::from(i32::MIN),
1529                i64::MAX,
1530            ];
1531            json!(n[rng.below(n.len())])
1532        }
1533        RType::F64 => {
1534            let n = [
1535                0.0,
1536                1.0,
1537                -1.0,
1538                2.0,
1539                3.0,
1540                10.0,
1541                0.5,
1542                -2.5,
1543                42.0,
1544                100.0,
1545                1000.0,
1546                1e6,
1547                2_147_483_648.0,
1548                9_007_199_254_740_992.0,
1549            ];
1550            match rng.below(n.len() + 4) {
1551                i if i < n.len() => json!(n[i]),
1552                i if i == n.len() => json!({ "$num": "-0" }),
1553                i if i == n.len() + 1 => json!({ "$num": "NaN" }),
1554                i if i == n.len() + 2 => json!({ "$num": "Infinity" }),
1555                _ => json!({ "$num": "-Infinity" }),
1556            }
1557        }
1558        RType::Bool => Value::Bool(rng.below(2) == 0),
1559        RType::Unit => json!({ "$undefined": true }),
1560        RType::Vec(inner) => Value::Array((0..rng.below(4)).map(|_| value(inner, rng)).collect()),
1561        RType::Opt(inner) => {
1562            if rng.below(4) == 0 {
1563                json!({ "$undefined": true })
1564            } else {
1565                value(inner, rng)
1566            }
1567        }
1568        RType::Json => {
1569            let values: Vec<Value> = serde_json::from_str(JSON_VALUES).unwrap_or_default();
1570            values
1571                .get(rng.below(values.len().max(1)))
1572                .cloned()
1573                .unwrap_or(Value::Null)
1574        }
1575    }
1576}
1577
1578/// xorshift64*: deterministic, so a recording is reproducible.
1579struct Rng(u64);
1580
1581impl Rng {
1582    fn new(seed: u64) -> Self {
1583        Self(seed | 1)
1584    }
1585
1586    fn below(&mut self, n: usize) -> usize {
1587        if n == 0 {
1588            return 0;
1589        }
1590        self.0 ^= self.0 >> 12;
1591        self.0 ^= self.0 << 25;
1592        self.0 ^= self.0 >> 27;
1593        let x = self.0.wrapping_mul(0x2545_F491_4F6C_DD1D);
1594        usize::try_from(x >> 33).unwrap_or(0) % n
1595    }
1596}
1597
1598/// How long one recorded case may run before the original is stopped on it:
1599/// `RUST_ANYTHING_CASE_TIMEOUT` seconds, 10 by default.
1600fn case_timeout() -> std::time::Duration {
1601    std::env::var("RUST_ANYTHING_CASE_TIMEOUT")
1602        .ok()
1603        .and_then(|v| v.parse::<f64>().ok())
1604        .and_then(crate::process::seconds)
1605        .unwrap_or(std::time::Duration::from_secs(10))
1606}
1607
1608/// Runs a record driver over `cases` with a watchdog. The driver appends the index of each case
1609/// it starts to `RUST_ANYTHING_PROGRESS` and flushes each recorded line. A case that runs past
1610/// the time limit (an input that makes the original allocate or loop for ever) stops the driver;
1611/// the lines recorded so far are kept, that input is left out, and the driver goes on with the
1612/// rest. Returns the inputs left out.
1613pub(crate) fn record_cases(
1614    cases: &[Value],
1615    work: &Path,
1616    out: &Path,
1617    what: &str,
1618    mut command: impl FnMut(&Path, &Path) -> Result<Command>,
1619) -> Result<Vec<Value>> {
1620    use std::process::Stdio;
1621    use std::time::Instant;
1622    std::fs::create_dir_all(work)?;
1623    let timeout = case_timeout();
1624    let inputs = work.join("record-inputs.json");
1625    let part = work.join("record-part.jsonl");
1626    let progress = work.join("record-progress");
1627    let stderr_path = work.join("record-stderr");
1628    let mut recorded = String::new();
1629    let mut timed_out = Vec::new();
1630    let mut start = 0;
1631    while start < cases.len() {
1632        std::fs::write(&inputs, serde_json::to_string(&cases[start..])?)?;
1633        std::fs::write(&progress, "")?;
1634        let _ = std::fs::remove_file(&part);
1635        let mut cmd = command(&inputs, &part)?;
1636        cmd.env("RUST_ANYTHING_PROGRESS", &progress)
1637            .stdin(Stdio::null())
1638            .stdout(Stdio::null())
1639            .stderr(std::fs::File::create(&stderr_path)?);
1640        #[cfg(unix)]
1641        {
1642            use std::os::unix::process::CommandExt as _;
1643            cmd.process_group(0);
1644        }
1645        let _scratch = scratch_cwd(&mut cmd)?;
1646        let mut child = cmd.spawn().with_context(|| format!("running {what}"))?;
1647        let mut current: Option<(usize, Instant)> = None;
1648        let status = loop {
1649            if let Some(status) = child.try_wait()? {
1650                break Some(status);
1651            }
1652            let started = std::fs::read_to_string(&progress).ok().and_then(|p| {
1653                p.lines()
1654                    .last()
1655                    .and_then(|l| l.trim().parse::<usize>().ok())
1656            });
1657            match (started, current) {
1658                (Some(i), Some((j, _))) if i == j => {}
1659                (Some(i), _) => current = Some((i, Instant::now())),
1660                (None, _) => {}
1661            }
1662            if let Some((_, since)) = current
1663                && since.elapsed() > timeout
1664            {
1665                #[cfg(unix)]
1666                {
1667                    let _ = Command::new("/bin/kill")
1668                        .args(["-KILL", "--", &format!("-{}", child.id())])
1669                        .stderr(Stdio::null())
1670                        .status();
1671                }
1672                let _ = child.kill();
1673                let _ = child.wait();
1674                break None;
1675            }
1676            std::thread::sleep(std::time::Duration::from_millis(20));
1677        };
1678        let written = std::fs::read_to_string(&part).unwrap_or_default();
1679        let complete = written.rfind('\n').map_or("", |end| &written[..=end]);
1680        recorded.push_str(complete);
1681        match (status, current) {
1682            (Some(status), _) if status.success() => break,
1683            (Some(status), _) => {
1684                let stderr = std::fs::read_to_string(&stderr_path).unwrap_or_default();
1685                let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
1686                bail!(
1687                    "{what} failed ({status}):\n{}",
1688                    tail.into_iter().rev().collect::<Vec<_>>().join("\n")
1689                );
1690            }
1691            (None, Some((i, _))) => {
1692                timed_out.push(cases[start + i].clone());
1693                start += i + 1;
1694            }
1695            (None, None) => unreachable!("the watchdog only stops a driver inside a case"),
1696        }
1697    }
1698    std::fs::write(out, recorded)?;
1699    std::fs::write(work.join(TIMED_OUT), serde_json::to_string(&timed_out)?)?;
1700    Ok(timed_out)
1701}
1702
1703/// Inputs the last `record` left out because the original ran past the time limit on them.
1704pub(crate) const TIMED_OUT: &str = "timed-out.json";
1705
1706pub(crate) struct Scratch(PathBuf);
1707
1708impl Drop for Scratch {
1709    fn drop(&mut self) {
1710        let _ = std::fs::remove_dir_all(&self.0);
1711    }
1712}
1713
1714pub(crate) fn scratch_cwd(cmd: &mut Command) -> Result<Option<Scratch>> {
1715    if cmd.get_current_dir().is_some() {
1716        return Ok(None);
1717    }
1718    let dir = crate::app::temp_dir("unit")?;
1719    cmd.current_dir(&dir);
1720    Ok(Some(Scratch(dir)))
1721}
1722
1723fn run(cmd: &mut Command, what: &str) -> Result<()> {
1724    let _scratch = scratch_cwd(cmd)?;
1725    let output = cmd.output().with_context(|| format!("running {what}"))?;
1726    if !output.status.success() {
1727        let stderr = String::from_utf8_lossy(&output.stderr);
1728        let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
1729        bail!(
1730            "{what} failed ({}):\n{}",
1731            output.status,
1732            tail.into_iter().rev().collect::<Vec<_>>().join("\n")
1733        );
1734    }
1735    Ok(())
1736}
1737
1738/// Python keyword-only parameters (after `*`) are passed by name: they move from `args` into
1739/// `kwargs`, and an omitted (`undefined`) one is left out.
1740/// Integral float arguments of `number` parameters, as ints.
1741fn intify(params: &[crate::ts::exports::Param], args: &mut Value) {
1742    let Some(items) = args.as_array_mut() else {
1743        return;
1744    };
1745    for (p, v) in params.iter().zip(items.iter_mut()) {
1746        if p.ts_type == "number"
1747            && let Some(x) = v.as_f64()
1748            && x.fract() == 0.0
1749            && x.abs() < 1e15
1750            && !(x == 0.0 && x.is_sign_negative())
1751        {
1752            *v = json!(x as i64);
1753        }
1754    }
1755}
1756
1757fn split_keyword_only(params: &[crate::ts::exports::Param], case: &mut Value) {
1758    if !params.iter().any(|p| p.keyword_only) {
1759        return;
1760    }
1761    let Some(args) = case["args"].as_array().cloned() else {
1762        return;
1763    };
1764    let mut positional = Vec::new();
1765    let mut kwargs = serde_json::Map::new();
1766    for (i, value) in args.into_iter().enumerate() {
1767        match params.get(i) {
1768            Some(p) if p.keyword_only => {
1769                if value.get("$undefined").is_none() {
1770                    kwargs.insert(p.name.clone(), value);
1771                }
1772            }
1773            _ => positional.push(value),
1774        }
1775    }
1776    case["args"] = Value::Array(positional);
1777    case["kwargs"] = Value::Object(kwargs);
1778}
1779
1780/// Workspace packages as `{ name: absolute source folder }` for the resolve hook: a monorepo
1781/// imports its own packages by name, and their build output may not exist.
1782fn workspace_env(manifest: &Manifest) -> String {
1783    let packages: BTreeMap<String, String> = crate::ts::discover::discover(&manifest.root)
1784        .map(|ws| {
1785            ws.packages
1786                .into_iter()
1787                .filter(|p| !p.dir.is_empty())
1788                .map(|p| {
1789                    let dir = manifest.root.join(&p.dir);
1790                    let src = if dir.join("src").is_dir() {
1791                        dir.join("src")
1792                    } else {
1793                        dir
1794                    };
1795                    (p.name, src.to_string_lossy().into_owned())
1796                })
1797                .collect()
1798        })
1799        .unwrap_or_default();
1800    serde_json::to_string(&packages).unwrap_or_else(|_| "{}".into())
1801}
1802
1803/// The tsconfig `paths` of the unit's files, as JSON for the resolve hook: `[[pattern, [absolute targets]]]`.
1804fn alias_env(manifest: &Manifest) -> String {
1805    let mut entries: Vec<(String, Vec<String>)> = Vec::new();
1806    let files = manifest
1807        .exports
1808        .iter()
1809        .map(|f| &f.file)
1810        .chain(manifest.classes.iter().map(|c| &c.file));
1811    for file in files {
1812        let dir = file.rsplit_once('/').map_or("", |(d, _)| d);
1813        for (pattern, targets) in
1814            crate::ts::tsconfig::PathAliases::nearest(&manifest.root, dir).entries
1815        {
1816            if entries.iter().all(|(p, _)| *p != pattern) {
1817                let absolute = targets
1818                    .iter()
1819                    .map(|t| manifest.root.join(t).to_string_lossy().into_owned())
1820                    .collect();
1821                entries.push((pattern, absolute));
1822            }
1823        }
1824    }
1825    serde_json::to_string(&entries).unwrap_or_else(|_| "[]".into())
1826}
1827
1828fn file_url(path: &Path) -> String {
1829    use std::fmt::Write as _;
1830
1831    let text = path.to_string_lossy();
1832    #[cfg(windows)]
1833    let text = text.replace('\\', "/");
1834    let mut url = if text.starts_with('/') {
1835        String::from("file://")
1836    } else {
1837        String::from("file:///")
1838    };
1839    for byte in text.bytes() {
1840        if byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b':' | b'-' | b'_' | b'.' | b'~') {
1841            url.push(char::from(byte));
1842        } else {
1843            let _ = write!(url, "%{byte:02X}");
1844        }
1845    }
1846    url
1847}
1848
1849const REGISTER_JS: &str =
1850    "import { register } from 'node:module'\nregister('./resolve.mjs', import.meta.url)\n";
1851
1852/// Node resolve hook: bundler-style relative imports, and npm packages from
1853/// `RUST_ANYTHING_RESOLVE_FROM` when the source tree has none installed.
1854const RESOLVE_JS: &str = r#"
1855import { existsSync, statSync } from 'node:fs'
1856import { fileURLToPath, pathToFileURL } from 'node:url'
1857
1858const extra = process.env.RUST_ANYTHING_RESOLVE_FROM
1859// tsconfig `paths`: exact keys first, then wildcard keys by longest prefix.
1860const aliasPriority = pattern => pattern.includes('*') ? pattern.indexOf('*') : Number.POSITIVE_INFINITY
1861const aliases = JSON.parse(process.env.RUST_ANYTHING_PATHS || '[]')
1862  .sort(([a], [b]) => aliasPriority(b) - aliasPriority(a))
1863// Workspace packages by name: `@x18n/core` and `@x18n/core/sub` resolve to source.
1864const workspace = JSON.parse(process.env.RUST_ANYTHING_WORKSPACE || '{}')
1865const workspaceTargets = (specifier) => {
1866  for (const [name, src] of Object.entries(workspace)) {
1867    if (specifier === name)
1868      return [`${src}/index`]
1869    if (specifier.startsWith(`${name}/`))
1870      return [`${src}/${specifier.slice(name.length + 1)}`, `${src}/${specifier.slice(name.length + 1)}/index`]
1871  }
1872  return []
1873}
1874const aliasTargets = (specifier) => {
1875  for (const [pattern, targets] of aliases) {
1876    const [prefix, suffix = ''] = pattern.split('*')
1877    const exact = !pattern.includes('*')
1878    if (exact ? specifier === pattern : specifier.startsWith(prefix) && specifier.endsWith(suffix) && specifier.length >= prefix.length + suffix.length) {
1879      const star = exact ? '' : specifier.slice(prefix.length, specifier.length - suffix.length)
1880      return targets.map(t => t.replace('*', () => star))
1881    }
1882  }
1883  return []
1884}
1885const suffixes = ['.ts', '.tsx', '.mts', '.js', '.mjs', '/index.ts', '/index.mts', '/index.js']
1886const sourceCandidates = path => {
1887  const exact = path.match(/\.(mjs|cjs|jsx)$/)
1888  if (exact) {
1889    const replacement = { mjs: 'mts', cjs: 'cts', jsx: 'tsx' }[exact[1]]
1890    return [path, path.slice(0, -exact[1].length) + replacement]
1891  }
1892  const stem = path.replace(/\.js$/, '')
1893  return [stem, ...suffixes.map(suffix => stem + suffix)]
1894}
1895const isFile = p => existsSync(p) && statSync(p).isFile()
1896
1897export async function resolve(specifier, context, next) {
1898  // Aliases first: `@/x` is not even a valid package name for Node.
1899  for (const target of [...aliasTargets(specifier), ...workspaceTargets(specifier)]) {
1900    for (const candidate of sourceCandidates(target)) {
1901      if (isFile(candidate))
1902        return next(pathToFileURL(candidate).href, context)
1903    }
1904  }
1905  try {
1906    return await next(specifier, context)
1907  }
1908  catch (error) {
1909    const missing = error?.code === 'ERR_MODULE_NOT_FOUND' || error?.code === 'ERR_UNSUPPORTED_DIR_IMPORT'
1910    if (!missing || !context.parentURL)
1911      throw error
1912    if (specifier.startsWith('.') || specifier.startsWith('/')) {
1913      const path = fileURLToPath(new URL(specifier, context.parentURL))
1914      for (const candidate of sourceCandidates(path)) {
1915        if (isFile(candidate))
1916          return next(pathToFileURL(candidate).href, context)
1917      }
1918    }
1919    else if (extra) {
1920      return next(specifier, { ...context, parentURL: pathToFileURL(`${extra}/`).href })
1921    }
1922    throw error
1923  }
1924}
1925"#;
1926
1927/// Encoding shared by the record, diff and shadow scripts. Lossless for what a JS caller
1928/// can observe: `undefined`, `NaN`, `-0`, BigInt, Map/Set order, key order, lone surrogates.
1929pub const CODEC_JS: &str = r#"
1930const enc = (v, stack = []) => {
1931  if (v === undefined) return { $undefined: true }
1932  if (typeof v === 'number') {
1933    if (Number.isNaN(v)) return { $num: 'NaN' }
1934    if (!Number.isFinite(v)) return { $num: v > 0 ? 'Infinity' : '-Infinity' }
1935    if (Object.is(v, -0)) return { $num: '-0' }
1936    return v
1937  }
1938  // Strings JS split inside a surrogate pair are not valid Unicode: keep their code units.
1939  if (typeof v === 'string' && !v.isWellFormed()) return { $utf16: Array.from({ length: v.length }, (_, i) => v.charCodeAt(i)) }
1940  if (typeof v === 'bigint') return { $bigint: String(v) }
1941  if (typeof v === 'function') return { $function: v.name }
1942  if (typeof v === 'symbol') return { $symbol: String(v.description) }
1943  if (v === null || typeof v !== 'object') return v
1944  if (stack.includes(v)) return { $cycle: true }
1945  const next = [...stack, v]
1946  if (Array.isArray(v)) return v.map(x => enc(x, next))
1947  if (typeof Buffer !== 'undefined' && Buffer.isBuffer(v)) return { $buffer: [...v] }
1948  if (v instanceof Uint8Array) return { $bytes: [...v] }
1949  if (ArrayBuffer.isView(v) && !(v instanceof DataView)) return { $typed: { kind: v.constructor.name, values: [...v].map(x => enc(x, next)) } }
1950  if (v instanceof Map) return { $map: [...v].map(([k, x]) => [enc(k, next), enc(x, next)]) }
1951  if (v instanceof Set) return { $set: [...v].map(x => enc(x, next)) }
1952  if (v instanceof Date) return { $date: Number.isNaN(v.getTime()) ? 'Invalid' : v.toISOString() }
1953  if (v instanceof RegExp) return { $regexp: String(v) }
1954  if (v instanceof Error) return { $error: v.message }
1955  const plain = Object.fromEntries(Object.keys(v).map(k => [k, enc(v[k], next)]))
1956  return looksLikeMarker(plain) ? { $object: plain } : plain
1957}
1958const MARKERS = ['$undefined', '$num', '$bigint', '$utf16', '$map', '$set', '$date', '$bytes', '$buffer', '$typed', '$object']
1959const looksLikeMarker = (v) => {
1960  const keys = Object.keys(v)
1961  return keys.length === 1 && MARKERS.includes(keys[0])
1962}
1963const dec = (v) => {
1964  if (Array.isArray(v)) return v.map(dec)
1965  if (v === null || typeof v !== 'object') return v
1966  if (!looksLikeMarker(v)) return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, dec(x)]))
1967  if ('$object' in v) return Object.fromEntries(Object.entries(v.$object).map(([k, x]) => [k, dec(x)]))
1968  if ('$undefined' in v) return undefined
1969  if ('$num' in v) return Number(v.$num)
1970  if ('$bigint' in v) return BigInt(v.$bigint)
1971  if ('$utf16' in v) {
1972    let text = ''
1973    for (let i = 0; i < v.$utf16.length; i += 8192)
1974      text += String.fromCharCode(...v.$utf16.slice(i, i + 8192))
1975    return text
1976  }
1977  if ('$map' in v) return new Map(v.$map.map(([k, x]) => [dec(k), dec(x)]))
1978  if ('$set' in v) return new Set(v.$set.map(dec))
1979  if ('$date' in v) return new Date(v.$date)
1980  if ('$bytes' in v) return Uint8Array.from(v.$bytes)
1981  if ('$typed' in v) return globalThis[v.$typed.kind].from(v.$typed.values.map(dec))
1982  return Buffer.from(v.$buffer)
1983}
1984const canon = (v, sort) => {
1985  if (Array.isArray(v)) return v.map(x => canon(x, sort))
1986  if (v === null || typeof v !== 'object') return v
1987  const keys = Object.keys(v)
1988  if (sort) keys.sort()
1989  return Object.fromEntries(keys.map(k => [k, canon(v[k], sort)]))
1990}
1991const same = (a, b, sort = false) => JSON.stringify(canon(a, sort)) === JSON.stringify(canon(b, sort))
1992"#;
1993
1994const RECORD_JS: &str = r#"
1995import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
1996import { pathToFileURL } from 'node:url'
1997
1998const [inputsPath, outPath] = process.argv.slice(2)
1999const inputs = JSON.parse(readFileSync(inputsPath, 'utf8'))
2000const modules = new Map()
2001const progress = process.env.RUST_ANYTHING_PROGRESS
2002writeFileSync(outPath, '')
2003const lines = { push: line => appendFileSync(outPath, `${line}\n`) }
2004// A class scenario: construct, then call each method in turn; every step's result is recorded.
2005const runScenario = async (Class, c) => {
2006  const results = []
2007  let instance
2008  try {
2009    instance = new Class(...c.ctor.map(dec))
2010    results.push({ ok: true })
2011  }
2012  catch (error) {
2013    results.push({ error: String(error?.message ?? error) })
2014    return results
2015  }
2016  for (const call of c.calls) {
2017    try {
2018      results.push({ ok: enc(await instance[call.method](...call.args.map(dec))) })
2019    }
2020    catch (error) {
2021      results.push({ error: String(error?.message ?? error) })
2022    }
2023  }
2024  return results
2025}
2026for (const [index, c] of inputs.entries()) {
2027  if (progress) appendFileSync(progress, `${index}\n`)
2028  let mod = modules.get(c.module)
2029  if (!mod) {
2030    mod = await import(pathToFileURL(c.module).href)
2031    modules.set(c.module, mod)
2032  }
2033  if (c.class) {
2034    const Class = mod[c.class] ?? mod.default?.[c.class]
2035    if (typeof Class !== 'function') {
2036      console.error(`${c.class} is not a class exported by ${c.module}`)
2037      process.exit(2)
2038    }
2039    pinCase(index)
2040    lines.push(JSON.stringify({ class: c.class, ctor: c.ctor, calls: c.calls, results: await runScenario(Class, c) }))
2041    continue
2042  }
2043  const fn = mod[c.fn] ?? mod.default?.[c.fn]
2044  if (typeof fn !== 'function') {
2045    console.error(`${c.fn} is not a function exported by ${c.module}`)
2046    process.exit(2)
2047  }
2048  pinCase(index)
2049  try {
2050    const value = await fn(...c.args.map(dec))
2051    lines.push(JSON.stringify({ fn: c.fn, args: c.args, ok: enc(value) }))
2052  }
2053  catch (error) {
2054    lines.push(JSON.stringify({ fn: c.fn, args: c.args, error: String(error?.message ?? error) }))
2055  }
2056}
2057"#;
2058
2059const BENCH_JS: &str = r#"
2060import { readFileSync, writeFileSync } from 'node:fs'
2061import { pathToFileURL } from 'node:url'
2062
2063const [modulesPath, nativePath, casesPath, outPath, minMs] = process.argv.slice(2)
2064const { functions: modules, classes: classModules, asyncFunctions } = JSON.parse(readFileSync(modulesPath, 'utf8'))
2065const loaded = await import(pathToFileURL(nativePath).href)
2066const native = { ...(loaded.default && typeof loaded.default === 'object' ? loaded.default : {}), ...loaded }
2067const cases = readFileSync(casesPath, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l))
2068const byFn = new Map()
2069const scenarios = new Map()
2070for (const c of cases.filter(c => c.class)) {
2071  if (!scenarios.has(c.class)) scenarios.set(c.class, [])
2072  scenarios.get(c.class).push(c)
2073}
2074for (const c of cases.filter(c => !c.class)) {
2075  if (!byFn.has(c.fn)) byFn.set(c.fn, [])
2076  byFn.get(c.fn).push(c.args.map(dec))
2077}
2078// Time whole passes over the cases until `minMs` has passed; errors count as calls.
2079const time = (fn, argsList) => {
2080  const pass = () => {
2081    for (const args of argsList) {
2082      try { fn(...args) } catch {}
2083    }
2084  }
2085  pass()
2086  let passes = 0
2087  const start = performance.now()
2088  do { pass(); passes++ } while (performance.now() - start < Number(minMs))
2089  return (performance.now() - start) * 1e6 / (passes * argsList.length)
2090}
2091const timeAsync = async (fn, argsList) => {
2092  const pass = async () => {
2093    for (const args of argsList) {
2094      try { await fn(...args) } catch {}
2095    }
2096  }
2097  await pass()
2098  let passes = 0
2099  const start = performance.now()
2100  do { await pass(); passes++ } while (performance.now() - start < Number(minMs))
2101  return (performance.now() - start) * 1e6 / (passes * argsList.length)
2102}
2103const rows = []
2104for (const [name, argsList] of byFn) {
2105  const original = (await import(pathToFileURL(modules[name]).href))[name]
2106  const rust = native[name]
2107  if (typeof original !== 'function' || typeof rust !== 'function') continue
2108  const timer = asyncFunctions.includes(name) ? timeAsync : time
2109  const originalNs = await timer(original, argsList)
2110  const rustNs = await timer(rust, argsList)
2111  rows.push({ fn: name, cases: argsList.length, original_ns: originalNs, rust_ns: rustNs, speedup: originalNs / rustNs })
2112}
2113// Classes: time whole scenarios (construct, then every call).
2114const play = (Class, list) => () => {
2115  for (const c of list) {
2116    try {
2117      const instance = new Class(...c.ctor.map(dec))
2118      for (const call of c.calls) {
2119        try { instance[call.method](...call.args.map(dec)) } catch {}
2120      }
2121    } catch {}
2122  }
2123}
2124for (const [name, list] of scenarios) {
2125  const original = (await import(pathToFileURL(classModules[name]).href))[name]
2126  const rust = native[name]
2127  if (typeof original !== 'function' || typeof rust !== 'function') continue
2128  const timeAll = (fn) => {
2129    fn()
2130    let passes = 0
2131    const start = performance.now()
2132    do { fn(); passes++ } while (performance.now() - start < Number(minMs))
2133    return (performance.now() - start) * 1e6 / (passes * list.length)
2134  }
2135  const originalNs = timeAll(play(original, list))
2136  const rustNs = timeAll(play(rust, list))
2137  rows.push({ fn: `class ${name}`, cases: list.length, original_ns: originalNs, rust_ns: rustNs, speedup: originalNs / rustNs })
2138}
2139writeFileSync(outPath, JSON.stringify(rows))
2140"#;
2141
2142const DIFF_JS: &str = r#"
2143import { readFileSync, writeFileSync } from 'node:fs'
2144import { pathToFileURL } from 'node:url'
2145
2146const [modulePath, casesPath, outPath, keyOrder] = process.argv.slice(2)
2147const loaded = await import(pathToFileURL(modulePath).href)
2148const mod = { ...(loaded.default && typeof loaded.default === 'object' ? loaded.default : {}), ...loaded }
2149const cases = readFileSync(casesPath, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l))
2150const summary = { total: cases.length, passed: 0, failed: 0, missing: [], mismatches: [] }
2151const scenario = async (Class, c) => {
2152  const results = []
2153  let instance
2154  try {
2155    instance = new Class(...c.ctor.map(dec))
2156    results.push({ ok: true })
2157  }
2158  catch (error) {
2159    results.push({ error: String(error?.message ?? error) })
2160    return results
2161  }
2162  for (const call of c.calls) {
2163    try {
2164      results.push({ ok: enc(await instance[call.method](...call.args.map(dec))) })
2165    }
2166    catch (error) {
2167      results.push({ error: String(error?.message ?? error) })
2168    }
2169  }
2170  return results
2171}
2172const stepsMatch = (want, got) => want.length === got.length && want.every((w, i) =>
2173  ('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')))
2174for (const [index, c] of cases.entries()) {
2175  pinCase(index)
2176  if (c.class) {
2177    const Class = mod[c.class]
2178    if (typeof Class !== 'function') {
2179      if (!summary.missing.includes(c.class)) summary.missing.push(c.class)
2180      summary.failed++
2181      continue
2182    }
2183    const got = await scenario(Class, c)
2184    if (stepsMatch(c.results, got)) {
2185      summary.passed++
2186    }
2187    else {
2188      summary.failed++
2189      summary.mismatches.push({ fn: c.class, args: [c.ctor, c.calls], expected: c.results, actual: got })
2190    }
2191    continue
2192  }
2193  const fn = mod[c.fn]
2194  let actual
2195  if (typeof fn !== 'function') {
2196    if (!summary.missing.includes(c.fn)) summary.missing.push(c.fn)
2197    actual = { missing: true }
2198  }
2199  else {
2200    try {
2201      actual = { ok: enc(await fn(...c.args.map(dec))) }
2202    }
2203    catch (error) {
2204      actual = { error: String(error?.message ?? error) }
2205    }
2206  }
2207  const expected = 'error' in c ? { error: c.error } : { ok: c.ok }
2208  // Both sides throwing counts as agreement: error messages are not part of the contract.
2209  const panicked = 'error' in actual && actual.error.startsWith('Rust panic:')
2210  const pass = !panicked && ('error' in expected && 'error' in actual) || ('ok' in expected && 'ok' in actual && same(expected.ok, actual.ok, keyOrder === 'sort'))
2211  if (pass) {
2212    summary.passed++
2213  }
2214  else {
2215    summary.failed++
2216    summary.mismatches.push({ fn: c.fn, args: c.args, expected, actual })
2217  }
2218}
2219writeFileSync(outPath, JSON.stringify(summary, null, 2))
2220"#;
2221
2222#[cfg(test)]
2223mod tests {
2224    use super::*;
2225    use crate::ts::exports::{ExportedFn, Param};
2226
2227    #[test]
2228    fn the_js_codec_keeps_marker_shaped_data_and_typed_arrays() {
2229        let script = format!(
2230            "{CODEC_JS}\n{}",
2231            r#"
2232const assert = (ok, what) => { if (!ok) { console.error(what); process.exit(1) } }
2233const round = v => dec(JSON.parse(JSON.stringify(enc(v))))
2234const plain = [{ $date: '2024-01-01T00:00:00.000Z' }, { $undefined: true }, { $bigint: '7' }, { $object: 1 }]
2235for (const v of plain) assert(JSON.stringify(round(v)) === JSON.stringify(v), 'plain ' + JSON.stringify(v))
2236const wide = dec({ $date: '2024-01-01T00:00:00.000Z', tz: 'UTC' })
2237assert(wide.tz === 'UTC' && typeof wide.$date === 'string', 'sibling keys are data')
2238assert(round(new Date(0)) instanceof Date, 'dates still decode')
2239for (const T of [Float64Array, Float32Array, Int32Array, Uint8ClampedArray, BigInt64Array]) {
2240  const v = T === BigInt64Array ? new T([1n, -2n]) : new T([1, 2])
2241  const back = round(v)
2242  assert(back instanceof T && back.length === 2 && back[1] === v[1], 'typed ' + T.name)
2243}
2244assert(JSON.stringify(enc(new Float64Array([1, 2]))) !== JSON.stringify(enc(new Int32Array([1, 2]))), 'kinds differ')
2245assert(round(new Uint8Array([1])) instanceof Uint8Array, 'bytes stay bytes')
2246"#
2247        );
2248        let Ok(out) = Command::new("node")
2249            .args(["--input-type=module", "-e", &script])
2250            .output()
2251        else {
2252            return;
2253        };
2254        assert!(
2255            out.status.success(),
2256            "{}",
2257            String::from_utf8_lossy(&out.stderr)
2258        );
2259    }
2260
2261    fn f(params: &[(&str, &str)]) -> ExportedFn {
2262        ExportedFn {
2263            name: "f".into(),
2264            file: "a.ts".into(),
2265            line: 1,
2266            params: params
2267                .iter()
2268                .map(|(n, t)| Param {
2269                    name: (*n).into(),
2270                    ts_type: (*t).into(),
2271                    optional: false,
2272                    rest: false,
2273                    ..Default::default()
2274                })
2275                .collect(),
2276            returns: "number".into(),
2277            is_async: false,
2278            is_generator: false,
2279            type_params: Vec::new(),
2280            uses_instanceof: false,
2281            ..Default::default()
2282        }
2283    }
2284
2285    #[test]
2286    fn reads_case_lines_deeper_than_128() {
2287        let deep = format!("{}1{}", "[".repeat(300), "]".repeat(300));
2288        assert!(serde_json::from_str::<Value>(&deep).is_err());
2289        assert!(parse_deep(&deep).is_ok());
2290        assert!(parse_deep("[1] x").is_err());
2291    }
2292
2293    #[test]
2294    fn generates_deterministic_distinct_inputs() {
2295        let a = generate(&f(&[("q", "string"), ("t", "string")]), 50, &[]);
2296        let b = generate(&f(&[("q", "string"), ("t", "string")]), 50, &[]);
2297        assert_eq!(a, b);
2298        assert_eq!(a.len(), 50);
2299        let unique: std::collections::HashSet<String> = a.iter().map(|v| v.to_string()).collect();
2300        assert_eq!(unique.len(), 50);
2301        assert!(
2302            a.iter()
2303                .any(|args| args.to_string().contains('😀') || args.to_string().contains('👍'))
2304        );
2305    }
2306
2307    #[test]
2308    fn generates_values_that_fit_object_types() {
2309        let types = crate::ts::exports::local_types(
2310            "m.ts",
2311            "export interface Edit { readonly range: { start: number, end: number }, readonly text: string }\n",
2312        );
2313        let cases = generate(&f(&[("edits", "readonly Edit[]")]), 60, &types);
2314        let fitting = cases
2315            .iter()
2316            .filter_map(|args| args[0].as_array())
2317            .flatten()
2318            .filter(|e| e["range"]["start"].is_number() || e["range"]["start"].is_object())
2319            .count();
2320        assert!(fitting > 20, "{fitting}");
2321    }
2322
2323    #[test]
2324    fn covers_number_edge_cases() {
2325        let cases = generate(&f(&[("n", "number")]), 18, &[]);
2326        let text = serde_json::to_string(&cases).unwrap();
2327        assert!(text.contains("NaN") && text.contains("-0"));
2328    }
2329}
2330
2331#[cfg(test)]
2332mod verdict_tests {
2333    use super::*;
2334
2335    fn row(name: &str, speedup: f64) -> BenchRow {
2336        BenchRow {
2337            name: name.into(),
2338            cases: 1,
2339            original_ns: speedup,
2340            rust_ns: 1.0,
2341            speedup,
2342        }
2343    }
2344
2345    #[test]
2346    fn advice_follows_the_numbers() {
2347        let ts = crate::lang::Lang::Ts;
2348        assert!(
2349            verdict(&[row("a", 3.0), row("b", 2.0)], ts)
2350                .advice
2351                .starts_with("Ship it: every")
2352        );
2353        assert!(
2354            verdict(&[row("a", 3.0), row("b", 1.0)], ts)
2355                .advice
2356                .starts_with("Ship it: no function")
2357        );
2358        let mixed = verdict(&[row("a", 4.0), row("b", 0.5)], ts);
2359        assert!(mixed.advice.contains("Keep the slower ones") && mixed.advice.ends_with("b."));
2360        assert!(
2361            verdict(&[row("a", 0.2), row("b", 0.3)], ts)
2362                .advice
2363                .starts_with("Do not ship")
2364        );
2365        assert!(
2366            verdict(&[row("a", 0.5)], crate::lang::Lang::C)
2367                .advice
2368                .starts_with("No call overhead")
2369        );
2370    }
2371}
2372
2373/// Parses one case line: recorded values (a pretty-printer's document trees) nest deeper than
2374/// serde_json's default limit of 128.
2375pub(crate) fn parse_deep(text: &str) -> serde_json::Result<Value> {
2376    let mut de = serde_json::Deserializer::from_str(text);
2377    de.disable_recursion_limit();
2378    let value = Value::deserialize(&mut de)?;
2379    de.end()?;
2380    Ok(value)
2381}