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.
Rust agent-skillsai-agentsclaude-codeclaude-code-plugincodexdeveloper-toolsffimcpmcp-servernapi-rsnodejsoptimizationperformanceprofilerpyo3pythonrewrite-it-in-rustrubyrusttypescript
node: port static methods (#43)
chessMan7085fab7cc75
diff --git a/src/node.rs b/src/node.rsindex 91a793d..609cc32 100644--- a/src/node.rs+++ b/src/node.rs@@ -180,7 +180,7 @@ pub fn record(ctx: &Ctx, node: &str, args: &[String], hs: &Hotspot, out: &Path,let backup = backup_dir.join(slug(&hs.file));fs::write(&backup, &original)?;- let f = &hs.name;+ let f = &target(&hs.name, hs.owner.as_deref());let wrap = format!("{f} = globalThis.__fastAnythingWrap ? globalThis.__fastAnythingWrap({f}) : {f};");let entry = hs.module.as_deref() == Some("__main__");let reassignable = redeclare(&original, "const", "let", f).unwrap_or_else(|| original.clone());@@ -512,7 +512,10 @@ pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {// inside the module, then the file goes back byte for byte.let file = ctx.root.join(&port.file);let text = fs::read_to_string(&file).with_context(|| format!("reading {}", port.file))?;- let hand_over = format!("if (globalThis.__fastAnythingOriginal) globalThis.__fastAnythingOriginal({});", port.func);+ let hand_over = format!(+ "if (globalThis.__fastAnythingOriginal) globalThis.__fastAnythingOriginal({});",+ target(&port.func, port.owner.as_deref())+ );let mut patches = crate::native::Patches::new(ctx)?;patches.write(&file, &backend::append_marked(&text, "//", &format!("verifying {}", port.id), &hand_over))?;let run = runner(ctx, node, "verify", job);@@ -548,6 +551,11 @@ fn is_esm(root: &Path, file: &Path) -> bool {false}+/// How the module refers to the function: its name, or Class.name for a static method.+fn target(name: &str, owner: Option<&str>) -> String {+ owner.map_or_else(|| name.to_string(), |class| format!("{class}.{name}"))+}+pub fn shim(port: &Port, addon_rel: &str, esm: bool) -> String {let load = if esm {format!("process.getBuiltinModule(\"node:module\").createRequire(import.meta.url)(\"{addon_rel}\")")@@ -559,7 +567,7 @@ pub fn shim(port: &Port, addon_rel: &str, esm: bool) -> String {format!("// Undo with: fast-anything disable {}", port.id),"if (!process.env.FAST_ANYTHING_DISABLE) {".to_string()," try {".to_string(),- format!(" {f} = {load}.{f};", f = port.func),+ format!(" {} = {load}.{};", target(&port.func, port.owner.as_deref()), port.func)," } catch {}".to_string(),"}".to_string(),]@@ -622,7 +630,7 @@ fn let_note(name: &str) -> String {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) {+ let (text, swapped) = match redeclare(text, "const", "let", &port.func).filter(|_| port.owner.is_none()) {Some(t) => (t, true),None => (text.to_string(), text.contains(¬e)), // already swapped by an earlier enable};@@ -785,6 +793,34 @@ mod tests {assert_eq!(without_shim(&on, &port), original);}+ #[test]+ fn static_methods_go_through_their_class() {+ let port = Port {+ id: "lib.Text.pairs".into(),+ file: "lib.mjs".into(),+ module: "lib".into(),+ func: "pairs".into(),+ ext: "fa_lib_text_pairs".into(),+ crate_dir: ".fast/ports/lib.Text.pairs".into(),+ recorded: 1,+ calls_seen: 1,+ verify: None,+ enabled: false,+ lang: backend::Lang::Node,+ owner: Some("Text".into()),+ line: 2,+ sources: vec![],+ };+ let block = shim(&port, "./x.node", true);+ assert!(block.contains("Text.pairs = process.getBuiltinModule"), "{block}");+ assert!(block.contains("(\"./x.node\").pairs;"), "{block}");+ // a same-named const elsewhere is left alone+ let original = "const pairs = 1;\nexport class Text {\n static pairs(n) {\n return n;\n }\n}\n";+ let on = with_shim(original, &port, &block);+ assert!(on.starts_with("const pairs = 1;"), "{on}");+ assert_eq!(without_shim(&on, &port), original);+ }+#[test]fn shim_loads_the_addon() {let port = Port {diff --git a/src/node/runner.mjs b/src/node/runner.mjsindex 18ff54a..435472f 100644--- a/src/node/runner.mjs+++ b/src/node/runner.mjs@@ -161,7 +161,19 @@ function describe(file, line0, name, entry, root) {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)");+ // a static method directly in the body of a top-level class is called as Class.name(...), like a function+ let owner = null;+ if (kind === "method" && m[2]) {+ for (const c of code.matchAll(new RegExp("^(?:export\\s+)?(?:default\\s+)?class\\s+(" + IDENT + ")[^{]*\\{", "gm"))) {+ const body = c.index + c[0].length - 1;+ if (body > lineStart || matching(code, body) < close) continue;+ let depth = 0;+ for (const ch of code.slice(body, lineStart)) depth += ch === "{" ? 1 : ch === "}" ? -1 : 0;+ if (depth === 1) owner = c[1];+ }+ }+ if ((kind === "method" && !owner) || (kind !== "method" && indent > 0))+ blockers.push("method or nested function (top-level functions and static methods only for now)");if (kind === "function" && m[4]) blockers.push("async");if (kind === "function" && m[5]) blockers.push("generator (function*)");if (kind === "binding" && m[5]) blockers.push("async");@@ -207,8 +219,9 @@ function describe(file, line0, name, entry, root) {factor *= 0.9;}return {- qualname: name,+ qualname: owner ? owner + "." + name : name,module,+ owner,kind: kind === "method" || indent > 0 ? "method" : "function",end_line: src.slice(0, bodyEnd + 1).split("\n").length,params: params.map(({ name, annotation }) => ({ name, annotation })),