# Developer Experience

## Interactive REPL

JVMRS provides a powerful interactive REPL for exploring and debugging JVM internals without writing code.

### Starting the REPL

```bash
# Run with REPL mode
cargo run -- --repl

# Or use the REPL directly
cargo run --example repl
```

### REPL Capabilities

The REPL supports:
- **Class loading and inspection**: Load classes and view their structure
- **Method execution**: Execute methods dynamically with arguments
- **Object manipulation**: Create instances and access fields
- **State inspection**: View loaded classes, memory usage, and GC statistics
- **Interactive debugging**: Step through execution and inspect state

### Example Session

```
jvmrs> load java/lang/String
Loaded class: java/lang/String

jvmrs> class java/lang/String

Class: java/lang/String
Super class: java/lang/Object
Access flags: 0x21

Fields:
  value [C
  hash I
  coder B

Methods:
  length ()I
  charAt (I)C
  ...

jvmrs> new java/lang/String
Created instance: 123456

jvmrs> exec java/lang/String length 123456
Result: 5

jvmrs> state

JVM State:
Loaded classes: 15
Memory usage: 1048576 bytes
GC runs: 3

jvmrs> help
Available Commands:
  load <class>          - Load a class
  class <class>         - Show class information
  method <class> <name> - Show method information
  exec <class> [method] - Execute a method (default: main)
  new <class> [args...] - Create a new instance
  get <ref> <field> <class> - Get a field value
  set <ref> <field> <class> <value> - Set a field value
  state                - Show current JVM state
  help                 - Show this help message
  exit                 - Exit REPL
```

## Performance Profiling with Rust Tooling

JVMRS includes an integrated profiler that exports data compatible with **cargo-flamegraph** and Brendan Gregg's **flamegraph.pl**.

### Usage

```bash
# Run with profiler, output collapsed stack format
./target/debug/jvmrs --profile --profile-output profile.txt HelloWorld

# Generate flame graph (requires flamegraph.pl or inferno)
cat profile.txt | flamegraph.pl > flamegraph.svg

# Or use cargo-flamegraph for Rust + JVM combined profiling
cargo flamegraph --bin jvmrs -- HelloWorld
```

### Output Format

The profiler writes collapsed stack format:
```
Main.main;Util.helper 1500
Main.main 800
```

Compatible with: flamegraph.pl, inferno, cargo-flamegraph.

---

## Hot Reloading for Java/Rust Hybrid Development

The `hot_reload` module provides an API for detecting when Java class files change and triggering reloads.

```rust
use jvmrs::hot_reload::HotReloadManager;

let mut mgr = HotReloadManager::new();
mgr.set_enabled(true);
mgr.register_reloadable("MyClass", "myMethod");

if mgr.class_file_changed(Path::new("MyClass.class")) {
    // Reload class and replace method
}
```

Full hotswap requires JIT support for function redefinition (planned).

---

## Inline Caching Statistics

Monitor the effectiveness of inline caching for optimizing virtual method dispatch:

```rust
let stats = interpreter.get_inline_cache_stats();
for (site, cache_stats) in stats {
    println!("Call site: {:?}", site);
    println!("  Hit rate: {:.2}%", cache_stats.hit_rate);
    println!("  Total lookups: {}", cache_stats.total_lookups);
    println!("  Cache hits: {}", cache_stats.cache_hits);
    println!("  Entry count: {}", cache_stats.entry_count);
}
```

### Understanding Cache Behavior

- **Monomorphic**: Single receiver type (hit rate > 95%)
- **Polymorphic**: Few receiver types (hit rate 70-90%)
- **Megamorphic**: Many receiver types (hit rate < 70%)

### Optimizing for Inline Caching

- Prefer monomorphic callsites where possible
- Use final classes for single implementation
- Consider devirtualization in hot code paths

---

## TLAB (Thread-Local Allocation) Statistics

Monitor TLAB effectiveness for optimizing allocation performance:

```rust
let stats = interpreter.get_tlab_stats();
println!("Total allocations: {}", stats.total_allocations);
println!("TLAB hits: {} ({:.2}%)", stats.tlab_hits, stats.hit_rate);
println!("TLAB misses: {}", stats.tlab_misses);
println!("Active TLABs: {}", stats.active_tlabs);
```

### TLAB Configuration

Adjust TLAB size for your workload:

```rust
use jvmrs::tlab::TlabConfig;

let config = TlabConfig {
    tlab_size: 128 * 1024,  // 128KB per TLAB
    max_tlabs: 32,              // Max TLABs in pool
    enabled: true,               // Enable TLAB
};
```

**Guidelines**:
- Small objects (few hundred bytes): 64KB TLAB
- Medium objects (few KB): 256KB TLAB
- Large objects (many KB): 512KB+ TLAB

---

## Property-Based Testing

JVMRS includes comprehensive property-based tests for verifying correctness:

```bash
# Run all property-based tests
cargo test --test property_tests

# Run specific property test
cargo test prop_iadd_commutative
```

### Property-Based Test Coverage

- **Arithmetic**: Commutativity, associativity, identity laws
- **Bitwise**: De Morgan's laws, idempotence, shift invariants
- **Arrays**: Length preservation, write/read consistency, bounds checking
- **Stack**: Push/pop reversibility, overflow/underflow handling
- **Strings**: Concatenation associativity, hashcode consistency
- **GC**: Live object preservation, identity retention
- **Method Dispatch**: Consistency, correctness, order independence

### Writing Property Tests

```rust
use proptest::prelude::*;

proptest! {
    #[test]
    fn prop_my_invariant(a in any::<i32>(), b in any::<i32>()) {
        let result1 = my_operation(a, b);
        let result2 = my_operation(b, a);
        prop_assert!(some_invariant(result1, result2));
    }
}
```

### Benefits of Property-Based Testing

- **Better coverage**: Tests many more cases than unit tests
- **Invariant detection**: Catches subtle bugs in edge cases
- **Regression prevention**: Automatically tests future changes
- **Documentation**: Properties serve as executable specifications

---

```rust
use jvmrs::hot_reload::HotReloadManager;

let mut mgr = HotReloadManager::new();
mgr.set_enabled(true);
mgr.register_reloadable("MyClass", "myMethod");

if mgr.class_file_changed(Path::new("MyClass.class")) {
    // Reload class and replace method
}
```

Full hotswap requires JIT support for function redefinition (planned).

---

## Rust Documentation for Java APIs

Use `cargo doc` to generate documentation. The `reflection` module exposes Java class metadata:

```rust
let reflection = interpreter.get_reflection_api();
let class_info = interpreter.get_class_reflection("java/lang/String");
// class_info contains method signatures, fields, etc.
```

For Java API docs, consider generating from `ClassReflection` to Markdown or HTML.

---

## IDE Support

Future work:
- VS Code / Cursor extension for cross-language debugging
- LSP for Java source when used with JVMRS
