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
Merge #122: C++ edge cases in child processes
EL4CTEO385e93729ef6
diff --cc src/cfamily.rsindex 751523e,82118e3..c035edb--- a/src/cfamily.rs+++ b/src/cfamily.rs@@@ -1524,152 -1385,63 +1524,209 @@@ pub fn disable(ctx: &Ctx, port: &Port)mod tests {use super::*;+ /// Compiles C++ `source` with the recording code of its function `name` and runs it; returns+ /// the recordings, or None without a C++ compiler.+ #[cfg(unix)]+ fn record_cpp(source: &str, name: &str) -> Option<Vec<Value>> {+ let cc = ["c++", "g++", "clang++"].into_iter().find(|c| Command::new(c).arg("--version").output().is_ok())?;+ let f = parse(source).into_iter().find(|f| f.name == name).unwrap();+ let hs = Hotspot {+ name: f.name.clone(),+ params: f.params.clone(),+ returns: Some(f.ret.clone()),+ ..Hotspot::default()+ };+ let dir = std::env::temp_dir().join(format!("fa-cpp-rec-test-{name}-{}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ fs::write(dir.join("fa_rec.hpp"), REC_HPP.replace("/*JSON*/", JSON_HPP)).unwrap();+ let prologue = cpp_record_prologue(&hs).replace('\n', " ");+ fs::write(dir.join("app.cpp"), insert_at(source, vec![(f.body_open + 1, format!(" {prologue}"))])).unwrap();+ let built = Command::new(cc)+ .args(["-std=c++17", "-O1", "-include", "fa_rec.hpp", "app.cpp", "-o", "app"])+ .current_dir(&dir)+ .output()+ .unwrap();+ assert!(built.status.success(), "{}", String::from_utf8_lossy(&built.stderr));+ let ran = Command::new(dir.join("app"))+ .current_dir(&dir)+ .env("FAST_ANYTHING_RECORD_OUT", dir.join("rec.jsonl"))+ .env("FAST_ANYTHING_RECORD_META", dir.join("meta.json"))+ .output()+ .unwrap();+ let text = fs::read_to_string(dir.join("rec.jsonl")).unwrap_or_default();+ let _ = fs::remove_dir_all(&dir);+ assert!(ran.status.success(), "{}", String::from_utf8_lossy(&ran.stderr));+ Some(text.lines().map(|l| serde_json::from_str(l).unwrap()).collect())+ }++ #[cfg(unix)]+ #[test]+ fn cpp_edge_cases_that_hang_or_crash_are_skipped() {+ use serde_json::json;+ // never returns for 0 or -1+ let spin = "long spin(long n) {\n long steps = 0;\n while (n != 1) {\n n = n % 2 ? 3 * n + 1 : n / 2;\n steps++;\n }\n return steps;\n}\nint main() {\n long t = 0;\n for (long k = 2; k < 30; k++) t += spin(k);\n return t > 0 ? 0 : 1;\n}\n";+ let started = std::time::Instant::now();+ let Some(cases) = record_cpp(spin, "spin") else {+ eprintln!("no C++ compiler on PATH, skipping");+ return;+ };+ assert!(started.elapsed().as_secs() < 30, "the recording finished");+ let edges: Vec<&Value> = cases.iter().filter(|c| c["derived"] == "edge").collect();+ assert!(edges.iter().any(|c| c["args"] == json!([1]) && c["result"] == json!(0)), "{edges:?}");+ assert!(edges.iter().all(|c| c["args"] != json!([0]) && c["args"] != json!([-1])), "{edges:?}");+ // reads xs[0] whatever the size: crashes on an empty vector+ let first = "#include <vector>\nint first(const std::vector<int> &xs) {\n return ((volatile const int *) xs.data())[0] * 0 + (int) xs.size();\n}\nint main() {\n std::vector<int> xs(20, 1);\n int t = 0;\n for (int k = 0; k < 3; k++) t += first(xs);\n return t > 0 ? 0 : 1;\n}\n";+ let cases = record_cpp(first, "first").unwrap();+ let edges: Vec<&Value> = cases.iter().filter(|c| c["derived"] == "edge").collect();+ assert!(!edges.is_empty() && edges.iter().all(|c| c["args"] != json!([[]])), "{edges:?}");+ }++ /// Compiles `source` with the recording prologue of its function `name` and runs it; returns+ /// the recordings, or None without a C compiler.+ fn record_c(source: &str, name: &str) -> Option<Vec<Value>> {+ let cc = ["cc", "gcc", "clang"].into_iter().find(|c| Command::new(c).arg("--version").output().is_ok())?;+ let f = parse(source).into_iter().find(|f| f.name == name).unwrap();+ let hs = Hotspot {+ name: f.name.clone(),+ params: f.params.clone(),+ returns: Some(f.ret.clone()),+ ..Hotspot::default()+ };+ let dir = std::env::temp_dir().join(format!("fa-c-rec-test-{name}-{}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ for (file, text) in [("fa_clock.h", CLOCK_H), ("fa_rec.h", REC_H), ("fa_rec.c", REC_C)] {+ fs::write(dir.join(file), text).unwrap();+ }+ let prologue = c_record_prologue(&hs).unwrap().replace('\n', " ");+ fs::write(dir.join("app.c"), insert_at(source, vec![(f.body_open + 1, format!(" {prologue}"))])).unwrap();+ let built = Command::new(cc)+ .args(["-O1", "-include", "fa_rec.h", "app.c", "fa_rec.c", "-o", "app"])+ .current_dir(&dir)+ .output()+ .unwrap();+ assert!(built.status.success(), "{}", String::from_utf8_lossy(&built.stderr));+ let ran = Command::new(dir.join("app"))+ .current_dir(&dir)+ .env("FAST_ANYTHING_RECORD_OUT", dir.join("rec.jsonl"))+ .env("FAST_ANYTHING_RECORD_META", dir.join("meta.json"))+ .output()+ .unwrap();+ let text = fs::read_to_string(dir.join("rec.jsonl")).unwrap_or_default();+ let _ = fs::remove_dir_all(&dir);+ assert!(ran.status.success(), "{}", String::from_utf8_lossy(&ran.stderr));+ Some(text.lines().map(|l| serde_json::from_str(l).unwrap()).collect())+ }++ #[cfg(unix)]+ #[test]+ fn c_edge_cases_run_where_a_crash_or_hang_is_contained() {+ use serde_json::json;+ // score crashes on an emoji, never returns for k == -1 and reads xs[0] even when n is 0+ let source = "#include <stddef.h>\n#include <string.h>\nlong score(const char *s, const int *xs, size_t n, int k)\n{\n if (strstr(s, \"\\xF0\\x9F\\x91\\x8D\")) { volatile int *p = 0; return *p; }\n if (k == -1) for (;;) {}\n long t = (long) strlen(s) + k + ((volatile const int *) xs)[0] * 0;\n for (size_t i = 0; i < n; i++) t += xs[i];\n return t;\n}\nint main(void) {\n char s[201] = {0};\n for (int i = 0; i < 40; i++) strcat(s, \"word \");\n int xs[24];\n for (int i = 0; i < 24; i++) xs[i] = i;\n long t = 0;\n for (int k = 0; k < 3; k++) t += score(s, xs, 20 + k, k);\n return t > 0 ? 0 : 1;\n}\n";+ let Some(cases) = record_c(source, "score") else {+ eprintln!("no C compiler on PATH, skipping");+ return;+ };+ let edges: Vec<&Value> = cases.iter().filter(|c| c["derived"] == "edge").collect();+ let has = |i: usize, want: Value| edges.iter().any(|c| c["args"][i] == want);+ let short: String = "word ".repeat(40).chars().take(64).collect();+ assert!(has(0, json!("")) && has(0, json!(format!("{short}\u{65e5}\u{672c}"))), "text: {edges:?}");+ assert!(has(3, json!(1)), "special numbers: {edges:?}");+ assert!(edges.iter().any(|c| c["args"][1].as_array().is_some_and(|a| a.len() == 8 * 16)), "bigger arrays");+ assert!(edges.iter().all(|c| c["args"][3] != json!(-1)), "a case that never returns");+ assert!(!cases.iter().any(|c| c["args"][0].as_str().is_some_and(|s| s.contains('\u{1f44d}'))), "a crash");+ assert!(!cases.iter().any(|c| c["args"][1] == json!([])), "an empty array the original reads anyway");+ for c in &cases {+ let a = c["args"].as_array().unwrap();+ let xs = a[1].as_array().unwrap();+ assert_eq!(xs.len() as u64, a[2].as_u64().unwrap(), "{c}");+ let want = a[0].as_str().unwrap().len() as i64+ + a[3].as_i64().unwrap()+ + xs.iter().map(|x| x.as_i64().unwrap()).sum::<i64>();+ assert_eq!(c["result"].as_i64(), Some(want), "{c}");+ }+ }++ #[test]+ fn c_recordings_carry_every_parameter() {+ // the port's glue and the bridge take the array's length as an argument of its own+ let source = "#include <stddef.h>\nlong total(const int *xs, size_t n, int scale)\n{\n long s = 0;\n for (size_t i = 0; i < n; i++) s += xs[i] * scale;\n return s;\n}\nint main(void) {\n int xs[40];\n for (int i = 0; i < 40; i++) xs[i] = i;\n long t = 0;\n for (int k = 0; k < 5; k++) t += total(xs, 30 + k, k);\n return t > 0 ? 0 : 1;\n}\n";+ let Some(cases) = record_c(source, "total") else {+ eprintln!("no C compiler on PATH, skipping");+ return;+ };+ assert!(cases.iter().any(|c| c.get("derived").is_some()), "no derived cases: {cases:?}");+ for c in &cases {+ let args = c["args"].as_array().unwrap();+ assert_eq!(args.len(), 3, "{c}");+ let (xs, n, scale) = (args[0].as_array().unwrap(), args[1].as_u64().unwrap(), args[2].as_i64().unwrap());+ assert_eq!(xs.len() as u64, n, "{c}");+ let sum: i64 = xs.iter().map(|x| x.as_i64().unwrap() * scale).sum();+ assert_eq!(c["result"].as_i64(), Some(sum), "{c}");+ }+ }++ #[test]+ fn bridges_compile_whatever_the_parameters_are_called() {+ // every name the bridges use for their own variables, as a parameter+ let c = "long pick(const int *b, size_t n, const char *text, double out, int ok, long r, int fallback) {\n return 0;\n}\n";+ let cpp = "long pick(const std::vector<int> &in, int n, const std::string &text, double p, int reply, int err, int ok, long out) {\n return 0;\n}\n";+ for (source, compilers, ext) in [(c, ["cc", "gcc", "clang"], "c"), (cpp, ["c++", "g++", "clang++"], "cpp")] {+ let Some(cc) = compilers.into_iter().find(|c| Command::new(c).arg("--version").output().is_ok()) else {+ eprintln!("no {ext} compiler on PATH, skipping");+ continue;+ };+ let f = parse(source).remove(0);+ let hs = Hotspot {+ id: "lib.pick".into(),+ name: f.name.clone(),+ params: f.params.clone(),+ returns: Some(f.ret.clone()),+ ..Hotspot::default()+ };+ let bridge = if ext == "c" {+ c_bridge(&hs, "t", "\"lib.so\"").unwrap()+ } else {+ cpp_bridge(&hs, "t", "\"lib.so\"", &[])+ };+ let dir = std::env::temp_dir().join(format!("fa-bridge-names-{ext}-{}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ fs::write(dir.join(format!("bridge.{ext}")), bridge).unwrap();+ let mut cmd = Command::new(cc);+ if ext == "cpp" {+ cmd.arg("-std=c++17");+ }+ let out = cmd.args(["-c", &format!("bridge.{ext}"), "-o", "bridge.o"]).current_dir(&dir).output().unwrap();+ let _ = fs::remove_dir_all(&dir);+ assert!(out.status.success(), "{ext}: {}", String::from_utf8_lossy(&out.stderr));+ }+ }++ #[test]+ fn duration_ends_an_app_that_runs_until_closed() {+ let Some(cc) = ["cc", "gcc", "clang"].into_iter().find(|c| Command::new(c).arg("--version").output().is_ok())+ else {+ eprintln!("no C compiler on PATH, skipping");+ return;+ };+ let tmp = std::env::temp_dir();+ // macOS's temp folder is behind a symlink; the profile has the real paths+ let tmp = if cfg!(windows) { tmp } else { tmp.canonicalize().unwrap() };+ let dir = tmp.join(format!("fa-c-duration-test-{}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ // a server's shape: work, forever+ let main = "long work(long n) {\n long s = 0;\n for (long i = 0; i < n; i++) s += i * i % 7;\n return s;\n}\n\nint main(void) {\n volatile long sink = 0;\n for (;;) sink += work(20000000);\n}\n";+ fs::write(dir.join("main.c"), main).unwrap();+ let ctx = Ctx::open(&dir).unwrap();+ let p = profile(&ctx, cc, &["-O1".into(), "main.c".into()], Lang::C, Some(1.0));+ let after = fs::read_to_string(dir.join("main.c")).unwrap();+ let _ = fs::remove_dir_all(&dir);+ let p = p.unwrap();+ assert!(p.functions.iter().any(|f| f.name == "work" && f.ncalls > 0), "{:?}", p.functions);+ assert!((0.9..10.0).contains(&p.wall), "{}", p.wall);+ assert_eq!(after, main);+ }+#[test]fn finds_c_and_cpp_functions() {let c = "#include <stdio.h>\n/* a { comment */\nstatic int lev(const char *a, const char *b) {\n return 0;\n}\n\nlong count(const int *xs, size_t n, int max)\n{\n if (n) { return 1; }\n printf(\"{\");\n return 0;\n}\nint main(void) { return lev(\"a\", \"b\"); }\n";