Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

Merge pull request #20

EL4CTEOa130efa2bf58
diff --cc examples/fuzzy-dedupe/__pycache__/fuzzy.cpython-315.pyc
index 0000000,0000000..87628d8
new file mode 100644
Binary files differ
diff --cc src/node.rs
index 88933fc,582c763..abcddd6
--- a/src/node.rs
+++ b/src/node.rs
@@@ -112,8 -99,8 +112,9 @@@ pub fn record(ctx: &Ctx, node: &str, ar
let f = &hs.name;
let wrap = format!("{f} = globalThis.__fastAnythingWrap ? globalThis.__fastAnythingWrap({f}) : {f};");
+ let entry = hs.module.as_deref() == Some("__main__");
- fs::write(&file, add_marked(&original, &format!("recording {}", hs.id), &wrap, entry))?;
+ let reassignable = redeclare(&original, "const", "let", f).unwrap_or_else(|| original.clone());
- fs::write(&file, backend::append_marked(&reassignable, "//", &format!("recording {}", hs.id), &wrap))?;
++ fs::write(&file, add_marked(&reassignable, &format!("recording {}", hs.id), &wrap, entry))?;
let recorder = ctx.fast.join("recorder.cjs");
fs::write(&recorder, RECORDER)?;
let meta = out.with_extension("meta.json");
@@@ -483,7 -460,56 +483,56 @@@ pub fn enable(ctx: &Ctx, port: &Port) -
pub fn disable(ctx: &Ctx, port: &Port) -> Result<()> {
let file = ctx.root.join(&port.file);
let text = fs::read_to_string(&file).with_context(|| format!("reading {}", port.file))?;
- fs::write(&file, backend::strip_marked(&text, "//", &port.id)).with_context(|| format!("writing {}", port.file))
+ fs::write(&file, without_shim(&text, port)).with_context(|| format!("writing {}", port.file))
+ }
+
+ /// Byte offset of the keyword in the top-level `[export] <keyword> <name>` declaration, if any.
+ /// A module can declare a name only once at the top level, so there's at most one.
+ fn declaration(text: &str, keyword: &str, name: &str) -> Option<usize> {
+ let ident = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
+ let mut offset = 0;
+ for line in text.split_inclusive('\n') {
+ let mut rest = line;
+ if let Some(r) = rest.strip_prefix("export").filter(|r| r.starts_with([' ', '\t'])) {
+ rest = r.trim_start();
+ }
+ let at = offset + line.len() - rest.len();
+ if let Some(r) = rest.strip_prefix(keyword).filter(|r| r.starts_with([' ', '\t']))
+ && r.trim_start().strip_prefix(name).is_some_and(|r| !r.starts_with(ident))
+ {
+ return Some(at);
+ }
+ offset += line.len();
+ }
+ None
+ }
+
+ /// The text with the declaration of name switched from one keyword to another (const <-> let).
+ fn redeclare(text: &str, from: &str, to: &str, name: &str) -> Option<String> {
+ let at = declaration(text, from, name)?;
+ Some(format!("{}{to}{}", &text[..at], &text[at + from.len()..]))
+ }
+
+ /// A const can't be reassigned, so a function declared with const is declared with let while
+ /// fast-anything swaps it; this note in the block tells disable to put the const back.
+ fn let_note(name: &str) -> String {
+ format!("// fast-anything declared {name} with let instead of const above; disable puts the const back.")
+ }
+
+ fn with_shim(text: &str, port: &Port, block: &str) -> String {
+ let note = let_note(&port.func);
+ let (text, swapped) = match redeclare(text, "const", "let", &port.func) {
+ Some(t) => (t, true),
+ None => (text.to_string(), text.contains(&note)), // already swapped by an earlier enable
+ };
+ let block = if swapped { format!("{block}\n{note}") } else { block.to_string() };
- backend::append_marked(&text, "//", &port.id, &block)
++ add_marked(&text, &port.id, &block, port.module == "__main__")
+ }
+
+ fn without_shim(text: &str, port: &Port) -> String {
+ let swapped = text.contains(&let_note(&port.func));
+ let text = backend::strip_marked(text, "//", &port.id);
+ if swapped { redeclare(&text, "let", "const", &port.func).unwrap_or(text) } else { text }
}
#[cfg(test)]
@@@ -516,19 -542,41 +565,54 @@@ mod tests
assert_eq!(snake("type"), "r#type");
}
+ #[test]
+ fn entry_script_blocks_go_before_the_main_block() {
+ let app = "function f(x) {\n return x;\n}\n\nif (import.meta.main) {\n console.log(f(1));\n}\n";
+ let on = add_marked(app, "app.mjs:f", "f = g;", true);
+ let (block, main) = (on.find("f = g;").unwrap(), on.find("if (import.meta.main)").unwrap());
+ assert!(block < main, "{on}");
+ assert_eq!(backend::strip_marked(&on, "//", "app.mjs:f"), app);
+ let cjs = "function f(x) {\n return x;\n}\nif (require.main === module) main();\n";
+ let on = add_marked(cjs, "app.js:f", "f = g;", true);
+ assert!(on.find("f = g;").unwrap() < on.find("if (require.main").unwrap(), "{on}");
+ assert!(add_marked(app, "m.f", "f = g;", false).trim_end().ends_with("// <<< fast-anything: m.f <<<"));
+ }
+
+ #[test]
+ fn const_functions_switch_to_let_and_back() {
+ let port = Port {
+ id: "lib.pairs".into(),
+ file: "lib.ts".into(),
+ module: "lib".into(),
+ func: "pairs".into(),
+ ext: "fa_lib_pairs".into(),
+ crate_dir: ".fast/ports/lib.pairs".into(),
+ recorded: 1,
+ calls_seen: 1,
+ verify: None,
+ enabled: false,
+ lang: backend::Lang::Node,
+ owner: None,
+ line: 1,
+ };
+ for original in [
+ "export const pairs = (names: string[]): number => {\n return 0;\n};\n",
+ "const pairs = function (names) {\n return 0;\n};\nmodule.exports = { pairs };\n",
+ "const pairsCount = 1;\nexport const\tpairs = (n) => n;\r\n",
+ ] {
+ let on = with_shim(original, &port, "pairs = rust.pairs;");
+ assert!(declaration(&on, "let", "pairs").is_some() && declaration(&on, "const", "pairs").is_none(), "{on}");
+ assert_eq!(on.contains("const pairsCount"), original.contains("const pairsCount"), "{on}");
+ assert_eq!(with_shim(&on, &port, "pairs = rust.pairs;"), on, "enabling twice changes nothing");
+ assert_eq!(without_shim(&on, &port), original);
+ }
+ // a function that was declared with let stays let
+ let original = "let pairs = (n) => n;\n";
+ let on = with_shim(original, &port, "pairs = rust.pairs;");
+ assert!(!on.contains("puts the const back"));
+ assert_eq!(without_shim(&on, &port), original);
+ }
+
#[test]
fn shim_loads_the_addon() {
let port = Port {