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 #94: Java edge cases

EL4CTEOa6e899ac5ac3
diff --cc src/java.rs
index cf44e6d,9d25f61..182d79f
--- a/src/java.rs
+++ b/src/java.rs
@@@ -616,54 -581,84 +616,111 @@@ pub fn disable(ctx: &Ctx, port: &Port)
mod tests {
use super::*;
- #[test]
- fn varargs_are_portable_as_arrays() {
- if !Command::new("java").arg("-version").output().is_ok_and(|o| o.status.success()) {
- eprintln!("no java on PATH, skipping");
- return;
- }
- let dir = std::env::temp_dir().join(format!("fa-java-varargs-test-{}", std::process::id()));
- fs::create_dir_all(&dir).unwrap();
- let app = "public class App {\n static int total(int scale, int... xs) {\n int s = 0;\n for (int x : xs) s += x * scale;\n return s;\n }\n\n static int count(String... words) {\n return words.length;\n }\n\n public static void main(String[] args) {\n System.out.println(total(2, 1, 2, 3) + count(\"a\", \"b\"));\n }\n}\n";
- fs::write(dir.join("App.java"), app).unwrap();
- let ctx = Ctx::open(&dir).unwrap();
- let found = describe(&ctx, "java", &[dir.join("App.java")]);
- let _ = fs::remove_dir_all(&dir);
- let found = found.unwrap();
- for (name, types) in [("total", vec!["int", "int[]"]), ("count", vec!["String[]"])] {
- let m = found.iter().find(|m| m.name == name).unwrap();
- assert!(m.blockers.is_empty(), "{name}: {:?}", m.blockers);
- assert_eq!(m.params.iter().map(|p| p.annotation.as_deref().unwrap()).collect::<Vec<_>>(), types);
- }
- }
-
+ #[test]
+ fn the_recorder_adds_edge_cases() {
+ use serde_json::json;
+ let has = |cmd: &str| Command::new(cmd).arg("-version").output().is_ok_and(|o| o.status.success());
+ if !has("java") {
+ eprintln!("no java on PATH, skipping");
+ return;
+ }
+ let dir = std::env::temp_dir().join(format!("fa-java-edges-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ let rec = REC.replace("/*PACKAGE*/", "").replace("/*ID*/", "Check.width").replace("/*JSON*/", JSON);
+ fs::write(dir.join("FastAnythingRec.java"), rec).unwrap();
+ // width throws on an emoji: inputs it throws on aren't fair tests and must be left out
+ let check = r#"
+ public class Check {
+ static int width(String s, int[] xs) {
+ if (s.indexOf(0x1F44D) >= 0) throw new IllegalArgumentException("emoji");
+ return s.codePointCount(0, s.length()) + xs.length;
+ }
+ public static void main(String[] a) {
+ String s = "word ".repeat(40);
+ for (int k = 0; k < 3; k++) {
+ int[] xs = new int[20 + k];
+ FastAnythingRec.record(new Object[] {s, xs}, args -> width((String) args[0], (int[]) args[1]));
+ }
+ }
+ }
+ "#;
+ fs::write(dir.join("Check.java"), check).unwrap();
+ let out = dir.join("rec.jsonl");
+ let run = Command::new("java")
+ .arg("Check.java")
+ .current_dir(&dir)
+ .env("FAST_ANYTHING_RECORD_OUT", &out)
+ .env("FAST_ANYTHING_RECORD_META", dir.join("meta.json"))
+ .output()
+ .unwrap();
+ let text = fs::read_to_string(&out).unwrap_or_default();
+ let _ = fs::remove_dir_all(&dir);
+ assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
+ let edges: Vec<Value> = text
+ .lines()
+ .map(|l| serde_json::from_str::<Value>(l).unwrap())
+ .filter(|c| c["derived"] == "edge")
+ .collect();
+ let has_arg = |want: &Value, i: usize| edges.iter().any(|c| &c["args"][i] == want);
+ assert!(has_arg(&json!(""), 0) && has_arg(&json!([]), 1), "empty inputs: {text}");
+ // non-ASCII text, added to the short version of the recorded input (64 characters, 8 items)
+ let short: String = "word ".repeat(40).chars().take(64).collect();
+ assert!(has_arg(&json!(format!("{short}\u{65e5}\u{672c}")), 0), "{text}");
+ assert!(!text.contains('\u{1f44d}'), "an input the original throws on");
+ assert!(edges.iter().any(|c| c["args"][1].as_array().is_some_and(|a| a.len() == 8 * 16)), "bigger arrays");
+ assert!(edges.iter().any(|c| c["args"][1][0] == json!(-1)), "special numbers in arrays");
+ assert!(edges.iter().all(|c| c["result"].is_i64()), "every edge has the original's answer");
+ assert!(edges.len() <= 100);
+ }
+
+ #[test]
+ fn varargs_are_portable_as_arrays() {
+ if !Command::new("java").arg("-version").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no java on PATH, skipping");
+ return;
+ }
+ let dir = std::env::temp_dir().join(format!("fa-java-varargs-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ let app = "public class App {\n static int total(int scale, int... xs) {\n int s = 0;\n for (int x : xs) s += x * scale;\n return s;\n }\n\n static int count(String... words) {\n return words.length;\n }\n\n public static void main(String[] args) {\n System.out.println(total(2, 1, 2, 3) + count(\"a\", \"b\"));\n }\n}\n";
+ fs::write(dir.join("App.java"), app).unwrap();
+ let ctx = Ctx::open(&dir).unwrap();
+ let found = describe(&ctx, "java", &[dir.join("App.java")]);
+ let _ = fs::remove_dir_all(&dir);
+ let found = found.unwrap();
+ for (name, types) in [("total", vec!["int", "int[]"]), ("count", vec!["String[]"])] {
+ let m = found.iter().find(|m| m.name == name).unwrap();
+ assert!(m.blockers.is_empty(), "{name}: {:?}", m.blockers);
+ assert_eq!(m.params.iter().map(|p| p.annotation.as_deref().unwrap()).collect::<Vec<_>>(), types);
+ }
+ }
+
+ #[test]
+ fn duration_stops_an_app_that_runs_until_closed() {
+ if !Command::new("java").arg("-version").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no java 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-java-duration-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ // a server's shape: work, forever
+ let app = "public class App {\n static long work(int n) {\n long s = 0;\n for (int i = 0; i < n; i++) s += (long) i * i % 7;\n return s;\n }\n\n public static void main(String[] args) throws Exception {\n long sink = 0;\n while (true) {\n sink += work(20_000_000);\n Thread.sleep(1);\n }\n }\n}\n";
+ fs::write(dir.join("App.java"), app).unwrap();
+ let ctx = Ctx::open(&dir).unwrap();
+ let started = Instant::now();
+ // the window starts with the JVM, and `java App.java` compiles the source inside it: that
+ // takes longer on Windows
+ let window = if cfg!(windows) { 8.0 } else { 3.0 };
+ let p = profile(&ctx, "java", &["App.java".into()], Some(window));
+ let took = started.elapsed().as_secs_f64();
+ let _ = fs::remove_dir_all(&dir);
+ let p = p.unwrap();
+ assert!(p.functions.iter().any(|f| f.name == "work" && f.cumtime > 0.0), "{:?}", p.functions);
+ assert!(took < window + 20.0, "{took}");
+ }
+
#[test]
fn java_types_map_to_rust() {
assert_eq!(rust_type("int[][]").as_deref(), Some("Vec<Vec<i32>>"));