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