jvmrs 0.1.2

A JVM implementation in Rust with Cranelift JIT, AOT compilation, and WebAssembly support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# JVMRS API Reference

This document provides a comprehensive reference for the JVMRS public API.

## Table of Contents

- [Core API]#core-api
- [Memory API]#memory-api
- [Reflection API]#reflection-api
- [JIT API]#jit-api
- [Native Methods]#native-methods
- [Polyglot API]#polyglot-api
- [Profiling & Debugging]#profiling--debugging
- [Error Handling]#error-handling

---

## Core API

### Interpreter

The main entry point for executing Java bytecode.

```rust
use jvmrs::Interpreter;
```

#### Constructors

```rust
// Create interpreter with default classpath
let mut interpreter = Interpreter::new();

// Create interpreter with custom classpath
use std::path::PathBuf;
let classpath = vec![PathBuf::from("./classes")];
let mut interpreter = Interpreter::with_classpath(classpath);
```

#### Execution Methods

##### `run_main`

Execute the main method of a class.

```rust
pub fn run_main(&mut self, class_name: &str) -> Result<(), JvmError>
```

**Example:**
```rust
interpreter.run_main("com/example/HelloWorld")?;
```

**Parameters:**
- `class_name`: Fully qualified class name (e.g., "java/lang/Object")

**Returns:**
- `Ok(())` on success
- `Err(JvmError)` on error

##### `load_class`

Load a class into the interpreter.

```rust
pub fn load_class(&mut self, class_name: &str) -> Result<(), JvmError>
```

**Example:**
```rust
interpreter.load_class("java/util/ArrayList")?;
```

##### `invoke_method`

Invoke a static or instance method.

```rust
pub fn invoke_method(
    &mut self,
    class_name: &str,
    method_name: &str,
    args: &[Value]
) -> Result<Value, JvmError>
```

**Example:**
```rust
use jvmrs::Value;

let result = interpreter.invoke_method(
    "java/lang/Math",
    "max",
    &[Value::Int(10), Value::Int(20)]
)?;

assert_eq!(result, Value::Int(20));
```

---

## Memory API

### Value

Represents JVM values (primitives, references, arrays).

```rust
use jvmrs::Value;
```

#### Variants

```rust
pub enum Value {
    Null,
    Int(i32),
    Long(i64),
    Float(f32),
    Double(f64),
    Reference(usize),      // Object reference
    ArrayRef(usize),      // Array reference
    ReturnAddress(u32),   // For JSR/RET
    String(String),        // Java string as Rust string
}
```

#### Methods

##### `as_int`

Convert value to i32.

```rust
pub fn as_int(&self) -> i32
```

##### `as_long`

Convert value to i64.

```rust
pub fn as_long(&self) -> i64
```

##### `is_category_2`

Check if value occupies two stack slots (long/double).

```rust
pub fn is_category_2(&self) -> bool
```

---

### StackFrame

Represents a method's execution context.

```rust
use jvmrs::StackFrame;
```

#### Constructor

```rust
pub fn new(max_locals: usize, max_stack: usize, method_name: String) -> Self
```

**Parameters:**
- `max_locals`: Maximum number of local variables
- `max_stack`: Maximum operand stack depth
- `method_name`: Name of the method

#### Methods

##### `push`

Push a value onto the operand stack.

```rust
pub fn push(&mut self, value: Value) -> Result<(), JvmError>
```

##### `pop`

Pop a value from the operand stack.

```rust
pub fn pop(&mut self) -> Result<Value, JvmError>
```

##### `store_local`

Store a value in a local variable.

```rust
pub fn store_local(&mut self, index: usize, value: Value) -> Result<(), JvmError>
```

##### `load_local`

Load a value from a local variable.

```rust
pub fn load_local(&self, index: usize) -> Result<Value, JvmError>
```

---

## Reflection API

### Runtime Introspection

JVMRS provides comprehensive reflection capabilities.

#### `get_class_info`

Get detailed information about a class.

```rust
pub fn get_class_info(&self, class_name: &str) -> Result<ClassInfo, JvmError>
```

**Example:**
```rust
let info = interpreter.get_class_info("java/lang/String")?;
println!("Superclass: {}", info.super_class);
for method in info.methods {
    println!("Method: {}", method);
}
```

#### `get_field_value`

Get the value of an object's field.

```rust
pub fn get_field_value(&self, obj: usize, field_name: &str) -> Result<Value, JvmError>
```

#### `set_field_value`

Set the value of an object's field.

```rust
pub fn set_field_value(&mut self, obj: usize, field_name: &str, value: Value) -> Result<(), JvmError>
```

#### `new_instance`

Create a new instance of a class.

```rust
pub fn new_instance(&mut self, class_name: &str) -> Result<usize, JvmError>
```

---

## JIT API

### Tiered Compilation

JVMRS uses tiered compilation for optimal performance.

### CompilationLevel

Represents the compilation tier.

```rust
pub enum CompilationLevel {
    Interpreter,   // Bytecode interpretation
    Baseline,      // Fast JIT compilation
    Optimized,     // Optimized JIT compilation
}
```

### TieredCompilationConfig

Configure JIT compilation behavior.

```rust
pub struct TieredCompilationConfig {
    pub baseline_threshold: u64,     // Invocations before baseline JIT
    pub optimized_threshold: u64,    // Invocations before optimized JIT
    pub enabled: bool,              // Enable/disable JIT
    pub max_method_size: usize,      // Maximum method size to compile
}
```

**Example:**
```rust
use jvmrs::jit::TieredCompilationConfig;

let config = TieredCompilationConfig {
    baseline_threshold: 50,
    optimized_threshold: 1000,
    ..Default::default()
};
```

---

## Native Methods

### Registering Native Methods

Register Rust functions as native Java methods.

```rust
interpreter.register_native_method(
    "com/example/NativeLib",
    "add",
    "(II)I",
    Box::new(|args, memory| {
        let a = args[0].as_int();
        let b = args[1].as_int();
        Ok(Value::Int(a + b))
    })
)?;
```

### Signature Format

Method signatures use JVM descriptor format:

```
(I)I          // int method(int)
(II)I         // int method(int, int)
(Ljava/lang/String;)V  // void method(String)
([I)V        // void method(int[])
```

**Type Codes:**
- `B` - byte
- `C` - char
- `D` - double
- `F` - float
- `I` - int
- `J` - long
- `S` - short
- `Z` - boolean
- `V` - void
- `L<name>;` - object
- `[<type>` - array

---

## Polyglot API

### Java-Rust Interop

Seamlessly call Java from Rust and vice versa.

#### Calling Java from Rust

```rust
// Create object
let list = interpreter.new_instance("java/util/ArrayList")?;

// Call method
interpreter.invoke_method(list, "add", &[Value::Int(42)])?;

// Get result
let size = interpreter.invoke_method(list, "size", &[])?;
println!("Size: {}", size.as_int());
```

#### Calling Rust from Java

```rust
// Register Rust function
interpreter.register_native_method(
    "com/example/RustApi",
    "process",
    "(I)I",
    Box::new(|args, _memory| {
        let value = args[0].as_int();
        Ok(Value::Int(value * 2))
    })
)?;

// Call from Java
interpreter.run_main("com/example/Caller")?;
```

---

## Profiling & Debugging

### Profiler

Collect performance metrics.

```rust
use jvmrs::profiler::Profiler;

let profiler = Profiler::new();
interpreter.set_profiler(Some(profiler.clone()));

// Run workload...

// Get statistics
let hot_methods = profiler.get_hot_methods(10);
for (method, time) in hot_methods {
    println!("{}: {}ms", method, time);
}

// Generate flame graph
profiler.generate_flame_graph("flamegraph.svg")?;
```

### Trace Recorder

Record execution trace for debugging.

```rust
use jvmrs::trace::TraceRecorder;

let recorder = TraceRecorder::new();
interpreter.set_trace_recorder(Some(recorder));

// Run workload...

// Get trace
let trace = interpreter.get_trace_recorder().unwrap().get_trace();
```

### Deterministic Execution

Execute in deterministic mode for reproducible results.

```rust
use jvmrs::deterministic::DeterministicConfig;

let config = DeterministicConfig {
    fixed_seed: 42,
    fixed_time: 0,
    ..Default::default()
};
interpreter.set_deterministic_config(Some(config));
```

---

## Error Handling

### JvmError

All JVMRS operations return `Result<T, JvmError>`.

```rust
pub enum JvmError {
    ClassNotFound(String),
    MethodNotFound(String, String),
    FieldNotFound(String, String),
    RuntimeError(RuntimeError),
    NativeError(NativeError),
    IoError(std::io::Error),
    // ... more variants
}
```

### Handling Errors

```rust
match interpreter.run_main("com/example/Missing") {
    Ok(_) => println!("Success"),
    Err(JvmError::ClassNotFound(name)) => {
        eprintln!("Class not found: {}", name);
    }
    Err(JvmError::MethodNotFound(class, method)) => {
        eprintln!("Method not found: {}.{}", class, method);
    }
    Err(e) => eprintln!("Error: {:?}", e),
}
```

---

## Best Practices

### 1. Error Handling

Always handle errors explicitly:

```rust
// Good
match interpreter.invoke_method(...) {
    Ok(result) => /* ... */,
    Err(e) => /* handle error */,
}

// Avoid
interpreter.invoke_method(...).unwrap();
```

### 2. Resource Management

Use RAII for automatic cleanup:

```rust
{
    let interpreter = Interpreter::new();
    // Use interpreter...
} // Automatically cleaned up
```

### 3. Type Safety

Use proper type conversions:

```rust
// Good
let value = interpreter.invoke_method(...)?;
if let Value::Int(i) = value {
    println!("Result: {}", i);
}

// Avoid
let i = unsafe { /* dangerous conversion */ };
```

### 4. Performance

- Enable JIT for long-running applications
- Use inline caching (default: enabled)
- Monitor GC and adjust heap sizes
- Profile hot paths and optimize

---

## Examples

### Complete Example

```rust
use jvmrs::{Interpreter, Value};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create interpreter
    let mut interpreter = Interpreter::new();
    
    // Load and run a Java class
    interpreter.run_main("com/example/App")?;
    
    // Create objects
    let list = interpreter.new_instance("java/util/ArrayList")?;
    
    // Add elements
    for i in 0..10 {
        interpreter.invoke_method(
            list,
            "add",
            &[Value::Int(i)]
        )?;
    }
    
    // Get size
    let size = interpreter.invoke_method(list, "size", &[])?;
    println!("List size: {}", size.as_int());
    
    Ok(())
}
```

---

## See Also

- [Architecture Documentation]ARCHITECTURE.md
- [Performance Tuning Guide]docs/performance-tuning.md
- [Polyglot Programming Guide]docs/polyglot-programming.md
- [Competitive Differentiation]docs/competitive-differentiation.md