javars 0.1.14

Java as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk, run on the shared three-tier Cranelift JIT — no bespoke VM or JVM
Documentation
//! Embedding entry point: run a Java program from Rust with a given stdin and
//! get its stdout back as a string.

use crate::host;

/// Stack for the interpreter thread each embedded run gets. A spawned thread
/// defaults to 2 MiB, well below the main-thread stack the `java` binary runs
/// deep recursion on.
const INTERPRETER_STACK: usize = 64 * 1024 * 1024;

/// Run `src` as a complete program with `input` as its stdin and return
/// everything it wrote to stdout.
///
/// Each call runs on its own interpreter thread, so the object heap, statics
/// and the `System.in` cursor start fresh, and concurrent calls never share an
/// output buffer. Every reader over `System.in` (`Scanner`, `BufferedReader`,
/// `System.in.read`) reads `input`; `System.out` (and any writer built over it)
/// appends to the returned string and never reaches the process stdout.
/// `System.err` still goes to the process stderr.
///
/// Returns `Err` for a parse or compile error, an uncaught exception, a
/// nonzero `System.exit`, or an internal panic. `System.exit(0)` returns `Ok`
/// with the output written up to that point.
pub fn run_program(src: &str, input: &str) -> Result<String, String> {
    let (src, input) = (src.to_string(), input.to_string());
    std::thread::Builder::new()
        .name("java".to_string())
        .stack_size(INTERPRETER_STACK)
        .spawn(move || run_captured(&src, &input))
        .map_err(|e| format!("javars: cannot start the interpreter thread: {e}"))?
        .join()
        .unwrap_or_else(|_| Err("javars: internal error: the interpreter panicked".to_string()))
}

/// The whole embedded run on the current thread: capture on, run, capture off.
fn run_captured(src: &str, input: &str) -> Result<String, String> {
    host::begin_embedded_io(input)?;
    let result = crate::run_str(src);
    let output = host::end_embedded_io();
    result?;
    match host::exit_code() {
        None | Some(0) => Ok(output),
        Some(code) => Err(format!("javars: exit status {code}")),
    }
}