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.

node: port functions from a guarded entry script

Mohit Mishra7af445d5f822
diff --git a/README.md b/README.md
index 1ab0796..aa0137c 100644
--- a/README.md
+++ b/README.md
@@ -97,7 +97,7 @@ fast-anything ports the outermost loop it can, not the tiny function called insi
| C and C++ (gcc or clang: `clang -O2 main.c lib.c`) | the same C bridge, through LoadLibrary or dlopen | ✅ |
| C# / .NET 8+ (`dotnet run -c Release`) | the same C bridge, through NativeLibrary; profiled with EventPipe, nothing to install | ✅ |
-It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`). In Java, C# and PHP that means static methods (and PHP functions), in Go plain functions, in C and C++ free functions and static methods. `scan` says why anything else can't move yet.
+It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`, or `if (import.meta.main)` / `if (require.main === module)`). In Java, C# and PHP that means static methods (and PHP functions), in Go plain functions, in C and C++ free functions and static methods. `scan` says why anything else can't move yet.
Ruby, Java, Go, PHP, C, C++ and C# need no headers, bindings or extra tools: the port is a plain Rust library with one C entry point taking and returning JSON, and fast-anything replays the recorded calls against it directly. Any language that can call C can use that bridge.
diff --git a/src/node.rs b/src/node.rs
index 2b1da84..88933fc 100644
--- a/src/node.rs
+++ b/src/node.rs
@@ -87,6 +87,19 @@ pub fn profile(ctx: &Ctx, node: &str, args: &[String]) -> Result<Profile> {
serde_json::from_str(&fs::read_to_string(&result)?).context("reading the profile")
}
+/// The entry script's main block, if its main code sits under one.
+const MAIN_GUARD: &[&str] = &["if(import.meta.main)", "if(require.main===module)", "if(module===require.main)"];
+
+/// Add a marked block to a module: at the end, or in the entry script just before its main block,
+/// so the app's main code already sees it. Function declarations are hoisted, so they exist there.
+fn add_marked(text: &str, id: &str, body: &str, entry: bool) -> String {
+ if entry {
+ backend::insert_marked(text, "//", id, body, |t| backend::line_starting(t, MAIN_GUARD))
+ } else {
+ backend::append_marked(text, "//", id, body)
+ }
+}
+
/// Re-run the app with a recorder wrapped around the function. The module gets a temporary
/// block appended (a copy waits in .fast/backup) and is restored byte for byte afterwards.
pub fn record(ctx: &Ctx, node: &str, args: &[String], hs: &Hotspot, out: &Path, limit: usize) -> Result<Recording> {
@@ -99,7 +112,8 @@ pub fn record(ctx: &Ctx, node: &str, args: &[String], hs: &Hotspot, out: &Path,
let f = &hs.name;
let wrap = format!("{f} = globalThis.__fastAnythingWrap ? globalThis.__fastAnythingWrap({f}) : {f};");
- fs::write(&file, backend::append_marked(&original, "//", &format!("recording {}", hs.id), &wrap))?;
+ let entry = hs.module.as_deref() == Some("__main__");
+ fs::write(&file, add_marked(&original, &format!("recording {}", hs.id), &wrap, entry))?;
let recorder = ctx.fast.join("recorder.cjs");
fs::write(&recorder, RECORDER)?;
let meta = out.with_extension("meta.json");
@@ -462,7 +476,7 @@ pub fn enable(ctx: &Ctx, port: &Port) -> Result<()> {
rel = format!("./{rel}");
}
let block = shim(port, &rel, is_esm(&ctx.root, &file));
- fs::write(&file, backend::append_marked(&text, "//", &port.id, &block))
+ fs::write(&file, add_marked(&text, &port.id, &block, port.module == "__main__"))
.with_context(|| format!("writing {}", port.file))
}
@@ -502,6 +516,19 @@ 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 shim_loads_the_addon() {
let port = Port {
diff --git a/src/node/runner.mjs b/src/node/runner.mjs
index 6527080..2288731 100644
--- a/src/node/runner.mjs
+++ b/src/node/runner.mjs
@@ -154,7 +154,13 @@ function describe(file, line0, name, entry, root) {
const rel = path.relative(root, file);
const isEntry = entry && path.resolve(entry) === path.resolve(file);
const module = isEntry ? "__main__" : rel.replace(/\.[cm]?[jt]sx?$/, "").split(path.sep).join(".");
- if (isEntry) blockers.push("lives in the entry script, move it into a module to port it");
+ if (isEntry) {
+ // like Python's if __name__ == "__main__": the main code must not run when verify imports the script
+ const guard = code.search(/^if\s*\(\s*(import\.meta\.main|require\.main\s*===\s*module|module\s*===\s*require\.main)\s*\)/m);
+ if (guard < 0)
+ blockers.push("lives in the entry script, which runs on import: put its main code under if (import.meta.main) (or require.main === module)");
+ else if (lineStart > guard) blockers.push("defined inside or after the if (import.meta.main) block");
+ }
if (kind === "method" || indent > 0) blockers.push("method or nested function (top-level functions only for now)");
if (kind === "function" && m[4]) blockers.push("async");
if (kind === "function" && m[5]) blockers.push("generator (function*)");