Skip to main content

rust_anything/
harness_java.rs

1//! The Java side of record, build, diff and bench. A generated driver calls the unit's static
2//! methods by reflection: compiled with the original sources to record, and with the JNI
3//! wrapper classes over the Rust library to diff.
4
5use crate::walk::Canonical;
6use std::path::{Path, PathBuf};
7use std::process::Command;
8
9use anyhow::{Context, Result, bail};
10use serde_json::Value;
11
12use crate::bridge::Manifest;
13use crate::harness::{BenchRow, CASES, DiffOutcome};
14
15const WORK_DIR: &str = ".rust-anything";
16
17fn run(cmd: &mut Command, what: &str) -> Result<()> {
18    let _scratch = crate::harness::scratch_cwd(cmd)?;
19    let output = cmd.output().with_context(|| format!("running {what}"))?;
20    if !output.status.success() {
21        let text = format!(
22            "{}{}",
23            String::from_utf8_lossy(&output.stdout),
24            String::from_utf8_lossy(&output.stderr)
25        );
26        let tail: Vec<&str> = text
27            .lines()
28            .filter(|l| !l.starts_with("Picked up JAVA_TOOL_OPTIONS"))
29            .rev()
30            .take(30)
31            .collect();
32        bail!(
33            "{what} failed ({}):\n{}",
34            output.status,
35            tail.into_iter().rev().collect::<Vec<_>>().join("\n")
36        );
37    }
38    Ok(())
39}
40
41fn java_files(dir: &Path) -> Vec<PathBuf> {
42    crate::walk::builder(dir)
43        .require_git(false)
44        .build()
45        .flatten()
46        .map(|e| e.into_path())
47        .filter(|p| p.extension().is_some_and(|e| e == "java"))
48        .collect()
49}
50
51/// Compiles the driver with the original sources (`rust: false`) or the wrapper classes.
52fn compile(crate_dir: &Path, m: &Manifest, rust: bool) -> Result<PathBuf> {
53    let work = crate_dir.canonical()?.join(WORK_DIR);
54    let support = work.join("java-support/rust-anything");
55    std::fs::create_dir_all(&support)?;
56    std::fs::write(
57        support.join("RustAnythingJson.java"),
58        crate::codegen_java::JSON_JAVA,
59    )?;
60    std::fs::write(
61        support.join("RustAnythingDriver.java"),
62        crate::codegen_java::DRIVER_JAVA,
63    )?;
64    let classes = work.join(if rust { "java-rust" } else { "java-original" });
65    if classes.exists() {
66        std::fs::remove_dir_all(&classes)?;
67    }
68    std::fs::create_dir_all(&classes)?;
69    let mut sources = java_files(&work.join("java-support"));
70    if rust {
71        sources.extend(
72            java_files(&crate_dir.join("java"))
73                .into_iter()
74                .filter(|p| !p.ends_with("rustanything/RustAnythingJson.java")),
75        );
76    } else {
77        // The whole source tree: the unit's classes may use others from the same module.
78        let ws = crate::lang::java::discover(&m.root)?;
79        sources.extend(
80            ws.files
81                .iter()
82                .filter(|f| f.kind == crate::ts::discover::FileKind::Source)
83                .map(|f| m.root.join(&f.path)),
84        );
85    }
86    let mut javac = Command::new("javac");
87    javac.args(["-encoding", "UTF-8", "-nowarn"]);
88    let user = user_classpath();
89    if !user.is_empty() {
90        javac.arg("-cp").arg(std::env::join_paths(user)?);
91    }
92    run(
93        javac.arg("-d").arg(&classes).args(&sources),
94        if rust {
95            "javac (driver and wrapper classes)"
96        } else {
97            "javac (driver and original sources)"
98        },
99    )
100    .map_err(|e| {
101        let text = format!("{e:#}");
102        if missing_classes(&text) {
103            anyhow::anyhow!(
104                "{text}\n\nThe sources use classes from outside their tree (a library or another \
105                 module). Set CLASSPATH to the jars and class folders the project builds against \
106                 and run again: javac and the driver both read it."
107            )
108        } else {
109            e
110        }
111    })?;
112    Ok(classes)
113}
114
115/// Whether javac failed on types it could not find, as a Gradle or Maven module compiled
116/// without its dependencies does.
117fn missing_classes(javac: &str) -> bool {
118    javac.lines().any(|l| {
119        l.contains(": error: cannot find symbol")
120            || (l.contains(": error: package ") && l.ends_with(" does not exist"))
121    })
122}
123
124/// The CLASSPATH variable's entries, which `-cp` would otherwise replace. Made absolute, since
125/// javac and java run in a scratch folder; a `lib/*` entry keeps its `*`.
126fn user_classpath() -> Vec<PathBuf> {
127    std::env::var_os("CLASSPATH")
128        .map(|v| {
129            std::env::split_paths(&v)
130                .filter(|p| !p.as_os_str().is_empty())
131                .map(|p| std::path::absolute(&p).unwrap_or(p))
132                .collect()
133        })
134        .unwrap_or_default()
135}
136
137fn driver(
138    crate_dir: &Path,
139    m: &Manifest,
140    mode: &str,
141    cases: &Path,
142    out: &Path,
143    min_ms: u64,
144    rust: bool,
145) -> Result<()> {
146    let mut cmd = driver_command(crate_dir, m, mode, cases, out, min_ms, rust)?;
147    run(&mut cmd, &format!("java driver ({mode})"))
148}
149
150/// Java class files for a dexed on-device run: support driver plus either the original Java
151/// sources (`rust: false`) or the generated JNI wrappers (`rust: true`).
152pub(crate) fn android_classes(crate_dir: &Path, m: &Manifest, rust: bool) -> Result<Vec<PathBuf>> {
153    let classes = compile(crate_dir, m, rust)?;
154    Ok(crate::walk::builder(&classes)
155        .require_git(false)
156        .build()
157        .flatten()
158        .map(|e| e.into_path())
159        .filter(|p| p.extension().is_some_and(|e| e == "class"))
160        .collect())
161}
162
163fn driver_command(
164    crate_dir: &Path,
165    m: &Manifest,
166    mode: &str,
167    cases: &Path,
168    out: &Path,
169    min_ms: u64,
170    rust: bool,
171) -> Result<Command> {
172    let classes = compile(crate_dir, m, rust)?;
173    let mut classpath = vec![classes];
174    if rust {
175        classpath.push(compile(crate_dir, m, false)?);
176    }
177    classpath.extend(user_classpath());
178    let classpath = std::env::join_paths(classpath)?;
179    let work = crate_dir.join(WORK_DIR);
180    let targets = work.join("targets.json");
181    std::fs::write(&targets, crate::codegen_java::targets(m).to_string())?;
182    let mut cmd = Command::new("java");
183    cmd.arg("-Dfile.encoding=UTF-8");
184    if rust {
185        let lib = crate::harness_c::built_library(crate_dir, m)?;
186        cmd.arg(format!(
187            "-Drust-anything.lib.{}={}",
188            m.lib_name(),
189            lib.canonical()?.display()
190        ));
191    }
192    cmd.arg("-cp")
193        .arg(&classpath)
194        .arg("rustanything.RustAnythingDriver")
195        .arg(mode)
196        .arg(&targets)
197        .arg(cases)
198        .arg(out)
199        .arg(min_ms.to_string());
200    Ok(cmd)
201}
202
203pub fn record(crate_dir: &Path, m: &Manifest, cases: &[Value]) -> Result<PathBuf> {
204    std::fs::create_dir_all(crate_dir.join(WORK_DIR))?;
205    let out = crate_dir.join(CASES);
206    crate::harness::record_cases(
207        cases,
208        &crate_dir.join(WORK_DIR),
209        &out,
210        "java driver (record)",
211        |inputs, part| driver_command(crate_dir, m, "record", inputs, part, 0, false),
212    )?;
213    Ok(out)
214}
215
216pub fn diff(crate_dir: &Path, m: &Manifest) -> Result<DiffOutcome> {
217    let cases = crate_dir.join(CASES);
218    if !cases.exists() {
219        bail!(
220            "no {CASES} in {} (run `rust-anything record` first)",
221            crate_dir.display()
222        );
223    }
224    let out = crate_dir.join(WORK_DIR).join("diff.json");
225    driver(crate_dir, m, "diff", &cases, &out, 0, true)?;
226    Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
227}
228
229pub fn bench(crate_dir: &Path, m: &Manifest, min_ms: u64) -> Result<Vec<BenchRow>> {
230    let cases = crate_dir.join(CASES);
231    if !cases.exists() {
232        bail!(
233            "no {CASES} in {} (run `rust-anything record` first)",
234            crate_dir.display()
235        );
236    }
237    let mut timings = Vec::new();
238    for rust in [false, true] {
239        let out = crate_dir.join(WORK_DIR).join(if rust {
240            "bench-rust.json"
241        } else {
242            "bench-original.json"
243        });
244        driver(crate_dir, m, "bench", &cases, &out, min_ms, rust)?;
245        timings.push(serde_json::from_str(&std::fs::read_to_string(&out)?)?);
246    }
247    Ok(crate::harness::bench_rows(m, &timings[0], &timings[1]))
248}