use fusevm::{NumOp, Value, VM};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
pub const JPRINTLN: u16 = 700;
pub const JPRINT: u16 = 701;
pub const DBG_LINE: u16 = 702;
pub const JFFI_COMPILE: u16 = 703;
pub const JFFI_CALL: u16 = 704;
pub const JSTR_DISPATCH: u16 = 705;
pub const JEPRINTLN: u16 = 706;
pub const JEPRINT: u16 = 707;
pub const JSTATIC_DISPATCH: u16 = 708;
pub const JARRAY_NEW: u16 = 709;
pub const JARRAY_LIT: u16 = 710;
pub const JARRAY_GET: u16 = 711;
pub const JARRAY_SET: u16 = 712;
pub const JNEW: u16 = 713;
pub const JFIELD_GET: u16 = 714;
pub const JFIELD_SET: u16 = 715;
pub const JINSTANCEOF: u16 = 716;
pub const JCLASSOF: u16 = 717;
pub const JARRAY_NEW_MULTI: u16 = 718;
pub const JDIV: u16 = 719;
pub const JIDIV: u16 = 745;
pub const JSB_NEW: u16 = 746;
pub const JTHROW: u16 = 720;
pub const JEXC_PENDING: u16 = 721;
pub const JEXC_TAKE: u16 = 722;
pub const JEXC_DEPTH: u16 = 723;
pub const JEXC_CUT: u16 = 724;
pub const JEXC_ABORT: u16 = 725;
pub const JFAULT: u16 = 726;
pub const JARGV: u16 = 727;
pub const JMAKE_CLOSURE: u16 = 728;
pub const JCLOSURE_CALL: u16 = 729;
pub const LAMBDA_CLASS: &str = "#lambda";
pub const JCOLL_NEW: u16 = 730;
pub const JCOLL_DISPATCH: u16 = 731;
pub const JITER_ARRAY: u16 = 732;
pub const JUSHR: u16 = 733;
pub const JCAST: u16 = 734;
pub const JCHR_STR: u16 = 735;
pub const JCHECKCAST: u16 = 736;
pub const JF32: u16 = 737;
pub const JF32_STR: u16 = 738;
pub const JF32_ARITH: u16 = 739;
pub const JF32_ROUND: u16 = 743;
pub const JBINARY_CLASS: u16 = 744;
pub const JBOX: u16 = 747;
pub const JNEW_STRING: u16 = 749;
pub const JUNBOX: u16 = 748;
pub const JCOMPARE_TO: u16 = 740;
pub const JFORMAT: u16 = 741;
pub const JSTRINGIFY: u16 = 742;
pub mod width {
pub const INT: i64 = 0;
pub const LONG: i64 = 1;
pub const FLOAT: i64 = 2;
pub const DOUBLE: i64 = 3;
}
pub mod f32_op {
pub const ADD: i64 = 0;
pub const SUB: i64 = 1;
pub const MUL: i64 = 2;
pub const DIV: i64 = 3;
pub const REM: i64 = 4;
}
enum HostObj {
Array(Vec<Value>),
Instance {
class: String,
fields: HashMap<String, Value>,
},
Closure {
name_idx: u16,
params: u8,
captures: Vec<Value>,
},
List {
items: Vec<Value>,
fixed: Fixity,
mods: u64,
},
SubList {
parent: u32,
offset: usize,
len: usize,
exp_mods: u64,
},
Map {
entries: Vec<(Value, Value)>,
order: Order,
fixed: Fixity,
index: KeyIndex,
},
Set {
items: Vec<Value>,
order: Order,
fixed: Fixity,
index: KeyIndex,
},
Builder {
s: String,
len: usize,
cap: usize,
buffer: bool,
},
Iterator {
source: u32,
pos: usize,
last: Option<usize>,
exp_mods: u64,
},
Optional {
class: &'static str,
value: Option<Value>,
},
Stream {
source: Vec<Value>,
stages: Vec<Stage>,
kind: StreamKind,
},
Collector {
kind: &'static str,
args: Vec<Value>,
},
Boxed,
}
#[derive(Clone)]
enum Stage {
Filter(Value),
Map(Value),
FlatMap(Value),
Peek(Value),
Limit(i64),
Skip(i64),
Distinct,
Sorted(Option<Value>),
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum StreamKind {
Ref,
Int,
Long,
Double,
}
impl StreamKind {
fn optional_class(self) -> &'static str {
match self {
StreamKind::Ref => "Optional",
StreamKind::Int => "OptionalInt",
StreamKind::Long => "OptionalLong",
StreamKind::Double => "OptionalDouble",
}
}
}
pub const BOX_CLASSES: [&str; 7] = [
"Integer",
"Long",
"Short",
"Byte",
"Character",
"Float",
"Double",
];
pub fn box_class_code(name: &str) -> Option<i64> {
BOX_CLASSES
.iter()
.position(|c| *c == name)
.map(|i| i as i64)
}
#[derive(PartialEq, Eq, Hash)]
enum IndexKey {
Int(i64),
Str(String),
Bool(bool),
Obj(u32),
Null,
}
const EXACT_INT_FLOAT: f64 = 9_007_199_254_740_992.0;
fn index_key(v: &Value) -> Option<IndexKey> {
Some(match v {
Value::Int(n) => IndexKey::Int(*n),
Value::Str(s) => IndexKey::Str(s.as_str().to_string()),
Value::Bool(b) => IndexKey::Bool(*b),
Value::Obj(id) => match unboxed(v) {
Some(inner) => return index_key(&inner),
None => IndexKey::Obj(*id),
},
Value::Undef => IndexKey::Null,
Value::Float(f) => {
let f = *f;
if f.fract() != 0.0 || f.abs() >= EXACT_INT_FLOAT {
return None;
}
IndexKey::Int(f as i64)
}
_ => return None,
})
}
struct KeyIndex {
by_key: HashMap<IndexKey, Vec<usize>>,
unindexed: usize,
dirty: bool,
}
impl Default for KeyIndex {
fn default() -> Self {
KeyIndex {
by_key: HashMap::new(),
unindexed: 0,
dirty: true,
}
}
}
impl KeyIndex {
fn push(&mut self, k: &Value, at: usize) {
match index_key(k) {
Some(key) => self.by_key.entry(key).or_default().push(at),
None => self.unindexed += 1,
}
}
fn invalidate(&mut self) {
self.dirty = true;
}
fn rebuild<'a>(&mut self, keys: impl Iterator<Item = &'a Value>) {
self.by_key.clear();
self.unindexed = 0;
self.dirty = false;
for (i, k) in keys.enumerate() {
self.push(k, i);
}
}
fn find<T>(
&self,
items: &[T],
key_of: impl Fn(&T) -> &Value,
q: &Value,
) -> Option<Option<usize>> {
if self.dirty || self.unindexed > 0 {
return None;
}
let key = index_key(q)?;
Some(self.by_key.get(&key).and_then(|cands| {
cands
.iter()
.copied()
.find(|&i| items.get(i).is_some_and(|it| value_eq(key_of(it), q)))
}))
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Order {
Hash,
Insertion,
Sorted,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Fixity {
Mutable,
FixedSize,
Immutable,
}
thread_local! {
static HEAP: RefCell<Vec<HostObj>> = const { RefCell::new(Vec::new()) };
static SUPERS: RefCell<HashMap<String, Vec<String>>> = RefCell::new(HashMap::new());
static BINARY: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
static PENDING: RefCell<Option<Value>> = const { RefCell::new(None) };
static EXC_ENABLED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static ARGV: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
static BOX_CACHE: RefCell<HashMap<(usize, i64), u32>> = RefCell::new(HashMap::new());
static INTERNED: RefCell<HashMap<String, Value>> = RefCell::new(HashMap::new());
static BOXES: RefCell<Vec<Option<(&'static str, Value)>>> = const { RefCell::new(Vec::new()) };
}
fn box_value(code: usize, v: Value) -> Value {
let class = BOX_CLASSES[code];
let cached = match class {
"Integer" | "Long" | "Short" | "Byte" => match &v {
Value::Int(n) if (-128..=127).contains(n) => Some(*n),
_ => None,
},
"Character" => match &v {
Value::Int(n) if (0..=127).contains(n) => Some(*n),
_ => None,
},
_ => None,
};
let Some(key) = cached else {
return Value::Obj(alloc_box(class, v));
};
if let Some(id) = BOX_CACHE.with(|c| c.borrow().get(&(code, key)).copied()) {
return Value::Obj(id);
}
let id = alloc_box(class, v);
BOX_CACHE.with(|c| c.borrow_mut().insert((code, key), id));
Value::Obj(id)
}
fn alloc_box(class: &'static str, v: Value) -> u32 {
let id = heap_alloc(HostObj::Boxed);
BOXES.with(|b| {
let mut b = b.borrow_mut();
b.resize(id as usize + 1, None);
b[id as usize] = Some((class, v));
});
id
}
fn unboxed(v: &Value) -> Option<Value> {
let Value::Obj(id) = v else {
return None;
};
BOXES.with(|b| {
b.borrow()
.get(*id as usize)?
.as_ref()
.map(|(_, v)| v.clone())
})
}
fn box_class(v: &Value) -> Option<&'static str> {
let Value::Obj(id) = v else {
return None;
};
BOXES.with(|b| b.borrow().get(*id as usize)?.as_ref().map(|(c, _)| *c))
}
fn deboxed(v: &Value) -> Value {
unboxed(v).unwrap_or_else(|| v.clone())
}
trait JavaNumeric {
fn jint(&self) -> i64;
fn jfloat(&self) -> f64;
}
impl JavaNumeric for Value {
fn jint(&self) -> i64 {
Value::to_int(&deboxed(self))
}
fn jfloat(&self) -> f64 {
Value::to_float(&deboxed(self))
}
}
pub fn intern_literals(chunk: &fusevm::Chunk) {
INTERNED.with(|table| {
let mut table = table.borrow_mut();
for c in &chunk.constants {
if let Value::Str(text) = c {
table
.entry(text.as_str().to_string())
.or_insert_with(|| c.clone());
}
}
});
}
fn intern(v: &Value) -> Value {
let text = java_str(v);
INTERNED.with(|table| {
table
.borrow_mut()
.entry(text)
.or_insert_with(|| v.clone())
.clone()
})
}
pub fn set_argv(argv: Vec<String>) {
ARGV.with(|a| *a.borrow_mut() = argv);
}
pub fn heap_reset() {
HEAP.with(|h| h.borrow_mut().clear());
BOX_CACHE.with(|c| c.borrow_mut().clear());
BOXES.with(|b| b.borrow_mut().clear());
INTERNED.with(|i| i.borrow_mut().clear());
SUPERS.with(|s| s.borrow_mut().clear());
BINARY.with(|b| b.borrow_mut().clear());
PENDING.with(|p| *p.borrow_mut() = None);
EXC_ENABLED.with(|e| e.set(false));
ARGV.with(|a| a.borrow_mut().clear());
USER_TOSTRING.with(|c| c.set(None));
USER_EQUALS.with(|c| c.set(None));
MEMBER_ENTRY.with(|t| t.borrow_mut().clear());
}
pub fn set_exceptions_enabled(on: bool) {
EXC_ENABLED.with(|e| e.set(on));
}
struct Fault {
class: &'static str,
msg: String,
}
impl Fault {
fn java(class: &'static str, msg: impl Into<String>) -> Self {
Fault {
class: class.rsplit('.').next().unwrap_or(class),
msg: msg.into(),
}
}
fn internal(msg: impl Into<String>) -> Self {
Fault {
class: "",
msg: msg.into(),
}
}
}
fn raise(vm: &mut VM, f: Fault) -> Value {
if f.class.is_empty() {
ffi_fault(vm, f.msg);
return Value::Undef;
}
if !EXC_ENABLED.with(|e| e.get()) {
let name =
crate::prelude::qualified_throwable(f.class).unwrap_or_else(|| f.class.to_string());
let detail = if f.msg.is_empty() {
String::new()
} else {
format!(": {}", f.msg)
};
ffi_fault(vm, format!("Exception in thread \"main\" {name}{detail}"));
return Value::Undef;
}
let mut fields = HashMap::new();
let msg = if f.msg.is_empty() {
Value::Undef
} else {
Value::str(f.msg)
};
fields.insert("detailMessage".to_string(), msg);
let id = heap_alloc(HostObj::Instance {
class: f.class.to_string(),
fields,
});
PENDING.with(|p| *p.borrow_mut() = Some(Value::Obj(id)));
Value::Undef
}
pub fn set_supertypes(map: HashMap<String, Vec<String>>) {
SUPERS.with(|s| *s.borrow_mut() = map);
}
pub fn set_binary_names(map: HashMap<String, String>) {
BINARY.with(|b| *b.borrow_mut() = map);
}
fn qualified_or_binary(class: &str) -> String {
if let Some(q) = crate::prelude::qualified_class(class) {
return q;
}
BINARY.with(|b| {
b.borrow()
.get(class)
.cloned()
.unwrap_or_else(|| class.to_string())
})
}
fn heap_alloc(obj: HostObj) -> u32 {
HEAP.with(|h| {
let mut h = h.borrow_mut();
let id = h.len() as u32;
h.push(obj);
id
})
}
fn jdk_supers(class: &str) -> &'static [&'static str] {
match class {
"String" => &["CharSequence", "Comparable", "Serializable"],
"Integer" | "Double" | "Long" | "Short" | "Byte" | "Float" => &["Number", "Comparable"],
"Number" => &["Serializable"],
"Boolean" | "Character" => &["Comparable", "Serializable"],
"Enum" => &["Comparable", "Serializable"],
"StringBuilder" | "StringBuffer" => {
&["AbstractStringBuilder", "Comparable", "Serializable"]
}
"AbstractStringBuilder" => &["CharSequence", "Appendable"],
"Throwable" => &["Serializable"],
"List" => &["Collection", "SequencedCollection"],
"Set" => &["Collection"],
"SequencedCollection" => &["Collection"],
"SequencedSet" => &["Set", "SequencedCollection"],
"Collection" => &["Iterable"],
"SortedSet" => &["SequencedSet"],
"NavigableSet" => &["SortedSet"],
"SequencedMap" => &["Map"],
"SortedMap" => &["SequencedMap"],
"NavigableMap" => &["SortedMap"],
"AbstractCollection" => &["Collection"],
"AbstractList" => &["AbstractCollection", "List"],
"AbstractSet" => &["AbstractCollection", "Set"],
"AbstractMap" => &["Map"],
"ArrayList" => &["AbstractList", "RandomAccess", "Cloneable", "Serializable"],
"HashMap" => &["AbstractMap", "Cloneable", "Serializable"],
"LinkedHashMap" => &["HashMap", "SequencedMap"],
"TreeMap" => &["AbstractMap", "NavigableMap", "Cloneable", "Serializable"],
"HashSet" => &["AbstractSet", "Cloneable", "Serializable"],
"LinkedHashSet" => &["HashSet", "SequencedSet"],
"TreeSet" => &["AbstractSet", "NavigableSet", "Cloneable", "Serializable"],
"[]" => &["Cloneable", "Serializable"],
"List$immutable" => &["AbstractCollection", "List", "RandomAccess", "Serializable"],
"Set$immutable" => &["AbstractCollection", "Set", "Serializable"],
"Iterator$of" => &["Iterator"],
"Optional" | "OptionalInt" | "OptionalLong" | "OptionalDouble" => &["Serializable"],
"Stream$of" => &["BaseStream"],
"Collector$of" => &["Collector"],
"Map$immutable" => &["AbstractMap", "Map", "Serializable"],
"List$fixed" => &["AbstractList", "RandomAccess", "Serializable"],
"List$sub" => &["AbstractList", "RandomAccess"],
_ => &[],
}
}
fn is_subclass_of(class: &str, target: &str) -> bool {
if class == target {
return true;
}
SUPERS.with(|s| {
let s = s.borrow();
let mut stack = vec![class.to_string()];
let mut seen = std::collections::HashSet::new();
while let Some(cur) = stack.pop() {
if cur == target {
return true;
}
if !seen.insert(cur.clone()) {
continue;
}
if let Some(sups) = s.get(&cur) {
stack.extend(sups.iter().cloned());
}
stack.extend(jdk_supers(&cur).iter().map(|t| t.to_string()));
}
false
})
}
thread_local! {
static FFI_ERROR: RefCell<Option<String>> = const { RefCell::new(None) };
}
pub fn take_ffi_error() -> Option<String> {
FFI_ERROR.with(|e| e.borrow_mut().take())
}
fn ffi_fault(vm: &mut VM, msg: impl Into<String>) {
FFI_ERROR.with(|e| *e.borrow_mut() = Some(msg.into()));
vm.request_halt();
}
pub fn install(vm: &mut VM) {
vm.register_builtin(JPRINTLN, b_println);
vm.register_builtin(JPRINT, b_print);
vm.register_builtin(JEPRINTLN, b_eprintln);
vm.register_builtin(JEPRINT, b_eprint);
vm.register_builtin(JFFI_COMPILE, b_ffi_compile);
vm.register_builtin(JFFI_CALL, b_ffi_call);
vm.register_builtin(JSTR_DISPATCH, b_str_dispatch);
vm.register_builtin(JSTATIC_DISPATCH, b_static_dispatch);
vm.register_builtin(JARRAY_NEW, b_array_new);
vm.register_builtin(JARRAY_NEW_MULTI, b_array_new_multi);
vm.register_builtin(JARRAY_LIT, b_array_lit);
vm.register_builtin(JARRAY_GET, b_array_get);
vm.register_builtin(JARRAY_SET, b_array_set);
vm.register_builtin(JNEW, b_new);
vm.register_builtin(JFIELD_GET, b_field_get);
vm.register_builtin(JFIELD_SET, b_field_set);
vm.register_builtin(JINSTANCEOF, b_instanceof);
vm.register_builtin(JCLASSOF, b_classof);
vm.register_builtin(JDIV, b_div);
vm.register_builtin(JIDIV, b_idiv);
vm.register_builtin(JUSHR, b_ushr);
vm.register_builtin(JCAST, b_cast);
vm.register_builtin(JCHR_STR, b_chr_str);
vm.register_builtin(JCHECKCAST, b_checkcast);
vm.register_builtin(JF32, b_f32);
vm.register_builtin(JF32_STR, b_f32_str);
vm.register_builtin(JF32_ARITH, b_f32_arith);
vm.register_builtin(JF32_ROUND, b_f32_round);
vm.register_builtin(JBINARY_CLASS, b_binary_class);
vm.register_builtin(JBOX, b_box);
vm.register_builtin(JUNBOX, b_unbox);
vm.register_builtin(JNEW_STRING, b_new_string);
vm.register_builtin(JCOMPARE_TO, b_compare_to);
vm.register_builtin(JFORMAT, b_format);
vm.register_builtin(JSTRINGIFY, b_stringify);
vm.register_builtin(JTHROW, b_throw);
vm.register_builtin(JEXC_PENDING, b_exc_pending);
vm.register_builtin(JEXC_TAKE, b_exc_take);
vm.register_builtin(JEXC_DEPTH, b_exc_depth);
vm.register_builtin(JEXC_CUT, b_exc_cut);
vm.register_builtin(JEXC_ABORT, b_exc_abort);
vm.register_builtin(JFAULT, b_fault);
vm.register_builtin(JARGV, b_argv);
vm.register_builtin(JMAKE_CLOSURE, b_make_closure);
vm.register_builtin(JCLOSURE_CALL, b_closure_call);
vm.register_builtin(JCOLL_NEW, b_coll_new);
vm.register_builtin(JSB_NEW, b_sb_new);
vm.register_builtin(JCOLL_DISPATCH, b_coll_dispatch);
vm.register_builtin(JITER_ARRAY, b_iter_array);
}
fn b_argv(vm: &mut VM, argc: u8) -> Value {
pop_args(vm, argc);
let elems = ARGV.with(|a| a.borrow().iter().cloned().map(Value::str).collect());
Value::Obj(heap_alloc(HostObj::Array(elems)))
}
fn b_fault(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let class = args
.first()
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default();
let msg = args
.get(1)
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default();
match crate::prelude::THROWABLES.iter().find(|(n, _)| *n == class) {
Some((n, _)) => raise(vm, Fault::java(n, msg)),
None => raise(
vm,
Fault::internal(format!("javars: unknown fault `{class}`")),
),
}
}
fn b_throw(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let exc = args.into_iter().next().unwrap_or(Value::Undef);
PENDING.with(|p| *p.borrow_mut() = Some(exc));
Value::Undef
}
fn b_exc_pending(vm: &mut VM, argc: u8) -> Value {
pop_args(vm, argc);
Value::bool(PENDING.with(|p| p.borrow().is_some()))
}
fn b_exc_take(vm: &mut VM, argc: u8) -> Value {
pop_args(vm, argc);
PENDING
.with(|p| p.borrow_mut().take())
.unwrap_or(Value::Undef)
}
fn b_exc_depth(vm: &mut VM, argc: u8) -> Value {
pop_args(vm, argc);
Value::Int(vm.stack.len() as i64)
}
fn b_exc_cut(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let depth = args.first().map(|v| v.jint()).unwrap_or(0).max(0) as usize;
if depth <= vm.stack.len() {
vm.stack.truncate(depth);
}
Value::Undef
}
fn b_exc_abort(vm: &mut VM, argc: u8) -> Value {
pop_args(vm, argc);
let exc = PENDING
.with(|p| p.borrow_mut().take())
.unwrap_or(Value::Undef);
let msg = format!("Exception in thread \"main\" {}", throwable_str(&exc));
ffi_fault(vm, msg);
Value::Undef
}
fn throwable_str(v: &Value) -> String {
let Value::Obj(id) = v else {
return java_str(v);
};
HEAP.with(|h| {
let h = h.borrow();
match h.get(*id as usize) {
Some(HostObj::Instance { class, fields }) => {
let name = qualified_or_binary(class);
match fields.get("detailMessage") {
Some(m) if !matches!(m, Value::Undef) => format!("{name}: {}", java_str(m)),
_ => name,
}
}
_ => java_str(v),
}
})
}
fn b_classof(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
match args.first() {
Some(Value::Obj(id)) => HEAP.with(|h| {
let h = h.borrow();
match h.get(*id as usize) {
Some(HostObj::Instance { class, .. }) => Value::str(class.clone()),
Some(HostObj::Closure { .. }) => Value::str(LAMBDA_CLASS),
_ => Value::str(""),
}
}),
_ => Value::str(""),
}
}
fn b_box(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let code = args
.get(1)
.map(as_i64)
.unwrap_or(0)
.clamp(0, BOX_CLASSES.len() as i64 - 1) as usize;
let v = args.first().cloned().unwrap_or(Value::Undef);
if matches!(v, Value::Undef) {
return v;
}
box_value(code, v)
}
fn b_new_string(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
Value::str(args.first().map(java_str).unwrap_or_default())
}
fn b_unbox(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let v = args.first().cloned().unwrap_or(Value::Undef);
deboxed(&v)
}
fn ref_eq(a: &Value, b: &Value) -> bool {
matches!((a, b), (Value::Obj(x), Value::Obj(y)) if x == y)
}
fn b_binary_class(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let array_type = args.get(1).map(|h| h.as_str_cow().into_owned());
let Some(v) = args.first() else {
return Value::str("");
};
if matches!(value_class(v).as_deref(), Some("[]")) {
return Value::str(
array_type
.as_deref()
.and_then(array_descriptor)
.unwrap_or_default(),
);
}
match value_class(v) {
Some(class) if class == LAMBDA_CLASS => Value::str(class),
Some(class) => Value::str(binary_name(&class, v).unwrap_or(class)),
None => Value::str(""),
}
}
fn array_descriptor(ty: &str) -> Option<String> {
let component = ty.strip_suffix("[]")?;
if let Some(inner) = array_descriptor(component) {
return Some(format!("[{inner}"));
}
Some(format!(
"[{}",
match component {
"int" => "I".to_string(),
"long" => "J".to_string(),
"short" => "S".to_string(),
"byte" => "B".to_string(),
"char" => "C".to_string(),
"double" => "D".to_string(),
"float" => "F".to_string(),
"boolean" => "Z".to_string(),
other => format!("L{};", jdk_name(other)),
}
))
}
fn simple_class_name(binary: &str) -> String {
if let Some(component) = binary.strip_prefix('[') {
let elem = descriptor_primitive(component)
.map(str::to_string)
.unwrap_or_else(|| simple_class_name(component));
return format!("{elem}[]");
}
if let Some(reference) = binary.strip_prefix('L').and_then(|r| r.strip_suffix(';')) {
return simple_class_name(reference);
}
let after_package = binary.rsplit('.').next().unwrap_or(binary);
after_package
.rsplit('$')
.next()
.unwrap_or(after_package)
.to_string()
}
fn descriptor_primitive(d: &str) -> Option<&'static str> {
Some(match d {
"I" => "int",
"J" => "long",
"S" => "short",
"B" => "byte",
"C" => "char",
"D" => "double",
"F" => "float",
"Z" => "boolean",
_ => return None,
})
}
fn b_make_closure(vm: &mut VM, _argc: u8) -> Value {
let ncap = vm.stack.pop().unwrap_or(Value::Undef).jint() as usize;
let params = vm.stack.pop().unwrap_or(Value::Undef).jint() as u8;
let name_idx = vm.stack.pop().unwrap_or(Value::Undef).jint() as u16;
let mut captures = Vec::with_capacity(ncap);
for _ in 0..ncap {
captures.push(vm.stack.pop().unwrap_or(Value::Undef));
}
captures.reverse();
Value::Obj(heap_alloc(HostObj::Closure {
name_idx,
params,
captures,
}))
}
fn closure_meta(v: &Value) -> Option<(u16, u8, Vec<Value>)> {
let Value::Obj(id) = v else {
return None;
};
HEAP.with(|h| {
let h = h.borrow();
match h.get(*id as usize) {
Some(HostObj::Closure {
name_idx,
params,
captures,
}) => Some((*name_idx, *params, captures.clone())),
_ => None,
}
})
}
fn b_closure_call(vm: &mut VM, argc: u8) -> Value {
let n = argc.saturating_sub(1) as usize;
let mut args = Vec::with_capacity(n);
for _ in 0..n {
args.push(vm.stack.pop().unwrap_or(Value::Undef));
}
args.reverse();
let clo = vm.stack.pop().unwrap_or(Value::Undef);
if PENDING.with(|p| p.borrow().is_some()) {
return Value::Undef;
}
let Some((name_idx, params, captures)) = closure_meta(&clo) else {
return raise(
vm,
Fault::java(
"NullPointerException",
"Cannot invoke a functional interface method because the target is null"
.to_string(),
),
);
};
let Some(entry) = vm.chunk.find_sub(name_idx) else {
return raise(vm, Fault::internal("javars: lambda body not found"));
};
let stack_base = vm.stack.len();
for i in 0..params as usize {
vm.stack.push(args.get(i).cloned().unwrap_or(Value::Undef));
}
for cap in captures {
vm.stack.push(cap);
}
run_sub(vm, entry, stack_base)
}
fn java_hash(v: &Value) -> Option<i32> {
if let Some(inner) = unboxed(v) {
return java_hash(&inner);
}
Some(match v {
Value::Str(s) => s
.chars()
.fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(c as i32)),
Value::Int(n) => {
if *n >= i32::MIN as i64 && *n <= i32::MAX as i64 {
*n as i32
} else {
(*n ^ ((*n as u64) >> 32) as i64) as i32
}
}
Value::Float(f) => {
let bits = canonical_bits(*f);
(bits ^ ((bits as u64) >> 32) as i64) as i32
}
Value::Bool(b) => {
if *b {
1231
} else {
1237
}
}
_ => return None,
})
}
fn element_hash(v: &Value) -> i32 {
match java_hash(v) {
Some(h) => h,
None => match v {
Value::Obj(id) => *id as i32,
_ => 0,
},
}
}
fn iterator_method(recv: &Value, method: &str, argc: usize) -> Option<Result<Value, Fault>> {
let Value::Obj(id) = recv else {
return None;
};
let state = HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Iterator {
source,
pos,
last,
exp_mods,
}) => Some((*source, *pos, *last, *exp_mods)),
_ => None,
})?;
let (source, pos, last, exp_mods) = state;
let items = sequence_items(&Value::Obj(source)).unwrap_or_default();
Some(match (method, argc) {
("hasNext", 0) => Ok(Value::bool(pos < items.len())),
("next", 0) => {
if iter_mods(source) != exp_mods {
return Some(Err(comodification()));
}
match items.get(pos) {
Some(v) => {
let v = v.clone();
HEAP.with(|h| {
if let Some(HostObj::Iterator { pos, last, .. }) =
h.borrow_mut().get_mut(*id as usize)
{
*last = Some(*pos);
*pos += 1;
}
});
Ok(v)
}
None => Err(Fault::java("NoSuchElementException", String::new())),
}
}
("remove", 0) => {
let Some(at) = last else {
return Some(Err(Fault::java("IllegalStateException", String::new())));
};
if iter_mods(source) != exp_mods {
return Some(Err(comodification()));
}
let removed = HEAP.with(|h| {
let mut heap = h.borrow_mut();
match heap.get_mut(source as usize) {
Some(HostObj::List { items, mods, .. }) if at < items.len() => {
items.remove(at);
*mods += 1;
Some(*mods)
}
Some(HostObj::Set { items, index, .. }) if at < items.len() => {
items.remove(at);
index.invalidate();
Some(0)
}
_ => None,
}
});
match removed {
Some(mods) => {
HEAP.with(|h| {
if let Some(HostObj::Iterator {
pos,
last,
exp_mods,
..
}) = h.borrow_mut().get_mut(*id as usize)
{
*pos = at;
*last = None;
*exp_mods = mods;
}
});
Ok(Value::Undef)
}
None => Err(Fault::java("IllegalStateException", String::new())),
}
}
_ => Err(Fault::internal(format!(
"javars: unsupported Iterator method `{method}` with {argc} argument(s)"
))),
})
}
fn list_hash(items: &[Value]) -> i64 {
items.iter().fold(1i32, |acc, e| {
acc.wrapping_mul(31).wrapping_add(element_hash(e))
}) as i64
}
fn set_hash(items: &[Value]) -> i64 {
items
.iter()
.fold(0i32, |acc, e| acc.wrapping_add(element_hash(e))) as i64
}
fn map_hash(entries: &[(Value, Value)]) -> i64 {
entries.iter().fold(0i32, |acc, (k, v)| {
acc.wrapping_add(element_hash(k) ^ element_hash(v))
}) as i64
}
fn hash_order(keys: &[Value]) -> Vec<usize> {
let n = keys.len();
let mut cap = 16usize;
while n > cap * 3 / 4 {
cap *= 2;
}
let mut idx: Vec<usize> = (0..n).collect();
idx.sort_by_key(|&i| {
let h = java_hash(&keys[i]).unwrap_or(0) as u32;
((cap as u32 - 1) & (h ^ (h >> 16))) as usize
});
idx
}
fn present_order(items: &[Value], order: Order) -> Vec<usize> {
match order {
Order::Insertion => (0..items.len()).collect(),
Order::Hash => hash_order(items),
Order::Sorted => {
let mut idx: Vec<usize> = (0..items.len()).collect();
idx.sort_by(|&a, &b| natural_cmp(&items[a], &items[b]));
idx
}
}
}
fn value_eq(a: &Value, b: &Value) -> bool {
match (box_class(a), box_class(b)) {
(Some(x), Some(y)) if x != y => return false,
(Some(_), _) | (_, Some(_)) => return value_eq(&deboxed(a), &deboxed(b)),
_ => {}
}
match (a, b) {
(Value::Str(x), Value::Str(y)) => x == y,
(Value::Obj(x), Value::Obj(y)) => x == y,
(Value::Undef, Value::Undef) => true,
(Value::Bool(x), Value::Bool(y)) => x == y,
(Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) => {
match (a, b) {
(Value::Int(x), Value::Int(y)) => x == y,
(Value::Float(_), Value::Float(_)) => float_compare(a.jfloat(), b.jfloat()) == 0,
_ => a.jfloat() == b.jfloat(),
}
}
_ => false,
}
}
fn eq_call(vm: &mut VM, q: &Value, other: &Value) -> bool {
match user_equals(vm, q) {
Some((id, entry)) => run_equals(vm, entry, id, other),
None => value_eq(q, other),
}
}
fn objects_equals(vm: &mut VM, a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Undef, Value::Undef) => true,
(Value::Undef, _) => false,
_ => eq_call(vm, a, b),
}
}
fn user_equals(vm: &VM, v: &Value) -> Option<(u32, usize)> {
let Value::Obj(id) = v else {
return None;
};
if !any_user_equals(vm) {
return None;
}
let class = instance_class(v)?;
Some((*id, equals_entry(vm, &class)?))
}
fn user_element_hash(vm: &mut VM, v: &Value) -> Option<i32> {
let Value::Obj(id) = v else {
return None;
};
let class = instance_class(v)?;
let entry = member_entry(vm, &class, HASHCODE_SUFFIX)?;
if PENDING.with(|p| p.borrow().is_some()) {
return None;
}
let stack_base = vm.stack.len();
vm.stack.push(Value::Obj(*id));
match run_sub(vm, entry, stack_base) {
Value::Int(h) => Some(h as i32),
_ => None,
}
}
fn collection_hash(vm: &mut VM, recv: &Value, method: &str, argc: usize) -> Option<Value> {
if method != "hashCode" || argc != 0 {
return None;
}
let each = |vm: &mut VM, e: &Value| user_element_hash(vm, e).unwrap_or_else(|| element_hash(e));
if let Some(entries) = map_entries(recv) {
let mut h = 0i32;
for (k, v) in &entries {
let (kh, vh) = (each(vm, k), each(vm, v));
h = h.wrapping_add(kh ^ vh);
}
return Some(Value::Int(h.into()));
}
let items = sequence_items(recv)?;
let is_set = value_class(recv).is_some_and(|c| c.contains("Set"));
let mut h = if is_set { 0i32 } else { 1i32 };
for e in &items {
let eh = each(vm, e);
h = if is_set {
h.wrapping_add(eh)
} else {
h.wrapping_mul(31).wrapping_add(eh)
};
}
Some(Value::Int(h.into()))
}
fn run_equals(vm: &mut VM, entry: usize, id: u32, other: &Value) -> bool {
if PENDING.with(|p| p.borrow().is_some()) {
return false;
}
let stack_base = vm.stack.len();
vm.stack.push(Value::Obj(id));
vm.stack.push(other.clone());
matches!(run_sub(vm, entry, stack_base), Value::Bool(true))
}
enum EqPlan {
Index(Option<usize>),
Same(bool),
Fresh(Vec<Value>),
}
fn eq_index(eq: Option<&EqPlan>, items: &[Value], q: &Value, from_end: bool) -> Option<usize> {
match eq {
Some(EqPlan::Index(at)) => *at,
_ if from_end => items.iter().rposition(|x| value_eq(x, q)),
_ => items.iter().position(|x| value_eq(x, q)),
}
}
fn eq_elements(recv: &Value) -> Option<Vec<Value>> {
let Value::Obj(id) = recv else {
return None;
};
if let Some(window) = sublist_items(*id as usize) {
return window.ok();
}
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::List { items, .. }) | Some(HostObj::Set { items, .. }) => Some(items.clone()),
Some(HostObj::Map { entries, .. }) => {
Some(entries.iter().map(|(k, _)| k.clone()).collect())
}
_ => None,
})
}
fn eq_map_values(recv: &Value) -> Option<Vec<Value>> {
let Value::Obj(id) = recv else {
return None;
};
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Map { entries, .. }) => {
Some(entries.iter().map(|(_, v)| v.clone()).collect())
}
_ => None,
})
}
enum EqShape {
List,
Set(Order),
Map(Order),
}
fn eq_shape(recv: &Value) -> Option<EqShape> {
let Value::Obj(id) = recv else {
return None;
};
if is_sublist(*id as usize) {
return Some(EqShape::List);
}
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::List { .. }) => Some(EqShape::List),
Some(HostObj::Set { order, .. }) => Some(EqShape::Set(*order)),
Some(HostObj::Map { order, .. }) => Some(EqShape::Map(*order)),
_ => None,
})
}
fn hash_consistent(vm: &VM, class: &str) -> bool {
member_entry(vm, class, HASHCODE_SUFFIX).is_some()
|| is_subclass_of(class, "Record")
|| is_subclass_of(class, "Enum")
}
fn is_hashed(order: Order) -> bool {
matches!(order, Order::Hash | Order::Insertion)
}
fn eq_plan(
vm: &mut VM,
recv: &Value,
method: &str,
args: &[Value],
arg_seqs: &[Option<Vec<Value>>],
) -> Option<EqPlan> {
if !any_user_equals(vm) {
return None;
}
let shape = eq_shape(recv)?;
if method == "equals" && args.len() == 1 && matches!(shape, EqShape::List) {
let mine = eq_elements(recv)?;
let other = arg_seqs.first()?.clone()?;
if !mine.iter().any(|v| user_equals(vm, v).is_some()) {
return None;
}
if mine.len() != other.len() {
return Some(EqPlan::Same(false));
}
let mut same = true;
for (a, b) in mine.iter().zip(&other) {
if !eq_call(vm, a, b) {
same = false;
break;
}
}
return Some(EqPlan::Same(same));
}
if method == "addAll" && args.len() == 1 && matches!(shape, EqShape::Set(o) if is_hashed(o)) {
let mut items = eq_elements(recv)?;
let add = arg_seqs.first()?.clone()?;
if !add.iter().any(|v| trusted_equals(vm, v, true)) {
return None;
}
let mut fresh = Vec::new();
for v in add {
let mut seen = false;
for x in &items {
if eq_call(vm, &v, x) {
seen = true;
break;
}
}
if !seen {
items.push(v.clone());
fresh.push(v);
}
}
return Some(EqPlan::Fresh(fresh));
}
let (by_value, hashed) = match shape {
EqShape::List => (
matches!(
(method, args.len()),
("contains", 1) | ("indexOf", 1) | ("lastIndexOf", 1) | ("removeObject", 1)
),
false,
),
EqShape::Set(order) => (
matches!(
(method, args.len()),
("contains", 1) | ("add", 1) | ("remove", 1)
) && is_hashed(order),
true,
),
EqShape::Map(order) => (
matches!(
(method, args.len()),
("get", 1)
| ("getOrDefault", 2)
| ("containsKey", 1)
| ("containsValue", 1)
| ("remove", 1)
| ("put", 2)
| ("putIfAbsent", 2)
) && is_hashed(order),
true,
),
};
if !by_value {
return None;
}
let q = args.first()?;
if !trusted_equals(vm, q, hashed) {
return None;
}
let against = if method == "containsValue" {
eq_map_values(recv)?
} else {
eq_elements(recv)?
};
let at = if method == "lastIndexOf" {
(0..against.len())
.rev()
.find(|i| eq_call(vm, q, &against[*i]))
} else {
(0..against.len()).find(|i| eq_call(vm, q, &against[*i]))
};
Some(EqPlan::Index(at))
}
fn trusted_equals(vm: &VM, v: &Value, hashed: bool) -> bool {
if user_equals(vm, v).is_none() {
return false;
}
!hashed || instance_class(v).is_some_and(|c| hash_consistent(vm, &c))
}
fn natural_cmp(a: &Value, b: &Value) -> std::cmp::Ordering {
use std::cmp::Ordering;
let (a, b) = (&deboxed(a), &deboxed(b));
match (a, b) {
(Value::Str(x), Value::Str(y)) => x.cmp(y),
(Value::Undef, Value::Undef) => Ordering::Equal,
(Value::Undef, _) => Ordering::Less,
(_, Value::Undef) => Ordering::Greater,
(Value::Int(x), Value::Int(y)) => x.cmp(y),
(Value::Bool(x), Value::Bool(y)) => x.cmp(y),
_ => float_compare(a.jfloat(), b.jfloat()).cmp(&0),
}
}
fn new_collection(vm: &mut VM, kind: &str, seed: &Value) -> Result<Value, Fault> {
let obj = match kind {
"ArrayList" | "LinkedList" | "List" => HostObj::List {
mods: 0,
items: sequence_items(seed).unwrap_or_default(),
fixed: Fixity::Mutable,
},
"HashMap" | "Map" => HostObj::Map {
fixed: Fixity::Mutable,
entries: map_entries(seed).unwrap_or_default(),
order: Order::Hash,
index: KeyIndex::default(),
},
"LinkedHashMap" => HostObj::Map {
fixed: Fixity::Mutable,
entries: map_entries(seed).unwrap_or_default(),
order: Order::Insertion,
index: KeyIndex::default(),
},
"TreeMap" => HostObj::Map {
fixed: Fixity::Mutable,
entries: map_entries(seed).unwrap_or_default(),
order: Order::Sorted,
index: KeyIndex::default(),
},
"HashSet" | "Set" => HostObj::Set {
items: distinct(vm, &sequence_items(seed).unwrap_or_default()),
order: Order::Hash,
fixed: Fixity::Mutable,
index: KeyIndex::default(),
},
"LinkedHashSet" => HostObj::Set {
items: distinct(vm, &sequence_items(seed).unwrap_or_default()),
order: Order::Insertion,
fixed: Fixity::Mutable,
index: KeyIndex::default(),
},
"TreeSet" => HostObj::Set {
items: distinct(vm, &sequence_items(seed).unwrap_or_default()),
order: Order::Sorted,
fixed: Fixity::Mutable,
index: KeyIndex::default(),
},
other => {
return Err(Fault::internal(format!(
"javars: `{other}` is not a collection javars models"
)))
}
};
Ok(Value::Obj(heap_alloc(obj)))
}
fn distinct(vm: &mut VM, vals: &[Value]) -> Vec<Value> {
let mut out: Vec<Value> = Vec::with_capacity(vals.len());
for v in vals {
let mut seen = false;
for x in &out {
let equal = if trusted_equals(vm, v, true) {
eq_call(vm, v, x)
} else {
value_eq(v, x)
};
if equal {
seen = true;
break;
}
}
if !seen {
out.push(v.clone());
}
}
out
}
fn first_repeat(vm: &mut VM, vals: &[Value]) -> Option<Value> {
for (i, v) in vals.iter().enumerate() {
for x in &vals[..i] {
let equal = if trusted_equals(vm, v, true) {
eq_call(vm, v, x)
} else {
value_eq(v, x)
};
if equal {
return Some(v.clone());
}
}
}
None
}
fn sequence_items(v: &Value) -> Option<Vec<Value>> {
let Value::Obj(id) = v else {
return None;
};
if let Some(items) = sublist_items(*id as usize) {
return items.ok();
}
HEAP.with(|h| {
let h = h.borrow();
match h.get(*id as usize) {
Some(HostObj::Array(items)) | Some(HostObj::List { items, .. }) => Some(items.clone()),
Some(HostObj::Set { items, order, .. }) => Some(
present_order(items, *order)
.into_iter()
.map(|i| items[i].clone())
.collect(),
),
_ => None,
}
})
}
fn sublist_items(id: usize) -> Option<Result<Vec<Value>, Fault>> {
if !is_sublist(id) {
return None;
}
Some(checked_window(id).and_then(|(root, offset, len)| {
HEAP.with(|h| match h.borrow().get(root) {
Some(HostObj::List { items, .. }) => Ok(items[offset..offset + len].to_vec()),
_ => Err(Fault::internal("javars: dangling subList backing")),
})
}))
}
fn map_entries(v: &Value) -> Option<Vec<(Value, Value)>> {
let Value::Obj(id) = v else {
return None;
};
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Map { entries, .. }) => Some(entries.clone()),
_ => None,
})
}
fn is_collection(v: &Value) -> bool {
let Value::Obj(id) = v else {
return false;
};
HEAP.with(|h| {
matches!(
h.borrow().get(*id as usize),
Some(
HostObj::List { .. }
| HostObj::Map { .. }
| HostObj::Set { .. }
| HostObj::SubList { .. }
)
)
})
}
pub const SB_DEFAULT_CAP: usize = 16;
fn sb_index_fault(i: i64, len: usize) -> Fault {
Fault::java(
"StringIndexOutOfBoundsException",
format!("Index {i} out of bounds for length {len}"),
)
}
fn sb_range_fault(start: i64, end: i64, len: usize) -> Fault {
Fault::java(
"StringIndexOutOfBoundsException",
format!("Range [{start}, {end}) out of bounds for length {len}"),
)
}
fn sb_char_offset(s: &str, i: i64, len: usize) -> Result<usize, Fault> {
if i < 0 || i as usize >= len {
return Err(sb_index_fault(i, len));
}
Ok(sb_byte_of(s, len, i as usize))
}
fn sb_byte_of(s: &str, len: usize, n: usize) -> usize {
if s.len() == len {
return n.min(s.len());
}
s.char_indices().nth(n).map(|(b, _)| b).unwrap_or(s.len())
}
fn sb_range(s: &str, start: i64, end: i64, len: usize) -> Result<(usize, usize), Fault> {
if start < 0 || start > end || end as usize > len {
return Err(sb_range_fault(start, end, len));
}
Ok((
sb_byte_of(s, len, start as usize),
sb_byte_of(s, len, end as usize),
))
}
fn sb_grow(cap: usize, min: usize) -> usize {
if min <= cap {
cap
} else {
(cap * 2 + 2).max(min)
}
}
fn sb_arg_str(vm: &mut VM, v: &Value) -> String {
match array_items(v) {
Some(items) => items.iter().map(|e| java_str_vm(vm, e)).collect(),
None => java_str_vm(vm, v),
}
}
fn builder_method(
vm: &mut VM,
id: u32,
method: &str,
args: &[Value],
) -> Option<Result<Value, Fault>> {
let rendered: Vec<String> = args.iter().map(|a| sb_arg_str(vm, a)).collect();
Some(HEAP.with(|h| {
let mut heap = h.borrow_mut();
let Some(HostObj::Builder {
s, len: count, cap, ..
}) = heap.get_mut(id as usize)
else {
return Err(Fault::internal("javars: dangling StringBuilder handle"));
};
let len = *count;
let this = Value::Obj(id);
match (method, args.len()) {
("toString", 0) | ("substring", 0) => Ok(Value::str(s.clone())),
("length", 0) => Ok(Value::Int(len as i64)),
("isEmpty", 0) => Ok(Value::bool(s.is_empty())),
("capacity", 0) => Ok(Value::Int(*cap as i64)),
("ensureCapacity", 1) => {
let want = args[0].jint();
if want > 0 {
*cap = sb_grow(*cap, want as usize);
}
Ok(Value::Undef)
}
("trimToSize", 0) => {
*cap = len;
Ok(Value::Undef)
}
("append", 1) => {
s.push_str(&rendered[0]);
*count = len + rendered[0].chars().count();
*cap = sb_grow(*cap, *count);
Ok(this)
}
("appendChars", 1) => {
if matches!(args[0], Value::Undef) {
return Err(Fault::java(
"NullPointerException",
"Cannot read the array length because \"str\" is null",
));
}
s.push_str(&rendered[0]);
*count = len + rendered[0].chars().count();
*cap = sb_grow(*cap, *count);
Ok(this)
}
("appendChars", 3) => {
let chars: Vec<char> = rendered[0].chars().collect();
let (off, n) = (args[1].jint(), args[2].jint());
if off < 0 || n < 0 || off + n > chars.len() as i64 {
return Err(Fault::java(
"IndexOutOfBoundsException",
format!("offset {off}, count {n}, length {}", chars.len()),
));
}
let text: String = chars[off as usize..(off + n) as usize].iter().collect();
s.push_str(&text);
*count = len + n as usize;
*cap = sb_grow(*cap, *count);
Ok(this)
}
("appendCodePoint", 1) => {
let cp = args[0].jint();
match u32::try_from(cp).ok().and_then(char::from_u32) {
Some(c) => {
s.push(c);
*count = len + 1;
*cap = sb_grow(*cap, *count);
Ok(this)
}
None => Err(Fault::java(
"IllegalArgumentException",
format!("Not a valid Unicode code point: 0x{cp:X}"),
)),
}
}
("repeat", 2) => {
let n = args[1].jint().max(0) as usize;
s.push_str(&rendered[0].repeat(n));
*count = len + rendered[0].chars().count() * n;
*cap = sb_grow(*cap, *count);
Ok(this)
}
("charAt", 1) => {
let at = sb_char_offset(s, args[0].jint(), len)?;
Ok(Value::Int(s[at..].chars().next().map_or(0, |c| c as i64)))
}
("setCharAt", 2) => {
let at = sb_char_offset(s, args[0].jint(), len)?;
let old = s[at..].chars().next().map_or(0, char::len_utf8);
s.replace_range(at..at + old, &rendered[1]);
*count = len - 1 + rendered[1].chars().count();
Ok(Value::Undef)
}
("deleteCharAt", 1) => {
let at = sb_char_offset(s, args[0].jint(), len)?;
let old = s[at..].chars().next().map_or(0, char::len_utf8);
s.replace_range(at..at + old, "");
*count = len - 1;
Ok(this)
}
("delete", 2) => {
let start = args[0].jint();
let end = args[1].jint().min(len as i64);
let (a, b) = sb_range(s, start, end, len)?;
s.replace_range(a..b, "");
*count = len - (end - start) as usize;
Ok(this)
}
("replace", 3) => {
let start = args[0].jint();
let end = args[1].jint().min(len as i64);
let (a, b) = sb_range(s, start, end, len)?;
s.replace_range(a..b, &rendered[2]);
*count = len - (end - start) as usize + rendered[2].chars().count();
*cap = sb_grow(*cap, *count);
Ok(this)
}
("substring", 1) => {
let (a, b) = sb_range(s, args[0].jint(), len as i64, len)?;
Ok(Value::str(s[a..b].to_string()))
}
("substring", 2) | ("subSequence", 2) => {
let (a, b) = sb_range(s, args[0].jint(), args[1].jint(), len)?;
Ok(Value::str(s[a..b].to_string()))
}
("insert", 2) => {
let at = args[0].jint();
if at < 0 || at as usize > len {
return Err(sb_range_fault(at, len as i64, len));
}
s.insert_str(sb_byte_of(s, len, at as usize), &rendered[1]);
*count = len + rendered[1].chars().count();
*cap = sb_grow(*cap, *count);
Ok(this)
}
("reverse", 0) => {
*s = s.chars().rev().collect();
Ok(this)
}
("setLength", 1) => {
let n = args[0].jint();
if n < 0 {
return Err(Fault::java(
"StringIndexOutOfBoundsException",
format!("String index out of range: {n}"),
));
}
let n = n as usize;
if n < len {
s.truncate(sb_byte_of(s, len, n));
} else {
s.extend(std::iter::repeat('\0').take(n - len));
}
*count = n;
*cap = sb_grow(*cap, n);
Ok(Value::Undef)
}
("indexOf", 1) => Ok(Value::Int(char_index_of(s, &rendered[0]))),
("indexOf", 2) => {
let from = args[1].jint().clamp(0, len as i64) as usize;
let byte = sb_byte_of(s, len, from);
Ok(Value::Int(match char_index_of(&s[byte..], &rendered[0]) {
-1 => -1,
i => i + from as i64,
}))
}
("lastIndexOf", 1) => Ok(Value::Int(char_last_index_of(s, &rendered[0], len as i64))),
("lastIndexOf", 2) => Ok(Value::Int(char_last_index_of(
s,
&rendered[0],
args[1].jint(),
))),
("compareTo", 1) => Ok(Value::Int(compare_strings(s, &rendered[0], false))),
("chars", 0) | ("codePoints", 0) => Err(Fault::internal(format!(
"javars: unsupported StringBuilder method `{method}` with 0 argument(s)"
))),
_ => Err(Fault::internal(format!(
"javars: unsupported StringBuilder method `{method}` with {} argument(s)",
args.len()
))),
}
}))
}
fn is_builder(v: &Value) -> Option<u32> {
let Value::Obj(id) = v else { return None };
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Builder { .. }) => Some(*id),
_ => None,
})
}
fn b_sb_new(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let buffer = args
.first()
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default()
== "StringBuffer";
let seed = args.get(1).cloned().unwrap_or(Value::Undef);
let (s, cap) = match &seed {
Value::Undef => {
return raise(
vm,
Fault::java(
"NullPointerException",
"Cannot invoke \"String.length()\" because \"str\" is null",
),
)
}
Value::Int(n) => {
if *n < 0 {
return raise(vm, Fault::java("NegativeArraySizeException", n.to_string()));
}
(String::new(), *n as usize)
}
other => {
let text = java_str_vm(vm, other);
let n = text.chars().count();
(text, n + SB_DEFAULT_CAP)
}
};
let len = s.chars().count();
Value::Obj(heap_alloc(HostObj::Builder {
s,
len,
cap,
buffer,
}))
}
fn b_coll_new(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let kind = args
.first()
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default();
let seed = args.get(1).cloned().unwrap_or(Value::Undef);
match new_collection(vm, &kind, &seed) {
Ok(v) => v,
Err(f) => raise(vm, f),
}
}
fn b_iter_array(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let it = args.into_iter().next().unwrap_or(Value::Undef);
if let Value::Obj(id) = it {
if HEAP.with(|h| matches!(h.borrow().get(id as usize), Some(HostObj::Array(_)))) {
return it;
}
}
match sequence_items(&it) {
Some(items) => Value::Obj(heap_alloc(HostObj::Array(items))),
None if matches!(it, Value::Undef) => raise(
vm,
Fault::java(
"NullPointerException",
"Cannot iterate over a null reference".to_string(),
),
),
None => raise(
vm,
Fault::internal("javars: the enhanced `for` needs an array or a collection"),
),
}
}
fn run_sub(vm: &mut VM, entry: usize, stack_base: usize) -> Value {
let return_ip = vm.chunk.ops.len();
vm.frames.push(fusevm::Frame {
return_ip,
stack_base,
slots: Vec::new(),
entry_ip: Some(entry),
});
let saved_ip = vm.ip;
vm.ip = entry;
let result = vm.run();
vm.ip = saved_ip;
match result {
fusevm::VMResult::Ok(v) => v,
fusevm::VMResult::Halted => vm.stack.pop().unwrap_or(Value::Undef),
fusevm::VMResult::Error(e) => {
ffi_fault(vm, format!("javars: {e}"));
Value::Undef
}
}
}
fn pop_args(vm: &mut VM, argc: u8) -> Vec<Value> {
let mut v = Vec::with_capacity(argc as usize);
for _ in 0..argc {
v.push(vm.stack.pop().unwrap_or(Value::Undef));
}
v.reverse();
v
}
fn pop_fixed<const N: usize>(vm: &mut VM, argc: u8) -> [Value; N] {
let mut out = std::array::from_fn(|_| Value::Undef);
for _ in N..argc as usize {
let _ = vm.stack.pop();
}
for slot in out.iter_mut().take(N.min(argc as usize)).rev() {
*slot = vm.stack.pop().unwrap_or(Value::Undef);
}
out
}
fn b_array_new(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let size = args.first().map(|v| v.jint()).unwrap_or(0);
let default = args.get(1).cloned().unwrap_or(Value::Undef);
if size < 0 {
return raise(
vm,
Fault::java("NegativeArraySizeException", size.to_string()),
);
}
let arr = vec![default; size as usize];
Value::Obj(heap_alloc(HostObj::Array(arr)))
}
fn b_array_new_multi(vm: &mut VM, argc: u8) -> Value {
let mut args = pop_args(vm, argc);
let default = args.pop().unwrap_or(Value::Undef);
let sizes: Vec<i64> = args.iter().map(|v| v.jint()).collect();
if let Some(&n) = sizes.iter().find(|&&s| s < 0) {
return raise(vm, Fault::java("NegativeArraySizeException", n.to_string()));
}
match build_nested(&sizes, &default) {
Some(v) => v,
None => raise(
vm,
Fault::internal("javars: multi-dimensional array needs a size"),
),
}
}
fn build_nested(sizes: &[i64], default: &Value) -> Option<Value> {
let (&head, rest) = sizes.split_first()?;
let n = head.max(0) as usize;
let elems: Vec<Value> = if rest.is_empty() {
vec![default.clone(); n]
} else {
(0..n)
.map(|_| build_nested(rest, default).unwrap_or(Value::Undef))
.collect()
};
Some(Value::Obj(heap_alloc(HostObj::Array(elems))))
}
fn b_array_lit(vm: &mut VM, argc: u8) -> Value {
let elems = pop_args(vm, argc);
Value::Obj(heap_alloc(HostObj::Array(elems)))
}
fn b_array_get(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let arr = args.first().cloned().unwrap_or(Value::Undef);
let idx = args.get(1).map(|v| v.jint()).unwrap_or(0);
let id = match arr {
Value::Obj(id) => id,
_ => return raise(vm, Fault::java("NullPointerException", NULL_ARRAY_LOAD)),
};
let got = HEAP.with(|h| {
let h = h.borrow();
match h.get(id as usize) {
Some(HostObj::Array(a)) => match usize::try_from(idx).ok().and_then(|i| a.get(i)) {
Some(v) => Ok(v.clone()),
None => Err(index_fault(idx, a.len())),
},
_ => Err(Fault::internal("javars: not an array")),
}
});
match got {
Ok(v) => v,
Err(f) => raise(vm, f),
}
}
fn index_fault(idx: i64, len: usize) -> Fault {
Fault::java(
"ArrayIndexOutOfBoundsException",
format!("Index {idx} out of bounds for length {len}"),
)
}
const NULL_ARRAY_LOAD: &str = "Cannot load from array because the array is null";
const NULL_ARRAY_STORE: &str = "Cannot store to array because the array is null";
const NULL_ARRAY_LENGTH: &str = "Cannot read the array length because the array is null";
fn b_array_set(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let arr = args.first().cloned().unwrap_or(Value::Undef);
let idx = args.get(1).map(|v| v.jint()).unwrap_or(0);
let val = args.get(2).cloned().unwrap_or(Value::Undef);
let id = match arr {
Value::Obj(id) => id,
_ => return raise(vm, Fault::java("NullPointerException", NULL_ARRAY_STORE)),
};
let stored = HEAP.with(|h| {
let mut h = h.borrow_mut();
match h.get_mut(id as usize) {
Some(HostObj::Array(a)) => match usize::try_from(idx).ok().filter(|&i| i < a.len()) {
Some(i) => {
a[i] = val.clone();
Ok(())
}
None => Err(index_fault(idx, a.len())),
},
_ => Err(Fault::internal("javars: not an array")),
}
});
match stored {
Ok(()) => val,
Err(f) => raise(vm, f),
}
}
fn b_new(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let class = args
.first()
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default();
Value::Obj(heap_alloc(HostObj::Instance {
class,
fields: HashMap::new(),
}))
}
fn b_field_get(vm: &mut VM, argc: u8) -> Value {
let [recv, name_v] = pop_fixed::<2>(vm, argc);
let name = name_v.as_str_cow();
let name = name.as_ref();
let id = match recv {
Value::Obj(id) => id,
_ => {
let msg = if name == "length" {
NULL_ARRAY_LENGTH.to_string()
} else {
format!("Cannot read field \"{name}\" because the receiver is null")
};
return raise(vm, Fault::java("NullPointerException", msg));
}
};
let got = HEAP.with(|h| {
let h = h.borrow();
match h.get(id as usize) {
Some(HostObj::Array(a)) if name == "length" => Ok(Value::Int(a.len() as i64)),
Some(HostObj::Instance { fields, .. }) => {
Ok(fields.get(name).cloned().unwrap_or(Value::Undef))
}
_ => Err(Fault::internal(format!("javars: no field `{name}`"))),
}
});
match got {
Ok(v) => v,
Err(f) => raise(vm, f),
}
}
fn b_field_set(vm: &mut VM, argc: u8) -> Value {
let [recv, name_v, val] = pop_fixed::<3>(vm, argc);
let name = name_v.as_str_cow();
let name = name.as_ref();
let id = match recv {
Value::Obj(id) => id,
_ => {
return raise(
vm,
Fault::java(
"NullPointerException",
format!("Cannot assign field \"{name}\" because the receiver is null"),
),
)
}
};
let ok = HEAP.with(|h| {
let mut h = h.borrow_mut();
match h.get_mut(id as usize) {
Some(HostObj::Instance { fields, .. }) => {
match fields.get_mut(name) {
Some(slot) => *slot = val.clone(),
None => {
fields.insert(name.to_string(), val.clone());
}
}
true
}
_ => false,
}
});
if ok {
val
} else {
raise(
vm,
Fault::internal(format!("javars: cannot assign field `{name}`")),
)
}
}
fn b_instanceof(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let obj = args.first().cloned().unwrap_or(Value::Undef);
let target = args
.get(1)
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default();
Value::bool(is_instance_of(&obj, &target))
}
fn value_class(v: &Value) -> Option<String> {
Some(match v {
Value::Str(_) => "String".to_string(),
Value::Int(_) => "Integer".to_string(),
Value::Float(_) => "Double".to_string(),
Value::Bool(_) => "Boolean".to_string(),
Value::Obj(id) => {
return HEAP.with(|h| {
Some(match h.borrow().get(*id as usize)? {
HostObj::Instance { class, .. } => class.clone(),
HostObj::Boxed => box_class(v)?.to_string(),
HostObj::Iterator { .. } => "Iterator$of".to_string(),
HostObj::Optional { class, .. } => (*class).to_string(),
HostObj::Stream { .. } => "Stream$of".to_string(),
HostObj::Collector { .. } => "Collector$of".to_string(),
HostObj::Array(_) => "[]".to_string(),
HostObj::List { fixed, .. } => match fixed {
Fixity::Mutable => "ArrayList".to_string(),
Fixity::FixedSize => "List$fixed".to_string(),
Fixity::Immutable => "List$immutable".to_string(),
},
HostObj::SubList { .. } => "List$sub".to_string(),
HostObj::Map { order, fixed, .. } => match (fixed, order) {
(Fixity::Immutable, _) => "Map$immutable".to_string(),
(_, Order::Hash) => "HashMap".to_string(),
(_, Order::Insertion) => "LinkedHashMap".to_string(),
(_, Order::Sorted) => "TreeMap".to_string(),
},
HostObj::Set { order, fixed, .. } => match (fixed, order) {
(Fixity::Mutable | Fixity::FixedSize, Order::Hash) => "HashSet".to_string(),
(Fixity::Mutable | Fixity::FixedSize, Order::Insertion) => {
"LinkedHashSet".to_string()
}
(Fixity::Mutable | Fixity::FixedSize, Order::Sorted) => {
"TreeSet".to_string()
}
(Fixity::Immutable, _) => "Set$immutable".to_string(),
},
HostObj::Builder { buffer, .. } => if *buffer {
"StringBuffer"
} else {
"StringBuilder"
}
.to_string(),
HostObj::Closure { .. } => return None,
})
});
}
_ => return None,
})
}
fn is_instance_of(v: &Value, target: &str) -> bool {
let Some(class) = value_class(v) else {
return target == "Object" && matches!(v, Value::Obj(_));
};
target == "Object" || is_subclass_of(&class, target)
}
fn b_ffi_compile(vm: &mut VM, argc: u8) -> Value {
let mut body = Value::Undef;
for _ in 0..argc {
body = vm.stack.pop().unwrap_or(Value::Undef);
}
let b64 = body.as_str_cow().into_owned();
if let Err(e) = fusevm::ffi::compile_and_register(&b64) {
ffi_fault(vm, format!("javars: rust {{}} block: {e}"));
}
Value::Undef
}
fn b_ffi_call(vm: &mut VM, argc: u8) -> Value {
let name = vm
.stack
.pop()
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default();
let n = argc.saturating_sub(1) as usize;
let mut args = Vec::with_capacity(n);
for _ in 0..n {
args.push(vm.stack.pop().unwrap_or(Value::Undef));
}
args.reverse();
match fusevm::ffi::try_call(&name, &args) {
Some(Ok(v)) => v,
Some(Err(e)) => {
ffi_fault(vm, format!("javars: rust FFI call {name}: {e}"));
Value::Undef
}
None => {
ffi_fault(vm, format!("javars: unresolved reference: {name}"));
Value::Undef
}
}
}
fn b_coll_dispatch(vm: &mut VM, argc: u8) -> Value {
let method = vm
.stack
.pop()
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default();
let n = argc.saturating_sub(2) as usize;
let mut args = Vec::with_capacity(n);
for _ in 0..n {
args.push(vm.stack.pop().unwrap_or(Value::Undef));
}
args.reverse();
let recv = vm.stack.pop().unwrap_or(Value::Undef);
coll_method(vm, &recv, &method, &args)
}
fn coll_method(vm: &mut VM, recv: &Value, method: &str, args: &[Value]) -> Value {
let Value::Obj(id) = recv else {
return raise(
vm,
Fault::java(
"NullPointerException",
format!("Cannot invoke \"{method}()\" because the receiver is null"),
),
);
};
let id = *id as usize;
if let Some(f) = stale_view(recv) {
return raise(vm, f);
}
if method == "subList" && args.len() == 2 {
return match make_sublist(id, args[0].jint(), args[1].jint()) {
Ok(v) => v,
Err(f) => raise(vm, f),
};
}
match (method, args.len()) {
("sort", 1) => {
let Some(items) = sequence_items(recv) else {
return raise(vm, Fault::internal("javars: `sort` needs a List receiver"));
};
let sorted = match sort_with(vm, items, &args[0]) {
Ok(v) => v,
Err(f) => return raise(vm, f),
};
if let Err(f) = write_sequence(id, sorted, true) {
return raise(vm, f);
}
return Value::Undef;
}
("forEach", 1) => {
if let Some(entries) = map_entries(recv) {
let order = map_order(recv);
let keys: Vec<Value> = entries.iter().map(|(k, _)| k.clone()).collect();
for i in present_order(&keys, order) {
let (k, v) = entries[i].clone();
invoke_closure(vm, &args[0], &[k, v]);
}
} else if let Some(items) = sequence_items(recv) {
for it in items {
invoke_closure(vm, &args[0], &[it]);
}
}
return Value::Undef;
}
_ => {}
}
if method == "toString" && args.is_empty() {
return Value::str(java_str_vm(vm, recv));
}
if let Some(h) = collection_hash(vm, recv, method, args.len()) {
return h;
}
if method == "stream" && args.is_empty() {
if let Some(items) = sequence_items(recv) {
return stream_of(items, StreamKind::Ref);
}
}
if method == "iterator" && args.is_empty() {
if let Value::Obj(id) = recv {
return Value::Obj(heap_alloc(HostObj::Iterator {
source: *id,
pos: 0,
last: None,
exp_mods: iter_mods(*id),
}));
}
}
let arg_seqs: Vec<Option<Vec<Value>>> = args.iter().map(sequence_items).collect();
let arg_entries: Vec<Option<Vec<(Value, Value)>>> = args.iter().map(map_entries).collect();
let eq = eq_plan(vm, recv, method, args, &arg_seqs);
if PENDING.with(|p| p.borrow().is_some()) {
return Value::Undef;
}
let eq = eq.as_ref();
if is_sublist(id) {
return match sublist_method(id, method, args, &arg_seqs, eq) {
Ok(v) => v,
Err(f) => raise(vm, f),
};
}
let result = HEAP.with(|h| {
let mut heap = h.borrow_mut();
let Some(obj) = heap.get_mut(id) else {
return Err(Fault::internal("javars: dangling collection handle"));
};
match obj {
HostObj::List { items, fixed, mods } => {
let before = items.len();
let r = list_method(items, *fixed, method, args, &arg_seqs, eq);
if items.len() != before {
*mods += 1;
}
r
}
HostObj::Map {
entries,
order,
fixed,
index,
} => map_method(
entries,
MapShape {
order: *order,
fixed: *fixed,
},
index,
method,
args,
&arg_entries,
eq,
),
HostObj::Set {
items,
fixed,
index,
..
} => set_method(items, *fixed, index, method, args, &arg_seqs, eq),
_ => Err(Fault::internal(format!(
"javars: `{method}` is not a collection method"
))),
}
});
match result {
Ok(NewColl::Value(v)) => v,
Ok(NewColl::Alloc(obj)) => Value::Obj(heap_alloc(obj)),
Err(f) => raise(vm, f),
}
}
enum NewColl {
Value(Value),
Alloc(HostObj),
}
fn is_sublist(id: usize) -> bool {
HEAP.with(|h| matches!(h.borrow().get(id), Some(HostObj::SubList { .. })))
}
fn stale_view(v: &Value) -> Option<Fault> {
let Value::Obj(id) = v else {
return None;
};
sublist_items(*id as usize)?.err()
}
fn resolve_window(id: usize) -> Option<(usize, usize, usize)> {
HEAP.with(|h| {
let heap = h.borrow();
let Some(HostObj::SubList { len, .. }) = heap.get(id) else {
return None;
};
let len = *len;
let mut offset = 0;
let mut cur = id;
for _ in 0..=heap.len() {
match heap.get(cur) {
Some(HostObj::SubList {
parent, offset: o, ..
}) => {
offset += o;
cur = *parent as usize;
}
Some(HostObj::List { .. }) => return Some((cur, offset, len)),
_ => return None,
}
}
None
})
}
fn list_mods(id: usize) -> Option<u64> {
HEAP.with(|h| match h.borrow().get(id) {
Some(HostObj::List { mods, .. }) => Some(*mods),
_ => None,
})
}
fn optional(v: Option<Value>) -> Value {
optional_of("Optional", v)
}
fn optional_of(class: &'static str, value: Option<Value>) -> Value {
Value::Obj(heap_alloc(HostObj::Optional { class, value }))
}
fn as_optional_full(v: &Value) -> Option<(&'static str, Option<Value>)> {
let Value::Obj(id) = v else {
return None;
};
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Optional { class, value }) => Some((*class, value.clone())),
_ => None,
})
}
fn as_stream(v: &Value) -> Option<(Vec<Value>, Vec<Stage>, StreamKind)> {
let Value::Obj(id) = v else {
return None;
};
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Stream {
source,
stages,
kind,
}) => Some((source.clone(), stages.clone(), *kind)),
_ => None,
})
}
fn stream_of(source: Vec<Value>, kind: StreamKind) -> Value {
Value::Obj(heap_alloc(HostObj::Stream {
source,
stages: Vec::new(),
kind,
}))
}
fn stream_with(recv: &Value, kind: StreamKind, stage: Option<Stage>) -> Option<Value> {
let (source, mut stages, _) = as_stream(recv)?;
if let Some(stage) = stage {
stages.push(stage);
}
Some(Value::Obj(heap_alloc(HostObj::Stream {
source,
stages,
kind,
})))
}
fn stream_push(
vm: &mut VM,
v: Value,
stages: &[Stage],
counters: &mut [i64],
sink: &mut dyn FnMut(&mut VM, Value) -> bool,
) -> bool {
let (Some(stage), rest) = (stages.first(), &stages[stages.len().min(1)..]) else {
return sink(vm, v);
};
let (count, rest_counts) = counters.split_first_mut().expect("one counter per stage");
match stage {
Stage::Filter(p) => {
if matches!(
invoke_closure(vm, p, std::slice::from_ref(&v)),
Value::Bool(true)
) {
stream_push(vm, v, rest, rest_counts, sink)
} else {
true
}
}
Stage::Map(f) => {
let mapped = invoke_closure(vm, f, &[v]);
stream_push(vm, mapped, rest, rest_counts, sink)
}
Stage::FlatMap(f) => {
let inner = invoke_closure(vm, f, &[v]);
let elems = match as_stream(&inner) {
Some((src, st, _)) => {
let mut out = Vec::new();
let mut cs = vec![0i64; st.len()];
for e in src {
if !stream_push(vm, e, &st, &mut cs, &mut |_vm, x| {
out.push(x);
true
}) {
break;
}
}
out
}
None => sequence_items(&inner).unwrap_or_default(),
};
for e in elems {
if !stream_push(vm, e, rest, rest_counts, sink) {
return false;
}
}
true
}
Stage::Peek(f) => {
invoke_closure(vm, f, std::slice::from_ref(&v));
stream_push(vm, v, rest, rest_counts, sink)
}
Stage::Skip(n) => {
*count += 1;
if *count <= *n {
true
} else {
stream_push(vm, v, rest, rest_counts, sink)
}
}
Stage::Limit(n) => {
if *count >= *n {
return false;
}
*count += 1;
let go = stream_push(vm, v, rest, rest_counts, sink);
go && *count < *n
}
Stage::Distinct | Stage::Sorted(_) => {
unreachable!("a barrier is split off before the element-wise walk")
}
}
}
fn stream_drive(
vm: &mut VM,
source: Vec<Value>,
stages: &[Stage],
sink: &mut dyn FnMut(&mut VM, Value) -> bool,
) {
if let Some(i) = stages
.iter()
.position(|s| matches!(s, Stage::Distinct | Stage::Sorted(_)))
{
let mut buf = Vec::new();
stream_drive(vm, source, &stages[..i], &mut |_vm, v| {
buf.push(v);
true
});
let buf = match &stages[i] {
Stage::Distinct => {
let mut seen: Vec<Value> = Vec::new();
for v in buf {
if !seen.iter().any(|x| value_eq(x, &v)) {
seen.push(v);
}
}
seen
}
Stage::Sorted(cmp) => sort_values(vm, buf, cmp.as_ref()),
_ => unreachable!("the position above found a barrier"),
};
return stream_drive(vm, buf, &stages[i + 1..], sink);
}
let mut counters = vec![0i64; stages.len()];
for v in source {
if !stream_push(vm, v, stages, &mut counters, sink) {
break;
}
}
}
fn sort_values(vm: &mut VM, items: Vec<Value>, cmp: Option<&Value>) -> Vec<Value> {
let mut out: Vec<Value> = Vec::with_capacity(items.len());
for v in items {
let mut at = out.len();
while at > 0 {
let ord = match cmp {
Some(c) => invoke_closure(vm, c, &[out[at - 1].clone(), v.clone()]).jint(),
None => natural_cmp(&out[at - 1], &v) as i64,
};
if ord <= 0 {
break;
}
at -= 1;
}
out.insert(at, v);
}
out
}
fn stream_collect(vm: &mut VM, source: Vec<Value>, stages: &[Stage]) -> Vec<Value> {
let mut out = Vec::new();
stream_drive(vm, source, stages, &mut |_vm, v| {
out.push(v);
true
});
out
}
fn stream_method(
vm: &mut VM,
recv: &Value,
method: &str,
args: &[Value],
) -> Option<Result<Value, Fault>> {
let (source, stages, kind) = as_stream(recv)?;
let stage = |st: Stage| Ok(stream_with(recv, kind, Some(st)).expect("receiver is a stream"));
let retyped = |k: StreamKind| Ok(stream_with(recv, k, None).expect("receiver is a stream"));
let all = |vm: &mut VM| stream_collect(vm, source.clone(), &stages);
Some(match (method, args.len()) {
("filter", 1) => stage(Stage::Filter(args[0].clone())),
("map", 1) => stage(Stage::Map(args[0].clone())),
("flatMap", 1) => stage(Stage::FlatMap(args[0].clone())),
("peek", 1) => stage(Stage::Peek(args[0].clone())),
("limit", 1) => stage(Stage::Limit(args[0].jint())),
("skip", 1) => stage(Stage::Skip(args[0].jint())),
("distinct", 0) => stage(Stage::Distinct),
("sorted", 0) => stage(Stage::Sorted(None)),
("sorted", 1) => stage(Stage::Sorted(Some(args[0].clone()))),
("mapToInt", 1) => {
Ok(
stream_with(recv, StreamKind::Int, Some(Stage::Map(args[0].clone())))
.expect("receiver is a stream"),
)
}
("mapToLong", 1) => {
Ok(
stream_with(recv, StreamKind::Long, Some(Stage::Map(args[0].clone())))
.expect("receiver is a stream"),
)
}
("mapToDouble", 1) => {
Ok(
stream_with(recv, StreamKind::Double, Some(Stage::Map(args[0].clone())))
.expect("receiver is a stream"),
)
}
("mapToObj", 1) => {
Ok(
stream_with(recv, StreamKind::Ref, Some(Stage::Map(args[0].clone())))
.expect("receiver is a stream"),
)
}
("boxed", 0) => retyped(StreamKind::Ref),
("asLongStream", 0) => retyped(StreamKind::Long),
("asDoubleStream", 0) => retyped(StreamKind::Double),
("toList", 0) => Ok(list_value(all(vm), Fixity::Immutable)),
("toArray", 0) => Ok(Value::Obj(heap_alloc(HostObj::Array(all(vm))))),
("count", 0) => Ok(Value::Int(all(vm).len() as i64)),
("forEach" | "forEachOrdered", 1) => {
let f = args[0].clone();
stream_drive(vm, source, &stages, &mut |vm, v| {
invoke_closure(vm, &f, &[v]);
true
});
Ok(Value::Undef)
}
("sum", 0) => {
let items = all(vm);
Ok(if kind == StreamKind::Double {
Value::float(items.iter().map(|v| v.jfloat()).sum())
} else {
Value::Int(items.iter().map(|v| v.jint()).sum())
})
}
("average", 0) => {
let items = all(vm);
Ok(optional_of(
"OptionalDouble",
(!items.is_empty()).then(|| {
Value::float(items.iter().map(|v| v.jfloat()).sum::<f64>() / items.len() as f64)
}),
))
}
("min" | "max", 0 | 1) => {
let items = all(vm);
let cmp = args.first().cloned();
let sorted = sort_values(vm, items, cmp.as_ref());
let pick = if method == "min" {
sorted.first()
} else {
sorted.last()
};
Ok(optional_of(kind.optional_class(), pick.cloned()))
}
("findFirst" | "findAny", 0) => {
let mut found = None;
stream_drive(vm, source, &stages, &mut |_vm, v| {
found = Some(v);
false
});
Ok(optional_of(kind.optional_class(), found))
}
("anyMatch" | "allMatch" | "noneMatch", 1) => {
let want = method != "allMatch";
let p = args[0].clone();
let mut hit = false;
stream_drive(vm, source, &stages, &mut |vm, v| {
let ok = matches!(invoke_closure(vm, &p, &[v]), Value::Bool(true));
if ok == want {
hit = true;
return false;
}
true
});
Ok(Value::bool(match method {
"anyMatch" => hit,
"noneMatch" => !hit,
_ => !hit,
}))
}
("reduce", 1) => {
let items = all(vm);
let f = args[0].clone();
let mut acc: Option<Value> = None;
for v in items {
acc = Some(match acc {
Some(a) => invoke_closure(vm, &f, &[a, v]),
None => v,
});
}
Ok(optional_of(kind.optional_class(), acc))
}
("reduce", 2) => {
let items = all(vm);
let f = args[1].clone();
let mut acc = args[0].clone();
for v in items {
acc = invoke_closure(vm, &f, &[acc, v]);
}
Ok(acc)
}
("collect", 1) => {
let items = all(vm);
collect_with(vm, items, &args[0])
}
_ => Err(Fault::internal(format!(
"javars: unsupported Stream method `{method}` with {} argument(s)",
args.len()
))),
})
}
fn primitive_stream_kind(class: &str) -> StreamKind {
match class {
"LongStream" => StreamKind::Long,
"DoubleStream" => StreamKind::Double,
_ => StreamKind::Int,
}
}
fn collector(kind: &'static str, args: Vec<Value>) -> Value {
Value::Obj(heap_alloc(HostObj::Collector { kind, args }))
}
fn list_value(items: Vec<Value>, fixed: Fixity) -> Value {
Value::Obj(heap_alloc(HostObj::List {
items,
fixed,
mods: 0,
}))
}
fn collect_with(vm: &mut VM, items: Vec<Value>, collector: &Value) -> Result<Value, Fault> {
let Value::Obj(id) = collector else {
return Err(Fault::internal(
"javars: `collect` takes a `Collectors.*` collector".to_string(),
));
};
let (kind, cargs) = HEAP
.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Collector { kind, args }) => Some((*kind, args.clone())),
_ => None,
})
.ok_or_else(|| {
Fault::internal("javars: `collect` takes a `Collectors.*` collector".to_string())
})?;
Ok(match kind {
"toList" => list_value(items, Fixity::Mutable),
"toSet" => {
let mut out: Vec<Value> = Vec::new();
for v in items {
if !out.iter().any(|x| value_eq(x, &v)) {
out.push(v);
}
}
Value::Obj(heap_alloc(HostObj::Set {
items: out,
order: Order::Hash,
fixed: Fixity::Mutable,
index: KeyIndex::default(),
}))
}
"counting" => Value::Int(items.len() as i64),
"joining" => {
let sep = cargs.first().map(java_str).unwrap_or_default();
let pre = cargs.get(1).map(java_str).unwrap_or_default();
let suf = cargs.get(2).map(java_str).unwrap_or_default();
let body: Vec<String> = items.iter().map(java_str).collect();
Value::str(format!("{pre}{}{suf}", body.join(&sep)))
}
"toMap" | "groupingBy" => {
let mut entries: Vec<(Value, Value)> = Vec::new();
for v in items {
let key = invoke_closure(vm, &cargs[0], std::slice::from_ref(&v));
let val = if kind == "toMap" {
invoke_closure(vm, &cargs[1], std::slice::from_ref(&v))
} else {
v
};
match entries.iter_mut().find(|(k, _)| value_eq(k, &key)) {
Some((_, slot)) if kind == "toMap" => *slot = val,
Some((_, slot)) => {
let mut group = sequence_items(slot).unwrap_or_default();
group.push(val);
*slot = list_value(group, Fixity::Mutable);
}
None => entries.push((
key,
if kind == "toMap" {
val
} else {
list_value(vec![val], Fixity::Mutable)
},
)),
}
}
Value::Obj(heap_alloc(HostObj::Map {
entries,
order: Order::Hash,
fixed: Fixity::Mutable,
index: KeyIndex::default(),
}))
}
other => {
return Err(Fault::internal(format!(
"javars: unsupported collector `Collectors.{other}`"
)))
}
})
}
fn optional_method(
vm: &mut VM,
recv: &Value,
method: &str,
args: &[Value],
) -> Option<Result<Value, Fault>> {
let (class, inner) = as_optional_full(recv)?;
let empty = || Fault::java("NoSuchElementException", "No value present");
Some(match (method, args.len()) {
("isPresent", 0) => Ok(Value::bool(inner.is_some())),
("isEmpty", 0) => Ok(Value::bool(inner.is_none())),
("get" | "orElseThrow" | "getAsInt" | "getAsLong" | "getAsDouble", 0) => {
inner.ok_or_else(empty)
}
("orElse", 1) => Ok(inner.unwrap_or_else(|| args[0].clone())),
("orElseGet", 1) => Ok(match inner {
Some(v) => v,
None => invoke_closure(vm, &args[0], &[]),
}),
("map", 1) => Ok(match inner {
Some(v) => {
let mapped = invoke_closure(vm, &args[0], &[v]);
optional((!matches!(mapped, Value::Undef)).then_some(mapped))
}
None => optional(None),
}),
("filter", 1) => Ok(match inner {
Some(v) => {
let keep = matches!(
invoke_closure(vm, &args[0], std::slice::from_ref(&v)),
Value::Bool(true)
);
optional(keep.then_some(v))
}
None => optional(None),
}),
("ifPresent", 1) => {
if let Some(v) = inner {
invoke_closure(vm, &args[0], &[v]);
}
Ok(Value::Undef)
}
("ifPresentOrElse", 2) => {
match inner {
Some(v) => invoke_closure(vm, &args[0], &[v]),
None => invoke_closure(vm, &args[1], &[]),
};
Ok(Value::Undef)
}
("equals", 1) => Ok(Value::bool(match (inner, as_optional_full(&args[0])) {
(Some(x), Some((other, Some(y)))) => other == class && value_eq(&x, &y),
(None, Some((other, None))) => other == class,
_ => false,
})),
("hashCode", 0) => Ok(Value::Int(match inner {
Some(v) => element_hash(&v).into(),
None => 0,
})),
("toString", 0) => Ok(Value::str(java_str(recv))),
_ => Err(Fault::internal(format!(
"javars: unsupported Optional method `{method}` with {} argument(s)",
args.len()
))),
})
}
fn iter_mods(id: u32) -> u64 {
list_mods(id as usize).unwrap_or(0)
}
fn comodification() -> Fault {
Fault::java("ConcurrentModificationException", String::new())
}
fn checked_window(id: usize) -> Result<(usize, usize, usize), Fault> {
let (root, offset, len) =
resolve_window(id).ok_or_else(|| Fault::internal("javars: dangling subList view"))?;
let exp = HEAP.with(|h| match h.borrow().get(id) {
Some(HostObj::SubList { exp_mods, .. }) => Some(*exp_mods),
_ => None,
});
if exp != list_mods(root) {
return Err(comodification());
}
Ok((root, offset, len))
}
fn make_sublist(id: usize, from: i64, to: i64) -> Result<Value, Fault> {
let (root, size) = if is_sublist(id) {
let (root, _, len) = checked_window(id)?;
(root, len)
} else {
let len = HEAP
.with(|h| match h.borrow().get(id) {
Some(HostObj::List { items, .. }) => Some(items.len()),
_ => None,
})
.ok_or_else(|| Fault::internal("javars: `subList` needs a List receiver"))?;
(id, len)
};
if from < 0 {
return Err(Fault::java(
"IndexOutOfBoundsException",
format!("fromIndex = {from}"),
));
}
if to > size as i64 {
return Err(Fault::java(
"IndexOutOfBoundsException",
format!("toIndex = {to}"),
));
}
if from > to {
return Err(Fault::java(
"IllegalArgumentException",
format!("fromIndex({from}) > toIndex({to})"),
));
}
let exp_mods = list_mods(root).unwrap_or_default();
Ok(Value::Obj(heap_alloc(HostObj::SubList {
parent: id as u32,
offset: from as usize,
len: (to - from) as usize,
exp_mods,
})))
}
fn sublist_method(
id: usize,
method: &str,
args: &[Value],
arg_seqs: &[Option<Vec<Value>>],
eq: Option<&EqPlan>,
) -> Result<Value, Fault> {
let (root, offset, len) = checked_window(id)?;
let (mut window, fixed) = HEAP
.with(|h| match h.borrow().get(root) {
Some(HostObj::List { items, fixed, .. }) => {
Some((items[offset..offset + len].to_vec(), *fixed))
}
_ => None,
})
.ok_or_else(|| Fault::internal("javars: dangling subList backing"))?;
let out = list_method(&mut window, fixed, method, args, arg_seqs, eq)?;
let delta = window.len() as isize - len as isize;
HEAP.with(|h| {
if let Some(HostObj::List { items, mods, .. }) = h.borrow_mut().get_mut(root) {
items.splice(offset..offset + len, window);
if delta != 0 {
*mods += 1;
}
}
});
if delta != 0 {
let new_mods = list_mods(root).unwrap_or_default();
resize_ancestors(id, delta, new_mods);
}
Ok(match out {
NewColl::Value(v) => v,
NewColl::Alloc(obj) => Value::Obj(heap_alloc(obj)),
})
}
fn resize_ancestors(id: usize, delta: isize, new_mods: u64) {
HEAP.with(|h| {
let mut heap = h.borrow_mut();
let mut cur = id;
for _ in 0..=heap.len() {
match heap.get_mut(cur) {
Some(HostObj::SubList {
parent,
len,
exp_mods,
..
}) => {
*len = len.saturating_add_signed(delta);
*exp_mods = new_mods;
cur = *parent as usize;
}
_ => return,
}
}
});
}
fn write_sequence(id: usize, items: Vec<Value>, structural: bool) -> Result<(), Fault> {
let (root, offset, len) = if is_sublist(id) {
checked_window(id)?
} else {
(id, 0, usize::MAX)
};
HEAP.with(|h| {
if let Some(HostObj::List {
items: dst, mods, ..
}) = h.borrow_mut().get_mut(root)
{
let end = len.min(dst.len().saturating_sub(offset)) + offset;
dst.splice(offset..end, items);
if structural {
*mods += 1;
}
}
});
Ok(())
}
fn map_order(v: &Value) -> Order {
let Value::Obj(id) = v else {
return Order::Insertion;
};
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Map { order, .. }) => *order,
_ => Order::Insertion,
})
}
fn sort_with(vm: &mut VM, mut items: Vec<Value>, cmp: &Value) -> Result<Vec<Value>, Fault> {
if matches!(cmp, Value::Undef) {
items.sort_by(natural_cmp);
return Ok(items);
}
if closure_meta(cmp).is_none() {
return Err(Fault::internal("javars: `sort` needs a Comparator lambda"));
}
let n = items.len();
let mut buf: Vec<Value> = items.clone();
let mut width = 1;
while width < n {
let mut lo = 0;
while lo < n {
let mid = (lo + width).min(n);
let hi = (lo + 2 * width).min(n);
let (mut i, mut j) = (lo, mid);
for slot in &mut buf[lo..hi] {
let take_left = if i >= mid {
false
} else if j >= hi {
true
} else {
invoke_closure(vm, cmp, &[items[j].clone(), items[i].clone()]).jint() >= 0
};
if take_left {
*slot = items[i].clone();
i += 1;
} else {
*slot = items[j].clone();
j += 1;
}
}
lo = hi;
}
std::mem::swap(&mut items, &mut buf);
width *= 2;
}
Ok(items)
}
fn invoke_closure(vm: &mut VM, clo: &Value, args: &[Value]) -> Value {
vm.stack.push(clo.clone());
for a in args {
vm.stack.push(a.clone());
}
b_closure_call(vm, args.len() as u8 + 1)
}
fn list_method(
items: &mut Vec<Value>,
fixed: Fixity,
method: &str,
args: &[Value],
arg_seqs: &[Option<Vec<Value>>],
eq: Option<&EqPlan>,
) -> Result<NewColl, Fault> {
let structural = || match fixed {
Fixity::Mutable => Ok(()),
_ => Err(Fault::java("UnsupportedOperationException", String::new())),
};
let replace = || match fixed {
Fixity::Immutable => Err(Fault::java("UnsupportedOperationException", String::new())),
_ => Ok(()),
};
let bounds = |i: i64, len: usize| -> Result<usize, Fault> {
if i < 0 || i as usize >= len {
return Err(Fault::java(
"IndexOutOfBoundsException",
format!("Index {i} out of bounds for length {len}"),
));
}
Ok(i as usize)
};
let v = match (method, args.len()) {
("size", 0) => Value::Int(items.len() as i64),
("isEmpty", 0) => Value::bool(items.is_empty()),
("add", 1) => {
structural()?;
items.push(args[0].clone());
Value::bool(true)
}
("add", 2) => {
structural()?;
let at = args[0].jint();
if at < 0 || at as usize > items.len() {
return Err(Fault::java(
"IndexOutOfBoundsException",
format!("Index: {at}, Size: {}", items.len()),
));
}
items.insert(at as usize, args[1].clone());
Value::Undef
}
("get", 1) => {
let i = bounds(args[0].jint(), items.len())?;
items[i].clone()
}
("set", 2) => {
replace()?;
let i = bounds(args[0].jint(), items.len())?;
std::mem::replace(&mut items[i], args[1].clone())
}
("remove", 1) => {
structural()?;
let i = bounds(args[0].jint(), items.len())?;
items.remove(i)
}
("removeObject", 1) => {
structural()?;
match eq_index(eq, items, &args[0], false) {
Some(i) => {
items.remove(i);
Value::bool(true)
}
None => Value::bool(false),
}
}
("clear", 0) => {
structural()?;
items.clear();
Value::Undef
}
("contains", 1) => Value::bool(eq_index(eq, items, &args[0], false).is_some()),
("indexOf", 1) => Value::Int(eq_index(eq, items, &args[0], false).map_or(-1, |i| i as i64)),
("lastIndexOf", 1) => {
Value::Int(eq_index(eq, items, &args[0], true).map_or(-1, |i| i as i64))
}
("addAll", 1) => {
structural()?;
let add = arg_seqs[0].clone().unwrap_or_default();
let changed = !add.is_empty();
items.extend(add);
Value::bool(changed)
}
("equals", 1) => match eq {
Some(EqPlan::Same(same)) => Value::bool(*same),
_ => {
let other = arg_seqs[0].clone().unwrap_or_default();
Value::bool(
other.len() == items.len()
&& items.iter().zip(&other).all(|(a, b)| value_eq(a, b)),
)
}
},
("hashCode", 0) => Value::Int(list_hash(items)),
_ => {
return Err(Fault::internal(format!(
"javars: unsupported List method `{method}` with {} argument(s)",
args.len()
)))
}
};
Ok(NewColl::Value(v))
}
#[derive(Clone, Copy)]
struct MapShape {
order: Order,
fixed: Fixity,
}
fn map_method(
entries: &mut Vec<(Value, Value)>,
shape: MapShape,
index: &mut KeyIndex,
method: &str,
args: &[Value],
arg_entries: &[Option<Vec<(Value, Value)>>],
eq: Option<&EqPlan>,
) -> Result<NewColl, Fault> {
let MapShape { order, fixed } = shape;
if fixed == Fixity::Immutable
&& matches!(
method,
"put"
| "remove"
| "clear"
| "putAll"
| "putIfAbsent"
| "merge"
| "replace"
| "replaceAll"
| "compute"
| "computeIfAbsent"
| "computeIfPresent"
)
{
return Err(Fault::java("UnsupportedOperationException", String::new()));
}
if index.dirty {
index.rebuild(entries.iter().map(|(k, _)| k));
}
let find = |entries: &Vec<(Value, Value)>, index: &KeyIndex, k: &Value| match eq {
Some(EqPlan::Index(at)) => *at,
_ => match index.find(entries, |(x, _)| x, k) {
Some(at) => at,
None => entries.iter().position(|(x, _)| value_eq(x, k)),
},
};
let out = match (method, args.len()) {
("size", 0) => NewColl::Value(Value::Int(entries.len() as i64)),
("isEmpty", 0) => NewColl::Value(Value::bool(entries.is_empty())),
("put", 2) => NewColl::Value(match find(entries, index, &args[0]) {
Some(i) => std::mem::replace(&mut entries[i].1, args[1].clone()),
None => {
index.push(&args[0], entries.len());
entries.push((args[0].clone(), args[1].clone()));
Value::Undef
}
}),
("putIfAbsent", 2) => NewColl::Value(match find(entries, index, &args[0]) {
Some(i) => entries[i].1.clone(),
None => {
index.push(&args[0], entries.len());
entries.push((args[0].clone(), args[1].clone()));
Value::Undef
}
}),
("get", 1) => NewColl::Value(
find(entries, index, &args[0]).map_or(Value::Undef, |i| entries[i].1.clone()),
),
("getOrDefault", 2) => NewColl::Value(
find(entries, index, &args[0])
.map_or_else(|| args[1].clone(), |i| entries[i].1.clone()),
),
("containsKey", 1) => NewColl::Value(Value::bool(find(entries, index, &args[0]).is_some())),
("containsValue", 1) => NewColl::Value(Value::bool(match eq {
Some(EqPlan::Index(at)) => at.is_some(),
_ => entries.iter().any(|(_, v)| value_eq(v, &args[0])),
})),
("remove", 1) => NewColl::Value(match find(entries, index, &args[0]) {
Some(i) => {
index.invalidate();
entries.remove(i).1
}
None => Value::Undef,
}),
("clear", 0) => {
entries.clear();
index.rebuild(std::iter::empty());
NewColl::Value(Value::Undef)
}
("keySet", 0) => {
let keys: Vec<Value> = entries.iter().map(|(k, _)| k.clone()).collect();
let ordered = present_order(&keys, order)
.into_iter()
.map(|i| keys[i].clone())
.collect();
NewColl::Alloc(HostObj::Set {
items: ordered,
order: Order::Insertion,
fixed: Fixity::Mutable,
index: KeyIndex::default(),
})
}
("values", 0) => {
let keys: Vec<Value> = entries.iter().map(|(k, _)| k.clone()).collect();
let ordered = present_order(&keys, order)
.into_iter()
.map(|i| entries[i].1.clone())
.collect();
NewColl::Alloc(HostObj::List {
mods: 0,
items: ordered,
fixed: Fixity::FixedSize,
})
}
("hashCode", 0) => NewColl::Value(Value::Int(map_hash(entries))),
("equals", 1) => {
let other = arg_entries.first().cloned().flatten();
NewColl::Value(Value::bool(match other {
Some(other) => {
other.len() == entries.len()
&& entries.iter().all(|(k, v)| {
other
.iter()
.find(|(ok, _)| value_eq(ok, k))
.is_some_and(|(_, ov)| value_eq(ov, v))
})
}
None => false,
}))
}
_ => {
return Err(Fault::internal(format!(
"javars: unsupported Map method `{method}` with {} argument(s)",
args.len()
)))
}
};
Ok(out)
}
fn set_method(
items: &mut Vec<Value>,
fixed: Fixity,
index: &mut KeyIndex,
method: &str,
args: &[Value],
arg_seqs: &[Option<Vec<Value>>],
eq: Option<&EqPlan>,
) -> Result<NewColl, Fault> {
if index.dirty {
index.rebuild(items.iter());
}
let member = |items: &Vec<Value>, index: &KeyIndex, q: &Value| match eq {
Some(EqPlan::Index(at)) => *at,
_ => match index.find(items, |x| x, q) {
Some(at) => at,
None => items.iter().position(|x| value_eq(x, q)),
},
};
let structural = || match fixed {
Fixity::Mutable => Ok(()),
_ => Err(Fault::java("UnsupportedOperationException", String::new())),
};
let v = match (method, args.len()) {
("size", 0) => Value::Int(items.len() as i64),
("isEmpty", 0) => Value::bool(items.is_empty()),
("add", 1) => {
structural()?;
if member(items, index, &args[0]).is_some() {
Value::bool(false)
} else {
index.push(&args[0], items.len());
items.push(args[0].clone());
Value::bool(true)
}
}
("contains", 1) => Value::bool(member(items, index, &args[0]).is_some()),
("remove", 1) => {
structural()?;
match member(items, index, &args[0]) {
Some(i) => {
index.invalidate();
items.remove(i);
Value::bool(true)
}
None => Value::bool(false),
}
}
("clear", 0) => {
structural()?;
items.clear();
index.rebuild(std::iter::empty());
Value::Undef
}
("addAll", 1) => {
structural()?;
match eq {
Some(EqPlan::Fresh(fresh)) => {
let changed = !fresh.is_empty();
for v in fresh {
index.push(v, items.len());
items.push(v.clone());
}
Value::bool(changed)
}
_ => {
let mut changed = false;
for v in arg_seqs[0].clone().unwrap_or_default() {
if member(items, index, &v).is_none() {
index.push(&v, items.len());
items.push(v);
changed = true;
}
}
Value::bool(changed)
}
}
}
("hashCode", 0) => Value::Int(set_hash(items)),
("equals", 1) => {
let other = arg_seqs[0].clone();
Value::bool(match other {
Some(other) => {
other.len() == items.len()
&& items.iter().all(|e| other.iter().any(|o| value_eq(o, e)))
}
None => false,
})
}
_ => {
return Err(Fault::internal(format!(
"javars: unsupported Set method `{method}` with {} argument(s)",
args.len()
)))
}
};
Ok(NewColl::Value(v))
}
fn render_sequence(items: &[Value]) -> String {
let body: Vec<String> = items.iter().map(java_str).collect();
format!("[{}]", body.join(", "))
}
fn render_set(items: &[Value], order: Order) -> String {
let ordered: Vec<Value> = present_order(items, order)
.into_iter()
.map(|i| items[i].clone())
.collect();
render_sequence(&ordered)
}
fn render_map(entries: &[(Value, Value)], order: Order) -> String {
let keys: Vec<Value> = entries.iter().map(|(k, _)| k.clone()).collect();
let body: Vec<String> = present_order(&keys, order)
.into_iter()
.map(|i| format!("{}={}", java_str(&entries[i].0), java_str(&entries[i].1)))
.collect();
format!("{{{}}}", body.join(", "))
}
fn b_str_dispatch(vm: &mut VM, argc: u8) -> Value {
let method = vm
.stack
.pop()
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default();
let n = argc.saturating_sub(2) as usize; let mut args = Vec::with_capacity(n);
for _ in 0..n {
args.push(vm.stack.pop().unwrap_or(Value::Undef));
}
args.reverse();
let recv = vm.stack.pop().unwrap_or(Value::Undef);
if closure_meta(&recv).is_some() {
vm.stack.push(recv);
for a in args {
vm.stack.push(a);
}
return b_closure_call(vm, n as u8 + 1);
}
if let Some(r) = stream_method(vm, &recv, &method, &args) {
return match r {
Ok(v) => v,
Err(f) => raise(vm, f),
};
}
if let Some(r) = optional_method(vm, &recv, &method, &args) {
return match r {
Ok(v) => v,
Err(f) => raise(vm, f),
};
}
if let Some(r) = iterator_method(&recv, &method, args.len()) {
return match r {
Ok(v) => v,
Err(f) => raise(vm, f),
};
}
if is_collection(&recv) {
return coll_method(vm, &recv, &method, &args);
}
if let Some(id) = is_builder(&recv) {
if !matches!(method.as_str(), "equals" | "hashCode" | "getClass") {
if let Some(r) = builder_method(vm, id, &method, &args) {
return match r {
Ok(v) => v,
Err(f) => raise(vm, f),
};
}
}
}
if method == "toString"
&& args.is_empty()
&& any_user_tostring(vm)
&& instance_class(&recv).is_some()
{
return Value::str(java_str_vm(vm, &recv));
}
if let Some(v) = object_method(&recv, &method, &args) {
return v;
}
if matches!(recv, Value::Undef) {
return raise(
vm,
Fault::java(
"NullPointerException",
format!("Cannot invoke \"String.{method}()\" because the receiver is null"),
),
);
}
if let Some(v) = boxed_method(&recv, &method, args.len()) {
return v;
}
if unboxed(&recv).is_some() {
match (method.as_str(), args.len()) {
("equals", 1) => return Value::bool(value_eq(&recv, &args[0])),
("hashCode", 0) => {
return java_hash(&recv).map_or(Value::Undef, |h| Value::Int(h.into()))
}
_ => {}
}
let inner = deboxed(&recv);
vm.stack.push(inner);
for a in args {
vm.stack.push(a);
}
vm.stack.push(Value::str(method));
return b_str_dispatch(vm, argc);
}
let args: Vec<Value> = args.iter().map(deboxed).collect();
let s = recv.as_str_cow();
if method == "formatted" && any_user_tostring(vm) {
return match java_format(&s, &args, &[], Some(&mut *vm)) {
Ok(v) => v,
Err(f) => raise(vm, f),
};
}
match string_method(&s, &method, &args) {
Ok(v) if method == "intern" => intern(&v),
Ok(Value::Str(text)) if text.as_str() == s.as_ref() => recv,
Ok(v) => v,
Err(f) => raise(vm, f),
}
}
fn instance_class(v: &Value) -> Option<String> {
let Value::Obj(id) = v else {
return None;
};
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Instance { class, .. }) => Some(class.clone()),
_ => None,
})
}
fn object_method(recv: &Value, method: &str, args: &[Value]) -> Option<Value> {
let Value::Obj(id) = recv else {
return None;
};
let inherits_object = HEAP.with(|h| {
matches!(
h.borrow().get(*id as usize),
Some(HostObj::Instance { .. } | HostObj::Builder { .. })
)
});
if !inherits_object {
return None;
}
match (method, args.len()) {
("equals", 1) => Some(Value::bool(
matches!(args[0], Value::Obj(other) if other == *id),
)),
("hashCode", 0) => Some(Value::Int(i64::from(*id))),
("toString", 0) => Some(Value::str(obj_default_str(*id))),
_ => None,
}
}
fn boxed_method(recv: &Value, method: &str, argc: usize) -> Option<Value> {
if argc != 0 || matches!(recv, Value::Obj(_) | Value::Undef) {
return None;
}
let int_value = match recv {
Value::Float(f) => *f as i32,
other => other.jint() as i32,
};
let long_value = match recv {
Value::Float(f) => *f as i64,
other => other.jint(),
};
Some(match method {
"hashCode" if !matches!(recv, Value::Str(_)) => Value::Int(java_hash(recv)?.into()),
"intValue" => Value::Int(int_value.into()),
"shortValue" => Value::Int((int_value as i16).into()),
"byteValue" => Value::Int((int_value as i8).into()),
"longValue" => Value::Int(long_value),
"doubleValue" => Value::float(recv.jfloat()),
"floatValue" => Value::float(recv.jfloat() as f32 as f64),
"booleanValue" if matches!(recv, Value::Bool(_)) => recv.clone(),
"charValue" => recv.clone(),
_ => return None,
})
}
fn compare_strings(a: &str, b: &str, fold_case: bool) -> i64 {
let norm = |s: &str| -> Vec<char> {
if fold_case {
s.chars().flat_map(|c| c.to_lowercase()).collect()
} else {
s.chars().collect()
}
};
let (x, y) = (norm(a), norm(b));
for (ca, cb) in x.iter().zip(&y) {
if ca != cb {
return *ca as i64 - *cb as i64;
}
}
x.len() as i64 - y.len() as i64
}
fn double_compare(a: f64, b: f64) -> i64 {
match a.total_cmp(&b) {
std::cmp::Ordering::Less => -1,
std::cmp::Ordering::Equal => 0,
std::cmp::Ordering::Greater => 1,
}
}
fn b_compare_to(vm: &mut VM, _argc: u8) -> Value {
let tag = vm
.stack
.pop()
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default();
let b = deboxed(&vm.stack.pop().unwrap_or(Value::Undef));
let a = deboxed(&vm.stack.pop().unwrap_or(Value::Undef));
if matches!(a, Value::Undef) {
return raise(
vm,
Fault::java(
"NullPointerException",
"Cannot invoke \"java.lang.Comparable.compareTo(Object)\" because the receiver is null",
),
);
}
if matches!(b, Value::Undef) {
let param = match tag.as_str() {
"Integer" | "int" => "anotherInteger",
"Long" | "long" => "anotherLong",
"Double" | "double" | "Float" | "float" => "anotherDouble",
"Character" | "char" => "anotherCharacter",
"Boolean" | "boolean" => "b",
"String" | "CharSequence" => "anotherString",
_ => match &a {
Value::Str(_) => "anotherString",
Value::Float(_) => "anotherDouble",
Value::Bool(_) => "b",
_ => "anotherInteger",
},
};
return raise(
vm,
Fault::java(
"NullPointerException",
format!("Cannot read field \"value\" because \"{param}\" is null"),
),
);
}
if is_builder(&a).is_some() || is_builder(&b).is_some() {
return Value::Int(compare_strings(&java_str(&a), &java_str(&b), false));
}
if let Value::Obj(id) = a {
let class = HEAP.with(|h| match h.borrow().get(id as usize) {
Some(HostObj::Instance { class, .. }) => Some(class.clone()),
_ => None,
});
if let Some(class) = class {
return raise(
vm,
Fault::internal(format!(
"javars: class `{class}` does not declare `compareTo`"
)),
);
}
}
Value::Int(match tag.as_str() {
"Integer" | "int" | "Long" | "long" => as_i64(&a).cmp(&as_i64(&b)) as i64,
"Character" | "char" | "Short" | "short" | "Byte" | "byte" => as_i64(&a) - as_i64(&b),
"Double" | "double" | "Float" | "float" => double_compare(as_f64(&a), as_f64(&b)),
"Boolean" | "boolean" => i64::from(a.is_truthy()) - i64::from(b.is_truthy()),
"String" | "CharSequence" => compare_strings(&a.as_str_cow(), &b.as_str_cow(), false),
_ => match (&a, &b) {
(Value::Str(_), _) | (_, Value::Str(_)) => {
compare_strings(&a.as_str_cow(), &b.as_str_cow(), false)
}
(Value::Float(_), _) | (_, Value::Float(_)) => double_compare(as_f64(&a), as_f64(&b)),
(Value::Bool(_), Value::Bool(_)) => i64::from(a.is_truthy()) - i64::from(b.is_truthy()),
_ => as_i64(&a).cmp(&as_i64(&b)) as i64,
},
})
}
fn next_after(start: f64, direction: f64) -> f64 {
if start.is_nan() || direction.is_nan() {
return f64::NAN;
}
if start == direction {
return direction;
}
let up = direction > start;
if start == 0.0 {
return if up {
f64::from_bits(1)
} else {
-f64::from_bits(1)
};
}
let bits = start.to_bits() as i64;
let step = if (start > 0.0) == up { 1 } else { -1 };
f64::from_bits((bits + step) as u64)
}
fn double_ulp(d: f64) -> f64 {
if d.is_nan() {
return f64::NAN;
}
if d.is_infinite() {
return f64::INFINITY;
}
let d = d.abs();
if d == f64::MAX {
return d - next_after(d, f64::NEG_INFINITY);
}
next_after(d, f64::INFINITY) - d
}
fn char_count(s: &str) -> usize {
s.as_bytes().iter().filter(|b| (*b & 0xC0) != 0x80).count()
}
fn char_at(s: &str, i: usize) -> Option<char> {
let bytes = s.as_bytes();
if i < bytes.len() && bytes[..i].is_ascii() {
return s[i..].chars().next();
}
s.chars().nth(i)
}
fn char_byte_of(s: &str, i: usize) -> usize {
let bytes = s.as_bytes();
if i <= bytes.len() && bytes[..i].is_ascii() {
return i;
}
s.char_indices().nth(i).map(|(b, _)| b).unwrap_or(s.len())
}
fn string_method(s: &str, method: &str, args: &[Value]) -> Result<Value, Fault> {
let char_len = || char_count(s) as i64;
null_string_argument(method, args)?;
match (method, args.len()) {
("length", 0) => Ok(Value::Int(char_len())),
("isEmpty", 0) => Ok(Value::bool(s.is_empty())),
("compareTo", 1) => Ok(Value::Int(compare_strings(s, &args[0].as_str_cow(), false))),
("compareToIgnoreCase", 1) => {
Ok(Value::Int(compare_strings(s, &args[0].as_str_cow(), true)))
}
("charAt", 1) => {
let i = args[0].jint();
match usize::try_from(i).ok().and_then(|i| char_at(s, i)) {
Some(c) => Ok(Value::Int(c as i64)),
None => Err(Fault::java(
"StringIndexOutOfBoundsException",
format!("Index {i} out of bounds for length {}", char_len()),
)),
}
}
("substring", 1) => substring(s, args[0].jint(), char_len()),
("substring", 2) => substring(s, args[0].jint(), args[1].jint()),
("indexOf", 1) => Ok(Value::Int(char_index_of(s, &args[0].as_str_cow()))),
("indexOf", 2) => {
let from = args[1].jint().clamp(0, char_len()) as usize;
let tail: String = s.chars().skip(from).collect();
let hit = char_index_of(&tail, &args[0].as_str_cow());
Ok(Value::Int(if hit < 0 { -1 } else { hit + from as i64 }))
}
("lastIndexOf", 1) => Ok(Value::Int(char_last_index_of(
s,
&args[0].as_str_cow(),
char_len(),
))),
("lastIndexOf", 2) => Ok(Value::Int(char_last_index_of(
s,
&args[0].as_str_cow(),
args[1].jint(),
))),
("codePointAt", 1) => {
let i = args[0].jint();
match usize::try_from(i).ok().and_then(|i| char_at(s, i)) {
Some(c) => Ok(Value::Int(c as i64)),
None => Err(Fault::java(
"StringIndexOutOfBoundsException",
format!("Index {i} out of bounds for length {}", char_len()),
)),
}
}
("strip", 0) => Ok(Value::str(s.trim_matches(java_is_whitespace).to_string())),
("stripLeading", 0) => Ok(Value::str(
s.trim_start_matches(java_is_whitespace).to_string(),
)),
("stripTrailing", 0) => Ok(Value::str(
s.trim_end_matches(java_is_whitespace).to_string(),
)),
("isBlank", 0) => Ok(Value::bool(s.chars().all(java_is_whitespace))),
("hashCode", 0) => Ok(Value::Int(
java_hash(&Value::str(s.to_string())).unwrap_or(0).into(),
)),
("intern", 0) | ("toString", 0) => Ok(Value::str(s.to_string())),
("contentEquals", 1) => Ok(Value::bool(s == args[0].as_str_cow().as_ref())),
("getSimpleName", 0) => Ok(Value::str(simple_class_name(s).to_string())),
("getName", 0) => Ok(Value::str(s.to_string())),
("toCharArray", 0) => Ok(Value::Obj(heap_alloc(HostObj::Array(
s.chars().map(|c| Value::Int(c as i64)).collect(),
)))),
("formatted", _) => java_format(s, args, &[], None),
("split", 1) | ("split", 2) => {
let compiled = crate::regex::compile(&args[0].as_str_cow());
let pat = compiled.as_ref().as_ref().map_err(|e| pattern_fault(e))?;
let limit = args.get(1).map_or(0, JavaNumeric::jint);
let parts = pat.split(s, limit).map_err(engine_fault)?;
Ok(Value::Obj(heap_alloc(HostObj::Array(
parts.into_iter().map(Value::str).collect(),
))))
}
("replaceAll", 2) | ("replaceFirst", 2) => {
let compiled = crate::regex::compile(&args[0].as_str_cow());
let pat = compiled.as_ref().as_ref().map_err(|e| pattern_fault(e))?;
let out = pat
.replace(s, &args[1].as_str_cow(), method == "replaceFirst")
.map_err(replacement_fault)?;
Ok(Value::str(out))
}
("matches", 1) => {
let compiled = crate::regex::compile_whole(&args[0].as_str_cow());
let pat = compiled.as_ref().as_ref().map_err(|e| pattern_fault(e))?;
Ok(Value::bool(pat.matches_whole(s).map_err(engine_fault)?))
}
("contains", 1) => Ok(Value::bool(s.contains(args[0].as_str_cow().as_ref()))),
("equals", 1) => Ok(Value::bool(s == args[0].as_str_cow().as_ref())),
("equalsIgnoreCase", 1) => {
let o = args[0].as_str_cow();
Ok(Value::bool(s.to_lowercase() == o.to_lowercase()))
}
("toUpperCase", 0) => Ok(Value::str(s.to_uppercase())),
("toLowerCase", 0) => Ok(Value::str(s.to_lowercase())),
("trim", 0) => Ok(Value::str(s.trim_matches(|c: char| c <= ' ').to_string())),
("startsWith", 1) => Ok(Value::bool(s.starts_with(args[0].as_str_cow().as_ref()))),
("startsWith", 2) => {
let off = args[1].jint();
let len = char_count(s);
Ok(Value::bool(usize::try_from(off).is_ok_and(|o| {
o <= len && s[char_byte_of(s, o)..].starts_with(args[0].as_str_cow().as_ref())
})))
}
("endsWith", 1) => Ok(Value::bool(s.ends_with(args[0].as_str_cow().as_ref()))),
("concat", 1) => Ok(Value::str(format!("{s}{}", args[0].as_str_cow()))),
("replace", 2) => Ok(Value::str(
s.replace(args[0].as_str_cow().as_ref(), &args[1].as_str_cow()),
)),
("repeat", 1) => {
let n = args[0].jint();
if n < 0 {
Err(Fault::java(
"IllegalArgumentException",
format!("count is negative: {n}"),
))
} else {
Ok(Value::str(s.repeat(n as usize)))
}
}
_ => Err(Fault::internal(format!(
"javars: unsupported String method `{method}` with {} argument(s)",
args.len()
))),
}
}
fn substring(s: &str, begin: i64, end: i64) -> Result<Value, Fault> {
let len = s.chars().count() as i64;
if begin < 0 || end > len || begin > end {
return Err(Fault::java(
"StringIndexOutOfBoundsException",
format!("Range [{begin}, {end}) out of bounds for length {len}"),
));
}
let sub: String = s
.chars()
.skip(begin as usize)
.take((end - begin) as usize)
.collect();
Ok(Value::str(sub))
}
fn char_index_of(s: &str, needle: &str) -> i64 {
match s.find(needle) {
Some(byte_pos) => s[..byte_pos].chars().count() as i64,
None => -1,
}
}
fn b_static_dispatch(vm: &mut VM, argc: u8) -> Value {
let method = vm
.stack
.pop()
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default();
let class = vm
.stack
.pop()
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default();
let n = argc.saturating_sub(2) as usize; let mut args = Vec::with_capacity(n);
for _ in 0..n {
args.push(vm.stack.pop().unwrap_or(Value::Undef));
}
args.reverse();
match collection_static(vm, &class, &method, &args) {
Some(Ok(v)) => return v,
Some(Err(f)) => return raise(vm, f),
None => {}
}
if any_user_tostring(vm) {
if let Some(v) = rendering_static(vm, &class, &method, &args) {
return v;
}
}
match static_method(&class, &method, &args) {
Ok(v) => v,
Err(f) => raise(vm, f),
}
}
fn rendering_static(vm: &mut VM, class: &str, method: &str, args: &[Value]) -> Option<Value> {
Some(match (class, method, args.len()) {
("String", "valueOf", 1) if matches!(args[0], Value::Str(_)) => args[0].clone(),
("String", "valueOf", 1) => Value::str(match array_items(&args[0]) {
Some(items) => items.iter().map(|v| java_str_vm(vm, v)).collect::<String>(),
None => java_str_vm(vm, &args[0]),
}),
("String", "join", n) if n >= 2 && !matches!(args[0], Value::Undef) => {
let sep = args[0].as_str_cow().into_owned();
let parts: Vec<String> = match (sequence_items(&args[1]), n) {
(Some(items), 2) => items.iter().map(|v| java_str_vm(vm, v)).collect(),
_ => args[1..].iter().map(|v| java_str_vm(vm, v)).collect(),
};
Value::str(parts.join(&sep))
}
("Arrays", "toString", 1) => match array_items(&args[0]) {
Some(items) => {
let inner: Vec<String> = items.iter().map(|v| java_str_vm(vm, v)).collect();
Value::str(format!("[{}]", inner.join(", ")))
}
None => Value::str(java_str_vm(vm, &args[0])),
},
("Arrays", "deepToString", 1) => Value::str(deep_to_string_vm(vm, &args[0])),
_ => return None,
})
}
fn deep_to_string_vm(vm: &mut VM, v: &Value) -> String {
match array_items(v) {
Some(items) => {
let inner: Vec<String> = items.iter().map(|e| deep_to_string_vm(vm, e)).collect();
format!("[{}]", inner.join(", "))
}
None => java_str_vm(vm, v),
}
}
fn collection_static(
vm: &mut VM,
class: &str,
method: &str,
args: &[Value],
) -> Option<Result<Value, Fault>> {
let list = |items: Vec<Value>, fixed: Fixity| {
Ok(Value::Obj(heap_alloc(HostObj::List {
items,
fixed,
mods: 0,
})))
};
Some(match (class, method) {
("Arrays", "asList") => list(varargs_items(args), Fixity::FixedSize),
("List", "of") => list(varargs_items(args), Fixity::Immutable),
("Set", "of") => {
let items = varargs_items(args);
let unique = distinct(vm, &items);
if unique.len() != items.len() {
let dup = first_repeat(vm, &items).unwrap_or(Value::Undef);
return Some(Err(Fault::java(
"IllegalArgumentException",
format!("duplicate element: {}", java_str_vm(vm, &dup)),
)));
}
Ok(Value::Obj(heap_alloc(HostObj::Set {
items: unique,
order: Order::Hash,
fixed: Fixity::Immutable,
index: KeyIndex::default(),
})))
}
("Comparator", "isKeyExtractor") if args.len() == 1 => Ok(Value::bool(
closure_meta(&args[0]).is_some_and(|(_, params, _)| params == 1),
)),
("Stream", "of") => Ok(stream_of(varargs_items(args), StreamKind::Ref)),
("Stream" | "IntStream" | "LongStream" | "DoubleStream", "iterate") if args.len() == 3 => {
let mut items = Vec::new();
let mut cur = args[0].clone();
while matches!(
invoke_closure(vm, &args[1], std::slice::from_ref(&cur)),
Value::Bool(true)
) {
items.push(cur.clone());
cur = invoke_closure(vm, &args[2], &[cur]);
}
Ok(stream_of(
items,
if class == "Stream" {
StreamKind::Ref
} else {
primitive_stream_kind(class)
},
))
}
("IntStream" | "LongStream" | "DoubleStream", "of") => {
Ok(stream_of(varargs_items(args), primitive_stream_kind(class)))
}
("IntStream" | "LongStream", "range" | "rangeClosed") if args.len() == 2 => {
let (lo, hi) = (args[0].jint(), args[1].jint());
let hi = if method == "rangeClosed" { hi + 1 } else { hi };
Ok(stream_of(
(lo..hi).map(Value::Int).collect(),
primitive_stream_kind(class),
))
}
("Arrays", "stream") if args.len() == 1 => {
let items = array_items(&args[0]).unwrap_or_default();
let kind = if items.iter().any(|v| matches!(v, Value::Float(_))) {
StreamKind::Double
} else if !items.is_empty() && items.iter().all(|v| matches!(v, Value::Int(_))) {
StreamKind::Int
} else {
StreamKind::Ref
};
Ok(stream_of(items, kind))
}
("Collectors", "toList" | "toUnmodifiableList") if args.is_empty() => {
Ok(collector("toList", Vec::new()))
}
("Collectors", "toSet" | "toUnmodifiableSet") if args.is_empty() => {
Ok(collector("toSet", Vec::new()))
}
("Collectors", "counting") if args.is_empty() => Ok(collector("counting", Vec::new())),
("Collectors", "joining") if args.len() <= 3 => Ok(collector("joining", args.to_vec())),
("Collectors", "toMap") if args.len() == 2 => Ok(collector("toMap", args.to_vec())),
("Collectors", "groupingBy") if args.len() == 1 => {
Ok(collector("groupingBy", args.to_vec()))
}
("Optional", "of") if args.len() == 1 => {
if matches!(args[0], Value::Undef) {
return Some(Err(Fault::java("NullPointerException", String::new())));
}
Ok(optional(Some(args[0].clone())))
}
("Optional", "ofNullable") if args.len() == 1 => Ok(optional(
(!matches!(args[0], Value::Undef)).then(|| args[0].clone()),
)),
("Optional", "empty") if args.is_empty() => Ok(optional(None)),
("Map", "of") if args.len() % 2 == 0 => {
let mut entries: Vec<(Value, Value)> = Vec::with_capacity(args.len() / 2);
for pair in args.chunks(2) {
let (k, v) = (pair[0].clone(), pair[1].clone());
if matches!(k, Value::Undef) || matches!(v, Value::Undef) {
return Some(Err(Fault::java("NullPointerException", String::new())));
}
if entries.iter().any(|(prev, _)| value_eq(prev, &k)) {
return Some(Err(Fault::java(
"IllegalArgumentException",
format!("duplicate key: {}", java_str_vm(vm, &k)),
)));
}
entries.push((k, v));
}
Ok(Value::Obj(heap_alloc(HostObj::Map {
entries,
order: Order::Hash,
fixed: Fixity::Immutable,
index: KeyIndex::default(),
})))
}
("Objects", "equals") if args.len() == 2 => {
Ok(Value::bool(objects_equals(vm, &args[0], &args[1])))
}
("Collections", "sort") if !args.is_empty() => {
let items = match sequence_items(&args[0]) {
Some(i) => i,
None => {
return Some(Err(Fault::internal(
"javars: `Collections.sort` needs a List",
)))
}
};
let cmp = args.get(1).cloned().unwrap_or(Value::Undef);
sort_with(vm, items, &cmp)
.and_then(|sorted| write_list(&args[0], sorted))
.map(|()| Value::Undef)
}
("Collections", "reverse") if args.len() == 1 => {
let mut items = sequence_items(&args[0]).unwrap_or_default();
items.reverse();
write_list(&args[0], items).map(|()| Value::Undef)
}
("Collections", "max") | ("Collections", "min") if matches!(args.len(), 1 | 2) => {
let items = sequence_items(&args[0]).unwrap_or_default();
if items.is_empty() {
return Some(Err(Fault::java("NoSuchElementException", String::new())));
}
let sorted = sort_values(vm, items, args.get(1));
Ok(if method == "max" {
sorted.last().cloned().unwrap_or(Value::Undef)
} else {
sorted.first().cloned().unwrap_or(Value::Undef)
})
}
_ => return None,
})
}
fn varargs_items(args: &[Value]) -> Vec<Value> {
if let [Value::Obj(id)] = args {
let spread = HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Array(items)) => Some(items.clone()),
_ => None,
});
if let Some(items) = spread {
return items;
}
}
args.to_vec()
}
fn write_list(target: &Value, items: Vec<Value>) -> Result<(), Fault> {
let Value::Obj(id) = target else {
return Ok(());
};
write_sequence(*id as usize, items, true)
}
fn static_method(class: &str, method: &str, args: &[Value]) -> Result<Value, Fault> {
let both_int = |a: &Value, b: &Value| {
matches!(deboxed(a), Value::Int(_)) && matches!(deboxed(b), Value::Int(_))
};
match (class, method, args.len()) {
("Math", "abs", 1) => Ok(match &args[0] {
Value::Int(n) => Value::Int(n.wrapping_abs()),
other => Value::float(other.jfloat().abs()),
}),
("Math", "max", 2) => Ok(if both_int(&args[0], &args[1]) {
Value::Int(args[0].jint().max(args[1].jint()))
} else {
Value::float(max_double(args[0].jfloat(), args[1].jfloat()))
}),
("Math", "min", 2) => Ok(if both_int(&args[0], &args[1]) {
Value::Int(args[0].jint().min(args[1].jint()))
} else {
Value::float(min_double(args[0].jfloat(), args[1].jfloat()))
}),
("Math", "pow", 2) => Ok(Value::float(pow_double(args[0].jfloat(), args[1].jfloat()))),
("Math", "sqrt", 1) => Ok(Value::float(args[0].jfloat().sqrt())),
("Math", "floor", 1) => Ok(Value::float(args[0].jfloat().floor())),
("Math", "ceil", 1) => Ok(Value::float(args[0].jfloat().ceil())),
("Math", "round", 1) => Ok(Value::Int(round_double(args[0].jfloat()))),
("Math", "floorDiv", 2) => floor_div(args[0].jint(), args[1].jint()).map(Value::Int),
("Math", "floorMod", 2) => {
let (a, b) = (args[0].jint(), args[1].jint());
floor_div(a, b).map(|q| Value::Int(a.wrapping_sub(q.wrapping_mul(b))))
}
("Math", "addExact", 3) => {
exact_arith(args[0].jint(), args[1].jint(), args[2].jint(), Exact::Add)
}
("Math", "subtractExact", 3) => {
exact_arith(args[0].jint(), args[1].jint(), args[2].jint(), Exact::Sub)
}
("Math", "multiplyExact", 3) => {
exact_arith(args[0].jint(), args[1].jint(), args[2].jint(), Exact::Mul)
}
("Math", "toIntExact", 2) => {
let v = args[0].jint();
match i32::try_from(v) {
Ok(n) => Ok(Value::Int(n.into())),
Err(_) => Err(Fault::java("ArithmeticException", "integer overflow")),
}
}
("Math", "incrementExact", 2) => exact_arith(args[0].jint(), 1, args[1].jint(), Exact::Add),
("Math", "decrementExact", 2) => exact_arith(args[0].jint(), 1, args[1].jint(), Exact::Sub),
("Math", "negateExact", 2) => exact_arith(0, args[0].jint(), args[1].jint(), Exact::Sub),
("Math", "absExact", 2) => {
let (v, width) = (args[0].jint(), args[1].jint());
let min = if width == width::LONG {
i64::MIN
} else {
i64::from(i32::MIN)
};
if v == min {
let name = if width == width::LONG {
"Long.MIN_VALUE"
} else {
"Integer.MIN_VALUE"
};
return Err(Fault::java(
"ArithmeticException",
format!("Overflow to represent absolute value of {name}"),
));
}
Ok(Value::Int(v.abs()))
}
("Math", "divideExact", 3) => exact_divide(
args[0].jint(),
args[1].jint(),
args[2].jint(),
Rounding::Truncate,
),
("Math", "floorDivExact", 3) => exact_divide(
args[0].jint(),
args[1].jint(),
args[2].jint(),
Rounding::Floor,
),
("Math", "ceilDivExact", 3) => exact_divide(
args[0].jint(),
args[1].jint(),
args[2].jint(),
Rounding::Ceil,
),
("Math", "clamp", 4) => math_clamp(&args[0], &args[1], &args[2], args[3].jint()),
("Math", "signum", 1) => Ok(Value::float(match args[0].jfloat() {
f if f > 0.0 => 1.0,
f if f < 0.0 => -1.0,
f => f,
})),
("Math", "toRadians", 1) => Ok(Value::float(args[0].jfloat().to_radians())),
("Math", "toDegrees", 1) => Ok(Value::float(args[0].jfloat().to_degrees())),
("Math", "rint", 1) => Ok(Value::float(args[0].jfloat().round_ties_even())),
("Math", "copySign", 2) => Ok(Value::float(args[0].jfloat().copysign(args[1].jfloat()))),
("Math", "fma", 3) => Ok(Value::float(
args[0].jfloat().mul_add(args[1].jfloat(), args[2].jfloat()),
)),
("Math", "ulp", 1) => Ok(Value::float(double_ulp(args[0].jfloat()))),
("Math", "nextUp", 1) => Ok(Value::float(next_after(args[0].jfloat(), f64::INFINITY))),
("Math", "nextDown", 1) => Ok(Value::float(next_after(
args[0].jfloat(),
f64::NEG_INFINITY,
))),
("Math", "nextAfter", 2) => {
Ok(Value::float(next_after(args[0].jfloat(), args[1].jfloat())))
}
("Integer", "parseInt", 1) if matches!(args[0], Value::Undef) => Err(null_number_fault()),
("Integer", "parseInt", 2) if matches!(args[0], Value::Undef) => Err(null_number_fault()),
("Long", "parseLong", 1) if matches!(args[0], Value::Undef) => Err(null_number_fault()),
("Integer", "parseInt", 1) => parse_int_radix(&args[0].as_str_cow(), 10, true),
("Integer", "parseInt", 2) => {
let radix = args[1].jint();
parse_int_radix(&args[0].as_str_cow(), radix, true)
}
("Long", "parseLong", 1) => parse_int_radix(&args[0].as_str_cow(), 10, false),
("Integer", "valueOf", 1) => match &args[0] {
Value::Str(s) => parse_int_radix(s, 10, true),
Value::Undef => Err(null_number_fault()),
other => Ok(Value::Int(other.jint())),
},
("Integer", "toString", 1) => Ok(Value::str(args[0].jint().to_string())),
("Integer", "toString", 2) => Ok(Value::str(int_to_radix_string(
args[0].jint(),
args[1].jint(),
))),
("Integer", "toBinaryString", 1) => {
Ok(Value::str(format!("{:b}", args[0].jint() as i32 as u32)))
}
("Integer", "toHexString", 1) => {
Ok(Value::str(format!("{:x}", args[0].jint() as i32 as u32)))
}
("Integer", "toOctalString", 1) => {
Ok(Value::str(format!("{:o}", args[0].jint() as i32 as u32)))
}
("Long", "toBinaryString", 1) => Ok(Value::str(format!("{:b}", args[0].jint() as u64))),
("Long", "toHexString", 1) => Ok(Value::str(format!("{:x}", args[0].jint() as u64))),
("Long", "toOctalString", 1) => Ok(Value::str(format!("{:o}", args[0].jint() as u64))),
("Integer" | "Long", "compare", 2) => {
Ok(Value::Int(cmp_to_int(args[0].jint().cmp(&args[1].jint()))))
}
("Integer" | "Long", "max", 2) => Ok(Value::Int(args[0].jint().max(args[1].jint()))),
("Integer" | "Long", "min", 2) => Ok(Value::Int(args[0].jint().min(args[1].jint()))),
("Integer" | "Long", "sum", 2) => {
Ok(Value::Int(args[0].jint().wrapping_add(args[1].jint())))
}
("Integer" | "Long", "signum", 1) => Ok(Value::Int(args[0].jint().signum())),
("Integer" | "Long" | "Double" | "Boolean" | "Character", "hashCode", 1) => {
let v = match class {
"Double" => Value::float(args[0].jfloat()),
"Boolean" => Value::bool(matches!(args[0], Value::Bool(true))),
"Character" => Value::Int(i64::from(char_arg(&args[0]) as u32)),
_ => Value::Int(args[0].jint()),
};
Ok(Value::Int(java_hash(&v).unwrap_or(0).into()))
}
("Float", "hashCode", 1) => Ok(Value::Int(
((args[0].jfloat() as f32).to_bits() as i32).into(),
)),
("Long", "toString", 1) => Ok(Value::str(args[0].jint().to_string())),
("Long", "valueOf", 1) => match &args[0] {
Value::Str(s) => parse_int_radix(s, 10, false),
Value::Undef => Err(null_number_fault()),
other => Ok(Value::Int(other.jint())),
},
("Double" | "Float", "parseDouble" | "parseFloat" | "valueOf", 1)
if matches!(args[0], Value::Undef) =>
{
Err(null_float_parse_fault())
}
("Double", "parseDouble", 1) | ("Double", "valueOf", 1) => {
let s = args[0].as_str_cow();
parse_java_double(&s)
.map(Value::float)
.ok_or_else(|| Fault::java("NumberFormatException", float_format_message(&s)))
}
("Double", "toString", 1) => Ok(Value::str(format_double(args[0].jfloat()))),
("Float", "toString", 1) => Ok(Value::str(format_float(args[0].jfloat() as f32))),
("Float", "parseFloat", 1) | ("Float", "valueOf", 1) => {
let s = args[0].as_str_cow();
parse_java_double(&s)
.map(|f| Value::float(f as f32 as f64))
.ok_or_else(|| Fault::java("NumberFormatException", float_format_message(&s)))
}
("Float", "compare", 2) => Ok(Value::Int(float_compare(
f64::from(args[0].jfloat() as f32),
f64::from(args[1].jfloat() as f32),
))),
("Float", "isNaN", 1) => Ok(Value::bool(args[0].jfloat().is_nan())),
("Float", "isInfinite", 1) => Ok(Value::bool(args[0].jfloat().is_infinite())),
("Double", "compare", 2) => Ok(Value::Int(float_compare(
args[0].jfloat(),
args[1].jfloat(),
))),
("Double", "isNaN", 1) => Ok(Value::bool(args[0].jfloat().is_nan())),
("Double", "isInfinite", 1) => Ok(Value::bool(args[0].jfloat().is_infinite())),
("Character", "isDigit", 1) => Ok(Value::bool(char_arg(&args[0]).is_ascii_digit())),
("Character", "isLetter", 1) => Ok(Value::bool(char_arg(&args[0]).is_alphabetic())),
("Character", "isLetterOrDigit", 1) => {
Ok(Value::bool(char_arg(&args[0]).is_alphanumeric()))
}
("Character", "isWhitespace", 1) => Ok(Value::bool(java_is_whitespace(char_arg(&args[0])))),
("Character", "isUpperCase", 1) => Ok(Value::bool(char_arg(&args[0]).is_uppercase())),
("Character", "isLowerCase", 1) => Ok(Value::bool(char_arg(&args[0]).is_lowercase())),
("Character", "toUpperCase", 1) => Ok(Value::Int(one_to_one_case(
char_arg(&args[0]),
char::to_uppercase,
))),
("Character", "toLowerCase", 1) => Ok(Value::Int(one_to_one_case(
char_arg(&args[0]),
char::to_lowercase,
))),
("Character", "toString", 1) => Ok(Value::str(char_arg(&args[0]).to_string())),
("Character", "getNumericValue", 1) => Ok(Value::Int(
char_arg(&args[0]).to_digit(36).map_or(-1, i64::from),
)),
("Boolean", "parseBoolean", 1) => Ok(Value::bool(
args[0].as_str_cow().eq_ignore_ascii_case("true"),
)),
("String", "valueOf", 1) if matches!(args[0], Value::Str(_)) => Ok(args[0].clone()),
("String", "valueOf" | "copyValueOf", 1) => Ok(Value::str(match array_items(&args[0]) {
Some(items) => items.iter().map(java_str).collect::<String>(),
None => java_str(&args[0]),
})),
("String", "format", _) if !args.is_empty() => {
let fmt = args[0].as_str_cow().into_owned();
java_format(&fmt, &args[1..], &[], None)
}
("String", "join", n) if n >= 2 && matches!(args[0], Value::Undef) => Err(Fault::java(
"NullPointerException",
"Cannot invoke \"java.lang.CharSequence.toString()\" because \"delimiter\" is null",
)),
("String", "join", n) if n >= 2 => {
let sep = args[0].as_str_cow().into_owned();
let parts: Vec<String> = match (sequence_items(&args[1]), n) {
(Some(items), 2) => items.iter().map(java_str).collect(),
_ => args[1..].iter().map(java_str).collect(),
};
Ok(Value::str(parts.join(&sep)))
}
("Boolean", "toString", 1) => Ok(Value::str(java_str(&args[0]))),
("Boolean", "compare", 2) => Ok(Value::Int(cmp_to_int(
args[0].is_truthy().cmp(&args[1].is_truthy()),
))),
("Arrays", "toString", 1) => Ok(Value::str(arrays_to_string(&args[0]))),
("Arrays", "deepToString", 1) => Ok(Value::str(arrays_deep_to_string(&args[0]))),
("Arrays", "sort", 1) => {
array_mutate(&args[0], |a| a.sort_by(natural_cmp))?;
Ok(Value::Undef)
}
("Arrays", "fill", 2) => {
let v = args[1].clone();
array_mutate(&args[0], |a| a.fill(v))?;
Ok(Value::Undef)
}
("Arrays", "equals", 2) => match (array_items(&args[0]), array_items(&args[1])) {
(Some(x), Some(y)) => Ok(Value::bool(
x.len() == y.len()
&& x.iter()
.zip(y.iter())
.all(|(p, q)| natural_cmp(p, q) == std::cmp::Ordering::Equal),
)),
_ => Ok(Value::bool(false)),
},
("Arrays", "copyOf", 2) => {
let items = array_items(&args[0]).unwrap_or_default();
let len = args[1].jint();
if len < 0 {
return Err(Fault::java("NegativeArraySizeException", len.to_string()));
}
let pad = element_default(&items);
let mut out = items;
out.resize(len as usize, pad);
Ok(Value::Obj(heap_alloc(HostObj::Array(out))))
}
("Arrays", "copyOfRange", 3) => {
let items = array_items(&args[0]).unwrap_or_default();
let (from, to) = (args[1].jint(), args[2].jint());
if from > to {
return Err(Fault::java(
"IllegalArgumentException",
format!("{from} > {to}"),
));
}
if from < 0 || from > items.len() as i64 {
return Err(Fault::java("ArrayIndexOutOfBoundsException", String::new()));
}
let (from, to) = (from as usize, to as usize);
let pad = element_default(&items);
let mut out: Vec<Value> = items
.get(from..to.min(items.len()))
.unwrap_or_default()
.to_vec();
out.resize(to - from, pad);
Ok(Value::Obj(heap_alloc(HostObj::Array(out))))
}
("Arrays", "binarySearch", 2) => {
let items = array_items(&args[0]).unwrap_or_default();
Ok(Value::Int(
match items.binary_search_by(|p| natural_cmp(p, &args[1])) {
Ok(i) => i as i64,
Err(i) => -(i as i64) - 1,
},
))
}
("Arrays", "hashCode", 1) => {
let items = array_items(&args[0]).unwrap_or_default();
let h = items.iter().fold(1i32, |acc, e| {
acc.wrapping_mul(31).wrapping_add(java_hash(e).unwrap_or(0))
});
Ok(Value::Int(h as i64))
}
_ => Err(Fault::internal(format!(
"javars: unsupported static method `{class}.{method}` with {} argument(s)",
args.len()
))),
}
}
fn char_last_index_of(hay: &str, needle: &str, from: i64) -> i64 {
let chars: Vec<char> = hay.chars().collect();
let pat: Vec<char> = needle.chars().collect();
let start = from.min(chars.len() as i64 - pat.len() as i64);
if start < 0 {
return -1;
}
if pat.is_empty() {
return start;
}
(0..=start)
.rev()
.find(|&i| chars[i as usize..].starts_with(&pat))
.unwrap_or(-1)
}
fn pattern_fault(msg: &str) -> Fault {
Fault::java("PatternSyntaxException", msg)
}
fn replacement_fault(msg: String) -> Fault {
if msg.starts_with("No group") && !msg.starts_with("No group with name") {
Fault::java("IndexOutOfBoundsException", msg)
} else {
Fault::java("IllegalArgumentException", msg)
}
}
fn engine_fault(msg: String) -> Fault {
Fault::internal(format!("javars: regular expression failed: {msg}"))
}
enum Exact {
Add,
Sub,
Mul,
}
fn exact_arith(a: i64, b: i64, width: i64, op: Exact) -> Result<Value, Fault> {
if width == width::LONG {
let r = match op {
Exact::Add => a.checked_add(b),
Exact::Sub => a.checked_sub(b),
Exact::Mul => a.checked_mul(b),
};
return match r {
Some(v) => Ok(Value::Int(v)),
None => Err(Fault::java("ArithmeticException", "long overflow")),
};
}
let r = match op {
Exact::Add => a + b,
Exact::Sub => a - b,
Exact::Mul => a * b,
};
match i32::try_from(r) {
Ok(n) => Ok(Value::Int(n.into())),
Err(_) => Err(Fault::java("ArithmeticException", "integer overflow")),
}
}
enum Rounding {
Truncate,
Floor,
Ceil,
}
fn exact_divide(a: i64, b: i64, width: i64, round: Rounding) -> Result<Value, Fault> {
if b == 0 {
return Err(Fault::java("ArithmeticException", "/ by zero"));
}
let overflow = || {
Fault::java(
"ArithmeticException",
if width == width::LONG {
"long overflow"
} else {
"integer overflow"
},
)
};
let q = match round {
Rounding::Truncate => a.checked_div(b),
Rounding::Floor => Some(floor_div(a, b)?),
Rounding::Ceil => floor_div(a, b)
.map(|f| {
if a.wrapping_rem(b) != 0 {
f.wrapping_add(1)
} else {
f
}
})
.map(Some)?,
};
let q = q.ok_or_else(overflow)?;
if width == width::LONG {
if a == i64::MIN && b == -1 {
return Err(overflow());
}
return Ok(Value::Int(q));
}
match i32::try_from(q) {
Ok(n) => Ok(Value::Int(n.into())),
Err(_) => Err(overflow()),
}
}
fn math_clamp(value: &Value, min: &Value, max: &Value, width: i64) -> Result<Value, Fault> {
if width == width::INT || width == width::LONG {
let (v, lo, hi) = (value.jint(), min.jint(), max.jint());
if lo > hi {
return Err(Fault::java(
"IllegalArgumentException",
format!("{lo} > {hi}"),
));
}
return Ok(Value::Int(v.max(lo).min(hi)));
}
let (v, lo, hi) = (value.jfloat(), min.jfloat(), max.jfloat());
let render = |x: f64| {
if width == width::FLOAT {
format_float(x as f32)
} else {
format_double(x)
}
};
if lo.is_nan() {
return Err(Fault::java("IllegalArgumentException", "min is NaN"));
}
if hi.is_nan() {
return Err(Fault::java("IllegalArgumentException", "max is NaN"));
}
if float_compare(lo, hi) > 0 {
return Err(Fault::java(
"IllegalArgumentException",
format!("{} > {}", render(lo), render(hi)),
));
}
Ok(Value::float(java_min(java_max(v, lo), hi)))
}
fn java_max(a: f64, b: f64) -> f64 {
if a.is_nan() || b.is_nan() {
return f64::NAN;
}
if float_compare(a, b) >= 0 {
a
} else {
b
}
}
fn java_min(a: f64, b: f64) -> f64 {
if a.is_nan() || b.is_nan() {
return f64::NAN;
}
if float_compare(a, b) <= 0 {
a
} else {
b
}
}
fn floor_div(a: i64, b: i64) -> Result<i64, Fault> {
if b == 0 {
return Err(Fault::java("ArithmeticException", "/ by zero"));
}
let q = a.wrapping_div(b);
Ok(if a.wrapping_rem(b) != 0 && (a ^ b) < 0 {
q.wrapping_sub(1)
} else {
q
})
}
fn java_is_whitespace(c: char) -> bool {
matches!(c,
'\u{09}'..='\u{0D}' | '\u{1C}'..='\u{1F}' | '\u{20}'
| '\u{1680}' | '\u{2000}'..='\u{2006}' | '\u{2008}'..='\u{200A}'
| '\u{205F}' | '\u{3000}'
| '\u{2028}' | '\u{2029}')
}
fn parse_java_double(text: &str) -> Option<f64> {
let s = text.trim_matches(|c: char| c <= ' ');
let (negative, body) = match s.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, s.strip_prefix('+').unwrap_or(s)),
};
if body.is_empty() {
return None;
}
let signed = |v: f64| if negative { -v } else { v };
if body == "NaN" {
return Some(f64::NAN);
}
if body == "Infinity" {
return Some(signed(f64::INFINITY));
}
let digits = match body.as_bytes().last() {
Some(b'f' | b'F' | b'd' | b'D') => &body[..body.len() - 1],
_ => body,
};
if !is_java_decimal_literal(digits) {
return None;
}
digits.parse::<f64>().ok().map(signed)
}
fn null_number_fault() -> Fault {
Fault::java("NumberFormatException", "Cannot parse null string")
}
fn null_float_parse_fault() -> Fault {
Fault::java(
"NullPointerException",
"Cannot invoke \"String.trim()\" because \"in\" is null",
)
}
fn float_format_message(text: &str) -> String {
if text.trim_matches(|c: char| c <= ' ').is_empty() {
"empty String".to_string()
} else {
format!("For input string: \"{text}\"")
}
}
fn is_java_decimal_literal(s: &str) -> bool {
let b = s.as_bytes();
let mut i = 0;
let mut significand_digits = 0;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
significand_digits += 1;
}
if i < b.len() && b[i] == b'.' {
i += 1;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
significand_digits += 1;
}
}
if significand_digits == 0 {
return false;
}
if i < b.len() && (b[i] == b'e' || b[i] == b'E') {
i += 1;
if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
i += 1;
}
let exponent_start = i;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
if i == exponent_start {
return false;
}
}
i == b.len()
}
fn max_double(a: f64, b: f64) -> f64 {
if a.is_nan() {
return a;
}
if a == 0.0 && b == 0.0 && a.is_sign_negative() {
return b;
}
if a >= b {
a
} else {
b
}
}
fn min_double(a: f64, b: f64) -> f64 {
if a.is_nan() {
return a;
}
if a == 0.0 && b == 0.0 && b.is_sign_negative() {
return b;
}
if a <= b {
a
} else {
b
}
}
fn pow_double(a: f64, b: f64) -> f64 {
if b == 0.0 {
return 1.0;
}
if b.is_nan() || (a.abs() == 1.0 && b.is_infinite()) {
return f64::NAN;
}
a.powf(b)
}
fn round_double(a: f64) -> i64 {
const EXP_BIT_MASK: i64 = 0x7FF0_0000_0000_0000u64 as i64;
const SIGNIF_BIT_MASK: i64 = 0x000F_FFFF_FFFF_FFFF;
let long_bits = a.to_bits() as i64;
let biased_exp = (long_bits & EXP_BIT_MASK) >> (53 - 1);
let shift = (53 - 2 + 1023) - biased_exp;
if (shift & -64) == 0 {
let mut r = (long_bits & SIGNIF_BIT_MASK) | (SIGNIF_BIT_MASK + 1);
if long_bits < 0 {
r = -r;
}
((r >> shift) + 1) >> 1
} else {
a as i64
}
}
fn round_float(a: f32) -> i32 {
const EXP_BIT_MASK: i32 = 0x7F80_0000;
const SIGNIF_BIT_MASK: i32 = 0x007F_FFFF;
let int_bits = a.to_bits() as i32;
let biased_exp = (int_bits & EXP_BIT_MASK) >> (24 - 1);
let shift = (24 - 2 + 127) - biased_exp;
if (shift & -32) == 0 {
let mut r = (int_bits & SIGNIF_BIT_MASK) | (SIGNIF_BIT_MASK + 1);
if int_bits < 0 {
r = -r;
}
((r >> shift) + 1) >> 1
} else {
a as i32
}
}
fn float_compare(a: f64, b: f64) -> i64 {
if a < b {
return -1;
}
if a > b {
return 1;
}
let (ab, bb) = (canonical_bits(a), canonical_bits(b));
cmp_to_int(ab.cmp(&bb))
}
fn canonical_bits(v: f64) -> i64 {
if v.is_nan() {
0x7ff8_0000_0000_0000u64 as i64
} else {
v.to_bits() as i64
}
}
fn cmp_to_int(o: std::cmp::Ordering) -> i64 {
match o {
std::cmp::Ordering::Less => -1,
std::cmp::Ordering::Equal => 0,
std::cmp::Ordering::Greater => 1,
}
}
fn one_to_one_case<I: Iterator<Item = char>>(c: char, map: fn(char) -> I) -> i64 {
let mut mapped = map(c);
match (mapped.next(), mapped.next()) {
(Some(m), None) => m as i64,
_ => c as i64,
}
}
fn char_arg(v: &Value) -> char {
match &deboxed(v) {
Value::Int(n) => char::from_u32(*n as u32).unwrap_or('\u{0}'),
other => other.as_str_cow().chars().next().unwrap_or('\u{0}'),
}
}
fn array_items(v: &Value) -> Option<Vec<Value>> {
let Value::Obj(id) = v else {
return None;
};
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Array(a)) => Some(a.clone()),
_ => None,
})
}
fn array_mutate(v: &Value, f: impl FnOnce(&mut Vec<Value>)) -> Result<(), Fault> {
let Value::Obj(id) = v else {
return Err(Fault::java(
"NullPointerException",
"null array".to_string(),
));
};
HEAP.with(|h| match h.borrow_mut().get_mut(*id as usize) {
Some(HostObj::Array(a)) => {
f(a);
Ok(())
}
_ => Err(Fault::java(
"NullPointerException",
"null array".to_string(),
)),
})
}
fn element_default(items: &[Value]) -> Value {
match items.first() {
Some(Value::Int(_)) => Value::Int(0),
Some(Value::Float(_)) => Value::float(0.0),
Some(Value::Bool(_)) => Value::bool(false),
_ => Value::Undef,
}
}
fn arrays_deep_to_string(v: &Value) -> String {
match array_items(v) {
Some(items) => {
let inner: Vec<String> = items.iter().map(arrays_deep_to_string).collect();
format!("[{}]", inner.join(", "))
}
None => java_str(v),
}
}
fn arrays_to_string(v: &Value) -> String {
match v {
Value::Obj(id) => HEAP.with(|h| {
let h = h.borrow();
match h.get(*id as usize) {
Some(HostObj::Array(a)) => {
let inner: Vec<String> = a.iter().map(java_str).collect();
format!("[{}]", inner.join(", "))
}
_ => java_str(v),
}
}),
Value::Undef => "null".to_string(),
_ => java_str(v),
}
}
fn java_format(
fmt: &str,
args: &[Value],
tags: &[&str],
mut vm: Option<&mut VM>,
) -> Result<Value, Fault> {
let mut out = String::new();
let mut chars = fmt.chars().peekable();
let mut argi = 0usize;
while let Some(c) = chars.next() {
if c != '%' {
out.push(c);
continue;
}
let mut spec = String::from("%");
let mut lead = String::new();
while let Some(&d) = chars.peek() {
if d.is_ascii_digit() {
lead.push(d);
spec.push(d);
chars.next();
} else {
break;
}
}
let mut explicit_index: Option<usize> = None;
if chars.peek() == Some(&'$') {
chars.next();
spec.push('$');
explicit_index = lead.parse::<usize>().ok().map(|n| n.saturating_sub(1));
lead.clear();
}
let mut left = false;
let mut zero = false;
let mut plus = false;
let mut group = false;
let mut parens = false;
let mut space = false;
let mut alt = false;
if lead.starts_with('0') {
zero = true;
lead.remove(0);
}
while let Some(&f) = chars.peek() {
match f {
'-' => left = true,
'0' => zero = true,
'+' => plus = true,
',' => group = true,
'(' => parens = true,
' ' => space = true,
'#' => alt = true,
_ => break,
}
spec.push(f);
chars.next();
}
let mut width = lead;
while let Some(&d) = chars.peek() {
if d.is_ascii_digit() {
width.push(d);
spec.push(d);
chars.next();
} else {
break;
}
}
let mut prec: Option<usize> = None;
if chars.peek() == Some(&'.') {
chars.next();
spec.push('.');
let mut p = String::new();
while let Some(&d) = chars.peek() {
if d.is_ascii_digit() {
p.push(d);
spec.push(d);
chars.next();
} else {
break;
}
}
prec = Some(int_format_field(&p, "IllegalFormatPrecisionException")?);
}
let conv = chars.next().ok_or_else(|| {
Fault::java("UnknownFormatConversionException", "Conversion = '%'")
})?;
spec.push(conv);
let width_n: Option<usize> = if width.is_empty() {
None
} else {
Some(int_format_field(&width, "IllegalFormatWidthException")?)
};
let flags = FmtFlags {
left,
alt,
plus,
space,
zero,
group,
parens,
};
check_format_flags(conv, &flags, width_n, prec, &spec)?;
match conv {
'%' => out.push_str(&pad("", "%", "", width_n, left, false)),
'n' => out.push('\n'),
_ => {
let idx = explicit_index.unwrap_or(argi);
let arg = args.get(idx).ok_or_else(|| {
Fault::java(
"MissingFormatArgumentException",
format!("Format specifier '{spec}'"),
)
})?;
if explicit_index.is_none() {
argi += 1;
}
let tag = tags.get(idx).copied().unwrap_or("");
check_conversion(conv, arg, tag)?;
let Rendered {
mut prefix,
mut body,
numeric,
} = format_conversion(conv, arg, prec, &flags, tag, vm.as_deref_mut())?;
if group && numeric {
body = group_digits(&body);
}
let mut suffix = "";
if parens && numeric && prefix == "-" {
prefix = "(".to_string();
suffix = ")";
}
out.push_str(&pad(&prefix, &body, suffix, width_n, left, zero && numeric));
}
}
}
Ok(Value::str(out))
}
fn boxed_class(tag: &str, v: &Value) -> Option<&'static str> {
if matches!(v, Value::Undef) {
return None;
}
Some(match tag {
"int" | "Integer" => "java.lang.Integer",
"long" | "Long" => "java.lang.Long",
"short" | "Short" => "java.lang.Short",
"byte" | "Byte" => "java.lang.Byte",
"char" | "Character" => "java.lang.Character",
"double" | "Double" => "java.lang.Double",
"float" | "Float" => "java.lang.Float",
"boolean" | "Boolean" => "java.lang.Boolean",
"String" => "java.lang.String",
_ => match v {
Value::Int(_) => "java.lang.Integer",
Value::Float(_) => "java.lang.Double",
Value::Bool(_) => "java.lang.Boolean",
Value::Str(_) => "java.lang.String",
_ => return None,
},
})
}
fn check_conversion(conv: char, arg: &Value, tag: &str) -> Result<(), Fault> {
let integral = [
"java.lang.Integer",
"java.lang.Long",
"java.lang.Short",
"java.lang.Byte",
];
let ok = |cls: &str| -> bool {
match conv {
'd' | 'x' | 'X' | 'o' => integral.contains(&cls),
'f' | 'e' | 'E' | 'g' | 'G' | 'a' | 'A' => {
matches!(cls, "java.lang.Double" | "java.lang.Float")
}
'c' | 'C' => {
cls == "java.lang.Character"
|| integral.contains(&cls)
}
_ => true,
}
};
let Some(cls) = boxed_class(tag, arg) else {
return Ok(());
};
if ok(cls) {
return Ok(());
}
if matches!(conv, 'c' | 'C') && tag.is_empty() {
return Ok(());
}
Err(Fault::java(
"IllegalFormatConversionException",
format!("{conv} != {cls}"),
))
}
fn b_format(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let tag_blob = args
.last()
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default();
let tags: Vec<&str> = if tag_blob.is_empty() {
Vec::new()
} else {
tag_blob.split('\x1f').collect()
};
let fmt = args
.first()
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default();
let body = &args[1..args.len().saturating_sub(1)];
match java_format(&fmt, body, &tags, Some(&mut *vm)) {
Ok(v) => v,
Err(f) => raise(vm, f),
}
}
struct FmtFlags {
left: bool,
alt: bool,
plus: bool,
space: bool,
zero: bool,
group: bool,
parens: bool,
}
impl FmtFlags {
fn spell(&self, want: &[char]) -> String {
[
('-', self.left),
('#', self.alt),
('+', self.plus),
(' ', self.space),
('0', self.zero),
(',', self.group),
('(', self.parens),
]
.iter()
.filter(|(c, set)| *set && want.contains(c))
.map(|(c, _)| *c)
.collect()
}
}
fn check_format_flags(
conv: char,
f: &FmtFlags,
width: Option<usize>,
prec: Option<usize>,
spec: &str,
) -> Result<(), Fault> {
let mismatch = |want: &[char]| -> Result<(), Fault> {
let bad = f.spell(want);
if bad.is_empty() {
return Ok(());
}
Err(Fault::java(
"FormatFlagsConversionMismatchException",
format!("Conversion = {conv}, Flags = {bad}"),
))
};
let bad_flags = |want: &[char]| -> Fault {
Fault::java(
"IllegalFormatFlagsException",
format!("Flags = '{}'", f.spell(want)),
)
};
let missing_width = || Fault::java("MissingFormatWidthException", spec.to_string());
let bad_precision = || {
Fault::java(
"IllegalFormatPrecisionException",
prec.unwrap_or(0).to_string(),
)
};
const ALL: &[char] = &['-', '#', '+', ' ', '0', ',', '('];
if conv == 'n' {
if !f.spell(ALL).is_empty() {
return Err(bad_flags(ALL));
}
if let Some(w) = width {
return Err(Fault::java("IllegalFormatWidthException", w.to_string()));
}
if let Some(p) = prec {
return Err(Fault::java(
"IllegalFormatPrecisionException",
p.to_string(),
));
}
return Ok(());
}
if conv == '%' {
if f.left && width.is_none() {
return Err(missing_width());
}
return Ok(());
}
match conv {
's' | 'S' | 'b' | 'B' | 'h' | 'H' => {
let mut bad: Vec<char> = vec!['+', ' ', '0', ',', '('];
if !matches!(conv, 's' | 'S') {
bad.push('#');
}
mismatch(&bad)?;
if f.left && width.is_none() {
return Err(missing_width());
}
if matches!(conv, 's' | 'S') {
mismatch(&['#'])?;
}
}
'c' | 'C' => {
if prec.is_some() {
return Err(bad_precision());
}
mismatch(&['#', '+', ' ', '0', ',', '('])?;
if f.left && width.is_none() {
return Err(missing_width());
}
}
_ => {
if width.is_none() && (f.left || f.zero) {
return Err(missing_width());
}
if f.plus && f.space {
return Err(bad_flags(&['+', ' ']));
}
if f.left && f.zero {
return Err(bad_flags(&['-', '0']));
}
match conv {
'd' => {
mismatch(&['#'])?;
if prec.is_some() {
return Err(bad_precision());
}
}
'o' | 'x' | 'X' => {
mismatch(&[','])?;
mismatch(&['+', ' ', '('])?;
if prec.is_some() {
return Err(bad_precision());
}
}
'e' | 'E' => mismatch(&[','])?,
'g' | 'G' => mismatch(&['#'])?,
_ => {}
}
}
}
Ok(())
}
struct Rendered {
prefix: String,
body: String,
numeric: bool,
}
impl Rendered {
fn text(body: String) -> Self {
Rendered {
prefix: String::new(),
body,
numeric: false,
}
}
}
fn format_conversion(
conv: char,
arg: &Value,
prec: Option<usize>,
flags: &FmtFlags,
tag: &str,
vm: Option<&mut VM>,
) -> Result<Rendered, Fault> {
let pos_sign = || {
if flags.plus {
"+"
} else if flags.space {
" "
} else {
""
}
};
let float_sign = |x: f64| {
if x.is_sign_negative() {
"-".to_string()
} else {
pos_sign().to_string()
}
};
if matches!(arg, Value::Undef) && !matches!(conv, 'b' | 'B') {
let mut s: String = "null".chars().take(prec.unwrap_or(4)).collect();
if conv.is_ascii_uppercase() {
s = s.to_uppercase();
}
return Ok(Rendered::text(s));
}
let num = |prefix: String, body: String| Rendered {
prefix,
body,
numeric: true,
};
match conv {
'd' => {
let n = arg.jint();
Ok(num(
if n < 0 {
"-".to_string()
} else {
pos_sign().to_string()
},
n.unsigned_abs().to_string(),
))
}
'f' => {
let x = arg.jfloat();
let mut body = fixed_half_up(x, prec.unwrap_or(6));
if flags.alt && !body.contains('.') {
body.push('.');
}
Ok(num(float_sign(x), body))
}
's' | 'S' => {
let mut s = match vm {
Some(vm) => java_str_vm(vm, arg),
None => java_str(arg),
};
if conv == 'S' {
s = s.to_uppercase();
}
if let Some(p) = prec {
s = s.chars().take(p).collect();
}
Ok(Rendered::text(s))
}
'b' | 'B' => {
let mut s = java_bool(arg).to_string();
if conv == 'B' {
s = s.to_uppercase();
}
if let Some(p) = prec {
s = s.chars().take(p).collect();
}
Ok(Rendered::text(s))
}
'x' | 'X' | 'o' => {
let bits = radix_bits(arg, tag);
let body = match conv {
'x' => format!("{bits:x}"),
'X' => format!("{bits:X}"),
_ => format!("{bits:o}"),
};
let prefix = if flags.alt {
match conv {
'x' => "0x",
'X' => "0X",
_ => "0",
}
} else {
""
};
Ok(num(prefix.to_string(), body))
}
'c' => Ok(Rendered::text(match arg {
Value::Int(n) => char::from_u32(*n as u32).unwrap_or('\u{fffd}').to_string(),
other => java_str(other),
})),
'e' | 'E' => {
let x = arg.jfloat();
let s = sci_notation(x, prec.unwrap_or(6));
let body = s.strip_prefix('-').unwrap_or(&s).to_string();
let body = if conv == 'E' {
body.to_uppercase()
} else {
body
};
Ok(num(float_sign(x), body))
}
'g' | 'G' => {
let x = arg.jfloat();
let p = prec.unwrap_or(6).max(1);
let s = if x != 0.0 && (x.abs() < 1e-4 || x.abs() >= 10f64.powi(p as i32)) {
sci_notation(x, p - 1)
} else {
let exp = if x == 0.0 {
0
} else {
x.abs().log10().floor() as i32
};
fixed_half_up(x, (p as i32 - 1 - exp).max(0) as usize)
};
let body = s.strip_prefix('-').unwrap_or(&s).to_string();
let body = if conv == 'G' {
body.to_uppercase()
} else {
body
};
Ok(num(float_sign(x), body))
}
'h' | 'H' => {
let s = match arg {
Value::Undef => "null".to_string(),
other => format!("{:x}", java_hash(other).unwrap_or(0) as u32),
};
let mut s = if conv == 'H' { s.to_uppercase() } else { s };
if let Some(p) = prec {
s = s.chars().take(p).collect();
}
Ok(Rendered::text(s))
}
other => Err(Fault::java(
"UnknownFormatConversionException",
format!("Conversion = '{other}'"),
)),
}
}
fn null_string_argument(method: &str, args: &[Value]) -> Result<(), Fault> {
if !matches!(args.first(), Some(Value::Undef)) {
return Ok(());
}
let detail = match method {
"compareTo" => "Cannot read field \"value\" because \"anotherString\" is null",
"compareToIgnoreCase" => "Cannot read field \"value\" because \"s2\" is null",
"contains" => "Cannot invoke \"java.lang.CharSequence.toString()\" because \"s\" is null",
"replace" => {
"Cannot invoke \"java.lang.CharSequence.toString()\" because \"target\" is null"
}
"indexOf" | "lastIndexOf" => "Cannot invoke \"String.coder()\" because \"str\" is null",
"startsWith" => "Cannot invoke \"String.length()\" because \"prefix\" is null",
"endsWith" => "Cannot invoke \"String.length()\" because \"suffix\" is null",
"concat" => "Cannot invoke \"String.isEmpty()\" because \"str\" is null",
"split" | "matches" | "replaceAll" | "replaceFirst" => {
"Cannot invoke \"String.length()\" because \"regex\" is null"
}
_ => return Ok(()),
};
Err(Fault::java("NullPointerException", detail))
}
fn int_format_field(digits: &str, class: &'static str) -> Result<usize, Fault> {
match digits.parse::<i32>() {
Ok(n) if n >= 0 => Ok(n as usize),
_ => Err(Fault::java(class, i32::MIN.to_string())),
}
}
fn fixed_half_up(x: f64, prec: usize) -> String {
if !x.is_finite() {
return java_str(&Value::float(x));
}
let mut exact = format!("{}", x.abs());
if !exact.contains('.') {
exact.push('.');
}
let point = exact.find('.').unwrap_or(exact.len());
let cut = point + if prec == 0 { 0 } else { prec + 1 };
while exact.len() <= point + prec + 1 {
exact.push('0');
}
let round_up = exact[cut..]
.chars()
.find(char::is_ascii_digit)
.is_some_and(|c| c >= '5');
let mut digits: Vec<u8> = exact[..cut].bytes().collect();
if round_up {
let mut i = digits.len();
loop {
if i == 0 {
digits.insert(0, b'1');
break;
}
i -= 1;
match digits[i] {
b'.' => continue,
b'9' => digits[i] = b'0',
d => {
digits[i] = d + 1;
break;
}
}
}
}
String::from_utf8(digits).unwrap_or_default()
}
fn sci_notation(x: f64, prec: usize) -> String {
let neg = if x.is_sign_negative() { "-" } else { "" };
if x == 0.0 {
return format!("{neg}{:.*}e+00", prec, 0.0);
}
let (digits, exp) = sci_digits_half_up(x.abs(), prec);
let mantissa = if prec == 0 {
digits
} else {
format!("{}.{}", &digits[..1], &digits[1..])
};
format!(
"{neg}{mantissa}e{}{:02}",
if exp < 0 { '-' } else { '+' },
exp.abs()
)
}
fn sci_digits_half_up(x: f64, prec: usize) -> (String, i32) {
let expanded = format!("{:e}", x);
let (mantissa, exp) = expanded.split_once('e').unwrap_or((expanded.as_str(), "0"));
let mut exp: i32 = exp.parse().unwrap_or(0);
let all: Vec<u8> = mantissa
.bytes()
.filter(u8::is_ascii_digit)
.map(|b| b - b'0')
.collect();
let keep = prec + 1;
let mut digits: Vec<u8> = all.iter().copied().take(keep).collect();
digits.resize(keep, 0);
if all.get(keep).is_some_and(|d| *d >= 5) {
let mut i = digits.len();
loop {
if i == 0 {
digits.insert(0, 1);
digits.pop();
exp += 1;
break;
}
i -= 1;
if digits[i] == 9 {
digits[i] = 0;
} else {
digits[i] += 1;
break;
}
}
}
(digits.iter().map(|d| (d + b'0') as char).collect(), exp)
}
fn group_digits(s: &str) -> String {
let (sign, rest) = match s.strip_prefix(['-', '+']) {
Some(r) => (&s[..1], r),
None => ("", s),
};
let (int_part, frac) = match rest.find('.') {
Some(i) => (&rest[..i], &rest[i..]),
None => (rest, ""),
};
let digits: Vec<char> = int_part.chars().collect();
let mut grouped = String::new();
for (i, c) in digits.iter().enumerate() {
if i > 0 && (digits.len() - i) % 3 == 0 {
grouped.push(',');
}
grouped.push(*c);
}
format!("{sign}{grouped}{frac}")
}
fn java_bool(v: &Value) -> bool {
match v {
Value::Bool(b) => *b,
Value::Undef => false,
_ => true,
}
}
fn radix_bits(arg: &Value, tag: &str) -> u64 {
let n = arg.jint();
match tag {
"byte" | "Byte" => n as u8 as u64,
"short" | "Short" => n as u16 as u64,
"long" | "Long" => n as u64,
"int" | "Integer" => n as i32 as u32 as u64,
_ if i32::try_from(n).is_ok() => n as i32 as u32 as u64,
_ => n as u64,
}
}
fn pad(
prefix: &str,
body: &str,
suffix: &str,
width: Option<usize>,
left: bool,
zero: bool,
) -> String {
let joined = || format!("{prefix}{body}{suffix}");
let w = match width {
Some(w) => w,
None => return joined(),
};
let len = prefix.chars().count() + body.chars().count() + suffix.chars().count();
if len >= w {
return joined();
}
let fill = w - len;
if left {
format!("{prefix}{body}{suffix}{}", " ".repeat(fill))
} else if zero {
format!("{prefix}{}{body}{suffix}", "0".repeat(fill))
} else {
format!("{}{prefix}{body}{suffix}", " ".repeat(fill))
}
}
fn parse_int_radix(s: &str, radix: i64, int_width: bool) -> Result<Value, Fault> {
let nfe = |m: String| Fault::java("NumberFormatException", m);
if radix < 2 {
return Err(nfe(format!("radix {radix} less than Character.MIN_RADIX")));
}
if radix > 36 {
return Err(nfe(format!(
"radix {radix} greater than Character.MAX_RADIX"
)));
}
let bad = || {
if radix == 10 {
nfe(format!("For input string: \"{s}\""))
} else {
nfe(format!("For input string: \"{s}\" under radix {radix}"))
}
};
let n = i64::from_str_radix(s, radix as u32).map_err(|_| bad())?;
if int_width && i32::try_from(n).is_err() {
return Err(bad());
}
Ok(Value::Int(n))
}
fn int_to_radix_string(n: i64, radix: i64) -> String {
if !(2..=36).contains(&radix) {
return n.to_string();
}
let radix = radix as u64;
if n == 0 {
return "0".to_string();
}
let neg = n < 0;
let mut v = (n as i128).unsigned_abs();
let mut digits = Vec::new();
while v > 0 {
let d = (v % radix as u128) as u32;
digits.push(std::char::from_digit(d, radix as u32).unwrap());
v /= radix as u128;
}
if neg {
digits.push('-');
}
digits.iter().rev().collect()
}
pub fn install_debug(vm: &mut VM) {
install(vm);
vm.register_builtin(DBG_LINE, b_dbg_line);
}
fn b_dbg_line(vm: &mut VM, _argc: u8) -> Value {
crate::dap::on_debug_line(vm);
Value::Undef
}
fn b_println(vm: &mut VM, argc: u8) -> Value {
print_args(vm, argc, true, false)
}
fn b_print(vm: &mut VM, argc: u8) -> Value {
print_args(vm, argc, false, false)
}
fn b_eprintln(vm: &mut VM, argc: u8) -> Value {
print_args(vm, argc, true, true)
}
fn b_eprint(vm: &mut VM, argc: u8) -> Value {
print_args(vm, argc, false, true)
}
fn b_stringify(vm: &mut VM, _argc: u8) -> Value {
let v = vm.stack.pop().unwrap_or(Value::Undef);
Value::str(java_str_vm(vm, &v))
}
fn print_args(vm: &mut VM, argc: u8, newline: bool, err: bool) -> Value {
use std::io::Write;
let mut vals = Vec::with_capacity(argc as usize);
for _ in 0..argc {
vals.push(vm.stack.pop().unwrap_or(Value::Undef));
}
vals.reverse();
if let Some(f) = vals.iter().find_map(stale_view) {
return raise(vm, f);
}
let text: String = if any_user_tostring(vm) {
let text: String = vals.iter().map(|v| java_str_vm(vm, v)).collect();
if PENDING.with(|p| p.borrow().is_some()) {
return Value::Undef;
}
text
} else {
vals.iter().map(java_str).collect()
};
let stdout = std::io::stdout();
let stderr = std::io::stderr();
let mut lock: Box<dyn Write> = if err {
Box::new(stderr.lock())
} else {
Box::new(stdout.lock())
};
let _ = write!(lock, "{text}");
if newline {
let _ = writeln!(lock);
}
Value::Undef
}
pub fn java_str(v: &Value) -> String {
match v {
Value::Bool(b) => if *b { "true" } else { "false" }.to_string(),
Value::Float(f) => format_double(*f),
Value::Undef => "null".to_string(),
Value::Obj(id) => obj_default_str(*id),
other => other.as_str_cow().into_owned(),
}
}
pub fn java_str_vm(vm: &mut VM, v: &Value) -> String {
match v {
Value::Obj(id) if any_user_tostring(vm) => obj_str_vm(vm, *id),
other => java_str(other),
}
}
const TOSTRING_SUFFIX: &str = "#toString#";
const EQUALS_SUFFIX: &str = "#equals#Object";
const HASHCODE_SUFFIX: &str = "#hashCode#";
thread_local! {
static USER_TOSTRING: Cell<Option<bool>> = const { Cell::new(None) };
static USER_EQUALS: Cell<Option<bool>> = const { Cell::new(None) };
static MEMBER_ENTRY: RefCell<HashMap<(&'static str, String), Option<usize>>> =
RefCell::new(HashMap::new());
}
fn any_user_tostring(vm: &VM) -> bool {
cached_flag(&USER_TOSTRING, vm, TOSTRING_SUFFIX)
}
fn any_user_equals(vm: &VM) -> bool {
cached_flag(&USER_EQUALS, vm, EQUALS_SUFFIX)
}
fn cached_flag(
cell: &'static std::thread::LocalKey<Cell<Option<bool>>>,
vm: &VM,
suffix: &str,
) -> bool {
cell.with(|c| match c.get() {
Some(b) => b,
None => {
let b = vm.chunk.names.iter().any(|n| n.contains(suffix));
c.set(Some(b));
b
}
})
}
fn tostring_entry(vm: &VM, class: &str) -> Option<usize> {
member_entry(vm, class, TOSTRING_SUFFIX)
}
fn equals_entry(vm: &VM, class: &str) -> Option<usize> {
member_entry(vm, class, EQUALS_SUFFIX)
}
fn member_entry(vm: &VM, class: &str, suffix: &'static str) -> Option<usize> {
let cache_key = (suffix, class.to_string());
if let Some(hit) = MEMBER_ENTRY.with(|t| t.borrow().get(&cache_key).copied()) {
return hit;
}
let mut stack = vec![class.to_string()];
let mut seen = std::collections::HashSet::new();
let mut found = None;
while let Some(cur) = stack.pop() {
if !seen.insert(cur.clone()) {
continue;
}
let key = format!("{cur}{suffix}");
if let Some(i) = vm.chunk.names.iter().position(|n| *n == key) {
if let Some(entry) = vm.chunk.find_sub(i as u16) {
found = Some(entry);
break;
}
}
SUPERS.with(|s| {
if let Some(sups) = s.borrow().get(&cur) {
stack.extend(sups.iter().cloned());
}
});
}
MEMBER_ENTRY.with(|t| t.borrow_mut().insert(cache_key, found));
found
}
enum RenderShape {
Instance(String, Option<String>),
Sequence(Vec<Value>),
Entries(Vec<(Value, Value)>),
Opaque,
}
fn obj_str_vm(vm: &mut VM, id: u32) -> String {
let shape = HEAP.with(|h| {
let h = h.borrow();
match h.get(id as usize) {
Some(HostObj::Instance { class, fields }) => RenderShape::Instance(
class.clone(),
fields
.get(crate::ast::ENUM_NAME)
.filter(|n| !matches!(n, Value::Undef))
.map(|n| n.as_str_cow().into_owned()),
),
Some(HostObj::List { items, .. }) => RenderShape::Sequence(items.clone()),
Some(HostObj::Set { items, order, .. }) => RenderShape::Sequence(
present_order(items, *order)
.into_iter()
.map(|i| items[i].clone())
.collect(),
),
Some(HostObj::Map { entries, order, .. }) => {
let keys: Vec<Value> = entries.iter().map(|(k, _)| k.clone()).collect();
RenderShape::Entries(
present_order(&keys, *order)
.into_iter()
.map(|i| entries[i].clone())
.collect(),
)
}
_ => RenderShape::Opaque,
}
});
match shape {
RenderShape::Opaque if is_sublist(id as usize) => {
let items = sublist_items(id as usize)
.and_then(Result::ok)
.unwrap_or_default();
render_sequence_vm(vm, &items)
}
RenderShape::Opaque => obj_default_str(id),
RenderShape::Instance(class, enum_name) => match tostring_entry(vm, &class) {
Some(entry) => run_tostring(vm, entry, id),
None => enum_name.unwrap_or_else(|| obj_default_str(id)),
},
RenderShape::Sequence(items) => render_sequence_vm(vm, &items),
RenderShape::Entries(entries) => {
let body: Vec<String> = entries
.iter()
.map(|(k, v)| format!("{}={}", java_str_vm(vm, k), java_str_vm(vm, v)))
.collect();
format!("{{{}}}", body.join(", "))
}
}
}
fn render_sequence_vm(vm: &mut VM, items: &[Value]) -> String {
let body: Vec<String> = items.iter().map(|e| java_str_vm(vm, e)).collect();
format!("[{}]", body.join(", "))
}
fn run_tostring(vm: &mut VM, entry: usize, id: u32) -> String {
if PENDING.with(|p| p.borrow().is_some()) {
return String::new();
}
let stack_base = vm.stack.len();
vm.stack.push(Value::Obj(id));
let out = run_sub(vm, entry, stack_base);
java_str(&out)
}
fn obj_default_str(id: u32) -> String {
let handle = Value::Obj(id);
if let (Some(class), Some(v)) = (box_class(&handle), unboxed(&handle)) {
return match class {
"Character" => char::from_u32(as_i64(&v) as u32)
.map(String::from)
.unwrap_or_default(),
"Float" => java_str(&float_to_string(&v)),
_ => java_str(&v),
};
}
HEAP.with(|h| {
let h = h.borrow();
match h.get(id as usize) {
Some(HostObj::Instance { class, fields }) => match fields.get(crate::ast::ENUM_NAME) {
Some(n) if !matches!(n, Value::Undef) => n.as_str_cow().into_owned(),
_ => format!("{}@{id:x}", qualified_or_binary(class)),
},
Some(HostObj::Array(_)) => format!("[@{id:x}"),
Some(HostObj::Builder { s, .. }) => s.clone(),
Some(HostObj::List { items, .. }) => render_sequence(items),
Some(HostObj::SubList { .. }) => render_sequence(
&sublist_items(id as usize)
.and_then(Result::ok)
.unwrap_or_default(),
),
Some(HostObj::Set { items, order, .. }) => render_set(items, *order),
Some(HostObj::Map { entries, order, .. }) => render_map(entries, *order),
Some(HostObj::Closure { .. }) => format!("<lambda>@{id:x}"),
Some(HostObj::Boxed) => unreachable!("a box is answered above"),
Some(HostObj::Iterator { .. }) => format!("<iterator>@{id:x}"),
Some(HostObj::Optional { class, value }) => match value {
Some(v) => format!("{class}[{}]", java_str(v)),
None => format!("{class}.empty"),
},
Some(HostObj::Stream { .. }) => format!("<stream>@{id:x}"),
Some(HostObj::Collector { .. }) => format!("<collector>@{id:x}"),
None => format!("(obj:{id})"),
}
})
}
fn format_double(f: f64) -> String {
let sci = format!("{f:e}");
if f.is_finite() && f != 0.0 && shortest_is_one_digit(&sci) {
if let Some((digits, exp)) = widen_exact(f) {
let sign = if f < 0.0 { "-" } else { "" };
return format_ieee(
f,
format!("{sign}{}", plain_form(&digits, exp)),
format!("{sign}{}", sci_form(&digits, exp)),
);
}
}
format_ieee(f, format!("{f}"), sci)
}
fn shortest_is_one_digit(sci: &str) -> bool {
sci.split_once('e')
.is_some_and(|(mantissa, _)| mantissa.bytes().filter(u8::is_ascii_digit).count() == 1)
}
fn widen_exact(v: f64) -> Option<(String, i32)> {
let exact = format!("{:.*e}", 18, v.abs());
let (mantissa, exp) = exact.split_once('e')?;
let exp: i32 = exp.parse().ok()?;
let d: Vec<u8> = mantissa
.bytes()
.filter(u8::is_ascii_digit)
.map(|b| b - b'0')
.collect();
let mut two = u32::from(d[0]) * 10 + u32::from(d[1]);
let beyond_half = d[2] > 5 || (d[2] == 5 && d[3..].iter().any(|&x| x != 0));
if beyond_half || (d[2] == 5 && two % 2 == 1) {
two += 1;
}
let (two, exp) = if two == 100 {
(10, exp + 1)
} else {
(two, exp)
};
if two % 10 == 0 {
return None;
}
Some((two.to_string(), exp))
}
fn format_float(f: f32) -> String {
if !f.is_finite() || f == 0.0 {
return format_ieee(f as f64, String::new(), String::new());
}
let (digits, exp10) = java_shortest_f32(f);
let (digits, exp10) = if digits.len() == 1 {
widen_exact(f64::from(f)).unwrap_or((digits, exp10))
} else {
(digits, exp10)
};
let sign = if f < 0.0 { "-" } else { "" };
format_ieee(
f as f64,
format!("{sign}{}", plain_form(&digits, exp10)),
format!("{sign}{}", sci_form(&digits, exp10)),
)
}
fn java_shortest_f32(v: f32) -> (String, i32) {
let sci = format!("{v:e}");
let (mantissa, exp) = sci.split_once('e').unwrap_or((sci.as_str(), "0"));
let exp: i32 = exp.parse().unwrap_or(0);
let neg = mantissa.starts_with('-');
let digits: String = mantissa.chars().filter(|c| c.is_ascii_digit()).collect();
let here = rebuild(&digits, exp, neg);
let delta = here - f64::from(v);
if delta == 0.0 {
return (digits, exp);
}
let toward = if (delta > 0.0) != neg { -1 } else { 1 };
let Some((other_digits, other_exp)) = step_last_digit(&digits, exp, toward) else {
return (digits, exp);
};
let other = rebuild(&other_digits, other_exp, neg);
if other as f32 != v {
return (digits, exp);
}
let (d_here, d_other) = (delta.abs(), (other - f64::from(v)).abs());
let tie = (d_here - d_other).abs() <= (d_here + d_other) * 1e-9;
if tie {
let even = |d: &str| d.as_bytes().last().is_some_and(|b| (b - b'0') % 2 == 0);
return if even(&digits) {
(digits, exp)
} else {
(other_digits, other_exp)
};
}
if d_other < d_here {
(other_digits, other_exp)
} else {
(digits, exp)
}
}
fn rebuild(digits: &str, exp: i32, neg: bool) -> f64 {
let mut s = String::new();
if neg {
s.push('-');
}
s.push_str(&digits[..1]);
if digits.len() > 1 {
s.push('.');
s.push_str(&digits[1..]);
}
s.push('e');
s.push_str(&exp.to_string());
s.parse().unwrap_or(f64::NAN)
}
fn step_last_digit(digits: &str, exp: i32, step: i8) -> Option<(String, i32)> {
let mut d: Vec<u8> = digits.bytes().map(|b| b - b'0').collect();
let mut i = d.len();
if step > 0 {
loop {
if i == 0 {
let mut out = vec![1u8];
out.resize(d.len(), 0);
return Some((to_digits(&out), exp + 1));
}
i -= 1;
if d[i] < 9 {
d[i] += 1;
break;
}
d[i] = 0;
}
} else {
loop {
if i == 0 {
return Some((("9").repeat(d.len()), exp - 1));
}
i -= 1;
if d[i] > 0 {
d[i] -= 1;
break;
}
d[i] = 9;
}
}
Some((to_digits(&d), exp))
}
fn to_digits(d: &[u8]) -> String {
d.iter().map(|b| (b + b'0') as char).collect()
}
fn plain_form(digits: &str, exp: i32) -> String {
if exp < 0 {
return format!("0.{}{digits}", "0".repeat((-exp - 1) as usize));
}
let int_len = exp as usize + 1;
if digits.len() <= int_len {
format!("{digits}{}.0", "0".repeat(int_len - digits.len()))
} else {
format!("{}.{}", &digits[..int_len], &digits[int_len..])
}
}
fn sci_form(digits: &str, exp: i32) -> String {
if digits.len() > 1 {
format!("{}.{}e{exp}", &digits[..1], &digits[1..])
} else {
format!("{digits}e{exp}")
}
}
fn format_ieee(f: f64, plain: String, sci: String) -> String {
if f.is_nan() {
return "NaN".to_string();
}
if f.is_infinite() {
return if f < 0.0 { "-Infinity" } else { "Infinity" }.to_string();
}
if f == 0.0 {
return if f.is_sign_negative() { "-0.0" } else { "0.0" }.to_string();
}
let mag = f.abs();
if (1e-3..1e7).contains(&mag) {
return if plain.contains('.') {
plain
} else {
format!("{plain}.0")
};
}
let (mantissa, exp) = match sci.split_once('e') {
Some((m, e)) => (m, e),
None => return sci,
};
let mantissa = if mantissa.contains('.') {
mantissa.to_string()
} else {
format!("{mantissa}.0")
};
format!("{mantissa}E{exp}")
}
fn is_java_number(v: &Value) -> bool {
matches!(v, Value::Int(_) | Value::Float(_))
|| unboxed(v).is_some_and(|inner| matches!(inner, Value::Int(_) | Value::Float(_)))
}
fn java_numeric(op: NumOp, a: &Value, b: &Value) -> Result<Value, String> {
if let (Value::Int(x), Value::Int(y)) = (a, b) {
let (x, y) = (*x, *y);
return match op {
NumOp::Add => Ok(Value::Int(x.wrapping_add(y))),
NumOp::Sub => Ok(Value::Int(x.wrapping_sub(y))),
NumOp::Mul => Ok(Value::Int(x.wrapping_mul(y))),
NumOp::Div | NumOp::Mod if y == 0 => {
Err("java.lang.ArithmeticException: / by zero".to_string())
}
NumOp::Div => Ok(Value::Int(x.wrapping_div(y))),
NumOp::Mod => Ok(Value::Int(x.wrapping_rem(y))),
NumOp::Eq => Ok(Value::bool(x == y)),
NumOp::Ne => Ok(Value::bool(x != y)),
NumOp::Lt => Ok(Value::bool(x < y)),
NumOp::Gt => Ok(Value::bool(x > y)),
NumOp::Le => Ok(Value::bool(x <= y)),
NumOp::Ge => Ok(Value::bool(x >= y)),
NumOp::Neg => Ok(Value::Int(x.wrapping_neg())),
NumOp::Pow => Err(NO_POW.to_string()),
};
}
let (x, y) = (as_f64(a), as_f64(b));
match op {
NumOp::Add => Ok(Value::float(x + y)),
NumOp::Sub => Ok(Value::float(x - y)),
NumOp::Mul => Ok(Value::float(x * y)),
NumOp::Div => Ok(Value::float(x / y)),
NumOp::Mod => Ok(Value::float(x % y)),
NumOp::Eq => Ok(Value::bool(x == y)),
NumOp::Ne => Ok(Value::bool(x != y)),
NumOp::Lt => Ok(Value::bool(x < y)),
NumOp::Gt => Ok(Value::bool(x > y)),
NumOp::Le => Ok(Value::bool(x <= y)),
NumOp::Ge => Ok(Value::bool(x >= y)),
NumOp::Neg => Ok(Value::float(-x)),
NumOp::Pow => Err(NO_POW.to_string()),
}
}
const NO_POW: &str = "javars: Java has no `**` operator";
pub fn numeric_hook(op: NumOp, a: &Value, b: &Value) -> Result<Value, String> {
if op == NumOp::Neg && is_java_number(a) {
return java_numeric(op, &deboxed(a), &Value::Int(0));
}
let both_handles = matches!((a, b), (Value::Obj(_), Value::Obj(_)));
let one_handle = matches!(a, Value::Obj(_)) || matches!(b, Value::Obj(_));
let unboxing_pair = one_handle && !both_handles && is_java_number(a) && is_java_number(b);
if one_handle && !unboxing_pair {
match op {
NumOp::Eq => return Ok(Value::bool(ref_eq(a, b))),
NumOp::Ne => return Ok(Value::bool(!ref_eq(a, b))),
_ => {}
}
}
if let (Value::Str(x), Value::Str(y)) = (a, b) {
match op {
NumOp::Eq => return Ok(Value::bool(std::sync::Arc::ptr_eq(x, y))),
NumOp::Ne => return Ok(Value::bool(!std::sync::Arc::ptr_eq(x, y))),
_ => {}
}
}
if is_java_number(a) && is_java_number(b) {
return java_numeric(op, &deboxed(a), &deboxed(b));
}
match op {
NumOp::Add => Ok(Value::str(format!("{}{}", java_str(a), java_str(b)))),
NumOp::Eq => Ok(Value::bool(java_str(a) == java_str(b))),
NumOp::Ne => Ok(Value::bool(java_str(a) != java_str(b))),
NumOp::Lt => Ok(Value::bool(java_str(a) < java_str(b))),
NumOp::Gt => Ok(Value::bool(java_str(a) > java_str(b))),
NumOp::Le => Ok(Value::bool(java_str(a) <= java_str(b))),
NumOp::Ge => Ok(Value::bool(java_str(a) >= java_str(b))),
NumOp::Sub | NumOp::Mul | NumOp::Div | NumOp::Mod | NumOp::Pow => Err(format!(
"javars: operator `{op:?}` is not defined for operands `{}` and `{}`",
java_str(a),
java_str(b)
)),
NumOp::Neg => Err(format!(
"javars: unary `-` is not defined for `{}`",
java_str(a)
)),
}
}
fn b_div(vm: &mut VM, _argc: u8) -> Value {
let b = vm.stack.pop().unwrap_or(Value::Undef);
let a = vm.stack.pop().unwrap_or(Value::Undef);
Value::float(as_f64(&a) / as_f64(&b))
}
fn b_idiv(vm: &mut VM, _argc: u8) -> Value {
let b = as_i64(&vm.stack.pop().unwrap_or(Value::Undef));
let a = as_i64(&vm.stack.pop().unwrap_or(Value::Undef));
Value::Int(if b == 0 { 0 } else { a.wrapping_div(b) })
}
fn b_ushr(vm: &mut VM, _argc: u8) -> Value {
let width = as_i64(&vm.stack.pop().unwrap_or(Value::Undef));
let count = as_i64(&vm.stack.pop().unwrap_or(Value::Undef)) as u32;
let value = as_i64(&vm.stack.pop().unwrap_or(Value::Undef));
if width == 32 {
Value::Int(((value as u32) >> count) as i32 as i64)
} else {
Value::Int(((value as u64) >> count) as i64)
}
}
fn b_cast(vm: &mut VM, _argc: u8) -> Value {
let ty = vm.stack.pop().unwrap_or(Value::Undef);
let ty = ty.as_str_cow().into_owned();
let v = vm.stack.pop().unwrap_or(Value::Undef);
match ty.as_str() {
"int" => Value::Int(match &v {
Value::Float(f) => *f as i32 as i64,
other => as_i64(other) as i32 as i64,
}),
"long" => Value::Int(match &v {
Value::Float(f) => *f as i64,
other => as_i64(other),
}),
"short" => Value::Int(cast_to_i64(&v) as i16 as i64),
"byte" => Value::Int(cast_to_i64(&v) as i8 as i64),
"char" => Value::Int(i64::from(cast_to_i64(&v) as u16)),
"double" => Value::float(as_f64(&v)),
"float" => Value::float(as_f64(&v) as f32 as f64),
_ => v,
}
}
fn b_chr_str(vm: &mut VM, _argc: u8) -> Value {
let v = vm.stack.pop().unwrap_or(Value::Undef);
match &v {
Value::Obj(_) => match array_items(&v) {
Some(items) => Value::Obj(heap_alloc(HostObj::Array(
items.iter().map(char_to_string).collect(),
))),
None => v,
},
_ => char_to_string(&v),
}
}
fn char_to_string(v: &Value) -> Value {
match v {
Value::Int(n) => Value::str(char::from_u32(*n as u32).unwrap_or('\u{fffd}').to_string()),
other => other.clone(),
}
}
fn b_f32(vm: &mut VM, _argc: u8) -> Value {
let v = vm.stack.pop().unwrap_or(Value::Undef);
match &v {
Value::Float(f) => Value::float(*f as f32 as f64),
Value::Int(n) => Value::float(*n as f32 as f64),
_ => v,
}
}
fn b_f32_arith(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let a = args.first().map(JavaNumeric::jfloat).unwrap_or(0.0) as f32;
let b = args.get(1).map(JavaNumeric::jfloat).unwrap_or(0.0) as f32;
let r = match args.get(2).map(JavaNumeric::jint).unwrap_or(f32_op::ADD) {
f32_op::SUB => a - b,
f32_op::MUL => a * b,
f32_op::DIV => a / b,
f32_op::REM => a % b,
_ => a + b,
};
Value::float(r as f64)
}
fn b_f32_round(vm: &mut VM, _argc: u8) -> Value {
let v = vm.stack.pop().unwrap_or(Value::Undef);
Value::Int(round_float(v.jfloat() as f32).into())
}
fn b_f32_str(vm: &mut VM, _argc: u8) -> Value {
let v = vm.stack.pop().unwrap_or(Value::Undef);
let v = unboxed(&v).unwrap_or(v);
match &v {
Value::Obj(_) => match array_items(&v) {
Some(items) => Value::Obj(heap_alloc(HostObj::Array(
items.iter().map(float_to_string).collect(),
))),
None => v,
},
_ => float_to_string(&v),
}
}
fn float_to_string(v: &Value) -> Value {
match v {
Value::Float(f) => Value::str(format_float(*f as f32)),
other => other.clone(),
}
}
fn b_checkcast(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let value = args.first().cloned().unwrap_or(Value::Undef);
let target = args
.get(1)
.map(|v| v.as_str_cow().into_owned())
.unwrap_or_default();
let Some(runtime) = value_class(&value) else {
return value;
};
if cast_allowed(&runtime, &target, &value) {
return value;
}
let Some(from) = binary_name(&runtime, &value) else {
return value;
};
raise(
vm,
Fault::java("ClassCastException", cast_message(&from, &target)),
);
Value::Undef
}
fn binary_name(class: &str, v: &Value) -> Option<String> {
let len = || sequence_len(v).unwrap_or(0);
Some(match class {
"[]" => return None,
"List$fixed" => "java.util.Arrays$ArrayList".to_string(),
"List$immutable" => match len() {
1 | 2 => "java.util.ImmutableCollections$List12".to_string(),
_ => "java.util.ImmutableCollections$ListN".to_string(),
},
"Set$immutable" => match len() {
1 | 2 => "java.util.ImmutableCollections$Set12".to_string(),
_ => "java.util.ImmutableCollections$SetN".to_string(),
},
"Map$immutable" => match len() {
1 => "java.util.ImmutableCollections$Map1".to_string(),
_ => "java.util.ImmutableCollections$MapN".to_string(),
},
"List$sub" => match sublist_root_fixity(v) {
Some(Fixity::Mutable) => "java.util.ArrayList$SubList".to_string(),
Some(Fixity::FixedSize) => "java.util.AbstractList$RandomAccessSubList".to_string(),
Some(Fixity::Immutable) => "java.util.ImmutableCollections$SubList".to_string(),
None => return None,
},
other => crate::prelude::qualified_throwable(other).unwrap_or_else(|| jdk_name(other)),
})
}
fn sequence_len(v: &Value) -> Option<usize> {
let Value::Obj(id) = v else { return None };
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::List { items, .. }) | Some(HostObj::Set { items, .. }) => Some(items.len()),
Some(HostObj::Map { entries, .. }) => Some(entries.len()),
_ => None,
})
}
fn sublist_root_fixity(v: &Value) -> Option<Fixity> {
let Value::Obj(id) = v else { return None };
HEAP.with(|h| {
let h = h.borrow();
let mut cur = *id as usize;
for _ in 0..64 {
match h.get(cur) {
Some(HostObj::SubList { parent, .. }) => cur = *parent as usize,
Some(HostObj::List { fixed, .. }) => return Some(*fixed),
_ => return None,
}
}
None
})
}
fn cast_allowed(runtime: &str, target: &str, value: &Value) -> bool {
if target == "Object" || runtime == target {
return true;
}
if is_subclass_of(runtime, target) {
return true;
}
match runtime {
"Integer" => matches!(target, "Long" | "Short" | "Byte" | "Character"),
"Double" => target == "Float",
"String" => target == "Character" && value.as_str_cow().chars().count() == 1,
"ArrayList" => target == "LinkedList",
_ => false,
}
}
fn cast_message(from: &str, target: &str) -> String {
let qual = |n: &str| crate::prelude::qualified_throwable(n).unwrap_or_else(|| jdk_name(n));
let (r, t) = (from.to_string(), qual(target));
let head = format!("class {r} cannot be cast to class {t}");
if r.starts_with("java.") && t.starts_with("java.") {
format!("{head} ({r} and {t} are in module java.base of loader 'bootstrap')")
} else {
head
}
}
pub fn is_checkable_cast_target(ty: &str) -> bool {
CHECKABLE_CAST_TARGETS.contains(&ty)
}
const CHECKABLE_CAST_TARGETS: &[&str] = &[
"String",
"Integer",
"Long",
"Short",
"Byte",
"Double",
"Float",
"Boolean",
"Character",
"Number",
"CharSequence",
"Comparable",
"Cloneable",
"Iterable",
"Enum",
"Record",
"Serializable",
"List",
"ArrayList",
"LinkedList",
"Collection",
"SequencedCollection",
"AbstractCollection",
"AbstractList",
"RandomAccess",
"Set",
"HashSet",
"LinkedHashSet",
"TreeSet",
"SortedSet",
"NavigableSet",
"SequencedSet",
"AbstractSet",
"Map",
"HashMap",
"LinkedHashMap",
"TreeMap",
"SortedMap",
"NavigableMap",
"SequencedMap",
"AbstractMap",
];
fn jdk_name(n: &str) -> String {
match n {
"String"
| "Integer"
| "Long"
| "Short"
| "Byte"
| "Double"
| "Float"
| "Boolean"
| "Character"
| "Number"
| "CharSequence"
| "Comparable"
| "Cloneable"
| "Iterable"
| "Enum"
| "Record"
| "Object"
| "StringBuilder"
| "StringBuffer"
| "AbstractStringBuilder"
| "Appendable" => {
format!("java.lang.{n}")
}
"Serializable" => "java.io.Serializable".to_string(),
"List"
| "ArrayList"
| "LinkedList"
| "Set"
| "HashSet"
| "LinkedHashSet"
| "TreeSet"
| "SortedSet"
| "NavigableSet"
| "SequencedSet"
| "SequencedCollection"
| "Collection"
| "Map"
| "HashMap"
| "LinkedHashMap"
| "TreeMap"
| "SortedMap"
| "NavigableMap"
| "SequencedMap"
| "AbstractCollection"
| "AbstractList"
| "AbstractSet"
| "AbstractMap"
| "RandomAccess" => format!("java.util.{n}"),
other => qualified_or_binary(other),
}
}
fn cast_to_i64(v: &Value) -> i64 {
match unboxed(v).as_ref().unwrap_or(v) {
Value::Float(f) => *f as i64,
other => as_i64(other),
}
}
fn as_i64(v: &Value) -> i64 {
if let Some(inner) = unboxed(v) {
return as_i64(&inner);
}
match v {
Value::Int(i) => *i,
Value::Float(f) => *f as i64,
Value::Bool(b) => i64::from(*b),
other => {
let s = other.as_str_cow();
let mut chars = s.chars();
match (chars.next(), chars.next()) {
(Some(c), None) => c as i64,
_ => s.parse::<i64>().unwrap_or(0),
}
}
}
}
fn as_f64(v: &Value) -> f64 {
if let Some(inner) = unboxed(v) {
return as_f64(&inner);
}
match v {
Value::Int(i) => *i as f64,
Value::Float(f) => *f,
Value::Bool(b) => {
if *b {
1.0
} else {
0.0
}
}
other => other.as_str_cow().parse::<f64>().unwrap_or(f64::NAN),
}
}
#[cfg(test)]
mod cast_target_tables {
use super::*;
#[test]
fn castable_targets_are_closed_over_the_supertype_graph() {
let mut missing = Vec::new();
for t in CHECKABLE_CAST_TARGETS {
for sup in jdk_supers(t) {
if !is_checkable_cast_target(sup) {
missing.push(format!("{t} -> {sup}"));
}
}
}
assert!(
missing.is_empty(),
"supertypes reachable from a checkable target but not checkable \
themselves (the cast would decline to check them):\n {}",
missing.join("\n ")
);
}
#[test]
fn the_internal_shape_names_are_unwritable_but_still_carry_supertypes() {
for internal in [
"[]",
"List$immutable",
"List$fixed",
"List$sub",
"Set$immutable",
"Map$immutable",
"Iterator$of",
"Stream$of",
"Collector$of",
] {
assert!(
!is_checkable_cast_target(internal),
"`{internal}` is not a legal Java type name and must not be a cast target"
);
assert!(
!jdk_supers(internal).is_empty(),
"`{internal}` carries no supertypes, so a value wearing it reaches nothing"
);
}
}
#[test]
fn object_is_not_a_checkable_target() {
assert!(!is_checkable_cast_target("Object"));
}
}