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
scan/enable: handle UTF-8 BOM in Python and Node source files and preserve it on restore
RRFZ86ffec96c8c6
diff --git a/src/backend.rs b/src/backend.rsindex 734aa08..787b5dc 100644--- a/src/backend.rs+++ b/src/backend.rs@@ -401,10 +401,11 @@ pub fn insert_marked(text: &str, comment: &str, id: &str, body: &str, at: impl Fpub fn line_starting(text: &str, prefixes: &[&str]) -> Option<usize> {let mut offset = 0;for line in text.split_inclusive('\n') {- let squashed: String = line.chars().filter(|c| !c.is_whitespace()).collect();- let top_level = !line.starts_with([' ', '\t']);+ let body = if offset == 0 { line.strip_prefix('\u{feff}').unwrap_or(line) } else { line };+ let squashed: String = body.chars().filter(|c| !c.is_whitespace()).collect();+ let top_level = !body.starts_with([' ', '\t']);if top_level && prefixes.iter().any(|p| squashed.starts_with(p)) {- return Some(offset);+ return Some(offset + line.len() - body.len());}offset += line.len();}@@ -459,5 +460,12 @@ mod tests {}let two = append_marked(&append_marked("a\n", "#", "one", "1"), "#", "two", "2");assert_eq!(strip_marked(&strip_marked(&two, "#", "one"), "#", "two"), "a\n");++ // Leading UTF-8 BOM on line 1 is preserved when inserting and stripping a block.+ let bom_main = "\u{feff}if __name__ == \"__main__\":\r\n main()\r\n";+ assert_eq!(guard(bom_main), Some("\u{feff}".len()));+ let bom_on = insert_marked(bom_main, "#", "m.f", "f = g", guard);+ assert!(bom_on.starts_with('\u{feff}'));+ assert_eq!(strip_marked(&bom_on, "#", "m.f"), bom_main);}}diff --git a/src/node.rs b/src/node.rsindex 609cc32..6532467 100644--- a/src/node.rs+++ b/src/node.rs@@ -601,7 +601,7 @@ 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;+ let mut rest = if offset == 0 { line.strip_prefix('\u{feff}').unwrap_or(line) } else { line };if let Some(r) = rest.strip_prefix("export").filter(|r| r.starts_with([' ', '\t'])) {rest = r.trim_start();}@@ -846,4 +846,62 @@ mod tests {let on = backend::append_marked(original, "//", &port.id, &esm);assert_eq!(backend::strip_marked(&on, "//", &port.id), original);}++ #[test]+ fn utf8_bom_node_file_scans_enables_and_restores_byte_for_byte() {+ if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {+ eprintln!("no node on PATH, skipping");+ return;+ }+ let cases = [+ (+ "func",+ b"\xef\xbb\xbfexport function crunch(n) {\r\n let t = 0;\r\n for (let i = 0; i < n; i++) t += (i * i) % 97;\r\n return t;\r\n}\r\n"+ .as_slice(),+ ),+ (+ "const",+ b"\xef\xbb\xbfexport const crunch = (n) => {\r\n let t = 0;\r\n for (let i = 0; i < n; i++) t += (i * i) % 97;\r\n return t;\r\n};\r\n"+ .as_slice(),+ ),+ ];+ let base = std::env::temp_dir().join(format!("fa-node-bom-{}", std::process::id()));+ let _ = fs::remove_dir_all(&base);+ for (name, work_bytes) in cases {+ let dir = base.join(name);+ fs::create_dir_all(&dir).unwrap();+ fs::write(dir.join("work.mjs"), work_bytes).unwrap();+ fs::write(+ dir.join("app.mjs"),+ b"\xef\xbb\xbfimport { crunch } from './work.mjs';\r\nlet s = 0;\r\nfor (let r = 0; r < 200; r++) s += crunch(100000);\r\nconsole.log(s);\r\n",+ )+ .unwrap();+ let scanned = crate::pipeline::scan(&dir, vec!["node".into(), "app.mjs".into()], None).unwrap();+ let h =+ scanned.hotspots.iter().find(|h| h.name == "crunch").unwrap_or_else(|| {+ panic!("{name}: BOM node file should appear in scan, got {:?}", scanned.hotspots)+ });+ assert!(h.portable(), "{name}: crunch should be portable, got {:?}", h.blockers);+ crate::pipeline::port(&dir, Some("work.crunch"), 10).unwrap();+ let ctx = Ctx::open(&dir).unwrap();+ let port = &ctx.state.ports["work.crunch"];+ assert!(!port.sources.is_empty(), "{name}: verbatim source should be captured for BOM file");+ assert!(!ctx.stale(port), "{name}: fresh BOM port must not be reported stale");+ crate::pipeline::enable(&dir, Some("work.crunch"), true).unwrap();+ let enabled_bytes = fs::read(dir.join("work.mjs")).unwrap();+ assert!(enabled_bytes.starts_with(b"\xef\xbb\xbf"), "{name}: enable must preserve UTF-8 BOM");+ if name == "const" {+ let text = String::from_utf8_lossy(&enabled_bytes);+ assert!(+ text.starts_with("\u{feff}export let crunch"),+ "{name}: const must switch to let after BOM: {text}"+ );+ }+ crate::pipeline::disable(&dir, Some("work.crunch")).unwrap();+ let restored_bytes = fs::read(dir.join("work.mjs")).unwrap();+ let _ = fs::remove_dir_all(&dir);+ assert_eq!(restored_bytes, work_bytes, "{name}: disable must restore BOM file byte for byte");+ }+ let _ = fs::remove_dir_all(&base);+ }}diff --git a/src/node/runner.mjs b/src/node/runner.mjsindex 435472f..800f064 100644--- a/src/node/runner.mjs+++ b/src/node/runner.mjs@@ -112,7 +112,7 @@ const parsed = new Map();function describe(file, line0, name, entry, root) {if (!parsed.has(file)) {try {- const src = readFileSync(file, "utf8");+ const src = readFileSync(file, "utf8").replace(/^\uFEFF/, "");parsed.set(file, { src, code: codeOnly(src), top: topLevelFunctions(src) });} catch {parsed.set(file, null);diff --git a/src/python.rs b/src/python.rsindex 12fe75f..1935e0b 100644--- a/src/python.rs+++ b/src/python.rs@@ -1352,6 +1352,42 @@ sys.exit(1 if fails else 0)assert!(!is_python("node"));}+ #[test]+ fn utf8_bom_python_file_scans_enables_and_restores_byte_for_byte() {+ let Some(python) = ["python3", "python"]+ .into_iter()+ .find(|p| Command::new(p).arg("--version").output().is_ok_and(|o| o.status.success()))+ else {+ eprintln!("no python on PATH, skipping");+ return;+ };+ let dir = std::env::temp_dir().join(format!("fa-py-bom-{}", std::process::id()));+ let _ = fs::remove_dir_all(&dir);+ fs::create_dir_all(&dir).unwrap();+ let work_bytes = b"\xef\xbb\xbfdef crunch(n: int) -> int:\r\n t = 0\r\n for i in range(n):\r\n t += (i * i) % 97\r\n return t\r\n";+ fs::write(dir.join("work.py"), work_bytes).unwrap();+ fs::write(+ dir.join("app.py"),+ b"\xef\xbb\xbffrom work import crunch\r\nif __name__ == '__main__':\r\n print(sum(crunch(500) for _ in range(50)))\r\n",+ )+ .unwrap();+ let scanned = crate::pipeline::scan(&dir, vec![python.into(), "app.py".into()], None).unwrap();+ let h = scanned.hotspots.iter().find(|h| h.name == "crunch").expect("BOM python file should appear in scan");+ assert!(h.portable(), "crunch should be portable, got {:?}", h.blockers);+ crate::pipeline::port(&dir, Some("work.crunch"), 10).unwrap();+ let ctx = Ctx::open(&dir).unwrap();+ let port = &ctx.state.ports["work.crunch"];+ assert!(!port.sources.is_empty(), "verbatim source should be captured for BOM file");+ assert!(!ctx.stale(port), "fresh BOM port must not be reported stale");+ crate::pipeline::enable(&dir, Some("work.crunch"), true).unwrap();+ let enabled_bytes = fs::read(dir.join("work.py")).unwrap();+ assert!(enabled_bytes.starts_with(b"\xef\xbb\xbf"), "enable must preserve UTF-8 BOM");+ crate::pipeline::disable(&dir, Some("work.crunch")).unwrap();+ let restored_bytes = fs::read(dir.join("work.py")).unwrap();+ let _ = fs::remove_dir_all(&dir);+ assert_eq!(restored_bytes, work_bytes, "disable must restore BOM file byte for byte");+ }+struct WorkerEnv {python: &'static str,dir: PathBuf,diff --git a/src/python/runner.py b/src/python/runner.pyindex 3b496ac..a95ea6c 100644--- a/src/python/runner.py+++ b/src/python/runner.py@@ -255,7 +255,7 @@ _files = {}def parse_file(path):if path not in _files:try:- with open(path, encoding="utf-8") as f:+ with open(path, encoding="utf-8-sig") as f:src = f.read()tree = ast.parse(src)except (OSError, SyntaxError, UnicodeDecodeError, ValueError):diff --git a/src/state.rs b/src/state.rsindex 7ceb3a3..f526ee2 100644--- a/src/state.rs+++ b/src/state.rs@@ -86,6 +86,7 @@ fn forms(source: &str) -> [String; 3] {/// The file without fast-anything's own marked blocks: an enabled Java, Go, C#, C/C++, PHP or/// Kotlin port puts one inside the function's body, and that isn't a change to the original.fn without_blocks(text: &str) -> String {+ let text = text.strip_prefix('\u{feff}').unwrap_or(text);let mut out = String::with_capacity(text.len());let mut inside = false;for line in text.split_inclusive('\n') {