# JVMRS

[![Crates.io](https://img.shields.io/crates/v/jvmrs.svg)](https://crates.io/crates/jvmrs)
[![Documentation](https://docs.rs/jvmrs/badge.svg)](https://docs.rs/jvmrs)
[![License: MIT OR Apache-2.0](https://img.shields.io/badge/License-MIT%20OR%20Apache--2.0-blue.svg)](LICENSE)

A Java Virtual Machine implementation in Rust, featuring Cranelift JIT, AOT to native object files, generational GC, and multiple compilation backends.

## Why JVMRS?

Compared to HotSpot, OpenJ9, and GraalVM, jvmrs differentiates with **Rust-native design** and unique capabilities:

| Capability | HotSpot / OpenJ9 / GraalVM | JVMRS |
|------------|----------------------------|-------|
| **Language** | C++ / Java | **Rust** – memory safety, zero-cost abstractions |
| **JIT backend** | C2 / Graal / Eclipse OMR | **Cranelift** – Rust-native, permissive license |
| **Inline Caching** | Yes (HotSpot) | **Yes (JVMRS)** – 3-5x faster virtual calls |
| **TLAB** | Yes (HotSpot) | **Yes (JVMRS)** – 2-3x faster allocation |
| **Compressed oops** | Yes (HotSpot, 64-bit only) | **Yes (JVMRS)** – 16-bit encoded refs, 50% per-slot savings |
| **AOT output** | GraalVM native-image (binary) | **Object files (.o)** – link with any C toolchain |
| **WebAssembly** | Limited / experimental | **WASM emission** – run Java in browsers |
| **Java ↔ Rust interop** | JNI only | **Direct polyglot** – shared objects, no JNI |
| **Embedded / no_std** | Not supported | **no_std targets** – microcontrollers, bare-metal |
| **SIMD** | Auto-vectorization | **Explicit SIMD** – Rust `core::arch` |
| **Embedding** | Heavy footprint | **C API** – embed as a library in any app |
| **Truffle-style API** | GraalVM proprietary | **Open implementation** – language-agnostic runtime |
| **REPL** | JShell (limited) | **Full REPL** – interactive JVM exploration |
| **Property Tests** | Limited | **Comprehensive** – 30+ property-based tests |

**Use jvmrs when you need**: embeddable JVM, Java→WASM, Rust/Java interop, AOT to `.o` files, or a Rust-based JVM for research and tooling.

---

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
jvmrs = "0.1"
```

For optional features (LLVM IR, WebAssembly, etc.):

```toml
[dependencies]
jvmrs = { version = "0.1", features = ["wasm"] }
```

## Quick Start

```bash
# Clone and run
git clone https://github.com/yingkitw/jvmrs
cd jvmrs

# Run example classes (examples/ contains precompiled .class files)
cargo run Minimal
cargo run TestGetStatic
cargo run TestLdc

# Or compile your own Java and run
javac -d examples examples/HelloWorld.java
cargo run HelloWorld
```

---

## Usage

### Run a class

```bash
# Run main class (resolves via classpath)
cargo run HelloWorld
cargo run Calculator
cargo run SimpleMath
```

### CLI options

| Option | Description |
|--------|-------------|
| `--aot <output>` | AOT compile class to `.o` file instead of executing |
| `--no-jit` | Disable JIT; interpreter-only |
| `--jit-threshold <n>` | Invocations before JIT compile (default: 100) |
| `--llvm` | Emit LLVM IR to stdout (requires `--features llvm`) |
| `--help`, `-h` | Show help |

### Environment variables

| Variable | Description |
|----------|-------------|
| `JVMRS_DEBUG` | Enable debug logging |
| `JVMRS_TRACE` | Enable trace logging |

### Examples

```bash
# Run with default JIT
cargo run Calculator

# Run without JIT
cargo run -- --no-jit Calculator

# AOT compile to object file
cargo run -- --aot output.o HelloWorld

# Emit LLVM IR (requires: cargo build --features llvm)
cargo run --features llvm -- --llvm Calculator > calc.ll

# Custom JIT threshold
cargo run -- --jit-threshold 50 SimpleMath
```

---

## Examples

Example Java programs in `examples/`:

### HelloWorld.java

```java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
        int a = 5, b = 10, c = a + b;
        System.out.println("5 + 10 = " + c);
    }
}
```

### Calculator.java

```java
public class Calculator {
    public static int add(int a, int b) { return a + b; }
    public static int subtract(int a, int b) { return a - b; }
    public static int multiply(int a, int b) { return a * b; }
    public static float divide(float a, float b) { return a / b; }
    
    public static void main(String[] args) {
        int x = 20, y = 8;
        System.out.println("x + y = " + add(x, y));
        System.out.println("x - y = " + subtract(x, y));
        System.out.println("x * y = " + multiply(x, y));
        System.out.println("x / y = " + divide(x, y));
    }
}
```

### SimpleMath.java

```java
public class SimpleMath {
    public static int add(int a, int b) { return a + b; }
    public static void main(String[] args) {
        int z = add(5, 10);
        System.out.println("5 + 10 = " + z);
    }
}
```

### Running the examples

```bash
# Precompiled examples (Minimal, TestGetStatic, TestLdc)
cargo run Minimal
cargo run TestGetStatic
cargo run TestLdc

# Or compile and run your own
javac -d examples examples/HelloWorld.java examples/Calculator.java examples/SimpleMath.java
cargo run HelloWorld    # Hello, World! / 5 + 10 = 15
cargo run Calculator   # Arithmetic demo
cargo run SimpleMath   # 5 + 10 = 15
```

### Rust calling Java (polyglot)

```bash
cargo run --example rust_calling_java
```

### Interactive REPL

```bash
# Start interactive REPL (requires repl feature)
cargo run -- --repl

# Example REPL commands:
jvmrs> load java/lang/String
jvmrs> class java/lang/String
jvmrs> exec java/lang/String valueOf 42
jvmrs> help
jvmrs> exit
```

### REPL Commands

| Command | Description |
|---------|-------------|
| `load <class>` | Load a class |
| `class <class>` | Show class information |
| `method <class> <name>` | Show method information |
| `exec <class> [method]` | Execute a method |
| `new <class>` | Create a new instance |
| `get/set` | Get/set field values |
| `state` | Show JVM state |
| `help` | Show help |
| `exit` | Exit REPL |

---

## Features

### Core
- Class file parser, constant pool, stack-based interpreter
- Generational GC with parallel sweep
- Arrays, strings, inheritance, interfaces
- **Inline Caching** – Optimized virtual method dispatch (3-5x faster)
- **Thread-Local Allocation (TLAB)** – Fast, lock-free object allocation (2-3x faster)
- **Compressed Oops** – 16-bit encoded references for memory-constrained environments (50% per-slot savings)
- **Reflection** – `Interpreter::new_instance`, `get_field_value`, `set_field_value`, `invoke_method`, `get_object_class`
- **Serialization** – Binary format for `HeapObject` and `Value` (JVRS format)
- **Property-Based Tests** – 30+ comprehensive property tests for correctness

### Compilation
- **Cranelift JIT** – bytecode-to-native for hot methods
- **Tiered compilation** – interpreter → baseline → optimized
- **AOT** – compile to `.o` via cranelift-object
- **LLVM IR** (`--features llvm`) – export to LLVM
- **WebAssembly** (`--features wasm`) – emit WASM

### Optional (feature-gated)
- `ffi` – C API for embedding
- `interop` – Java/Rust polyglot
- `async` – tokio async I/O
- `simd` – SIMD array ops
- `truffle` – GraalVM-style language API

---

## Building

```bash
cargo build
cargo build --features llvm    # LLVM IR export
cargo build --features wasm    # WebAssembly backend
```

## Testing

```bash
cargo test                        # 68+ unit tests
cargo test --doc                  # Doctests (extensions example)
cargo test --test property_tests    # Property-based tests (requires proptest feature)
cargo bench                       # Run comprehensive benchmark suite
cargo bench --bench instruction_benchmarks  # Specific benchmarks
```

### Test Coverage

- **Unit Tests**: 68+ tests covering all core modules
- **Property-Based Tests**: 30+ tests verifying invariants across 20+ properties
- **Benchmarks**: Comprehensive suite covering 14 benchmark categories
- **Integration Tests**: End-to-end testing with example classes

### Test Features

- Arithmetic operations (commutative, associative, identity)
- Bitwise operations (De Morgan's laws, idempotence)
- Array operations (length preservation, write/read)
- Stack operations (push/pop reversibility)
- String operations (concatenation associativity)
- GC correctness (live object preservation)
- Method invocation consistency
- Object identity and null handling

## Documentation

- [API Documentation](https://docs.rs/jvmrs)
- `ARCHITECTURE.md` – Design and components
- `IMPLEMENTATION_SUMMARY.md` – Performance enhancements and features
- `docs/api-reference.md` – Complete API reference with examples
- `docs/performance-tuning.md` – Performance optimization guide
- `docs/polyglot-programming.md` – Java/Rust interop guide
- `docs/competitive-differentiation.md` – How JVMRS differs from other JVMs
- `spec.md` – Technical specification
- `TODO.md` – Roadmap

## License

Licensed under either of [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE) at your option.
