rust-anything 4.1.0

Rewrite your app in Rust, one piece at a time, checked against the original's recorded behavior at every step. TypeScript/JavaScript, Python, C, Go, Ruby, Java, Kotlin, PHP, C# and PowerShell
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
//! `enable` and `disable`: switch a ported unit in and out of the app with one command.
//!
//! `enable` puts one marked block in each original source file of the unit (TS/JS or Python).
//! The block loads the built Rust module and rebinds the ported functions, so every caller gets
//! Rust without an import changing. `disable` removes exactly the lines `enable` added. At run
//! time `RUST_ANYTHING_MODE=old` or the unit's `RUST_ANYTHING_UNIT_<NAME>=original` keeps the
//! original, and a module that fails to load falls back to it (`RUST_ANYTHING_MODE=new` makes
//! that an error instead).

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{Context, Result, bail};
use serde::Serialize;

use crate::bridge::{Kind, Manifest};
use crate::lang::Lang;
use crate::walk::Canonical;

const START: &str = ">>> rust-anything:";
const END: &str = "<<< rust-anything:";
const EOF_NOTE: &str = " (newline added)";

#[derive(Debug, Serialize)]
pub struct Switched {
    pub crate_name: String,
    pub on: bool,
    /// Source files that changed.
    pub files: Vec<PathBuf>,
    /// Functions that run in Rust while the unit is on.
    pub functions: Vec<String>,
    /// Exports left to the original, with why.
    pub skipped: Vec<String>,
    /// The variable that sends this unit back to the original for one run.
    pub switch: String,
}

/// Whether `enable` left its block in any of the unit's files.
pub fn is_enabled(crate_dir: &Path) -> Result<bool> {
    let manifest = Manifest::load(crate_dir)?;
    Ok(files(&manifest).iter().any(|f| {
        std::fs::read_to_string(manifest.root.join(f))
            .is_ok_and(|text| find_block(&text, &manifest.crate_name).is_some())
    }))
}

/// Sets the unit's kill switch on a command that runs the original, so a recording, diff or
/// bench of an enabled unit measures the original, not the port.
pub fn original_only(cmd: &mut Command, manifest: &Manifest) {
    cmd.env(
        crate::front_door::kill_switch(&manifest.crate_name),
        "original",
    );
}

pub fn enable(crate_dir: &Path) -> Result<Switched> {
    enable_only(crate_dir, None, &[])
}

/// Switches on either all exports (`only = None`) or a specific subset (`only = Some(names)`).
/// `extra_skipped` holds human-readable skip reasons already decided by the caller (e.g.
/// per-function diff counts under `--partial`).
pub fn enable_only(
    crate_dir: &Path,
    only: Option<&[String]>,
    extra_skipped: &[String],
) -> Result<Switched> {
    let crate_dir = crate_dir.canonical().with_context(|| {
        format!(
            "resolving {} (run `rust-anything bridge` first)",
            crate_dir.display()
        )
    })?;
    let manifest = Manifest::load(&crate_dir)?;
    supported(&manifest)?;
    let selected: Option<Vec<&str>> = match only {
        Some(names) => {
            let mut unknown = Vec::new();
            let mut chosen = Vec::new();
            for name in names {
                if manifest.exports.iter().any(|e| e.name == *name) {
                    if !chosen.contains(&name.as_str()) {
                        chosen.push(name.as_str());
                    }
                } else {
                    unknown.push(name.as_str());
                }
            }
            if !unknown.is_empty() {
                bail!(
                    "unknown export(s) in {}: {}",
                    manifest.crate_name,
                    unknown.join(", ")
                );
            }
            if manifest.language == Lang::Powershell && chosen.len() < manifest.exports.len() {
                bail!(
                    "partial enable (--only / --partial) is not supported for PowerShell units: \
                     dot-sourcing the wrapper rebinds every function in the file"
                );
            }
            Some(chosen)
        }
        None => None,
    };
    let switch = crate::front_door::kill_switch(&manifest.crate_name);
    let mut by_file: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    for f in &manifest.exports {
        by_file.entry(&f.file).or_default().push(&f.name);
    }
    let mut skipped: Vec<String> = manifest
        .js_only
        .iter()
        .map(|j| format!("{}: kept in the original", j.name))
        .collect();
    skipped.extend(extra_skipped.iter().cloned());
    if let Some(chosen) = &selected {
        for f in &manifest.exports {
            if !chosen.contains(&f.name.as_str())
                && !extra_skipped
                    .iter()
                    .any(|s| s.starts_with(&format!("{}:", f.name)))
            {
                skipped.push(format!(
                    "{}: not selected (--only), kept in the original",
                    f.name
                ));
            }
        }
    }
    let mut out = Switched {
        crate_name: manifest.crate_name.clone(),
        on: true,
        files: Vec::new(),
        functions: Vec::new(),
        skipped,
        switch: switch.clone(),
    };
    let mut edits = Vec::new();
    for (file, names) in by_file {
        let path = manifest.root.join(file);
        let text = std::fs::read_to_string(&path)
            .with_context(|| format!("reading {}", path.display()))?;
        let base = remove(&text, &manifest.crate_name).unwrap_or_else(|| text.clone());
        let wanted: Vec<&str> = match &selected {
            Some(chosen) => names.into_iter().filter(|n| chosen.contains(n)).collect(),
            None => names,
        };
        let (swap, skip): (Vec<&str>, Vec<&str>) = wanted
            .into_iter()
            .partition(|n| declared(&base, n, manifest.language));
        out.skipped.extend(skip.iter().map(|n| {
            format!("{n}: not a plain function declaration in {file}, so callers keep the original")
        }));
        if swap.is_empty() {
            if base != text {
                edits.push((path.clone(), base));
                out.files.push(path);
            }
            continue;
        }
        let dir = path
            .parent()
            .context("source file has no folder")?
            .canonical()?;
        let block = match manifest.language {
            Lang::Python => python_block(&manifest, &crate_dir, &dir, &swap, &switch),
            Lang::Powershell => powershell_block(&manifest, &crate_dir, &dir, &switch),
            _ => js_block(
                &manifest,
                &crate_dir,
                &dir,
                &swap,
                &switch,
                esm(file, &base),
            ),
        };
        let edited = insert(&base, &block, manifest.language);
        if edited != text {
            edits.push((path.clone(), edited));
            out.files.push(path);
        }
        out.functions.extend(swap.iter().map(|n| n.to_string()));
    }
    if out.functions.is_empty() {
        bail!(
            "nothing to switch on in {}: {}",
            manifest.crate_name,
            out.skipped.join("; ")
        );
    }
    for (path, text) in edits {
        std::fs::write(&path, text).with_context(|| format!("writing {}", path.display()))?;
    }
    Ok(out)
}

/// Picks which exports to switch on from per-function diff counts.
///
/// - When `only` is non-empty (`--only`), validates each requested export exists and that all of
///   its recorded cases match, returning `(selected, skipped_reasons)`.
/// - When `only` is empty (`--partial`), selects every export whose recorded cases all match and
///   lists the rest as `"<name>: <passed>/<total> match, kept in the original"`.
pub fn select_matching(
    manifest: &Manifest,
    outcome: &crate::harness::DiffOutcome,
    counts: &BTreeMap<String, (usize, usize)>,
    only: &[String],
) -> Result<(Vec<String>, Vec<String>)> {
    let status = |name: &str| -> (bool, String) {
        if outcome.missing.iter().any(|m| m == name) {
            return (
                false,
                format!("{name}: missing from the Rust module, kept in the original"),
            );
        }
        match counts.get(name).copied() {
            Some((passed, total)) if total > 0 && passed == total => (true, String::new()),
            Some((passed, total)) if total > 0 => (
                false,
                format!("{name}: {passed}/{total} match, kept in the original"),
            ),
            _ => (
                false,
                format!("{name}: no recorded cases, kept in the original"),
            ),
        }
    };

    if !only.is_empty() {
        let mut unknown = Vec::new();
        let mut selected = Vec::new();
        let mut failures = Vec::new();
        for name in only {
            if !manifest.exports.iter().any(|e| e.name == *name) {
                unknown.push(name.as_str());
                continue;
            }
            if selected.contains(name) {
                continue;
            }
            let (ok, reason) = status(name);
            if ok {
                selected.push(name.clone());
            } else {
                failures.push(reason);
            }
        }
        if !unknown.is_empty() {
            bail!(
                "unknown export(s) in {}: {}",
                manifest.crate_name,
                unknown.join(", ")
            );
        }
        if !failures.is_empty() {
            bail!(
                "requested function(s) do not match all recorded cases ({}); pass --force to switch them on anyway",
                failures.join("; ")
            );
        }
        let skipped = manifest
            .exports
            .iter()
            .filter(|e| !selected.contains(&e.name))
            .map(|e| format!("{}: not selected (--only), kept in the original", e.name))
            .collect();
        return Ok((selected, skipped));
    }

    let mut selected = Vec::new();
    let mut skipped = Vec::new();
    for e in &manifest.exports {
        let (ok, reason) = status(&e.name);
        if ok {
            selected.push(e.name.clone());
        } else {
            skipped.push(reason);
        }
    }
    if selected.is_empty() {
        bail!(
            "no functions in {} have all recorded cases matching ({})",
            manifest.crate_name,
            skipped.join("; ")
        );
    }
    Ok((selected, skipped))
}

pub fn disable(crate_dir: &Path) -> Result<Switched> {
    let crate_dir = crate_dir.canonical().with_context(|| {
        format!(
            "resolving {} (run `rust-anything bridge` first)",
            crate_dir.display()
        )
    })?;
    let manifest = Manifest::load(&crate_dir)?;
    let mut out = Switched {
        crate_name: manifest.crate_name.clone(),
        on: false,
        files: Vec::new(),
        functions: Vec::new(),
        skipped: Vec::new(),
        switch: crate::front_door::kill_switch(&manifest.crate_name),
    };
    for file in files(&manifest) {
        let path = manifest.root.join(file);
        let Ok(text) = std::fs::read_to_string(&path) else {
            continue;
        };
        if let Some(restored) = remove(&text, &manifest.crate_name) {
            std::fs::write(&path, restored)
                .with_context(|| format!("writing {}", path.display()))?;
            out.files.push(path);
        }
    }
    out.functions = manifest.exports.iter().map(|f| f.name.clone()).collect();
    Ok(out)
}

pub fn is_supported(manifest: &Manifest) -> bool {
    matches!(
        (manifest.language, manifest.kind),
        (Lang::Python, Kind::Pyo3)
            | (Lang::Ts, Kind::Napi | Kind::Wasm)
            | (Lang::Powershell, Kind::Ffi)
    )
}

fn supported(manifest: &Manifest) -> Result<()> {
    match manifest.language {
        _ if is_supported(manifest) => Ok(()),
        lang => bail!(
            "`enable` switches TS/JS, Python and PowerShell ports in place; for {} use the shadow module \
             (`rust-anything shadow`), imported where the app imported the original, and \
             RUST_ANYTHING_MODE=old|shadow|new",
            lang.name()
        ),
    }
}

fn files(manifest: &Manifest) -> Vec<&str> {
    let mut files: Vec<&str> = manifest.exports.iter().map(|f| f.file.as_str()).collect();
    files.sort_unstable();
    files.dedup();
    files
}

/// A function the block can rebind: a top-level `def` (Python) or a `function` declaration.
fn declared(text: &str, name: &str, lang: Lang) -> bool {
    let name = regex::escape(name);
    let pattern = if lang == Lang::Python {
        format!(r"(?m)^(async\s+)?def\s+{name}\s*\(")
    } else if lang == Lang::Powershell {
        format!(r"(?mi)^\s*function\s+{name}\s*[{{(\s]")
    } else {
        format!(r"(?m)^\s*(export\s+)?(default\s+)?(async\s+)?function\s*\*?\s*{name}\s*[<(]")
    };
    regex::Regex::new(&pattern).is_ok_and(|re| re.is_match(text))
}

fn esm(file: &str, text: &str) -> bool {
    if file.ends_with(".cjs") || file.ends_with(".cts") {
        return false;
    }
    file.ends_with(".mjs")
        || file.ends_with(".mts")
        || text
            .lines()
            .any(|l| l.starts_with("import ") || l.starts_with("export "))
}

fn marker(comment: &str, crate_name: &str, crate_dir: &Path, dir: &Path) -> (String, String) {
    let at = crate::shadow::relative(dir, crate_dir);
    (
        format!(
            "{comment} {START} {crate_name} is on. `rust-anything disable {at}` removes this block."
        ),
        format!("{comment} {END} {crate_name}"),
    )
}

fn js_block(
    manifest: &Manifest,
    crate_dir: &Path,
    dir: &Path,
    names: &[&str],
    switch: &str,
    esm: bool,
) -> String {
    let (start, end) = marker("//", &manifest.crate_name, crate_dir, dir);
    // `index.cjs` for every kind, including wasm: the raw `pkg/<crate>.js` wasm-bindgen module
    // takes pre-serialized JSON strings, while the wrapper accepts the JS values a caller passes
    // and maps the `$num`/`$undefined` markers.
    let module = crate_dir.join("index.cjs");
    let rel = crate::shadow::relative(dir, &module);
    let here = if esm {
        "import.meta.dirname"
    } else {
        "__dirname"
    };
    let var = format!(
        "__rustAnything_{}",
        crate::front_door::ident(&manifest.crate_name)
    );
    let assign: Vec<String> = names.iter().map(|n| format!("{n} = {var}.{n}")).collect();
    format!(
        "{start}\n\
         // @ts-ignore\n\
         const {var} = ((p) => p && p.env.RUST_ANYTHING_MODE !== 'old' && p.env.{switch} !== 'original' && (() => {{ try {{ const m = p.getBuiltinModule('node:module'); const at = p.getBuiltinModule('node:path').join({here}, {rel:?}); return m.createRequire(at)(at) }} catch (e) {{ if (p.env.RUST_ANYTHING_MODE === 'new') throw e }} }})())(globalThis.process)\n\
         // @ts-ignore\n\
         if ({var}) {{ {} }}\n\
         {end}\n",
        assign.join("; ")
    )
}

fn python_block(
    manifest: &Manifest,
    crate_dir: &Path,
    dir: &Path,
    names: &[&str],
    switch: &str,
) -> String {
    let (start, end) = marker("#", &manifest.crate_name, crate_dir, dir);
    let (package_dir, lib) = crate::harness_py::package(crate_dir, manifest);
    let rel = crate::shadow::relative(dir, &package_dir);
    let fun = format!(
        "_rust_anything_{}",
        crate::front_door::ident(&manifest.crate_name)
    );
    let names: Vec<String> = names.iter().map(|n| format!("{n:?}")).collect();
    format!(
        "{start}\n\
         def {fun}():\n\
         \x20   import importlib, os, sys\n\
         \x20   mode = os.environ.get(\"RUST_ANYTHING_MODE\")\n\
         \x20   if mode == \"old\" or os.environ.get(\"{switch}\") == \"original\":\n\
         \x20       return\n\
         \x20   at = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), {rel:?}))\n\
         \x20   sys.path.insert(0, at)\n\
         \x20   try:\n\
         \x20       native = importlib.import_module({lib:?})\n\
         \x20   except ImportError:\n\
         \x20       if mode == \"new\":\n\
         \x20           raise\n\
         \x20       return\n\
         \x20   finally:\n\
         \x20       sys.path.remove(at)\n\
         \x20   globals().update({{name: getattr(native, name) for name in [{}]}})\n\
         \n\
         \n\
         {fun}()\n\
         del {fun}\n\
         {end}\n",
        names.join(", ")
    )
}

fn powershell_block(manifest: &Manifest, crate_dir: &Path, dir: &Path, switch: &str) -> String {
    let (start, end) = marker("#", &manifest.crate_name, crate_dir, dir);
    let wrapper = crate_dir.join(crate::codegen_powershell::wrapper_path(manifest));
    let rel = crate::shadow::relative(dir, &wrapper).replace('\'', "''");
    format!(
        "{start}\n\
         if ($env:RUST_ANYTHING_MODE -ne 'old' -and $env:{switch} -ne 'original') {{\n\
         \x20   try {{\n\
         \x20       . (Join-Path $PSScriptRoot '{rel}')\n\
         \x20   }} catch {{\n\
         \x20       if ($env:RUST_ANYTHING_MODE -eq 'new') {{ throw }}\n\
         \x20   }}\n\
         }}\n\
         {end}\n"
    )
}

/// Puts the block on its own lines: Python before a top-level `if __name__ == "__main__":`
/// (else at the end, after every `def`), JS after a shebang and `"use strict"`, where hoisted
/// function declarations can already be rebound.
fn insert(text: &str, block: &str, lang: Lang) -> String {
    let at = if lang == Lang::Powershell {
        crate::lang::powershell::after_functions(text).unwrap_or(text.len())
    } else if lang == Lang::Python {
        line_starts(text)
            .find(|&i| {
                let line = &text[i..];
                line.starts_with("if __name__ == \"__main__\"")
                    || line.starts_with("if __name__ == '__main__'")
            })
            .unwrap_or(text.len())
    } else {
        line_starts(text)
            .find(|&i| {
                let line = text[i..].lines().next().unwrap_or_default().trim();
                !(line.starts_with("#!")
                    || line == "'use strict'"
                    || line == "\"use strict\""
                    || line == "'use strict';"
                    || line == "\"use strict\";")
            })
            .unwrap_or(text.len())
    };
    let mut out = String::with_capacity(text.len() + block.len() + 1);
    out.push_str(&text[..at]);
    if at == text.len() && !text.is_empty() && !text.ends_with('\n') {
        out.push('\n');
        let (first, rest) = block.split_once('\n').unwrap_or((block, ""));
        out.push_str(first);
        out.push_str(EOF_NOTE);
        out.push('\n');
        out.push_str(rest);
    } else {
        out.push_str(block);
    }
    out.push_str(&text[at..]);
    out
}

fn line_starts(text: &str) -> impl Iterator<Item = usize> + '_ {
    std::iter::once(0)
        .chain(text.match_indices('\n').map(|(i, _)| i + 1))
        .filter(move |&i| i < text.len())
}

/// The byte range of the unit's block, from its first line to the end of its last.
fn find_block(text: &str, crate_name: &str) -> Option<(usize, usize, bool)> {
    let start_tag = format!("{START} {crate_name} is on.");
    let end_tag = format!("{END} {crate_name}");
    let mut start = None;
    for i in std::iter::once(0).chain(text.match_indices('\n').map(|(i, _)| i + 1)) {
        let line = text[i..].split('\n').next().unwrap_or_default();
        match start {
            None if line.contains(&start_tag) => start = Some((i, line.ends_with(EOF_NOTE))),
            Some((s, added)) if line.trim_end().ends_with(&end_tag) => {
                let end = (i + line.len() + 1).min(text.len());
                return Some((s, end, added));
            }
            _ => {}
        }
    }
    None
}

fn remove(text: &str, crate_name: &str) -> Option<String> {
    let (start, end, added) = find_block(text, crate_name)?;
    let start = if added && end == text.len() && start > 0 {
        start - 1
    } else {
        start
    };
    Some(format!("{}{}", &text[..start], &text[end..]))
}

#[cfg(test)]
mod tests {
    use super::*;

    const BLOCK: &str = "# >>> rust-anything: fuzzy-rs is on. `rust-anything disable x` removes this block.\nx = 1\n# <<< rust-anything: fuzzy-rs\n";

    #[test]
    fn python_goes_before_the_main_guard_and_comes_out_byte_for_byte() {
        let text = "def f(a):\n    return a\n\nif __name__ == \"__main__\":\n    print(f(1))\n";
        let on = insert(text, BLOCK, Lang::Python);
        assert!(
            on.find("x = 1").unwrap() < on.find("if __name__").unwrap(),
            "{on}"
        );
        assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
        assert!(remove(text, "fuzzy-rs").is_none());
    }

    #[test]
    fn a_file_without_a_final_newline_gets_it_back_the_same() {
        let text = "def f(a):\n    return a";
        let on = insert(text, BLOCK, Lang::Python);
        assert!(on.contains(EOF_NOTE), "{on}");
        assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
    }

    #[test]
    fn js_goes_after_the_shebang_and_use_strict() {
        let text = "#!/usr/bin/env node\n'use strict'\nfunction f(a) { return a }\nmodule.exports = { f }\n";
        let block = BLOCK.replace('#', "//");
        let on = insert(text, &block, Lang::Ts);
        assert!(
            on.starts_with("#!/usr/bin/env node\n'use strict'\n// >>>"),
            "{on}"
        );
        assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
    }

    #[test]
    fn only_declarations_can_be_rebound() {
        let js = "export function score(a: string): number { return 1 }\nexport const other = () => 2\nexport async function* gen<T>(x: T) {}\n";
        assert!(declared(js, "score", Lang::Ts));
        assert!(!declared(js, "other", Lang::Ts));
        assert!(declared(js, "gen", Lang::Ts));
        let py = "def dedupe(names):\n    pass\n\nclass A:\n    def inner(self):\n        pass\n";
        assert!(declared(py, "dedupe", Lang::Python));
        assert!(!declared(py, "inner", Lang::Python));
    }

    #[test]
    fn module_kind_follows_the_syntax() {
        assert!(esm("a.ts", "import x from 'y'\n"));
        assert!(esm("a.mjs", ""));
        assert!(!esm(
            "a.js",
            "const x = require('y')\nmodule.exports = {}\n"
        ));
        assert!(!esm("a.cjs", "export function f() {}\n"));
    }

    #[test]
    fn select_matching_handles_partial_and_only_modes() {
        use crate::harness::DiffOutcome;
        use crate::ts::exports::ExportedFn;

        let export = |name: &str| ExportedFn {
            name: name.into(),
            file: "util.py".into(),
            line: 1,
            ..Default::default()
        };
        let manifest = Manifest {
            schema: "1".into(),
            root: PathBuf::from("/tmp"),
            root_written: None,
            unit: "util.py".into(),
            language: Lang::Python,
            kind: Kind::Pyo3,
            crate_name: "util-rs".into(),
            exports: vec![export("slug"), export("words"), export("missing_fn")],
            classes: Vec::new(),
            js_only: Vec::new(),
            batches: Vec::new(),
            allocator: Default::default(),
            float_tolerance: None,
            ignore_key_order: false,
        };
        let outcome = DiffOutcome {
            total: 446,
            passed: 223,
            failed: 223,
            missing: vec!["missing_fn".into()],
            ..Default::default()
        };
        let counts = BTreeMap::from([
            ("slug".into(), (223, 223)),
            ("words".into(), (0, 223)),
            ("missing_fn".into(), (0, 10)),
        ]);

        // --partial picks only `slug` and reports per-function skip reasons for the rest.
        let (selected, skipped) = select_matching(&manifest, &outcome, &counts, &[]).unwrap();
        assert_eq!(selected, ["slug"]);
        assert_eq!(
            skipped,
            [
                "words: 0/223 match, kept in the original",
                "missing_fn: missing from the Rust module, kept in the original",
            ]
        );

        // --only accepts a matching function even while others fail.
        let (selected, skipped) =
            select_matching(&manifest, &outcome, &counts, &["slug".into()]).unwrap();
        assert_eq!(selected, ["slug"]);
        assert_eq!(skipped.len(), 2);

        // --only rejects a failing requested function.
        let err = select_matching(&manifest, &outcome, &counts, &["words".into()]).unwrap_err();
        assert!(format!("{err:#}").contains("words: 0/223 match"), "{err:#}");

        // --only rejects an unknown export name.
        let err = select_matching(&manifest, &outcome, &counts, &["nope".into()]).unwrap_err();
        assert!(format!("{err:#}").contains("unknown export(s)"), "{err:#}");

        // --partial fails clearly when nothing matches.
        let none_counts = BTreeMap::from([("slug".into(), (1, 2)), ("words".into(), (0, 223))]);
        let err = select_matching(&manifest, &outcome, &none_counts, &[]).unwrap_err();
        assert!(
            format!("{err:#}").contains("no functions in util-rs have all recorded cases matching"),
            "{err:#}"
        );
    }
}