# 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)