Skip to main content

rust_anything/
enable.rs

1//! `enable` and `disable`: switch a ported unit in and out of the app with one command.
2//!
3//! `enable` puts one marked block in each original source file of the unit (TS/JS or Python).
4//! The block loads the built Rust module and rebinds the ported functions, so every caller gets
5//! Rust without an import changing. `disable` removes exactly the lines `enable` added. At run
6//! time `RUST_ANYTHING_MODE=old` or the unit's `RUST_ANYTHING_UNIT_<NAME>=original` keeps the
7//! original, and a module that fails to load falls back to it (`RUST_ANYTHING_MODE=new` makes
8//! that an error instead).
9
10use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12use std::process::Command;
13
14use anyhow::{Context, Result, bail};
15use serde::Serialize;
16
17use crate::bridge::{Kind, Manifest};
18use crate::lang::Lang;
19use crate::walk::Canonical;
20
21const START: &str = ">>> rust-anything:";
22const END: &str = "<<< rust-anything:";
23const EOF_NOTE: &str = " (newline added)";
24
25#[derive(Debug, Serialize)]
26pub struct Switched {
27    pub crate_name: String,
28    pub on: bool,
29    /// Source files that changed.
30    pub files: Vec<PathBuf>,
31    /// Functions that run in Rust while the unit is on.
32    pub functions: Vec<String>,
33    /// Exports left to the original, with why.
34    pub skipped: Vec<String>,
35    /// The variable that sends this unit back to the original for one run.
36    pub switch: String,
37}
38
39/// Whether `enable` left its block in any of the unit's files.
40pub fn is_enabled(crate_dir: &Path) -> Result<bool> {
41    let manifest = Manifest::load(crate_dir)?;
42    Ok(files(&manifest).iter().any(|f| {
43        std::fs::read_to_string(manifest.root.join(f))
44            .is_ok_and(|text| find_block(&text, &manifest.crate_name).is_some())
45    }))
46}
47
48/// Sets the unit's kill switch on a command that runs the original, so a recording, diff or
49/// bench of an enabled unit measures the original, not the port.
50pub fn original_only(cmd: &mut Command, manifest: &Manifest) {
51    cmd.env(
52        crate::front_door::kill_switch(&manifest.crate_name),
53        "original",
54    );
55}
56
57pub fn enable(crate_dir: &Path) -> Result<Switched> {
58    let crate_dir = crate_dir.canonical().with_context(|| {
59        format!(
60            "resolving {} (run `rust-anything bridge` first)",
61            crate_dir.display()
62        )
63    })?;
64    let manifest = Manifest::load(&crate_dir)?;
65    supported(&manifest)?;
66    let switch = crate::front_door::kill_switch(&manifest.crate_name);
67    let mut by_file: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
68    for f in &manifest.exports {
69        by_file.entry(&f.file).or_default().push(&f.name);
70    }
71    let mut out = Switched {
72        crate_name: manifest.crate_name.clone(),
73        on: true,
74        files: Vec::new(),
75        functions: Vec::new(),
76        skipped: manifest
77            .js_only
78            .iter()
79            .map(|j| format!("{}: kept in the original", j.name))
80            .collect(),
81        switch: switch.clone(),
82    };
83    let mut edits = Vec::new();
84    for (file, names) in by_file {
85        let path = manifest.root.join(file);
86        let text = std::fs::read_to_string(&path)
87            .with_context(|| format!("reading {}", path.display()))?;
88        if find_block(&text, &manifest.crate_name).is_some() {
89            out.functions.extend(names.iter().map(|n| n.to_string()));
90            continue;
91        }
92        let (swap, skip): (Vec<&str>, Vec<&str>) = names
93            .into_iter()
94            .partition(|n| declared(&text, n, manifest.language));
95        out.skipped.extend(skip.iter().map(|n| {
96            format!("{n}: not a plain function declaration in {file}, so callers keep the original")
97        }));
98        if swap.is_empty() {
99            continue;
100        }
101        let dir = path
102            .parent()
103            .context("source file has no folder")?
104            .canonical()?;
105        let block = match manifest.language {
106            Lang::Python => python_block(&manifest, &crate_dir, &dir, &swap, &switch),
107            Lang::Powershell => powershell_block(&manifest, &crate_dir, &dir, &switch),
108            _ => js_block(
109                &manifest,
110                &crate_dir,
111                &dir,
112                &swap,
113                &switch,
114                esm(file, &text),
115            ),
116        };
117        let edited = insert(&text, &block, manifest.language);
118        edits.push((path.clone(), edited));
119        out.files.push(path);
120        out.functions.extend(swap.iter().map(|n| n.to_string()));
121    }
122    if out.functions.is_empty() {
123        bail!(
124            "nothing to switch on in {}: {}",
125            manifest.crate_name,
126            out.skipped.join("; ")
127        );
128    }
129    for (path, text) in edits {
130        std::fs::write(&path, text).with_context(|| format!("writing {}", path.display()))?;
131    }
132    Ok(out)
133}
134
135pub fn disable(crate_dir: &Path) -> Result<Switched> {
136    let crate_dir = crate_dir.canonical().with_context(|| {
137        format!(
138            "resolving {} (run `rust-anything bridge` first)",
139            crate_dir.display()
140        )
141    })?;
142    let manifest = Manifest::load(&crate_dir)?;
143    let mut out = Switched {
144        crate_name: manifest.crate_name.clone(),
145        on: false,
146        files: Vec::new(),
147        functions: Vec::new(),
148        skipped: Vec::new(),
149        switch: crate::front_door::kill_switch(&manifest.crate_name),
150    };
151    for file in files(&manifest) {
152        let path = manifest.root.join(file);
153        let Ok(text) = std::fs::read_to_string(&path) else {
154            continue;
155        };
156        if let Some(restored) = remove(&text, &manifest.crate_name) {
157            std::fs::write(&path, restored)
158                .with_context(|| format!("writing {}", path.display()))?;
159            out.files.push(path);
160        }
161    }
162    out.functions = manifest.exports.iter().map(|f| f.name.clone()).collect();
163    Ok(out)
164}
165
166pub fn is_supported(manifest: &Manifest) -> bool {
167    matches!(
168        (manifest.language, manifest.kind),
169        (Lang::Python, Kind::Pyo3)
170            | (Lang::Ts, Kind::Napi | Kind::Wasm)
171            | (Lang::Powershell, Kind::Ffi)
172    )
173}
174
175fn supported(manifest: &Manifest) -> Result<()> {
176    match manifest.language {
177        _ if is_supported(manifest) => Ok(()),
178        lang => bail!(
179            "`enable` switches TS/JS, Python and PowerShell ports in place; for {} use the shadow module \
180             (`rust-anything shadow`), imported where the app imported the original, and \
181             RUST_ANYTHING_MODE=old|shadow|new",
182            lang.name()
183        ),
184    }
185}
186
187fn files(manifest: &Manifest) -> Vec<&str> {
188    let mut files: Vec<&str> = manifest.exports.iter().map(|f| f.file.as_str()).collect();
189    files.sort_unstable();
190    files.dedup();
191    files
192}
193
194/// A function the block can rebind: a top-level `def` (Python) or a `function` declaration.
195fn declared(text: &str, name: &str, lang: Lang) -> bool {
196    let name = regex::escape(name);
197    let pattern = if lang == Lang::Python {
198        format!(r"(?m)^(async\s+)?def\s+{name}\s*\(")
199    } else if lang == Lang::Powershell {
200        format!(r"(?mi)^\s*function\s+{name}\s*[{{(\s]")
201    } else {
202        format!(r"(?m)^\s*(export\s+)?(default\s+)?(async\s+)?function\s*\*?\s*{name}\s*[<(]")
203    };
204    regex::Regex::new(&pattern).is_ok_and(|re| re.is_match(text))
205}
206
207fn esm(file: &str, text: &str) -> bool {
208    if file.ends_with(".cjs") || file.ends_with(".cts") {
209        return false;
210    }
211    file.ends_with(".mjs")
212        || file.ends_with(".mts")
213        || text
214            .lines()
215            .any(|l| l.starts_with("import ") || l.starts_with("export "))
216}
217
218fn marker(comment: &str, crate_name: &str, crate_dir: &Path, dir: &Path) -> (String, String) {
219    let at = crate::shadow::relative(dir, crate_dir);
220    (
221        format!(
222            "{comment} {START} {crate_name} is on. `rust-anything disable {at}` removes this block."
223        ),
224        format!("{comment} {END} {crate_name}"),
225    )
226}
227
228fn js_block(
229    manifest: &Manifest,
230    crate_dir: &Path,
231    dir: &Path,
232    names: &[&str],
233    switch: &str,
234    esm: bool,
235) -> String {
236    let (start, end) = marker("//", &manifest.crate_name, crate_dir, dir);
237    // `index.cjs` for every kind, including wasm: the raw `pkg/<crate>.js` wasm-bindgen module
238    // takes pre-serialized JSON strings, while the wrapper accepts the JS values a caller passes
239    // and maps the `$num`/`$undefined` markers.
240    let module = crate_dir.join("index.cjs");
241    let rel = crate::shadow::relative(dir, &module);
242    let here = if esm {
243        "import.meta.dirname"
244    } else {
245        "__dirname"
246    };
247    let var = format!(
248        "__rustAnything_{}",
249        crate::front_door::ident(&manifest.crate_name)
250    );
251    let assign: Vec<String> = names.iter().map(|n| format!("{n} = {var}.{n}")).collect();
252    format!(
253        "{start}\n\
254         // @ts-ignore\n\
255         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\
256         // @ts-ignore\n\
257         if ({var}) {{ {} }}\n\
258         {end}\n",
259        assign.join("; ")
260    )
261}
262
263fn python_block(
264    manifest: &Manifest,
265    crate_dir: &Path,
266    dir: &Path,
267    names: &[&str],
268    switch: &str,
269) -> String {
270    let (start, end) = marker("#", &manifest.crate_name, crate_dir, dir);
271    let (package_dir, lib) = crate::harness_py::package(crate_dir, manifest);
272    let rel = crate::shadow::relative(dir, &package_dir);
273    let fun = format!(
274        "_rust_anything_{}",
275        crate::front_door::ident(&manifest.crate_name)
276    );
277    let names: Vec<String> = names.iter().map(|n| format!("{n:?}")).collect();
278    format!(
279        "{start}\n\
280         def {fun}():\n\
281         \x20   import importlib, os, sys\n\
282         \x20   mode = os.environ.get(\"RUST_ANYTHING_MODE\")\n\
283         \x20   if mode == \"old\" or os.environ.get(\"{switch}\") == \"original\":\n\
284         \x20       return\n\
285         \x20   at = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), {rel:?}))\n\
286         \x20   sys.path.insert(0, at)\n\
287         \x20   try:\n\
288         \x20       native = importlib.import_module({lib:?})\n\
289         \x20   except ImportError:\n\
290         \x20       if mode == \"new\":\n\
291         \x20           raise\n\
292         \x20       return\n\
293         \x20   finally:\n\
294         \x20       sys.path.remove(at)\n\
295         \x20   globals().update({{name: getattr(native, name) for name in [{}]}})\n\
296         \n\
297         \n\
298         {fun}()\n\
299         del {fun}\n\
300         {end}\n",
301        names.join(", ")
302    )
303}
304
305fn powershell_block(manifest: &Manifest, crate_dir: &Path, dir: &Path, switch: &str) -> String {
306    let (start, end) = marker("#", &manifest.crate_name, crate_dir, dir);
307    let wrapper = crate_dir.join(crate::codegen_powershell::wrapper_path(manifest));
308    let rel = crate::shadow::relative(dir, &wrapper).replace('\'', "''");
309    format!(
310        "{start}\n\
311         if ($env:RUST_ANYTHING_MODE -ne 'old' -and $env:{switch} -ne 'original') {{\n\
312         \x20   try {{\n\
313         \x20       . (Join-Path $PSScriptRoot '{rel}')\n\
314         \x20   }} catch {{\n\
315         \x20       if ($env:RUST_ANYTHING_MODE -eq 'new') {{ throw }}\n\
316         \x20   }}\n\
317         }}\n\
318         {end}\n"
319    )
320}
321
322/// Puts the block on its own lines: Python before a top-level `if __name__ == "__main__":`
323/// (else at the end, after every `def`), JS after a shebang and `"use strict"`, where hoisted
324/// function declarations can already be rebound.
325fn insert(text: &str, block: &str, lang: Lang) -> String {
326    let at = if lang == Lang::Powershell {
327        crate::lang::powershell::after_functions(text).unwrap_or(text.len())
328    } else if lang == Lang::Python {
329        line_starts(text)
330            .find(|&i| {
331                let line = &text[i..];
332                line.starts_with("if __name__ == \"__main__\"")
333                    || line.starts_with("if __name__ == '__main__'")
334            })
335            .unwrap_or(text.len())
336    } else {
337        line_starts(text)
338            .find(|&i| {
339                let line = text[i..].lines().next().unwrap_or_default().trim();
340                !(line.starts_with("#!")
341                    || line == "'use strict'"
342                    || line == "\"use strict\""
343                    || line == "'use strict';"
344                    || line == "\"use strict\";")
345            })
346            .unwrap_or(text.len())
347    };
348    let mut out = String::with_capacity(text.len() + block.len() + 1);
349    out.push_str(&text[..at]);
350    if at == text.len() && !text.is_empty() && !text.ends_with('\n') {
351        out.push('\n');
352        let (first, rest) = block.split_once('\n').unwrap_or((block, ""));
353        out.push_str(first);
354        out.push_str(EOF_NOTE);
355        out.push('\n');
356        out.push_str(rest);
357    } else {
358        out.push_str(block);
359    }
360    out.push_str(&text[at..]);
361    out
362}
363
364fn line_starts(text: &str) -> impl Iterator<Item = usize> + '_ {
365    std::iter::once(0)
366        .chain(text.match_indices('\n').map(|(i, _)| i + 1))
367        .filter(move |&i| i < text.len())
368}
369
370/// The byte range of the unit's block, from its first line to the end of its last.
371fn find_block(text: &str, crate_name: &str) -> Option<(usize, usize, bool)> {
372    let start_tag = format!("{START} {crate_name} is on.");
373    let end_tag = format!("{END} {crate_name}");
374    let mut start = None;
375    for i in std::iter::once(0).chain(text.match_indices('\n').map(|(i, _)| i + 1)) {
376        let line = text[i..].split('\n').next().unwrap_or_default();
377        match start {
378            None if line.contains(&start_tag) => start = Some((i, line.ends_with(EOF_NOTE))),
379            Some((s, added)) if line.trim_end().ends_with(&end_tag) => {
380                let end = (i + line.len() + 1).min(text.len());
381                return Some((s, end, added));
382            }
383            _ => {}
384        }
385    }
386    None
387}
388
389fn remove(text: &str, crate_name: &str) -> Option<String> {
390    let (start, end, added) = find_block(text, crate_name)?;
391    let start = if added && end == text.len() && start > 0 {
392        start - 1
393    } else {
394        start
395    };
396    Some(format!("{}{}", &text[..start], &text[end..]))
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402
403    const BLOCK: &str = "# >>> rust-anything: fuzzy-rs is on. `rust-anything disable x` removes this block.\nx = 1\n# <<< rust-anything: fuzzy-rs\n";
404
405    #[test]
406    fn python_goes_before_the_main_guard_and_comes_out_byte_for_byte() {
407        let text = "def f(a):\n    return a\n\nif __name__ == \"__main__\":\n    print(f(1))\n";
408        let on = insert(text, BLOCK, Lang::Python);
409        assert!(
410            on.find("x = 1").unwrap() < on.find("if __name__").unwrap(),
411            "{on}"
412        );
413        assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
414        assert!(remove(text, "fuzzy-rs").is_none());
415    }
416
417    #[test]
418    fn a_file_without_a_final_newline_gets_it_back_the_same() {
419        let text = "def f(a):\n    return a";
420        let on = insert(text, BLOCK, Lang::Python);
421        assert!(on.contains(EOF_NOTE), "{on}");
422        assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
423    }
424
425    #[test]
426    fn js_goes_after_the_shebang_and_use_strict() {
427        let text = "#!/usr/bin/env node\n'use strict'\nfunction f(a) { return a }\nmodule.exports = { f }\n";
428        let block = BLOCK.replace('#', "//");
429        let on = insert(text, &block, Lang::Ts);
430        assert!(
431            on.starts_with("#!/usr/bin/env node\n'use strict'\n// >>>"),
432            "{on}"
433        );
434        assert_eq!(remove(&on, "fuzzy-rs").unwrap(), text);
435    }
436
437    #[test]
438    fn only_declarations_can_be_rebound() {
439        let js = "export function score(a: string): number { return 1 }\nexport const other = () => 2\nexport async function* gen<T>(x: T) {}\n";
440        assert!(declared(js, "score", Lang::Ts));
441        assert!(!declared(js, "other", Lang::Ts));
442        assert!(declared(js, "gen", Lang::Ts));
443        let py = "def dedupe(names):\n    pass\n\nclass A:\n    def inner(self):\n        pass\n";
444        assert!(declared(py, "dedupe", Lang::Python));
445        assert!(!declared(py, "inner", Lang::Python));
446    }
447
448    #[test]
449    fn module_kind_follows_the_syntax() {
450        assert!(esm("a.ts", "import x from 'y'\n"));
451        assert!(esm("a.mjs", ""));
452        assert!(!esm(
453            "a.js",
454            "const x = require('y')\nmodule.exports = {}\n"
455        ));
456        assert!(!esm("a.cjs", "export function f() {}\n"));
457    }
458}