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