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
//! Custom error types for JVMRS

use std::fmt;
use std::sync::Arc;

/// Main error type for JVM operations
#[derive(Debug, Clone)]
pub enum JvmError {
    /// Class file parsing errors
    ParseError(ParseError),
    /// Runtime execution errors
    RuntimeError(RuntimeError),
    /// Memory management errors
    MemoryError(MemoryError),
    /// Class loading errors
    ClassLoadingError(ClassLoadingError),
    /// Native method errors
    NativeError(NativeError),
}

impl fmt::Display for JvmError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            JvmError::ParseError(e) => write!(f, "Parse error: {}", e),
            JvmError::RuntimeError(e) => write!(f, "Runtime error: {}", e),
            JvmError::MemoryError(e) => write!(f, "Memory error: {}", e),
            JvmError::ClassLoadingError(e) => write!(f, "Class loading error: {}", e),
            JvmError::NativeError(e) => write!(f, "Native error: {}", e),
        }
    }
}

impl std::error::Error for JvmError {}

impl From<String> for JvmError {
    fn from(err: String) -> Self {
        JvmError::RuntimeError(RuntimeError::Unimplemented(err))
    }
}

impl From<&str> for JvmError {
    fn from(err: &str) -> Self {
        JvmError::RuntimeError(RuntimeError::Unimplemented(err.to_string()))
    }
}

impl From<RuntimeError> for JvmError {
    fn from(err: RuntimeError) -> Self {
        JvmError::RuntimeError(err)
    }
}

impl From<MemoryError> for JvmError {
    fn from(err: MemoryError) -> Self {
        JvmError::MemoryError(err)
    }
}

impl From<ClassLoadingError> for JvmError {
    fn from(err: ClassLoadingError) -> Self {
        JvmError::ClassLoadingError(err)
    }
}

impl From<ParseError> for JvmError {
    fn from(err: ParseError) -> Self {
        JvmError::ParseError(err)
    }
}

impl From<NativeError> for JvmError {
    fn from(err: NativeError) -> Self {
        JvmError::NativeError(err)
    }
}

/// Class file parsing errors
#[derive(Debug, Clone)]
pub enum ParseError {
    /// Invalid magic number (not 0xCAFEBABE)
    InvalidMagic(u32),
    /// Unsupported class file version
    UnsupportedVersion(u16, u16),
    /// Invalid constant pool tag
    InvalidConstantPoolTag(u8),
    /// Invalid attribute length
    InvalidAttributeLength,
    /// Invalid UTF-8 string in constant pool
    InvalidUtf8String,
    /// Invalid method descriptor
    InvalidMethodDescriptor(String),
    /// Invalid field descriptor
    InvalidFieldDescriptor(String),
    /// Invalid opcode
    InvalidOpcode(u8),
    /// Invalid bytecode
    InvalidBytecode(String),
    /// IO error
    IoError(Arc<dyn std::error::Error>),
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseError::InvalidMagic(magic) => write!(
                f,
                "Invalid magic number: 0x{:08X} (expected 0xCAFEBABE)",
                magic
            ),
            ParseError::UnsupportedVersion(major, minor) => {
                write!(f, "Unsupported class file version: {}.{}", major, minor)
            }
            ParseError::InvalidConstantPoolTag(tag) => {
                write!(f, "Invalid constant pool tag: {}", tag)
            }
            ParseError::InvalidAttributeLength => write!(f, "Invalid attribute length"),
            ParseError::InvalidUtf8String => write!(f, "Invalid UTF-8 string in constant pool"),
            ParseError::InvalidMethodDescriptor(desc) => {
                write!(f, "Invalid method descriptor: {}", desc)
            }
            ParseError::InvalidFieldDescriptor(desc) => {
                write!(f, "Invalid field descriptor: {}", desc)
            }
            ParseError::InvalidOpcode(opcode) => write!(f, "Invalid opcode: 0x{:02X}", opcode),
            ParseError::InvalidBytecode(msg) => write!(f, "Invalid bytecode: {}", msg),
            ParseError::IoError(e) => write!(f, "IO error: {}", e),
        }
    }
}

impl From<std::io::Error> for ParseError {
    fn from(err: std::io::Error) -> Self {
        ParseError::IoError(Arc::new(err))
    }
}

/// Runtime execution errors
#[derive(Debug, Clone)]
pub enum RuntimeError {
    /// Stack underflow (pop from empty stack)
    StackUnderflow,
    /// Stack overflow (push to full stack)
    StackOverflow,
    /// Local variable index out of bounds
    LocalVariableOutOfBounds(usize),
    /// Array index out of bounds
    ArrayIndexOutOfBounds(usize, usize),
    /// Null pointer exception
    NullPointerException,
    /// Division by zero
    DivisionByZero,
    /// Class not found
    ClassNotFound(String),
    /// Method not found
    MethodNotFound(String, String),
    /// Field not found
    FieldNotFound(String, String),
    /// Invalid type conversion
    InvalidTypeConversion(String, String),
    /// Unsupported operation
    UnsupportedOperation(String),
    /// Arithmetic overflow
    ArithmeticOverflow,
    /// Invalid object reference
    InvalidReference(u32),
    /// Invalid array type
    InvalidArrayType(String),
    /// Invalid array length
    InvalidArrayLength(usize),
    /// Invalid monitor state
    InvalidMonitorState,
    /// Illegal monitor state
    IllegalMonitorState,
    /// Illegal argument
    IllegalArgument(String),
    /// Illegal state
    IllegalState(String),
    /// Unimplemented feature
    Unimplemented(String),
    /// Invalid opcode
    InvalidOpcode(u8),
    /// Exception thrown
    ExceptionThrown(String),
    /// Class cast exception
    ClassCastException(String, String),
    /// Array store exception
    ArrayStoreException,
    /// Negative array size exception
    NegativeArraySizeException(i32),
    /// Illegal access exception
    IllegalAccessException(String),
    /// Instantiation exception
    InstantiationException(String),
    /// String index out of bounds
    StringIndexOutOfBounds(usize, usize),
}

impl fmt::Display for RuntimeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RuntimeError::StackUnderflow => write!(f, "Stack underflow"),
            RuntimeError::StackOverflow => write!(f, "Stack overflow"),
            RuntimeError::LocalVariableOutOfBounds(index) => {
                write!(f, "Local variable index {} out of bounds", index)
            }
            RuntimeError::ArrayIndexOutOfBounds(index, length) => write!(
                f,
                "Array index {} out of bounds (length: {})",
                index, length
            ),
            RuntimeError::NullPointerException => write!(f, "Null pointer exception"),
            RuntimeError::DivisionByZero => write!(f, "Division by zero"),
            RuntimeError::ClassNotFound(name) => write!(f, "Class not found: {}", name),
            RuntimeError::MethodNotFound(class, method) => {
                write!(f, "Method {} not found in class {}", method, class)
            }
            RuntimeError::FieldNotFound(class, field) => {
                write!(f, "Field {} not found in class {}", field, class)
            }
            RuntimeError::InvalidTypeConversion(from, to) => {
                write!(f, "Invalid type conversion from {} to {}", from, to)
            }
            RuntimeError::UnsupportedOperation(op) => write!(f, "Unsupported operation: {}", op),
            RuntimeError::ArithmeticOverflow => write!(f, "Arithmetic overflow"),
            RuntimeError::InvalidReference(addr) => write!(f, "Invalid object reference: {}", addr),
            RuntimeError::InvalidArrayType(ty) => write!(f, "Invalid array type: {}", ty),
            RuntimeError::InvalidArrayLength(len) => write!(f, "Invalid array length: {}", len),
            RuntimeError::InvalidMonitorState => write!(f, "Invalid monitor state"),
            RuntimeError::IllegalMonitorState => write!(f, "Illegal monitor state"),
            RuntimeError::IllegalArgument(msg) => write!(f, "Illegal argument: {}", msg),
            RuntimeError::IllegalState(msg) => write!(f, "Illegal state: {}", msg),
            RuntimeError::Unimplemented(feature) => write!(f, "Unimplemented feature: {}", feature),
            RuntimeError::InvalidOpcode(opcode) => write!(f, "Invalid opcode: 0x{:02X}", opcode),
            RuntimeError::ExceptionThrown(msg) => write!(f, "Exception thrown: {}", msg),
            RuntimeError::ClassCastException(from, to) => write!(
                f,
                "Class cast exception: cannot cast from {} to {}",
                from, to
            ),
            RuntimeError::ArrayStoreException => write!(f, "Array store exception"),
            RuntimeError::NegativeArraySizeException(size) => {
                write!(f, "Negative array size exception: {}", size)
            }
            RuntimeError::IllegalAccessException(msg) => {
                write!(f, "Illegal access exception: {}", msg)
            }
            RuntimeError::InstantiationException(msg) => {
                write!(f, "Instantiation exception: {}", msg)
            }
            RuntimeError::StringIndexOutOfBounds(index, length) => write!(
                f,
                "String index {} out of bounds (length: {})",
                index, length
            ),
        }
    }
}

/// Memory management errors
#[derive(Debug, Clone)]
pub enum MemoryError {
    /// Out of memory
    OutOfMemory,
    /// Invalid heap address
    InvalidHeapAddress(u32),
    /// Invalid object reference
    InvalidReference(u32),
    /// Invalid monitor state
    InvalidMonitorState,
    /// Illegal monitor state
    IllegalMonitorState,
    /// Heap corruption detected
    HeapCorruption,
    /// Garbage collection failed
    GcError(String),
    /// Memory limit exceeded
    MemoryLimitExceeded(usize),
    /// Invalid object header
    InvalidObjectHeader,
    /// Invalid array header
    InvalidArrayHeader,
    /// Memory allocation failed
    AllocationFailed(String),
    /// Invalid array length
    InvalidArrayLength(usize),
    /// Invalid array type
    InvalidArrayType(String),
    /// Array index out of bounds
    ArrayIndexOutOfBounds(usize, usize), // index, length
    /// Invalid array operation
    InvalidArrayOperation(String),
    /// Compressed oops overflow (handle too large for compressed encoding)
    CompressedOopsOverflow(u32),
}

impl fmt::Display for MemoryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MemoryError::OutOfMemory => write!(f, "Out of memory"),
            MemoryError::InvalidHeapAddress(addr) => write!(f, "Invalid heap address: {}", addr),
            MemoryError::InvalidReference(addr) => write!(f, "Invalid object reference: {}", addr),
            MemoryError::InvalidMonitorState => write!(f, "Invalid monitor state"),
            MemoryError::IllegalMonitorState => write!(f, "Illegal monitor state"),
            MemoryError::HeapCorruption => write!(f, "Heap corruption detected"),
            MemoryError::GcError(msg) => write!(f, "Garbage collection error: {}", msg),
            MemoryError::MemoryLimitExceeded(limit) => {
                write!(f, "Memory limit exceeded: {} bytes", limit)
            }
            MemoryError::InvalidObjectHeader => write!(f, "Invalid object header"),
            MemoryError::InvalidArrayHeader => write!(f, "Invalid array header"),
            MemoryError::AllocationFailed(msg) => write!(f, "Memory allocation failed: {}", msg),
            MemoryError::InvalidArrayLength(len) => write!(f, "Invalid array length: {}", len),
            MemoryError::InvalidArrayType(ty) => write!(f, "Invalid array type: {}", ty),
            MemoryError::ArrayIndexOutOfBounds(index, length) => write!(
                f,
                "Array index {} out of bounds (length: {})",
                index, length
            ),
            MemoryError::InvalidArrayOperation(msg) => {
                write!(f, "Invalid array operation: {}", msg)
            }
            MemoryError::CompressedOopsOverflow(addr) => write!(
                f,
                "Compressed oops overflow: handle {} does not fit in 16-bit compressed space",
                addr
            ),
        }
    }
}

impl From<MemoryError> for RuntimeError {
    fn from(err: MemoryError) -> Self {
        match err {
            MemoryError::InvalidMonitorState => RuntimeError::InvalidMonitorState,
            MemoryError::IllegalMonitorState => RuntimeError::IllegalMonitorState,
            MemoryError::InvalidReference(addr) => RuntimeError::InvalidReference(addr),
            _ => RuntimeError::Unimplemented(err.to_string()),
        }
    }
}

/// Class loading errors
#[derive(Debug, Clone)]
pub enum ClassLoadingError {
    /// Class file not found
    ClassFileNotFound(String),
    /// Class format error
    ClassFormatError(String),
    /// Class circularity error
    ClassCircularityError(String),
    /// No class definition found
    NoClassDefFound(String),
    /// Unsupported class version
    UnsupportedClassVersion(String, u16, u16),
    /// Class verification failed
    VerificationFailed(String),
    /// Linkage error
    LinkageError(String),
    /// Illegal access error
    IllegalAccessError(String),
    /// Instantiation error
    InstantiationError(String),
    /// Class loader constraint violation
    ClassLoaderConstraintViolation(String),
}

impl fmt::Display for ClassLoadingError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ClassLoadingError::ClassFileNotFound(name) => {
                write!(f, "Class file not found: {}", name)
            }
            ClassLoadingError::ClassFormatError(msg) => write!(f, "Class format error: {}", msg),
            ClassLoadingError::ClassCircularityError(name) => {
                write!(f, "Class circularity error: {}", name)
            }
            ClassLoadingError::NoClassDefFound(name) => {
                write!(f, "No class definition found: {}", name)
            }
            ClassLoadingError::UnsupportedClassVersion(name, major, minor) => write!(
                f,
                "Unsupported class version for {}: {}.{}",
                name, major, minor
            ),
            ClassLoadingError::VerificationFailed(msg) => {
                write!(f, "Class verification failed: {}", msg)
            }
            ClassLoadingError::LinkageError(msg) => write!(f, "Linkage error: {}", msg),
            ClassLoadingError::IllegalAccessError(msg) => {
                write!(f, "Illegal access error: {}", msg)
            }
            ClassLoadingError::InstantiationError(msg) => write!(f, "Instantiation error: {}", msg),
            ClassLoadingError::ClassLoaderConstraintViolation(msg) => {
                write!(f, "Class loader constraint violation: {}", msg)
            }
        }
    }
}

/// Native method errors
#[derive(Debug, Clone)]
pub enum NativeError {
    /// Native method not found
    NativeMethodNotFound(String, String),
    /// Native method failed
    NativeMethodFailed(String, String),
    /// Native library not found
    NativeLibraryNotFound(String),
    /// Native library load failed
    NativeLibraryLoadFailed(String),
    /// Unsatisfied link error
    UnsatisfiedLinkError(String),
    /// Native method signature mismatch
    NativeMethodSignatureMismatch(String),
}

impl fmt::Display for NativeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NativeError::NativeMethodNotFound(class, method) => {
                write!(f, "Native method {}.{} not found", class, method)
            }
            NativeError::NativeMethodFailed(class, method) => {
                write!(f, "Native method {}.{} failed", class, method)
            }
            NativeError::NativeLibraryNotFound(lib) => {
                write!(f, "Native library not found: {}", lib)
            }
            NativeError::NativeLibraryLoadFailed(lib) => {
                write!(f, "Native library load failed: {}", lib)
            }
            NativeError::UnsatisfiedLinkError(msg) => write!(f, "Unsatisfied link error: {}", msg),
            NativeError::NativeMethodSignatureMismatch(msg) => {
                write!(f, "Native method signature mismatch: {}", msg)
            }
        }
    }
}

/// Result type for JVM operations
pub type JvmResult<T> = Result<T, JvmError>;

/// Convenience result type for interpreter operations
pub type InterpreterResult = Result<(), JvmError>;

/// Convenience result type for class file operations
pub type ClassFileResult<T> = Result<T, JvmError>;

/// Convenience result type for memory operations
pub type MemoryResult<T> = Result<T, JvmError>;

/// Helper to convert string errors to JvmError
pub fn to_runtime_error<T: ToString>(msg: T) -> JvmError {
    JvmError::RuntimeError(RuntimeError::Unimplemented(msg.to_string()))
}

/// Helper to convert parse errors
pub fn to_parse_error<T: Into<ParseError>>(err: T) -> JvmError {
    JvmError::ParseError(err.into())
}

/// Helper to convert runtime errors
pub fn to_runtime_error_enum<T: Into<RuntimeError>>(err: T) -> JvmError {
    JvmError::RuntimeError(err.into())
}

/// Helper to convert memory errors
pub fn to_memory_error<T: Into<MemoryError>>(err: T) -> JvmError {
    JvmError::MemoryError(err.into())
}

/// Helper to convert class loading errors
pub fn to_class_loading_error<T: Into<ClassLoadingError>>(err: T) -> JvmError {
    JvmError::ClassLoadingError(err.into())
}

/// Generic trait for converting error types to JvmError
pub trait ToJvmError<T> {
    /// Convert this error type to JvmError
    fn to_jvm_error(self) -> JvmError;
}

/// Implement for ParseError
impl ToJvmError<ParseError> for ParseError {
    fn to_jvm_error(self) -> JvmError {
        JvmError::ParseError(self)
    }
}

/// Implement for RuntimeError
impl ToJvmError<RuntimeError> for RuntimeError {
    fn to_jvm_error(self) -> JvmError {
        JvmError::RuntimeError(self)
    }
}

/// Implement for MemoryError
impl ToJvmError<MemoryError> for MemoryError {
    fn to_jvm_error(self) -> JvmError {
        JvmError::MemoryError(self)
    }
}

/// Implement for ClassLoadingError
impl ToJvmError<ClassLoadingError> for ClassLoadingError {
    fn to_jvm_error(self) -> JvmError {
        JvmError::ClassLoadingError(self)
    }
}

/// Implement for String
impl ToJvmError<String> for String {
    fn to_jvm_error(self) -> JvmError {
        JvmError::RuntimeError(RuntimeError::Unimplemented(self))
    }
}

/// Implement for &str
impl ToJvmError<&str> for &str {
    fn to_jvm_error(self) -> JvmError {
        JvmError::RuntimeError(RuntimeError::Unimplemented(self.to_string()))
    }
}

/// Convenience macro for converting results with JvmError
#[macro_export]
macro_rules! convert_result {
    ($expr:expr) => {
        $expr.map_err(|e| e.to_jvm_error())
    };
}