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
//! javars — Java as a fusevm frontend.
//!
//! Pipeline: `lexer` → `parser` builds a Java AST → `compiler` lowers it to a
//! `fusevm::Chunk` → fusevm executes it on the shared three-tier Cranelift JIT,
//! calling back into `host` (the strict numeric hook) for Java's `String` `+`
//! overload. There is no bespoke VM or JVM here — execution and codegen live in
//! fusevm, the same engine behind zshrs, stryke, awkrs, elisp, and ruby.

pub mod ast;
pub mod banner;
pub mod cli;
pub mod compiler;
pub mod dap;
pub mod embed;
pub mod fdlibm;
pub mod flow;
pub mod host;
pub mod hotspot_trig;
pub mod jbig;
pub mod jbigdec;
pub mod jbitset;
pub mod jdk_generic_statics;
pub mod jdk_supertypes;
pub mod jio;
pub mod jrandom;
pub mod jstr;
pub mod lexer;
pub mod lsp;
pub mod parser;
pub mod prelude;
pub mod reference;
pub mod regex;
pub mod regex_names;
pub mod regex_syntax;
pub mod rust_ffi;
pub mod tiers;
pub mod unicode_tables;
pub mod uninames;

pub use banner::version_banner;
pub use embed::run_program;
use fusevm::{VMResult, Value, VM};

/// Parse Java `src` to an AST. Inline `rust { ... }` FFI blocks are desugared to
/// `__rust_compile(...)` statements first (see [`rust_ffi`]), so every parse
/// path — run, `--dump-ast`, `--disasm`, `--dap` — sees the same rewritten
/// source. No-op when the source has no `rust` block.
pub fn parse(src: &str) -> Result<ast::Program, String> {
    let src = rust_ffi::desugar(src);
    let mut prog = parser::parse(&src)?;
    // A name declared twice is a `javac` error, and every table javars would
    // have put it in keeps exactly one of the two — so the program used to run
    // against whichever declaration won. Checked before the prelude is injected,
    // so it sees the user's declarations only (see
    // [`compiler::check_duplicate_declarations`]).
    compiler::check_duplicate_declarations(&prog)?;
    // The member rules `javac` checks on declarations alone (access, defaults,
    // forward references, unassigned finals), on the user's declarations too.
    compiler::check_member_rules(&prog)?;
    // Definite assignment (JLS 16) and the checks that ride on it: final
    // reassignment, forward references, effective finality.
    flow::check(&prog)?;
    // A program that throws or catches also declares, implicitly, the
    // `java.lang` throwable classes it names — there is no JDK to import them
    // from. No-op for every other program (see [`prelude::inject`]).
    prelude::inject(&mut prog)?;
    Ok(prog)
}

/// The type → direct-supertypes map (superclass + interfaces) that drives
/// runtime `instanceof`, `catch` matching, checked casts, and default
/// `toString`.
///
/// Every entry point that runs a program builds this — the normal run and the
/// DAP debugger — so it lives here rather than being spelled out at each, which
/// is how the debugger came to walk a *different* graph from the interpreter.
///
/// Beyond what the source declares, this supplies the two supertypes `javac`
/// gives a declaration implicitly and the text therefore never mentions:
/// an `enum` extends `java.lang.Enum` (and so is `Comparable`), and a `record`
/// extends `java.lang.Record`. `java.lang.Object` is deliberately NOT an edge
/// here: every non-null reference is an `Object` whether or not its class is
/// declared in this program, so that is answered once at the type test rather
/// than by rooting the graph.
pub(crate) fn supertype_map(prog: &ast::Program) -> std::collections::HashMap<String, Vec<String>> {
    prog.classes
        .iter()
        .map(|c| {
            let mut sups: Vec<String> = c.superclass.clone().into_iter().collect();
            sups.extend(c.interfaces.iter().cloned());
            if c.is_enum {
                sups.push("Enum".to_string());
            }
            if c.is_record {
                sups.push("Record".to_string());
            }
            (c.name.clone(), sups)
        })
        .collect()
}

/// Every functional interface the program can name → the name of its single
/// abstract method: each declared interface with exactly one abstract method
/// (the prelude's, once injected, among them), plus every modeled
/// `java.util.function` interface whether or not the prelude was injected —
/// a class can `implements Comparator<T>` without the program writing a
/// lambda. Read by the host to call an *object* where a lambda is expected.
pub(crate) fn functional_sam_map(prog: &ast::Program) -> std::collections::HashMap<String, String> {
    let mut map: std::collections::HashMap<String, String> = prelude::FUNCTIONAL
        .iter()
        .filter_map(|(name, sam, _)| {
            let head = sam.split('(').next()?;
            Some((
                name.to_string(),
                head.split_whitespace().last()?.to_string(),
            ))
        })
        .collect();
    for c in prog.classes.iter().filter(|c| c.is_interface) {
        let mut abstracts = c.methods.iter().filter(|m| m.is_abstract);
        if let (Some(m), None) = (abstracts.next(), abstracts.next()) {
            map.insert(c.name.clone(), m.name.clone());
        }
    }
    map
}

/// Every user class's simple name → Java's binary name (`Outer$Nested`).
pub(crate) fn binary_name_map(prog: &ast::Program) -> std::collections::HashMap<String, String> {
    prog.classes
        .iter()
        .map(|c| (c.name.clone(), c.binary.clone()))
        .collect()
}

/// Parse and lower Java `src` to a runnable fusevm chunk.
pub fn compile(src: &str) -> Result<fusevm::Chunk, String> {
    let prog = parse(src)?;
    compiler::compile(&prog)
}

/// Register the javars builtins + strict numeric hook on a fresh VM, enable the
/// tracing JIT, and run the chunk. `supers` is the class → direct-superclass
/// map (for `instanceof`/`toString`); `exceptions` says whether the chunk was
/// compiled with the exception machinery (so a runtime fault can become a
/// catchable throwable rather than an abort). Returns the last top-of-stack
/// value.
fn run_chunk(
    chunk: fusevm::Chunk,
    supers: std::collections::HashMap<String, Vec<String>>,
    binaries: std::collections::HashMap<String, String>,
    exceptions: bool,
    argv: &[String],
) -> Result<Value, String> {
    // A fresh object heap per run — no handle leaks across programs.
    host::heap_reset();
    host::set_supertypes(supers);
    host::set_binary_names(binaries);
    host::set_exceptions_enabled(exceptions);
    host::set_argv(argv.to_vec());
    // Java interns string literals; javars gives a `String` its identity through
    // its `Arc`, so the canonical object for a text that appears as a literal
    // has to be that literal's. The constant pool is the only place they live,
    // and it is read once here rather than at every `intern()` call.
    host::intern_literals(&chunk);
    let mut vm = VM::new(chunk);
    host::install(&mut vm);
    vm.set_numeric_hook(std::sync::Arc::new(host::numeric_hook));
    vm.enable_tracing_jit();
    let result = vm.run();
    // A host builtin fault (inline-Rust FFI compile/call error, or a `String`
    // method fault such as an out-of-range index) stashes its message and halts
    // the VM. The VM reports `Ok(top-of-stack)` when a value remains on the
    // stack and `Halted` only when it is empty, so the pending message must be
    // checked on **both** paths — a fault mid-expression (e.g. inside a
    // `println(...)` argument) leaves its `Undef` return on the stack and would
    // otherwise be silently swallowed.
    if let Some(e) = host::take_ffi_error() {
        return Err(e);
    }
    match result {
        VMResult::Ok(v) => Ok(v),
        VMResult::Halted => Ok(vm.stack.last().cloned().unwrap_or(Value::Undef)),
        VMResult::Error(e) => Err(e),
    }
}

/// Compile and run a Java source string with no program arguments (`args` is a
/// zero-length `String[]`); return the last VM value.
pub fn run_str(src: &str) -> Result<Value, String> {
    run_str_args(src, &[])
}

/// Compile and run a Java source string, binding `argv` to `main`'s `String[]`
/// parameter.
pub fn run_str_args(src: &str, argv: &[String]) -> Result<Value, String> {
    let prog = parse(src)?;
    let supers = supertype_map(&prog);
    let binaries = binary_name_map(&prog);
    let chunk = compiler::compile(&prog)?;
    host::set_functional_sams(functional_sam_map(&prog));
    run_chunk(chunk, supers, binaries, prog.uses_exceptions, argv)
}

/// Read and run a `.java` file.
pub fn run_file(path: &str) -> Result<Value, String> {
    let src =
        std::fs::read_to_string(path).map_err(|e| format!("javars: cannot read {path}: {e}"))?;
    run_str(&src)
}

/// Compile `src` and return a human-readable disassembly of the fusevm chunk
/// (for `java --disasm`).
pub fn disassemble(src: &str) -> Result<String, String> {
    Ok(compile(src)?.disassemble())
}