use fusevm::{NumOp, Value, VM};
use std::cell::RefCell;
use std::collections::HashMap;
pub const GPRINTLN: u16 = 800;
pub const GPRINT: u16 = 801;
pub const GPRINTF: u16 = 802;
pub const GEPRINTLN: u16 = 803;
pub const GEPRINT: u16 = 804;
pub const GFFI_COMPILE: u16 = 805;
pub const GFFI_CALL: u16 = 806;
pub const DBG_LINE: u16 = 807;
pub const GMAKE: u16 = 810;
pub const GSLICE_LIT: u16 = 811;
pub const GMAP_LIT: u16 = 812;
pub const GINDEX_GET: u16 = 813;
pub const GINDEX_SET: u16 = 814;
pub const GLEN: u16 = 815;
pub const GCAP: u16 = 816;
pub const GAPPEND: u16 = 817;
pub const GDELETE: u16 = 818;
pub const GSTRUCT_NEW: u16 = 820;
pub const GFIELD_GET: u16 = 821;
pub const GFIELD_SET: u16 = 822;
pub const GSTRUCT_COPY: u16 = 823;
pub const GSTRUCT_BIND: u16 = 857;
pub const GWRITE_FD: u16 = 858;
pub const GRANGE_KEYS: u16 = 824;
pub const GTYPEOF: u16 = 825;
pub const GMIN: u16 = 826;
pub const GMAX: u16 = 827;
pub const GCLOSURE_NEW: u16 = 828;
pub const GCLOSURE_GET: u16 = 829;
pub const GCLOSURE_NAMEIDX: u16 = 819;
pub const GDEFER_ENTER: u16 = 881;
pub const GDEFER_PUSH: u16 = 882;
pub const GDEFER_LEN: u16 = 883;
pub const GDEFER_POP: u16 = 884;
pub const GDEFER_LEAVE: u16 = 885;
pub const GPANIC: u16 = 886;
pub const GPANIC_ACTIVE: u16 = 887;
pub const GRECOVER: u16 = 888;
pub const GPANIC_FINISH: u16 = 889;
pub const GDEFER_PARK: u16 = 961;
pub const GDEFER_UNPARK: u16 = 962;
pub const GCHAN_VAL: u16 = 963;
pub const GCHAN_OK: u16 = 964;
pub const GARRAY_COPY: u16 = 965;
pub const GLIT_EXTEND: u16 = 966;
pub const GARRAY_TAG: u16 = 967;
pub const GELEM_TAG: u16 = 968;
pub const GNAMED_BOX: u16 = 969;
pub const GIFACE_EQ: u16 = 970;
pub const GSPREAD: u16 = 971;
pub const GCELL_NEW: u16 = 890;
pub const GCELL_GET: u16 = 891;
pub const GCELL_SET: u16 = 892;
pub const GSPRINTF: u16 = 893;
pub const GSPRINT: u16 = 894;
pub const GSPRINTLN: u16 = 895;
pub const GSLICE_SUB: u16 = 896;
pub const GSET_PANIC_MODE: u16 = 897;
pub const GIDIV: u16 = 898;
pub const GIMOD: u16 = 899;
pub const GCONV: u16 = 900;
pub const GTYPETAG: u16 = 901;
pub const GASSERT: u16 = 902;
pub const GRANGE_VAL: u16 = 903;
pub const GCOPY: u16 = 904;
pub const GMAP_GET2: u16 = 905;
pub const GAPPEND_SPREAD: u16 = 906;
pub const GDYNDIV: u16 = 950;
pub const GPTR_MARK: u16 = 955;
pub const GPTR_TO: u16 = 859;
pub const GDEREF_SET: u16 = 990;
pub const GREG_METHODS: u16 = 952;
pub const GIFACE_OK: u16 = 953;
pub const GASSERT_IFACE: u16 = 954;
pub const GFDIV: u16 = 951;
pub const GF32_BOX: u16 = 957;
pub const GF32_ARITH: u16 = 958;
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 GU64_BOX: u16 = 959;
pub const GU64_ARITH: u16 = 960;
pub mod u64_op {
pub const DIV: i64 = 0;
pub const MOD: i64 = 1;
pub const SHR: i64 = 2;
pub const LT: i64 = 3;
pub const LE: i64 = 4;
pub const GT: i64 = 5;
pub const GE: i64 = 6;
pub const TOFLOAT: i64 = 7;
}
pub const GNIL_OF: u16 = 956;
pub fn install(vm: &mut VM) {
vm.register_builtin(GPRINTLN, b_println);
vm.register_builtin(GPRINT, b_print);
vm.register_builtin(GPRINTF, b_printf);
vm.register_builtin(GEPRINTLN, b_eprintln);
vm.register_builtin(GEPRINT, b_eprint);
vm.register_builtin(GFFI_COMPILE, b_ffi_compile);
vm.register_builtin(GFFI_CALL, b_ffi_call);
vm.register_builtin(GMAKE, b_make);
vm.register_builtin(GSLICE_LIT, b_slice_lit);
vm.register_builtin(GMAP_LIT, b_map_lit);
vm.register_builtin(GINDEX_GET, b_index_get);
vm.register_builtin(GINDEX_SET, b_index_set);
vm.register_builtin(GLEN, b_len);
vm.register_builtin(GCAP, b_cap);
vm.register_builtin(GAPPEND, b_append);
vm.register_builtin(GDELETE, b_delete);
vm.register_builtin(GSTRUCT_NEW, b_struct_new);
vm.register_builtin(GFIELD_GET, b_field_get);
vm.register_builtin(GFIELD_SET, b_field_set);
vm.register_builtin(GSTRUCT_COPY, b_struct_copy);
vm.register_builtin(GSTRUCT_BIND, b_struct_bind);
vm.register_builtin(GWRITE_FD, b_write_fd);
vm.register_builtin(GARRAY_COPY, b_array_copy);
vm.register_builtin(GLIT_EXTEND, b_lit_extend);
vm.register_builtin(GARRAY_TAG, b_array_tag);
vm.register_builtin(GELEM_TAG, b_elem_tag);
vm.register_builtin(GNAMED_BOX, b_named_box);
vm.register_builtin(GSPREAD, b_spread);
vm.register_builtin(GIFACE_EQ, b_iface_eq);
vm.register_builtin(GRANGE_KEYS, b_range_keys);
vm.register_builtin(GTYPEOF, b_typeof);
vm.register_builtin(GMIN, b_min);
vm.register_builtin(GMAX, b_max);
vm.register_builtin(GCLOSURE_NEW, b_closure_new);
vm.register_builtin(GCLOSURE_GET, b_closure_get);
vm.register_builtin(GCLOSURE_NAMEIDX, b_closure_nameidx);
vm.register_builtin(GDEFER_ENTER, b_defer_enter);
vm.register_builtin(GDEFER_PUSH, b_defer_push);
vm.register_builtin(GDEFER_LEN, b_defer_len);
vm.register_builtin(GDEFER_POP, b_defer_pop);
vm.register_builtin(GDEFER_LEAVE, b_defer_leave);
vm.register_builtin(GDEFER_PARK, b_defer_park);
vm.register_builtin(GDEFER_UNPARK, b_defer_unpark);
vm.register_builtin(GCHAN_VAL, b_chan_val);
vm.register_builtin(GCHAN_OK, b_chan_ok);
vm.register_builtin(GPANIC, b_panic);
vm.register_builtin(GPANIC_ACTIVE, b_panic_active);
vm.register_builtin(GRECOVER, b_recover);
vm.register_builtin(GPANIC_FINISH, b_panic_finish);
vm.register_builtin(GCELL_NEW, b_cell_new);
vm.register_builtin(GCELL_GET, b_cell_get);
vm.register_builtin(GCELL_SET, b_cell_set);
vm.register_builtin(GSPRINTF, b_sprintf);
vm.register_builtin(GSPRINT, b_sprint);
vm.register_builtin(GSPRINTLN, b_sprintln);
vm.register_builtin(GSLICE_SUB, b_slice_sub);
vm.register_builtin(GSET_PANIC_MODE, b_set_panic_mode);
vm.register_builtin(GIDIV, b_idiv);
vm.register_builtin(GIMOD, b_imod);
vm.register_builtin(GCONV, b_conv);
vm.register_builtin(GTYPETAG, b_typetag);
vm.register_builtin(GASSERT, b_assert);
vm.register_builtin(GRANGE_VAL, b_range_val);
vm.register_builtin(GCOPY, b_copy);
vm.register_builtin(GMAP_GET2, b_map_get2);
vm.register_builtin(GAPPEND_SPREAD, b_append_spread);
vm.register_builtin(GDYNDIV, b_dyndiv);
vm.register_builtin(GFDIV, b_fdiv);
vm.register_builtin(GPTR_MARK, b_ptr_mark);
vm.register_builtin(GPTR_TO, b_ptr_to);
vm.register_builtin(GDEREF_SET, b_deref_set);
vm.register_builtin(GNIL_OF, b_nil_of);
vm.register_builtin(GF32_BOX, b_f32_box);
vm.register_builtin(GF32_ARITH, b_f32_arith);
vm.register_builtin(GU64_BOX, b_u64_box);
vm.register_builtin(GU64_ARITH, b_u64_arith);
vm.register_builtin(GREG_METHODS, b_reg_methods);
vm.register_builtin(GIFACE_OK, b_iface_ok);
vm.register_builtin(GASSERT_IFACE, b_assert_iface);
stdlib::install(vm);
}
thread_local! {
static METHOD_SETS: RefCell<std::collections::HashMap<String, Vec<String>>> =
RefCell::new(std::collections::HashMap::new());
}
fn b_reg_methods(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let ty = args.first().map(go_str).unwrap_or_default();
let methods: Vec<String> = args
.get(1)
.map(go_str)
.unwrap_or_default()
.split(',')
.filter(|m| !m.is_empty())
.map(str::to_string)
.collect();
METHOD_SETS.with(|m| m.borrow_mut().insert(ty, methods));
Value::Undef
}
fn missing_method(v: &Value, want: &str) -> Option<String> {
let tag = type_tag_of(v);
METHOD_SETS.with(|m| {
let m = m.borrow();
let have = m.get(&tag);
want.split(',')
.filter(|w| !w.is_empty())
.find(|w| !have.is_some_and(|h| h.iter().any(|x| x == w)))
.map(str::to_string)
})
}
fn b_iface_ok(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let v = args.first().cloned().unwrap_or(Value::Undef);
let want = args.get(1).map(go_str).unwrap_or_default();
Value::bool(missing_method(&v, &want).is_none())
}
fn b_assert_iface(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let v = args.first().cloned().unwrap_or(Value::Undef);
let want = args.get(1).map(go_str).unwrap_or_default();
let display = args.get(2).map(go_str).unwrap_or_default();
match missing_method(&v, &want) {
None => v,
Some(m) => {
let msg = if matches!(v, Value::Undef) {
format!("interface conversion: interface is nil, not {display}")
} else {
let name = m.split('/').next().unwrap_or(&m);
format!(
"interface conversion: {} is not {display}: missing method {name}",
go_type_name(&v)
)
};
plain_panic(vm, msg);
Value::Undef
}
}
}
fn b_assert(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let v = args.first().cloned().unwrap_or(Value::Undef);
let want = args.get(1).map(go_str).unwrap_or_default();
let got = type_tag_of(&v);
if want.is_empty() || want == got {
v
} else {
plain_panic(
vm,
format!("interface conversion: interface {{}} is {got}, not {want}"),
);
Value::Undef
}
}
fn type_tag_of(v: &Value) -> String {
match v {
Value::Int(_) => "int".to_string(),
Value::Float(_) => "float64".to_string(),
Value::Str(_) => "string".to_string(),
Value::Bool(_) => "bool".to_string(),
Value::Obj(id) => HEAP.with(|h| match h.borrow().get(follow(*id) as usize) {
Some(HostObj::Struct { type_name, .. }) => type_name.clone(),
Some(HostObj::Slice { .. }) | Some(HostObj::SliceView { .. }) => "[]".to_string(),
Some(HostObj::Map(_)) => "map".to_string(),
Some(HostObj::Nil { kind, .. }) => match kind {
NilKind::Slice => "[]".to_string(),
NilKind::Map => "map".to_string(),
},
Some(HostObj::Closure { .. }) => "func".to_string(),
_ => "nil".to_string(),
}),
_ => "nil".to_string(),
}
}
fn b_typetag(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
Value::str(type_tag_of(args.first().unwrap_or(&Value::Undef)))
}
fn b_conv(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let v = args.first().cloned().unwrap_or(Value::Undef);
let ty = args.get(1).map(go_str).unwrap_or_default();
match ty.as_str() {
"int" | "int64" | "uint" | "uint64" | "uintptr" => Value::Int(to_int_wide(&v)),
"int8" => Value::Int(to_int_wide(&v) as i8 as i64),
"int16" => Value::Int(to_int_wide(&v) as i16 as i64),
"int32" | "rune" => Value::Int(to_int_wide(&v) as i32 as i64),
"uint8" | "byte" => Value::Int(to_int_wide(&v) as u8 as i64),
"uint16" => Value::Int(to_int_wide(&v) as u16 as i64),
"uint32" => Value::Int(to_int_wide(&v) as u32 as i64),
"float32" => Value::Float(v.to_float() as f32 as f64),
"float64" => Value::Float(v.to_float()),
"bool" => Value::bool(v.is_truthy()),
"string" => conv_string(&v),
"[]byte" => match &v {
Value::Str(s) => {
let elems = s.bytes().map(|b| Value::Int(b as i64)).collect();
Value::Obj(heap_alloc(HostObj::slice(elems)))
}
_ => v,
},
"[]rune" => match &v {
Value::Str(s) => {
let elems = s.chars().map(|c| Value::Int(c as i64)).collect();
Value::Obj(heap_alloc(HostObj::slice(elems)))
}
_ => v,
},
_ => v,
}
}
fn to_int_wide(v: &Value) -> i64 {
match v {
Value::Float(f) => *f as i64,
other => other.to_int(),
}
}
fn conv_string(v: &Value) -> Value {
match v {
Value::Str(_) => v.clone(),
Value::Int(n) => {
let s = char::from_u32(*n as u32)
.map(|c| c.to_string())
.unwrap_or_else(|| "\u{FFFD}".to_string());
Value::str(s)
}
Value::Obj(id) => {
if let Some((_, _, len)) = slice_backing(*id) {
let elems: Vec<i64> = (0..len)
.filter_map(|i| slice_get(*id, i))
.map(|e| e.to_int())
.collect();
let all_bytes = elems.iter().all(|&e| (0..=255).contains(&e));
let has_high = elems.iter().any(|&e| e >= 128);
if all_bytes && has_high {
let bytes: Vec<u8> = elems.iter().map(|&e| e as u8).collect();
if let Ok(s) = std::str::from_utf8(&bytes) {
return Value::str(s.to_string());
}
}
let s: String = elems
.iter()
.filter_map(|&e| char::from_u32(e as u32))
.collect();
Value::str(s)
} else {
v.clone()
}
}
_ => Value::str(go_str(v)),
}
}
fn b_idiv(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let a = args.first().map(Value::to_int).unwrap_or(0);
let b = args.get(1).map(Value::to_int).unwrap_or(0);
if b == 0 {
runtime_panic(vm, "integer divide by zero");
return Value::Int(0);
}
Value::Int(a.wrapping_div(b))
}
fn b_dyndiv(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let a = args.first().cloned().unwrap_or(Value::Undef);
let b = args.get(1).cloned().unwrap_or(Value::Undef);
match (&a, &b) {
(Value::Int(x), Value::Int(y)) => {
if *y == 0 {
runtime_panic(vm, "integer divide by zero");
return Value::Int(0);
}
Value::Int(x.wrapping_div(*y))
}
_ => Value::Float(a.to_float() / b.to_float()),
}
}
fn b_fdiv(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let a = args.first().map(Value::to_float).unwrap_or(0.0);
let b = args.get(1).map(Value::to_float).unwrap_or(0.0);
Value::Float(a / b)
}
fn b_imod(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let a = args.first().map(Value::to_int).unwrap_or(0);
let b = args.get(1).map(Value::to_int).unwrap_or(0);
if b == 0 {
runtime_panic(vm, "integer divide by zero");
return Value::Int(0);
}
Value::Int(a.wrapping_rem(b))
}
fn b_slice_sub(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let recv = args.first().cloned().unwrap_or(Value::Undef);
let lo_raw = args.get(1).map(Value::to_int).unwrap_or(-1);
let hi_raw = args.get(2).map(Value::to_int).unwrap_or(-1);
let max_raw = args.get(3).map(Value::to_int).unwrap_or(-1);
match recv {
Value::Obj(id) => {
let Some((backing, base, len)) = slice_backing(id) else {
return Value::Undef;
};
let cap = slice_cap(id).unwrap_or(len) as i64;
let len = len as i64;
let lo = if lo_raw < 0 { 0 } else { lo_raw }.clamp(0, cap) as usize;
let hi = if hi_raw < 0 { len } else { hi_raw }.clamp(0, cap) as usize;
let hi = hi.max(lo);
let mx = if max_raw < 0 { cap } else { max_raw }.clamp(0, cap) as usize;
let mx = mx.max(hi);
Value::Obj(heap_alloc(HostObj::SliceView {
backing,
offset: base + lo,
len: hi - lo,
cap: mx - lo,
}))
}
Value::Str(s) => {
let bytes = s.as_bytes();
let len = bytes.len() as i64;
let lo = if lo_raw < 0 { 0 } else { lo_raw }.clamp(0, len) as usize;
let hi = if hi_raw < 0 { len } else { hi_raw }.clamp(0, len) as usize;
let slice = bytes.get(lo..hi.max(lo)).unwrap_or(&[]);
Value::str(String::from_utf8_lossy(slice).into_owned())
}
_ => Value::Undef,
}
}
fn b_sprintf(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
Value::str(sprintf(&args))
}
fn b_sprint(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
Value::str(go_print_spacing(&args))
}
fn b_sprintln(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let text: Vec<String> = args.iter().map(go_str).collect();
Value::str(format!("{}\n", text.join(" ")))
}
fn b_cell_new(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let v = args.into_iter().next().unwrap_or(Value::Undef);
Value::Obj(heap_alloc(HostObj::Cell(v)))
}
fn b_cell_get(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
match args.first() {
Some(Value::Obj(id)) => HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Cell(v)) => v.clone(),
_ => Value::Undef,
}),
_ => Value::Undef,
}
}
fn b_cell_set(vm: &mut VM, argc: u8) -> Value {
let mut args = pop_args(vm, argc);
let cell = args.pop().unwrap_or(Value::Undef);
let value = args.pop().unwrap_or(Value::Undef);
if let Value::Obj(id) = cell {
HEAP.with(|h| {
if let Some(HostObj::Cell(slot)) = h.borrow_mut().get_mut(id as usize) {
*slot = value;
}
});
}
Value::Undef
}
fn b_panic(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let v = args.into_iter().next().unwrap_or(Value::Undef);
PANIC.with(|p| *p.borrow_mut() = Some(v));
Value::Undef
}
fn b_panic_active(_vm: &mut VM, _argc: u8) -> Value {
Value::bool(PANIC.with(|p| p.borrow().is_some()))
}
fn b_recover(vm: &mut VM, _argc: u8) -> Value {
PARKED.with(|p| {
let mut parked = p.borrow_mut();
let Some(top) = parked.last_mut() else {
return Value::Undef;
};
if top.recovered || vm.frames.len() != top.depth + DEFERRED_BODY_DEPTH {
return Value::Undef;
}
match top.val.take() {
Some(v) => {
top.recovered = true;
v
}
None => Value::Undef,
}
})
}
fn b_defer_park(vm: &mut VM, _argc: u8) -> Value {
let val = PANIC.with(|p| p.borrow_mut().take());
PARKED.with(|p| {
p.borrow_mut().push(Park {
val,
depth: vm.frames.len(),
recovered: false,
})
});
Value::Undef
}
pub fn chan_closed_sentinel() -> Value {
CHAN_CLOSED.with(|c| {
c.borrow_mut()
.get_or_insert_with(|| Value::Obj(heap_alloc(HostObj::ChanClosed)))
.clone()
})
}
fn is_chan_closed(v: &Value) -> bool {
let Value::Obj(id) = v else { return false };
HEAP.with(|h| matches!(h.borrow().get(*id as usize), Some(HostObj::ChanClosed)))
}
fn b_chan_val(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let v = args.first().cloned().unwrap_or(Value::Undef);
if is_chan_closed(&v) {
return args.get(1).cloned().unwrap_or(Value::Undef);
}
v
}
fn b_chan_ok(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
Value::bool(!args.first().map(is_chan_closed).unwrap_or(false))
}
fn b_defer_unpark(_vm: &mut VM, _argc: u8) -> Value {
let Some(park) = PARKED.with(|p| p.borrow_mut().pop()) else {
return Value::Undef;
};
if let Some(v) = park.val {
PANIC.with(|p| {
let mut slot = p.borrow_mut();
if slot.is_none() {
*slot = Some(v);
}
});
}
Value::Undef
}
fn b_panic_finish(_vm: &mut VM, _argc: u8) -> Value {
if let Some(v) = PANIC.with(|p| p.borrow_mut().take()) {
eprintln!("panic: {}", go_str(&v));
std::process::exit(2);
}
Value::Undef
}
fn b_defer_enter(_vm: &mut VM, _argc: u8) -> Value {
DEFERS.with(|d| d.borrow_mut().push(Vec::new()));
Value::Undef
}
fn b_defer_push(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
if let Some(c) = args.into_iter().next() {
DEFERS.with(|d| {
if let Some(frame) = d.borrow_mut().last_mut() {
frame.push(c);
}
});
}
Value::Undef
}
fn b_defer_len(_vm: &mut VM, _argc: u8) -> Value {
Value::Int(DEFERS.with(|d| d.borrow().last().map(|f| f.len()).unwrap_or(0)) as i64)
}
fn b_defer_pop(_vm: &mut VM, _argc: u8) -> Value {
DEFERS.with(|d| {
d.borrow_mut()
.last_mut()
.and_then(|f| f.pop())
.unwrap_or(Value::Undef)
})
}
fn b_defer_leave(_vm: &mut VM, _argc: u8) -> Value {
DEFERS.with(|d| {
d.borrow_mut().pop();
});
Value::Undef
}
fn b_closure_nameidx(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::Closure { name_idx, .. }) => Value::Int(*name_idx),
_ => Value::Int(-1),
}
}),
_ => Value::Int(-1),
}
}
fn b_closure_new(vm: &mut VM, argc: u8) -> Value {
let mut args = pop_args(vm, argc);
let name_idx = args.pop().map(|v| v.to_int()).unwrap_or(-1);
Value::Obj(heap_alloc(HostObj::Closure {
name_idx,
captures: args,
}))
}
fn b_closure_get(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let idx = args.get(1).map(|v| v.to_int()).unwrap_or(0);
match args.first() {
Some(Value::Obj(id)) => HEAP.with(|h| {
let h = h.borrow();
match h.get(*id as usize) {
Some(HostObj::Closure { captures, .. }) => usize::try_from(idx)
.ok()
.and_then(|i| captures.get(i))
.cloned()
.unwrap_or(Value::Undef),
_ => Value::Undef,
}
}),
_ => Value::Undef,
}
}
fn b_min(vm: &mut VM, argc: u8) -> Value {
fold_extreme(vm, argc, true)
}
fn b_max(vm: &mut VM, argc: u8) -> Value {
fold_extreme(vm, argc, false)
}
fn fold_extreme(vm: &mut VM, argc: u8, want_min: bool) -> Value {
let args = pop_args(vm, argc);
let all_str = args.iter().all(|v| matches!(v, Value::Str(_)));
args.into_iter()
.reduce(|a, b| {
let pick_b = if all_str {
let (x, y) = (go_str(&a), go_str(&b));
if want_min {
y < x
} else {
y > x
}
} else if want_min {
b.to_float() < a.to_float()
} else {
b.to_float() > a.to_float()
};
if pick_b {
b
} else {
a
}
})
.unwrap_or(Value::Undef)
}
fn b_typeof(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(follow(*id) as usize) {
Some(HostObj::Struct { type_name, .. }) => Value::str(type_name.clone()),
_ => Value::str(""),
}
}),
_ => Value::str(""),
}
}
fn b_range_keys(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let keys: Vec<Value> = match args.first() {
Some(Value::Str(s)) => s
.char_indices()
.map(|(i, _)| Value::Int(i as i64))
.collect(),
Some(Value::Obj(id)) => {
if let Some((_, _, len)) = slice_backing(*id) {
(0..len as i64).map(Value::Int).collect()
} else {
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Map(m)) => m.iter().map(|(k, _)| k.clone()).collect(),
_ => Vec::new(),
})
}
}
Some(Value::Int(n)) => (0..*n).map(Value::Int).collect(),
_ => Vec::new(),
};
Value::Obj(heap_alloc(HostObj::slice(keys)))
}
fn b_range_val(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let iter = args.first().cloned().unwrap_or(Value::Undef);
let key = args.get(1).cloned().unwrap_or(Value::Undef);
match &iter {
Value::Str(s) => {
let off = key.to_int().max(0) as usize;
match s.get(off..).and_then(|rest| rest.chars().next()) {
Some(c) => Value::Int(c as i64),
None => Value::Int(0),
}
}
Value::Int(_) => key,
_ => {
vm.push(iter);
vm.push(key);
b_index_get(vm, 2)
}
}
}
pub(crate) enum HostObj {
Slice {
elems: Vec<Value>,
arr_ty: Option<String>,
elem_ty: Option<String>,
},
SliceView {
backing: u32,
offset: usize,
len: usize,
cap: usize,
},
Map(GoMap),
Ptr { target: u32 },
Struct {
type_name: String,
fields: Vec<(String, Value)>,
by_ref: bool,
},
Closure { name_idx: i64, captures: Vec<Value> },
Cell(Value),
F32(f32),
U64 { val: u64, ty: String },
ChanClosed,
Spread(Vec<Value>),
Nil { kind: NilKind, ty: String },
Named { ty: String, inner: Value },
}
impl HostObj {
fn slice(elems: Vec<Value>) -> HostObj {
HostObj::Slice {
elems,
arr_ty: None,
elem_ty: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NilKind {
Slice,
Map,
}
thread_local! {
static NILS: RefCell<std::collections::HashMap<String, Value>> =
RefCell::new(std::collections::HashMap::new());
}
fn typed_nil(ty: &str) -> Value {
let ty = ty.to_string();
NILS.with(|n| {
n.borrow_mut()
.entry(ty.clone())
.or_insert_with(|| {
let kind = if ty.starts_with("map[") {
NilKind::Map
} else {
NilKind::Slice
};
Value::Obj(heap_alloc(HostObj::Nil { kind, ty }))
})
.clone()
})
}
fn b_nil_of(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
typed_nil(&args.first().map(go_str).unwrap_or_default())
}
fn b_f32_box(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let v = args.first().cloned().unwrap_or(Value::Undef);
let spec = args.get(1).map(go_str).unwrap_or_default();
box_for_fmt(&v, &spec, BoxTag::F32)
}
fn b_u64_box(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let v = args.first().cloned().unwrap_or(Value::Undef);
let spec = args.get(1).map(go_str).unwrap_or_default();
let ty = args
.get(2)
.map(go_str)
.unwrap_or_else(|| "uint64".to_string());
box_for_fmt(&v, &spec, BoxTag::U64(&ty))
}
#[derive(Clone, Copy)]
enum BoxTag<'a> {
F32,
U64(&'a str),
}
fn box_leaf(v: &Value, tag: BoxTag) -> Value {
match tag {
BoxTag::F32 => box_f32(v),
BoxTag::U64(ty) => box_u64(v, ty),
}
}
fn box_u64(v: &Value, ty: &str) -> Value {
match v {
Value::Int(n) => Value::Obj(heap_alloc(HostObj::U64 {
val: *n as u64,
ty: ty.to_string(),
})),
other => other.clone(),
}
}
fn unbox_u64(v: &Value) -> Option<u64> {
let Value::Obj(id) = v else { return None };
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::U64 { val, .. }) => Some(*val),
_ => None,
})
}
fn b_u64_arith(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let a = args.first().map(arg_int).unwrap_or(0) as u64;
let b = args.get(1).map(arg_int).unwrap_or(0) as u64;
match args.get(2).map(Value::to_int).unwrap_or(u64_op::DIV) {
u64_op::DIV => match a.checked_div(b) {
Some(q) => Value::Int(q as i64),
None => {
runtime_panic(vm, "integer divide by zero");
Value::Int(0)
}
},
u64_op::MOD => match a.checked_rem(b) {
Some(r) => Value::Int(r as i64),
None => {
runtime_panic(vm, "integer divide by zero");
Value::Int(0)
}
},
u64_op::SHR => Value::Int(if b >= 64 { 0 } else { (a >> b) as i64 }),
u64_op::LT => Value::bool(a < b),
u64_op::LE => Value::bool(a <= b),
u64_op::GT => Value::bool(a > b),
u64_op::GE => Value::bool(a >= b),
_ => Value::Float(a as f64),
}
}
fn box_for_fmt(v: &Value, spec: &str, tag: BoxTag) -> Value {
if let Some(es) = slice_elems(v) {
let elems = es.iter().map(|e| box_for_fmt(e, spec, tag)).collect();
let arr_ty = match v {
Value::Obj(id) => HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Slice { arr_ty, .. }) => arr_ty.clone(),
_ => None,
}),
_ => None,
};
return Value::Obj(heap_alloc(HostObj::Slice {
elems,
arr_ty,
elem_ty: None,
}));
}
if let Some(pairs) = map_pairs(v) {
let boxed = pairs
.into_iter()
.map(|(k, val)| (k, box_for_fmt(&val, spec, tag)))
.collect();
return Value::Obj(heap_alloc(HostObj::Map(GoMap::from_pairs(boxed))));
}
if spec.is_empty() {
return box_leaf(v, tag);
}
let Value::Obj(id) = v else { return v.clone() };
let snapshot = HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Struct {
type_name,
fields,
by_ref,
}) => Some((type_name.clone(), fields.clone(), *by_ref)),
_ => None,
});
let Some((type_name, fields, by_ref)) = snapshot else {
return v.clone();
};
let fields = fields
.into_iter()
.map(|(n, fv)| {
let named = spec.split(',').any(|f| f == n);
let fv = if named { box_leaf(&fv, tag) } else { fv };
(n, fv)
})
.collect();
Value::Obj(heap_alloc(HostObj::Struct {
type_name,
fields,
by_ref,
}))
}
fn map_pairs(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(m)) => Some(m.to_vec()),
_ => None,
})
}
fn box_f32(v: &Value) -> Value {
match v {
Value::Float(f) => Value::Obj(heap_alloc(HostObj::F32(*f as f32))),
Value::Int(n) => Value::Obj(heap_alloc(HostObj::F32(*n as f32))),
other => other.clone(),
}
}
fn unbox_f32(v: &Value) -> Option<f32> {
let Value::Obj(id) = v else { return None };
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::F32(f)) => Some(*f),
_ => None,
})
}
fn arg_float(v: &Value) -> f64 {
unbox_f32(v).map_or_else(|| v.to_float(), f64::from)
}
fn arg_int(v: &Value) -> i64 {
if let Some(u) = unbox_u64(v) {
return u as i64;
}
unbox_f32(v).map_or_else(|| v.to_int(), |f| f as i64)
}
fn arg_uint(v: &Value) -> Option<u64> {
unbox_u64(v)
}
fn b_f32_arith(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let a = args.first().map(Value::to_float).unwrap_or(0.0) as f32;
let b = args.get(1).map(Value::to_float).unwrap_or(0.0) as f32;
let r = match args.get(2).map(Value::to_int).unwrap_or(f32_op::ADD) {
f32_op::SUB => a - b,
f32_op::MUL => a * b,
f32_op::DIV => a / b,
_ => a + b,
};
Value::Float(f64::from(r))
}
fn nil_kind(v: &Value) -> Option<NilKind> {
let Value::Obj(id) = v else { return None };
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Nil { kind, .. }) => Some(*kind),
_ => None,
})
}
const DEFERRED_BODY_DEPTH: usize = 2;
struct Park {
val: Option<Value>,
depth: usize,
recovered: bool,
}
thread_local! {
static HEAP: RefCell<Vec<HostObj>> = const { RefCell::new(Vec::new()) };
static DEFERS: RefCell<Vec<Vec<Value>>> = const { RefCell::new(Vec::new()) };
static PANIC: RefCell<Option<Value>> = const { RefCell::new(None) };
static PARKED: RefCell<Vec<Park>> = const { RefCell::new(Vec::new()) };
static CHAN_CLOSED: RefCell<Option<Value>> = const { RefCell::new(None) };
static STRUCT_PLAN: RefCell<HashMap<String, Vec<(String, String)>>> =
RefCell::new(HashMap::new());
}
pub fn set_struct_plan(plan: HashMap<String, Vec<(String, String)>>) {
STRUCT_PLAN.with(|p| *p.borrow_mut() = plan);
}
pub fn heap_reset() {
HEAP.with(|h| h.borrow_mut().clear());
METHOD_SETS.with(|m| m.borrow_mut().clear());
DEFERS.with(|d| d.borrow_mut().clear());
PANIC.with(|p| *p.borrow_mut() = None);
PARKED.with(|p| p.borrow_mut().clear());
CHAN_CLOSED.with(|c| *c.borrow_mut() = None);
PANIC_MODE.with(|m| *m.borrow_mut() = false);
NILS.with(|n| n.borrow_mut().clear());
stdlib::sentinels_reset();
}
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 slice_backing(id: u32) -> Option<(u32, usize, usize)> {
HEAP.with(|h| match h.borrow().get(id as usize) {
Some(HostObj::Slice { elems: a, .. }) => Some((id, 0, a.len())),
Some(HostObj::SliceView {
backing,
offset,
len,
..
}) => Some((*backing, *offset, *len)),
Some(HostObj::Nil {
kind: NilKind::Slice,
..
}) => Some((id, 0, 0)),
_ => None,
})
}
fn slice_cap(id: u32) -> Option<usize> {
HEAP.with(|h| match h.borrow().get(id as usize) {
Some(HostObj::Slice { elems: a, .. }) => Some(a.len()),
Some(HostObj::SliceView { cap, .. }) => Some(*cap),
Some(HostObj::Nil {
kind: NilKind::Slice,
..
}) => Some(0),
_ => None,
})
}
fn slice_get(id: u32, i: usize) -> Option<Value> {
let (backing, offset, len) = slice_backing(id)?;
if i >= len {
return None;
}
HEAP.with(|h| match h.borrow().get(backing as usize) {
Some(HostObj::Slice { elems: a, .. }) => a.get(offset + i).cloned(),
_ => None,
})
}
fn slice_set(id: u32, i: usize, v: Value) -> bool {
let Some((backing, offset, len)) = slice_backing(id) else {
return false;
};
if i >= len {
return false;
}
HEAP.with(|h| {
if let Some(HostObj::Slice { elems: a, .. }) = h.borrow_mut().get_mut(backing as usize) {
if let Some(slot) = a.get_mut(offset + i) {
*slot = v;
return true;
}
}
false
})
}
fn b_copy(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let Some(Value::Obj(dst)) = args.first().cloned() else {
return Value::Int(0);
};
let dst_len = slice_backing(dst).map(|(_, _, l)| l).unwrap_or(0);
let src_vals: Vec<Value> = match args.get(1) {
Some(Value::Obj(sid)) => {
let slen = slice_backing(*sid).map(|(_, _, l)| l).unwrap_or(0);
(0..slen).filter_map(|i| slice_get(*sid, i)).collect()
}
Some(Value::Str(s)) => s.bytes().map(|b| Value::Int(b as i64)).collect(),
_ => return Value::Int(0),
};
let n = dst_len.min(src_vals.len());
for (i, v) in src_vals.into_iter().take(n).enumerate() {
slice_set(dst, i, v);
}
Value::Int(n as i64)
}
fn key_eq(a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Str(x), Value::Str(y)) => x == y,
(Value::Bool(x), Value::Bool(y)) => x == y,
(Value::Obj(x), Value::Obj(y)) => {
if x == y {
return true;
}
HEAP.with(|h| {
let h = h.borrow();
match (h.get(*x as usize), h.get(*y as usize)) {
(
Some(HostObj::Struct {
type_name: tx,
fields: fx,
..
}),
Some(HostObj::Struct {
type_name: ty,
fields: fy,
..
}),
) => {
tx == ty
&& fx.len() == fy.len()
&& fx.iter().zip(fy).all(|((_, va), (_, vb))| key_eq(va, vb))
}
(
Some(HostObj::Slice { elems: ex, .. }),
Some(HostObj::Slice { elems: ey, .. }),
) => ex.len() == ey.len() && ex.iter().zip(ey).all(|(a, b)| key_eq(a, b)),
_ => false,
}
})
}
(Value::Undef, Value::Undef) => true,
(Value::Str(_) | Value::Bool(_) | Value::Obj(_) | Value::Undef, _)
| (_, Value::Str(_) | Value::Bool(_) | Value::Obj(_) | Value::Undef) => false,
(Value::Int(_), Value::Float(_)) | (Value::Float(_), Value::Int(_)) => false,
_ => a.to_float() == b.to_float(),
}
}
#[derive(PartialEq, Eq, Hash, Clone)]
enum MapKey {
Nil,
Str(std::sync::Arc<String>),
Bool(bool),
Int(i64),
Float(u64),
Struct(String, Vec<MapKey>),
Array(Vec<MapKey>),
}
fn map_key(v: &Value) -> Option<MapKey> {
match v {
Value::Undef => Some(MapKey::Nil),
Value::Str(s) => Some(MapKey::Str(s.clone())),
Value::Bool(b) => Some(MapKey::Bool(*b)),
Value::Obj(id) => HEAP.with(|h| {
let h = h.borrow();
match h.get(*id as usize) {
Some(HostObj::Struct {
type_name, fields, ..
}) => Some(MapKey::Struct(
type_name.clone(),
fields
.iter()
.map(|(_, v)| map_key(v))
.collect::<Option<Vec<_>>>()?,
)),
Some(HostObj::Slice { elems, .. }) => Some(MapKey::Array(
elems.iter().map(map_key).collect::<Option<Vec<_>>>()?,
)),
_ => None,
}
}),
Value::Int(n) => Some(MapKey::Int(*n)),
other => {
let f = other.to_float();
(!f.is_nan()).then(|| MapKey::Float(if f == 0.0 { 0.0 } else { f }.to_bits()))
}
}
}
enum Probe {
Answered(Option<usize>),
Scan,
}
const INDEX_THRESHOLD: usize = 8;
#[derive(Clone, Default)]
pub(crate) struct GoMap {
pairs: Vec<(Value, Value)>,
keys: Vec<Option<MapKey>>,
index: Option<HashMap<MapKey, usize>>,
unindexable: bool,
}
impl std::ops::Deref for GoMap {
type Target = [(Value, Value)];
fn deref(&self) -> &Self::Target {
&self.pairs
}
}
impl GoMap {
fn from_pairs(pairs: Vec<(Value, Value)>) -> Self {
let mut m = GoMap::default();
for (k, v) in pairs {
let mk = map_key(&k);
m.put(None, mk, k, v);
}
m
}
fn probe(&self, mk: Option<&MapKey>) -> Probe {
let (Some(index), Some(k)) = (self.index.as_ref(), mk) else {
return Probe::Scan;
};
Probe::Answered(index.get(k).copied())
}
fn find(&self, mk: Option<&MapKey>, key: &Value) -> Option<usize> {
match self.probe(mk) {
Probe::Answered(hit) => hit,
Probe::Scan => self.pairs.iter().position(|(k, _)| key_eq(k, key)),
}
}
fn put(&mut self, at: Option<usize>, mk: Option<MapKey>, key: Value, val: Value) {
if let Some(i) = at {
self.pairs[i].1 = val;
return;
}
let pos = self.pairs.len();
match &mk {
Some(k) => {
if let Some(index) = self.index.as_mut() {
index.insert(k.clone(), pos);
}
}
None => {
self.unindexable = true;
self.index = None;
}
}
self.keys.push(mk);
self.pairs.push((key, val));
if self.index.is_none() && !self.unindexable && self.pairs.len() > INDEX_THRESHOLD {
self.build_index();
}
}
fn build_index(&mut self) {
let mut index = HashMap::with_capacity(self.pairs.len() * 2);
for (i, mk) in self.keys.iter().enumerate() {
let Some(mk) = mk else {
self.unindexable = true;
return;
};
index.insert(mk.clone(), i);
}
self.index = Some(index);
}
fn remove(&mut self, i: usize) {
self.pairs.remove(i);
let removed = self.keys.remove(i);
let Some(index) = self.index.as_mut() else {
return;
};
if let Some(k) = removed {
index.remove(&k);
}
for pos in index.values_mut() {
if *pos > i {
*pos -= 1;
}
}
}
}
fn map_find_index(id: u32, key: &Value) -> Option<usize> {
let mk = map_key(key);
let probe = HEAP.with(|h| match h.borrow().get(id as usize) {
Some(HostObj::Map(m)) => m.probe(mk.as_ref()),
_ => Probe::Answered(None),
});
match probe {
Probe::Answered(hit) => hit,
Probe::Scan => {
let keys: Vec<Value> = HEAP.with(|h| match h.borrow().get(id as usize) {
Some(HostObj::Map(m)) => m.iter().map(|(k, _)| k.clone()).collect(),
_ => Vec::new(),
});
keys.iter().position(|k| key_eq(k, key))
}
}
}
fn b_make(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let kind = args.first().map(go_str).unwrap_or_default();
match kind.as_str() {
"map" => Value::Obj(heap_alloc(HostObj::Map(GoMap::default()))),
_ => {
let n = args.get(1).map(|v| v.to_int()).unwrap_or(0);
let zero = args.get(2).cloned().unwrap_or(Value::Int(0));
let c = args.get(3).map(|v| v.to_int()).unwrap_or(-1);
if n < 0 {
ffi_fault(vm, format!("go-rs: makeslice: len out of range ({n})"));
return Value::Undef;
}
if c >= 0 && c < n {
ffi_fault(vm, format!("go-rs: makeslice: cap out of range ({c})"));
return Value::Undef;
}
let (len, cap) = (n as usize, if c < 0 { n as usize } else { c as usize });
let elem_ty = args.get(4).map(go_str).unwrap_or_default();
let fill = |k: usize| -> Vec<Value> {
(0..k).map(|_| value_copy(zero.clone(), &elem_ty)).collect()
};
if cap == len {
return Value::Obj(heap_alloc(HostObj::slice(fill(len))));
}
let backing = heap_alloc(HostObj::slice(fill(cap)));
Value::Obj(heap_alloc(HostObj::SliceView {
backing,
offset: 0,
len,
cap,
}))
}
}
}
fn b_slice_lit(vm: &mut VM, argc: u8) -> Value {
let elems = pop_args(vm, argc);
Value::Obj(heap_alloc(HostObj::slice(elems)))
}
fn map_insert_all(map: &mut GoMap, flat: Vec<Value>) {
let mut it = flat.into_iter();
while let (Some(k), Some(v)) = (it.next(), it.next()) {
let mk = map_key(&k);
let at = map.find(mk.as_ref(), &k);
map.put(at, mk, k, v);
}
}
fn b_map_lit(vm: &mut VM, argc: u8) -> Value {
let flat = pop_args(vm, argc);
let mut m = GoMap::default();
map_insert_all(&mut m, flat);
Value::Obj(heap_alloc(HostObj::Map(m)))
}
fn b_lit_extend(vm: &mut VM, argc: u8) -> Value {
let mut args = pop_args(vm, argc);
if args.is_empty() {
return Value::Undef;
}
let container = args.remove(0);
let Value::Obj(id) = container else {
return container;
};
enum Kind {
Slice,
Map,
Struct,
Other,
}
let id = follow(id);
let kind = HEAP.with(|h| match h.borrow().get(id as usize) {
Some(HostObj::Slice { .. }) => Kind::Slice,
Some(HostObj::Map(_)) => Kind::Map,
Some(HostObj::Struct { .. }) => Kind::Struct,
_ => Kind::Other,
});
match kind {
Kind::Slice => HEAP.with(|h| {
if let Some(HostObj::Slice { elems, .. }) = h.borrow_mut().get_mut(id as usize) {
elems.append(&mut args);
}
}),
Kind::Map => {
let mut pairs = HEAP.with(|h| match h.borrow_mut().get_mut(id as usize) {
Some(HostObj::Map(p)) => std::mem::take(p),
_ => GoMap::default(),
});
map_insert_all(&mut pairs, args);
HEAP.with(|h| {
if let Some(HostObj::Map(slot)) = h.borrow_mut().get_mut(id as usize) {
*slot = pairs;
}
});
}
Kind::Struct => {
let mut more = Vec::with_capacity(args.len() / 2);
let mut it = args.into_iter();
while let (Some(name), Some(val)) = (it.next(), it.next()) {
more.push((go_str(&name), val));
}
HEAP.with(|h| {
if let Some(HostObj::Struct { fields, .. }) = h.borrow_mut().get_mut(id as usize) {
fields.append(&mut more);
}
});
}
Kind::Other => {}
}
container
}
fn b_array_tag(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let ty = args.get(1).map(go_str).unwrap_or_default();
let val = args.first().cloned().unwrap_or(Value::Undef);
if let Value::Obj(id) = val {
HEAP.with(|h| {
if let Some(HostObj::Slice { arr_ty, .. }) = h.borrow_mut().get_mut(id as usize) {
*arr_ty = Some(ty);
}
});
}
val
}
fn b_index_get(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let recv = args.first().cloned().unwrap_or(Value::Undef);
let key = args.get(1).cloned().unwrap_or(Value::Undef);
let id = match recv {
Value::Obj(id) => id,
Value::Str(ref s) => {
let i = key.to_int();
let len = s.len();
return match usize::try_from(i).ok().and_then(|i| s.as_bytes().get(i)) {
Some(b) => Value::Int(*b as i64),
None => {
runtime_panic(vm, format!("index out of range [{i}] with length {len}"));
Value::Undef
}
};
}
_ => {
ffi_fault(vm, "go-rs: invalid index of nil".to_string());
return Value::Undef;
}
};
if let Some((_, _, len)) = slice_backing(id) {
let i = key.to_int();
return match usize::try_from(i).ok().filter(|&i| i < len) {
Some(i) => slice_get(id, i).unwrap_or(Value::Undef),
None => {
runtime_panic(vm, format!("index out of range [{i}] with length {len}"));
Value::Undef
}
};
}
let is_map = HEAP.with(|h| {
matches!(
h.borrow().get(id as usize),
Some(HostObj::Map(_))
| Some(HostObj::Nil {
kind: NilKind::Map,
..
})
)
});
if !is_map {
ffi_fault(vm, "go-rs: invalid index target".to_string());
return Value::Undef;
}
match map_find_index(id, &key) {
Some(i) => HEAP.with(|h| match h.borrow().get(id as usize) {
Some(HostObj::Map(m)) => m[i].1.clone(),
_ => Value::Undef,
}),
None => args.get(2).cloned().unwrap_or(Value::Int(0)),
}
}
fn b_append_spread(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let elem_ty = args.first().map(go_str).unwrap_or_default();
let mut out: Vec<Value> = Vec::new();
let mut extend_from = |v: &Value| {
if let Value::Obj(id) = v {
if let Some((_, _, len)) = slice_backing(*id) {
for i in 0..len {
if let Some(e) = slice_get(*id, i) {
out.push(if elem_ty.is_empty() {
e
} else {
value_copy(e, &elem_ty)
});
}
}
}
}
};
for a in args.iter().skip(1) {
extend_from(a);
}
Value::Obj(heap_alloc(HostObj::slice(out)))
}
fn b_map_get2(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let recv = args.first().cloned().unwrap_or(Value::Undef);
let key = args.get(1).cloned().unwrap_or(Value::Undef);
let absent = args.get(2).cloned().unwrap_or(Value::Int(0));
let (val, present) = match recv {
Value::Obj(id) => match map_find_index(id, &key) {
Some(i) => HEAP.with(|h| match h.borrow().get(id as usize) {
Some(HostObj::Map(m)) => (m[i].1.clone(), true),
_ => (absent.clone(), false),
}),
None => (absent, false),
},
_ => (absent, false),
};
Value::Obj(heap_alloc(HostObj::slice(vec![val, Value::bool(present)])))
}
fn b_index_set(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let recv = args.first().cloned().unwrap_or(Value::Undef);
let key = args.get(1).cloned().unwrap_or(Value::Undef);
let val = args.get(2).cloned().unwrap_or(Value::Undef);
let id = match recv {
Value::Obj(id) => id,
_ => {
ffi_fault(vm, "go-rs: assignment to entry in nil".to_string());
return Value::Undef;
}
};
if let Some((backing, offset, len)) = slice_backing(id) {
let i = key.to_int();
let err = match usize::try_from(i).ok().filter(|&i| i < len) {
Some(i) => HEAP.with(|h| {
if let Some(HostObj::Slice { elems: a, .. }) =
h.borrow_mut().get_mut(backing as usize)
{
a[offset + i] = val.clone();
}
None::<String>
}),
None => Some(format!("index out of range [{i}] with length {len}")),
};
return match err {
None => val,
Some(msg) => {
runtime_panic(vm, msg);
Value::Undef
}
};
}
if nil_kind(&recv) == Some(NilKind::Map) {
plain_panic(vm, "assignment to entry in nil map".to_string());
return Value::Undef;
}
let existing = map_find_index(id, &key);
let mk = map_key(&key);
let err = HEAP.with(|h| {
let mut h = h.borrow_mut();
match h.get_mut(id as usize) {
Some(HostObj::Map(m)) => {
m.put(existing, mk, key.clone(), val.clone());
None
}
_ => Some("go-rs: invalid assignment target".to_string()),
}
});
match err {
None => val,
Some(msg) => {
if msg.starts_with("go-rs:") {
ffi_fault(vm, msg);
} else {
runtime_panic(vm, msg);
}
Value::Undef
}
}
}
fn b_len(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
match args.first() {
Some(Value::Str(s)) => Value::Int(s.len() as i64),
Some(Value::Obj(id)) => {
if let Some((_, _, len)) = slice_backing(*id) {
return Value::Int(len as i64);
}
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Map(m)) => Value::Int(m.len() as i64),
_ => Value::Int(0),
})
}
_ => Value::Int(0),
}
}
fn b_cap(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
match args.first() {
Some(Value::Str(s)) => Value::Int(s.len() as i64),
Some(Value::Obj(id)) => Value::Int(slice_cap(*id).unwrap_or(0) as i64),
_ => Value::Int(0),
}
}
fn next_slice_cap(new_len: usize, old_cap: usize) -> usize {
let doublecap = old_cap.saturating_mul(2);
if new_len > doublecap {
return new_len;
}
const THRESHOLD: usize = 256;
if old_cap < THRESHOLD {
return doublecap;
}
let mut newcap = old_cap;
loop {
newcap += (newcap + 3 * THRESHOLD) >> 2;
if newcap >= new_len {
return newcap;
}
}
}
fn grow_slice(elems: Vec<Value>, old_cap: usize) -> Value {
let new_len = elems.len();
let cap = next_slice_cap(new_len, old_cap);
let mut backing = elems;
backing.resize(cap, Value::Int(0));
let id = heap_alloc(HostObj::slice(backing));
Value::Obj(heap_alloc(HostObj::SliceView {
backing: id,
offset: 0,
len: new_len,
cap,
}))
}
fn b_append(vm: &mut VM, argc: u8) -> Value {
let mut args = pop_args(vm, argc);
if args.is_empty() {
return Value::Undef;
}
let recv = args.remove(0);
match recv {
Value::Obj(id) => {
let is_view = HEAP
.with(|h| matches!(h.borrow().get(id as usize), Some(HostObj::SliceView { .. })));
if is_view {
let (backing, offset, len) = match slice_backing(id) {
Some(t) => t,
None => return Value::Obj(heap_alloc(HostObj::slice(args))),
};
let new_len = len + args.len();
let cap = slice_cap(id).unwrap_or(0);
if new_len <= cap {
HEAP.with(|h| {
if let Some(HostObj::Slice { elems: a, .. }) =
h.borrow_mut().get_mut(backing as usize)
{
for (k, v) in args.into_iter().enumerate() {
a[offset + len + k] = v;
}
}
});
return Value::Obj(heap_alloc(HostObj::SliceView {
backing,
offset,
len: new_len,
cap,
}));
}
let mut out = HEAP.with(|h| match h.borrow().get(backing as usize) {
Some(HostObj::Slice { elems: a, .. }) => a[offset..offset + len].to_vec(),
_ => Vec::new(),
});
out.extend(args);
return grow_slice(out, cap);
}
let existing = HEAP.with(|h| match h.borrow().get(id as usize) {
Some(HostObj::Slice { elems: a, .. }) => Some(a.clone()),
Some(HostObj::Nil {
kind: NilKind::Slice,
..
}) => Some(Vec::new()),
_ => None,
});
if let Some(mut out) = existing {
let old_cap = out.len();
out.extend(args);
return grow_slice(out, old_cap);
}
{
ffi_fault(
vm,
"go-rs: first argument to append must be a slice".to_string(),
);
Value::Undef
}
}
_ => Value::Obj(heap_alloc(HostObj::slice(args))),
}
}
fn b_delete(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let recv = args.first().cloned().unwrap_or(Value::Undef);
let key = args.get(1).cloned().unwrap_or(Value::Undef);
if let Value::Obj(id) = recv {
if let Some(i) = map_find_index(id, &key) {
HEAP.with(|h| {
if let Some(HostObj::Map(m)) = h.borrow_mut().get_mut(id as usize) {
m.remove(i);
}
});
}
}
Value::Undef
}
fn b_struct_new(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let type_name = args.first().map(go_str).unwrap_or_default();
let mut fields = Vec::new();
let mut it = args.into_iter().skip(1);
while let (Some(name), Some(val)) = (it.next(), it.next()) {
fields.push((go_str(&name), val));
}
Value::Obj(heap_alloc(HostObj::Struct {
type_name,
fields,
by_ref: false,
}))
}
pub(crate) fn make_error(msg: String) -> Value {
Value::Obj(heap_alloc(HostObj::Struct {
type_name: "$errorString".to_string(),
fields: vec![("s".to_string(), Value::str(msg))],
by_ref: true,
}))
}
fn b_ptr_mark(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let v = args.first().cloned().unwrap_or(Value::Undef);
if let Value::Obj(id) = v {
HEAP.with(|h| {
if let Some(HostObj::Struct { by_ref, .. }) = h.borrow_mut().get_mut(id as usize) {
*by_ref = true;
}
});
}
v
}
fn follow(id: u32) -> u32 {
let mut cur = id;
for _ in 0..16 {
let next = HEAP.with(|h| match h.borrow().get(cur as usize) {
Some(HostObj::Ptr { target }) => Some(*target),
_ => None,
});
match next {
Some(t) => cur = t,
None => break,
}
}
cur
}
fn ptr_identity(v: &Value) -> Option<u32> {
let Value::Obj(id) = v else { return None };
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Ptr { target }) => Some(*target),
Some(HostObj::Struct { by_ref: true, .. }) => Some(*id),
_ => None,
})
}
fn is_ptr(v: &Value) -> bool {
ptr_identity(v).is_some()
}
pub(crate) fn ptr_eq(a: &Value, b: &Value) -> Option<bool> {
if !is_ptr(a) && !is_ptr(b) {
return None;
}
Some(match (ptr_identity(a), ptr_identity(b)) {
(Some(x), Some(y)) => x == y,
_ => false,
})
}
pub fn iface_eq(a: &Value, b: &Value) -> bool {
if go_type_name(a) != go_type_name(b) {
return false;
}
if let Some(same) = ptr_eq(a, b) {
return same;
}
match (a, b) {
(Value::Undef, Value::Undef) => true,
(Value::Bool(x), Value::Bool(y)) => x == y,
(Value::Int(x), Value::Int(y)) => x == y,
(Value::Float(x), Value::Float(y)) => x == y,
_ => go_str(a) == go_str(b),
}
}
fn b_iface_eq(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let a = args.first().cloned().unwrap_or(Value::Undef);
let b = args.get(1).cloned().unwrap_or(Value::Undef);
let ne = args.get(2).map(|v| v.to_int() != 0).unwrap_or(false);
Value::bool(iface_eq(&a, &b) != ne)
}
fn b_field_get(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let recv = args.first().cloned().unwrap_or(Value::Undef);
let name = args.get(1).map(go_str).unwrap_or_default();
let id = match recv {
Value::Obj(id) => id,
_ => {
runtime_panic(vm, "invalid memory address or nil pointer dereference");
return Value::Undef;
}
};
let id = follow(id);
HEAP.with(|h| {
let h = h.borrow();
match h.get(id as usize) {
Some(HostObj::Struct { fields, .. }) => {
if let Some((_, v)) = fields.iter().find(|(f, _)| *f == name) {
return v.clone();
}
match embedded_field_owner(&h, id, &name) {
Some(owner) => match h.get(owner as usize) {
Some(HostObj::Struct { fields, .. }) => fields
.iter()
.find(|(f, _)| *f == name)
.map(|(_, v)| v.clone())
.unwrap_or(Value::Undef),
_ => Value::Undef,
},
None => Value::Undef,
}
}
_ => {
ffi_fault(vm, format!("go-rs: no field `{name}`"));
Value::Undef
}
}
})
}
fn embedded_field_owner(heap: &[HostObj], root: u32, name: &str) -> Option<u32> {
let mut frontier = vec![root];
for _ in 0..16 {
let mut next = Vec::new();
for id in frontier {
let Some(HostObj::Struct { fields, .. }) = heap.get(id as usize) else {
continue;
};
for (fname, fval) in fields {
let Value::Obj(inner) = fval else { continue };
let Some(HostObj::Struct {
type_name,
fields: inner_fields,
..
}) = heap.get(*inner as usize)
else {
continue;
};
if fname != type_name {
continue; }
if inner_fields.iter().any(|(f, _)| f == name) {
return Some(*inner);
}
next.push(*inner);
}
}
if next.is_empty() {
return None;
}
frontier = next;
}
None
}
fn b_field_set(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let recv = args.first().cloned().unwrap_or(Value::Undef);
let name = args.get(1).map(go_str).unwrap_or_default();
let val = args.get(2).cloned().unwrap_or(Value::Undef);
let id = match recv {
Value::Obj(id) => id,
_ => {
runtime_panic(vm, "invalid memory address or nil pointer dereference");
return Value::Undef;
}
};
let id = follow(id);
let ok = HEAP.with(|h| {
let mut h = h.borrow_mut();
let target = match h.get(id as usize) {
Some(HostObj::Struct { fields, .. }) if !fields.iter().any(|(f, _)| *f == name) => {
embedded_field_owner(&h, id, &name).unwrap_or(id)
}
_ => id,
};
match h.get_mut(target as usize) {
Some(HostObj::Struct { fields, .. }) => {
if let Some(slot) = fields.iter_mut().find(|(f, _)| *f == name) {
slot.1 = val.clone();
} else {
fields.push((name.clone(), val.clone()));
}
true
}
_ => false,
}
});
if ok {
val
} else {
ffi_fault(vm, format!("go-rs: cannot assign field `{name}`"));
Value::Undef
}
}
fn b_struct_copy(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
struct_copy(args.first().cloned().unwrap_or(Value::Undef))
}
fn b_write_fd(vm: &mut VM, argc: u8) -> Value {
use std::io::Write as _;
let args = pop_args(vm, argc);
let text = args.get(1).map(go_str).unwrap_or_default();
match args.first().map(|v| v.to_int()) {
Some(2) => {
let mut e = std::io::stderr();
let _ = e.write_all(text.as_bytes());
let _ = e.flush();
}
_ => {
let mut o = std::io::stdout();
let _ = o.write_all(text.as_bytes());
let _ = o.flush();
}
}
Value::Undef
}
fn b_ptr_to(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let v = args.first().cloned().unwrap_or(Value::Undef);
match v {
Value::Obj(id) => Value::Obj(heap_alloc(HostObj::Ptr { target: id })),
other => other,
}
}
fn b_deref_set(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let target = args.first().cloned().unwrap_or(Value::Undef);
let val = args.get(1).cloned().unwrap_or(Value::Undef);
let Value::Obj(id) = target else {
ffi_fault(vm, "go-rs: cannot assign through a pointer to a non-composite value (`&x` on a scalar has no address)".to_string(),);
return Value::Undef;
};
let id = follow(id);
let fields = match struct_copy(val.clone()) {
Value::Obj(src) => HEAP.with(|h| match h.borrow().get(follow(src) as usize) {
Some(HostObj::Struct { fields, .. }) => Some(fields.clone()),
_ => None,
}),
_ => None,
};
match fields {
Some(f) => HEAP.with(|h| {
if let Some(HostObj::Struct { fields, .. }) = h.borrow_mut().get_mut(id as usize) {
*fields = f;
}
}),
None => {
ffi_fault(vm, "go-rs: cannot assign through a pointer to a non-composite value (`&x` on a scalar has no address)".to_string(),);
}
}
val
}
fn b_struct_bind(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
struct_bind(args.first().cloned().unwrap_or(Value::Undef))
}
fn struct_bind(v: Value) -> Value {
let Value::Obj(id) = v else { return v };
let is_ptr = HEAP.with(|h| {
matches!(
h.borrow().get(id as usize),
Some(HostObj::Struct { by_ref: true, .. }) | Some(HostObj::Ptr { .. })
)
});
if is_ptr {
return v;
}
struct_copy(v)
}
fn b_array_copy(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let elem_ty = args.get(1).map(go_str).unwrap_or_default();
array_copy(args.first().cloned().unwrap_or(Value::Undef), &elem_ty)
}
fn value_copy(v: Value, ty: &str) -> Value {
match crate::ast::array_elem_ty(ty) {
Some(elem) => array_copy(v, elem),
None => struct_bind(v),
}
}
fn array_copy(v: Value, elem_ty: &str) -> Value {
let Value::Obj(id) = v else { return v };
let Some((_, _, len)) = slice_backing(id) else {
return v;
};
let elems: Vec<Value> = (0..len)
.map(|i| value_copy(slice_get(id, i).unwrap_or(Value::Undef), elem_ty))
.collect();
let arr_ty = HEAP.with(|h| match h.borrow().get(id as usize) {
Some(HostObj::Slice { arr_ty, .. }) => arr_ty.clone(),
_ => None,
});
Value::Obj(heap_alloc(HostObj::Slice {
elems,
arr_ty,
elem_ty: None,
}))
}
fn struct_copy(v: Value) -> Value {
let Value::Obj(id) = v else { return v };
let id = follow(id);
let parts = HEAP.with(|h| match h.borrow().get(id as usize) {
Some(HostObj::Struct {
type_name, fields, ..
}) => Some((type_name.clone(), fields.clone())),
_ => None,
});
let Some((type_name, mut fields)) = parts else {
return v;
};
let nested = STRUCT_PLAN.with(|p| p.borrow().get(&type_name).cloned().unwrap_or_default());
for (name, fv) in fields.iter_mut() {
if let Some((_, fty)) = nested.iter().find(|(n, _)| n == name) {
*fv = value_copy(fv.clone(), fty);
}
}
Value::Obj(heap_alloc(HostObj::Struct {
type_name,
fields,
by_ref: false,
}))
}
pub fn install_debug(vm: &mut VM) {
install(vm);
vm.register_builtin(DBG_LINE, b_dbg_line);
}
thread_local! {
static FFI_ERROR: RefCell<Option<String>> = const { RefCell::new(None) };
static PANIC_MODE: RefCell<bool> = const { RefCell::new(false) };
}
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();
}
fn runtime_panic(vm: &mut VM, msg: impl Into<String>) {
plain_panic(vm, format!("runtime error: {}", msg.into()));
}
fn plain_panic(vm: &mut VM, full: String) {
if PANIC_MODE.with(|m| *m.borrow()) {
PANIC.with(|p| *p.borrow_mut() = Some(Value::str(full)));
} else {
use std::io::Write as _;
let _ = std::io::stdout().flush();
eprintln!("panic: {full}");
vm.request_halt();
std::process::exit(2);
}
}
fn b_set_panic_mode(_vm: &mut VM, _argc: u8) -> Value {
PANIC_MODE.with(|m| *m.borrow_mut() = true);
Value::Undef
}
fn b_ffi_compile(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let b64 = args.first().map(go_str).unwrap_or_default();
if let Err(e) = fusevm::ffi::compile_and_register(&b64) {
ffi_fault(vm, format!("go-rs: 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!("go-rs: rust FFI call {name}: {e}"));
Value::Undef
}
None => {
ffi_fault(vm, format!("go-rs: undefined: {name}"));
Value::Undef
}
}
}
fn b_dbg_line(vm: &mut VM, _argc: u8) -> Value {
crate::dap::on_debug_line(vm);
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();
expand_spread(v)
}
fn expand_spread(args: Vec<Value>) -> Vec<Value> {
let spread = |v: &Value| match v {
Value::Obj(id) => HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Spread(xs)) => Some(xs.clone()),
_ => None,
}),
_ => None,
};
if !args.iter().any(|v| spread(v).is_some()) {
return args;
}
let mut out = Vec::with_capacity(args.len());
for v in args {
match spread(&v) {
Some(xs) => out.extend(xs),
None => out.push(v),
}
}
out
}
fn b_spread(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let v = args.into_iter().next().unwrap_or(Value::Undef);
let elems = slice_elems(&v).unwrap_or_default();
Value::Obj(heap_alloc(HostObj::Spread(elems)))
}
pub fn go_str(v: &Value) -> String {
go_str_mode(v, FmtMode::V)
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum FmtMode {
V,
PlusV,
SharpV,
}
pub(crate) fn go_str_mode(v: &Value, mode: FmtMode) -> String {
match v {
Value::Bool(b) => if *b { "true" } else { "false" }.to_string(),
Value::Int(n) => n.to_string(),
Value::Float(f) => format_float(*f),
Value::Str(s) => {
if mode == FmtMode::SharpV {
go_quote(s.as_str())
} else {
s.as_str().to_string()
}
}
Value::Undef => "<nil>".to_string(),
Value::Obj(id) => obj_str_mode(*id, mode),
other => other.as_str_cow().into_owned(),
}
}
pub(crate) fn go_quote(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
'\u{7}' => out.push_str("\\a"),
'\u{8}' => out.push_str("\\b"),
'\u{c}' => out.push_str("\\f"),
'\u{b}' => out.push_str("\\v"),
c if !go_is_print(c) => out.push_str(&escape_rune(c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
fn escape_rune(c: u32) -> String {
match c {
0..=0x1f | 0x7f => format!("\\x{c:02x}"),
0..=0xffff => format!("\\u{c:04x}"),
_ => format!("\\U{c:08x}"),
}
}
fn go_is_print(c: char) -> bool {
if c.is_control() {
return false;
}
if c == ' ' {
return true;
}
if c.is_whitespace() {
return false;
}
!matches!(c as u32, 0xe000..=0xf8ff | 0xf0000..=0xffffd | 0x100000..=0x10fffd)
}
pub(crate) fn go_quote_rune(n: i64) -> String {
let Some(c) = u32::try_from(n).ok().and_then(char::from_u32) else {
return "'\u{fffd}'".to_string();
};
let inner = go_quote(&c.to_string());
let body = &inner[1..inner.len() - 1];
let body = body.replace("\\\"", "\"").replace('\'', "\\'");
format!("'{body}'")
}
pub(crate) fn go_type_name(v: &Value) -> String {
match v {
Value::Bool(_) => "bool".to_string(),
Value::Int(_) => "int".to_string(),
Value::Float(_) => "float64".to_string(),
Value::Str(_) => "string".to_string(),
Value::Undef => "<nil>".to_string(),
Value::Obj(id) => HEAP.with(|h| {
let h = h.borrow();
match h.get(follow(*id) as usize) {
Some(HostObj::Slice {
elems: a,
arr_ty: None,
elem_ty,
}) => match elem_ty {
Some(t) => format!("[]{}", go_type_spelling(t)),
None => format!("[]{}", elem_type_name(a.first())),
},
Some(HostObj::Slice {
arr_ty: Some(ty), ..
}) => ty.clone(),
Some(HostObj::SliceView {
backing, offset, ..
}) => {
let e = match h.get(*backing as usize) {
Some(HostObj::Slice { elems: a, .. }) => a.get(*offset).cloned(),
_ => None,
};
format!("[]{}", elem_type_name(e.as_ref()))
}
Some(HostObj::Map(m)) => format!(
"map[{}]{}",
elem_type_name(m.first().map(|(k, _)| k)),
elem_type_name(m.first().map(|(_, v)| v))
),
Some(HostObj::Struct { type_name, .. }) => format!("main.{type_name}"),
Some(HostObj::Closure { .. }) => "func()".to_string(),
Some(HostObj::Cell(v)) => go_type_name(v),
Some(HostObj::Named { ty, .. }) => go_type_spelling(ty),
Some(HostObj::Nil { ty, .. }) => go_type_spelling(ty),
Some(HostObj::F32(_)) => "float32".to_string(),
Some(HostObj::U64 { ty, .. }) => ty.clone(),
Some(HostObj::ChanClosed) => "<nil>".to_string(),
Some(HostObj::Ptr { .. }) => "<nil>".to_string(),
Some(HostObj::Spread(xs)) => xs
.first()
.map(go_type_name)
.unwrap_or_else(|| "<nil>".to_string()),
None => "<nil>".to_string(),
}
}),
_ => "interface {}".to_string(),
}
}
fn elem_type_name(v: Option<&Value>) -> String {
match v {
Some(v) => go_type_name(v),
None => "interface {}".to_string(),
}
}
pub(crate) fn go_type_spelling(ty: &str) -> String {
let mut out = String::with_capacity(ty.len());
let mut word = String::new();
let flush = |word: &mut String, out: &mut String| {
match word.as_str() {
"" => {}
"byte" => out.push_str("uint8"),
"rune" => out.push_str("int32"),
w if is_predeclared_type(w) => out.push_str(w),
w => {
out.push_str("main.");
out.push_str(w);
}
}
word.clear();
};
for c in ty.chars() {
if c.is_alphanumeric() || c == '_' {
word.push(c);
} else {
flush(&mut word, &mut out);
out.push(c);
}
}
flush(&mut word, &mut out);
out
}
fn is_predeclared_type(w: &str) -> bool {
matches!(
w,
"bool"
| "string"
| "int"
| "int8"
| "int16"
| "int32"
| "int64"
| "uint"
| "uint8"
| "uint16"
| "uint32"
| "uint64"
| "uintptr"
| "float32"
| "float64"
| "complex64"
| "complex128"
| "error"
| "any"
| "interface"
| "struct"
| "map"
| "chan"
| "func"
) || w.chars().all(|c| c.is_ascii_digit())
}
fn elem_ty_spelling(ty: &str) -> Option<String> {
if let Some(rest) = ty.strip_prefix("[]") {
return Some(rest.to_string());
}
if let Some(rest) = ty.strip_prefix("map[") {
let mut depth = 0usize;
for (i, c) in rest.char_indices() {
match c {
'[' => depth += 1,
']' if depth == 0 => return Some(rest[i + 1..].to_string()),
']' => depth -= 1,
_ => {}
}
}
return None;
}
let rest = ty.strip_prefix('[')?;
let close = rest.find(']')?;
rest[..close]
.chars()
.all(|c| c.is_ascii_digit())
.then(|| rest[close + 1..].to_string())
}
fn key_ty_spelling(ty: &str) -> Option<String> {
let rest = ty.strip_prefix("map[")?;
let mut depth = 0usize;
for (i, c) in rest.char_indices() {
match c {
'[' => depth += 1,
']' if depth == 0 => return Some(rest[..i].to_string()),
']' => depth -= 1,
_ => {}
}
}
None
}
fn b_named_box(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let inner = args.first().cloned().unwrap_or(Value::Undef);
let ty = args.get(1).map(go_str).unwrap_or_default();
Value::Obj(heap_alloc(HostObj::Named { ty, inner }))
}
pub(crate) fn unname(v: &Value) -> Value {
let Value::Obj(id) = v else { return v.clone() };
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Named { inner, .. }) => inner.clone(),
_ => v.clone(),
})
}
fn b_elem_tag(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let v = args.first().cloned().unwrap_or(Value::Undef);
let ty = args.get(1).map(go_str).unwrap_or_default();
tag_elem_ty(&v, &ty)
}
fn tag_elem_ty(v: &Value, ty: &str) -> Value {
let Some(elem) = elem_ty_spelling(ty) else {
return v.clone();
};
if nil_composite_kind(v).is_some() {
return v.clone();
}
if let Some(pairs) = map_pairs(v) {
let key = key_ty_spelling(ty).unwrap_or_default();
let tagged = pairs
.into_iter()
.map(|(k, val)| (tag_elem_ty(&k, &key), tag_elem_ty(&val, &elem)))
.collect();
return Value::Obj(heap_alloc(HostObj::Map(GoMap::from_pairs(tagged))));
}
let Some(es) = slice_elems(v) else {
return v.clone();
};
let elems: Vec<Value> = es.iter().map(|e| tag_elem_ty(e, &elem)).collect();
let arr_ty = match v {
Value::Obj(id) => HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Slice { arr_ty, .. }) => arr_ty.clone(),
_ => None,
}),
_ => None,
};
Value::Obj(heap_alloc(HostObj::Slice {
elems,
arr_ty,
elem_ty: Some(elem),
}))
}
pub(crate) fn slice_elems(v: &Value) -> Option<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::Slice { elems: a, .. }) => Some(a.clone()),
Some(HostObj::SliceView {
backing,
offset,
len,
..
}) => match h.get(*backing as usize) {
Some(HostObj::Slice { elems: a, .. }) => Some(a[*offset..*offset + *len].to_vec()),
_ => Some(Vec::new()),
},
Some(HostObj::Nil {
kind: NilKind::Slice,
..
}) => Some(Vec::new()),
_ => None,
}
})
}
pub(crate) fn bytes_of(v: &Value) -> Option<Vec<u8>> {
match v {
Value::Str(s) => Some(s.as_str().as_bytes().to_vec()),
_ => {
let es = slice_elems(v)?;
es.iter()
.map(|e| match e {
Value::Int(n) if (0..=255).contains(n) => Some(*n as u8),
_ => None,
})
.collect()
}
}
}
fn obj_str_mode(id: u32, mode: FmtMode) -> String {
let sharp = mode == FmtMode::SharpV;
let sep = if sharp { ", " } else { " " };
let elems = |vs: &[Value]| -> String {
vs.iter()
.map(|v| go_str_mode(v, mode))
.collect::<Vec<_>>()
.join(sep)
};
let id = follow(id);
HEAP.with(|h| {
let h = h.borrow();
match h.get(id as usize) {
Some(HostObj::Ptr { .. }) => String::new(),
Some(HostObj::Slice {
elems: a, elem_ty, ..
}) => {
if !sharp {
return format!("[{}]", elems(a));
}
if elem_ty.as_deref().is_some_and(is_byte_elem) {
let bytes: Vec<String> =
a.iter().map(|e| format!("{:#04x}", e.to_int())).collect();
return format!("[]byte{{{}}}", bytes.join(", "));
}
format!("{}{{{}}}", go_type_name(&Value::Obj(id)), elems(a))
}
Some(HostObj::SliceView {
backing,
offset,
len,
..
}) => {
let view: Vec<Value> = match h.get(*backing as usize) {
Some(HostObj::Slice { elems: a, .. }) => a[*offset..*offset + *len].to_vec(),
_ => Vec::new(),
};
if sharp {
format!("{}{{{}}}", go_type_name(&Value::Obj(id)), elems(&view))
} else {
format!("[{}]", elems(&view))
}
}
Some(HostObj::Map(m)) => {
let mut pairs: Vec<(String, String)> = m
.iter()
.map(|(k, v)| (go_str_mode(k, mode), go_str_mode(v, mode)))
.collect();
pairs.sort_by(|a, b| map_key_cmp(&a.0, &b.0));
let body = pairs
.into_iter()
.map(|(k, v)| format!("{k}:{v}"))
.collect::<Vec<_>>()
.join(sep);
if sharp {
format!("{}{{{}}}", go_type_name(&Value::Obj(id)), body)
} else {
format!("map[{body}]")
}
}
Some(HostObj::F32(f)) => format_float32(*f),
Some(HostObj::U64 { val, .. }) => val.to_string(),
Some(HostObj::ChanClosed) => "<nil>".to_string(),
Some(HostObj::Spread(xs)) => xs
.iter()
.map(|x| go_str_mode(x, mode))
.collect::<Vec<_>>()
.join(" "),
Some(HostObj::Nil { kind, ty }) => match (mode, kind) {
(FmtMode::SharpV, _) => format!("{ty}(nil)"),
(_, NilKind::Slice) => "[]".to_string(),
(_, NilKind::Map) => "map[]".to_string(),
},
Some(HostObj::Struct {
type_name, fields, ..
}) => match mode {
FmtMode::V => {
let parts: Vec<String> =
fields.iter().map(|(_, v)| go_str_mode(v, mode)).collect();
format!("{{{}}}", parts.join(" "))
}
FmtMode::PlusV => {
let parts: Vec<String> = fields
.iter()
.map(|(n, v)| format!("{n}:{}", go_str_mode(v, mode)))
.collect();
format!("{{{}}}", parts.join(" "))
}
FmtMode::SharpV => {
let parts: Vec<String> = fields
.iter()
.map(|(n, v)| format!("{n}:{}", go_str_mode(v, mode)))
.collect();
format!("main.{type_name}{{{}}}", parts.join(", "))
}
},
Some(HostObj::Closure { .. }) => "<func>".to_string(),
Some(HostObj::Cell(v)) => go_str_mode(v, mode),
Some(HostObj::Named { ty, inner }) => {
let body = go_str_mode(inner, mode);
let composite = slice_elems(inner).is_some() || map_pairs(inner).is_some();
match body.find('{').filter(|_| sharp && composite) {
Some(i) => format!("{}{}", go_type_spelling(ty), &body[i..]),
None => body,
}
}
None => "<nil>".to_string(),
}
})
}
fn map_key_cmp(a: &str, b: &str) -> std::cmp::Ordering {
match (a.parse::<f64>(), b.parse::<f64>()) {
(Ok(x), Ok(y)) => x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal),
_ => a.cmp(b),
}
}
pub(crate) fn format_float(f: f64) -> String {
if f.is_nan() {
return "NaN".to_string();
}
if f.is_infinite() {
return if f < 0.0 { "-Inf" } else { "+Inf" }.to_string();
}
let (mant, exp) = shortest_sci(f);
if !(-4..6).contains(&exp) {
format_e(&mant, exp, 'e')
} else {
format!("{f}")
}
}
pub(crate) fn format_float32(f: f32) -> String {
if f.is_nan() {
return "NaN".to_string();
}
if f.is_infinite() {
return if f < 0.0 { "-Inf" } else { "+Inf" }.to_string();
}
let (mant, exp) = shortest_sci_32(f);
if !(-4..6).contains(&exp) {
format_e(&mant, exp, 'e')
} else {
plain_form(&mant, exp)
}
}
fn shortest_sci_32(f: f32) -> (String, i32) {
let s = format!("{f:e}");
let (mant, exp) = s.split_once('e').unwrap_or((s.as_str(), "0"));
(go_even_tie(mant, f), exp.parse().unwrap_or(0))
}
fn go_even_tie(mant: &str, f: f32) -> String {
let Some(last) = mant.chars().last() else {
return mant.to_string();
};
if !matches!(last, '1' | '3' | '5' | '7' | '9') {
return mant.to_string();
}
let digits: String = mant.chars().filter(char::is_ascii_digit).collect();
let exact = exact_sig_digits(f);
let lower = format!("{}{}", &digits[..digits.len() - 1], step_down(last));
if exact.len() != digits.len() + 1 || !exact.ends_with('5') || exact[..digits.len()] != lower {
return mant.to_string();
}
let mut out: Vec<char> = mant.chars().collect();
if let Some(c) = out.last_mut() {
*c = step_down(last);
}
out.into_iter().collect()
}
fn step_down(d: char) -> char {
char::from(d as u8 - 1)
}
fn exact_sig_digits(f: f32) -> String {
let s = format!("{:.*}", 160, f64::from(f).abs());
let digits: String = s.chars().filter(char::is_ascii_digit).collect();
digits
.trim_start_matches('0')
.trim_end_matches('0')
.to_string()
}
fn plain_form(mant: &str, exp: i32) -> String {
let (sign, m) = match mant.strip_prefix('-') {
Some(rest) => ("-", rest),
None => ("", mant),
};
let digits: String = m.chars().filter(char::is_ascii_digit).collect();
let point = exp + 1; if point <= 0 {
format!(
"{sign}0.{}{digits}",
"0".repeat(point.unsigned_abs() as usize)
)
} else if point as usize >= digits.len() {
format!(
"{sign}{digits}{}",
"0".repeat(point as usize - digits.len())
)
} else {
format!(
"{sign}{}.{}",
&digits[..point as usize],
&digits[point as usize..]
)
}
}
fn shortest_sci(f: f64) -> (String, i32) {
let s = format!("{f:e}");
match s.split_once('e') {
Some((m, e)) => (m.to_string(), e.parse().unwrap_or(0)),
None => (s, 0),
}
}
fn format_e(mant: &str, exp: i32, e: char) -> String {
let sign = if exp < 0 { '-' } else { '+' };
let mag = exp.unsigned_abs();
if mag < 10 {
format!("{mant}{e}{sign}0{mag}")
} else {
format!("{mant}{e}{sign}{mag}")
}
}
fn format_float_e(f: f64, prec: Option<usize>, upper: bool) -> String {
if f.is_nan() {
return "NaN".to_string();
}
if f.is_infinite() {
return if f < 0.0 { "-Inf" } else { "+Inf" }.to_string();
}
let e = if upper { 'E' } else { 'e' };
match prec {
None => {
let (mant, exp) = shortest_sci(f);
format_e(&mant, exp, e)
}
Some(p) => {
let s = format!("{:.*e}", p, f);
match s.split_once('e') {
Some((m, ex)) => format_e(m, ex.parse().unwrap_or(0), e),
None => s,
}
}
}
}
fn format_float_g(f: f64, prec: Option<usize>, upper: bool) -> String {
if f.is_nan() {
return "NaN".to_string();
}
if f.is_infinite() {
return if f < 0.0 { "-Inf" } else { "+Inf" }.to_string();
}
let Some(p) = prec else {
let s = format_float(f);
return if upper { s.replace('e', "E") } else { s };
};
let p = p.max(1);
let (mant, exp) = match format!("{:.*e}", p - 1, f).split_once('e') {
Some((m, e)) => (m.to_string(), e.parse::<i32>().unwrap_or(0)),
None => (format!("{f}"), 0),
};
let e = if upper { 'E' } else { 'e' };
if exp < -4 || exp >= p as i32 {
format_e(trim_zeros(&mant), exp, e)
} else {
let decimals = (p as i32 - 1 - exp).max(0) as usize;
trim_zeros(&format!("{:.*}", decimals, f)).to_string()
}
}
fn trim_zeros(s: &str) -> &str {
if !s.contains('.') {
return s;
}
s.trim_end_matches('0').trim_end_matches('.')
}
fn b_println(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let text: Vec<String> = args.iter().map(go_str).collect();
println!("{}", text.join(" "));
Value::Undef
}
fn b_print(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
print!("{}", go_print_spacing(&args));
Value::Undef
}
fn b_printf(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
print!("{}", sprintf(&args));
Value::Undef
}
fn b_eprintln(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let text: Vec<String> = args.iter().map(go_str).collect();
eprintln!("{}", text.join(" "));
Value::Undef
}
fn b_eprint(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
eprint!("{}", go_print_spacing(&args));
Value::Undef
}
fn go_print_spacing(args: &[Value]) -> String {
let mut out = String::new();
for (i, v) in args.iter().enumerate() {
if i > 0 {
let prev_str = matches!(args[i - 1], Value::Str(_));
let cur_str = matches!(v, Value::Str(_));
if !prev_str && !cur_str {
out.push(' ');
}
}
out.push_str(&go_str(v));
}
out
}
#[derive(Clone, Copy, Default)]
struct Spec {
left: bool,
zero: bool,
plus: bool,
sharp: bool,
space: bool,
width: Option<usize>,
prec: Option<usize>,
}
fn sign_of(neg: bool, spec: &Spec) -> &'static str {
if neg {
"-"
} else if spec.plus {
"+"
} else if spec.space {
" "
} else {
""
}
}
fn sprintf(args: &[Value]) -> String {
let fmt = args.first().map(go_str).unwrap_or_default();
let operands: &[Value] = args.get(1..).unwrap_or(&[]);
let mut next = 0usize;
let mut out = String::new();
let chars: Vec<char> = fmt.chars().collect();
let mut i = 0;
let mut reordered = false;
while i < chars.len() {
if chars[i] != '%' {
out.push(chars[i]);
i += 1;
continue;
}
i += 1;
let mut good_arg_num = true;
let mut spec = Spec::default();
while i < chars.len() {
match chars[i] {
'-' => spec.left = true,
'0' => spec.zero = true,
'+' => spec.plus = true,
'#' => spec.sharp = true,
' ' => spec.space = true,
_ => break,
}
i += 1;
}
let mut after_index = arg_number(
&chars,
&mut i,
&mut next,
operands.len(),
&mut reordered,
&mut good_arg_num,
);
if i < chars.len() && chars[i] == '*' {
i += 1;
after_index = false;
match star_arg(operands, &mut next) {
Some(n) if n < 0 => {
spec.left = true;
spec.width = Some(n.unsigned_abs() as usize);
}
Some(n) => spec.width = Some(n as usize),
None => out.push_str("%!(BADWIDTH)"),
}
} else {
let mut width = 0usize;
let mut has_width = false;
while i < chars.len() && chars[i].is_ascii_digit() {
has_width = true;
width = width * 10 + (chars[i] as usize - '0' as usize);
i += 1;
}
spec.width = has_width.then_some(width);
if after_index && spec.width.is_some() {
good_arg_num = false;
}
}
if i < chars.len() && chars[i] == '.' {
i += 1;
if after_index {
good_arg_num = false;
}
after_index = arg_number(
&chars,
&mut i,
&mut next,
operands.len(),
&mut reordered,
&mut good_arg_num,
);
if i < chars.len() && chars[i] == '*' {
i += 1;
after_index = false;
match star_arg(operands, &mut next) {
Some(n) if n >= 0 => spec.prec = Some(n as usize),
_ => out.push_str("%!(BADPREC)"),
}
} else {
let mut p = 0usize;
while i < chars.len() && chars[i].is_ascii_digit() {
p = p * 10 + (chars[i] as usize - '0' as usize);
i += 1;
}
spec.prec = Some(p);
}
}
if !after_index {
arg_number(
&chars,
&mut i,
&mut next,
operands.len(),
&mut reordered,
&mut good_arg_num,
);
}
if i >= chars.len() {
out.push_str("%!(NOVERB)");
break;
}
let verb = chars[i];
i += 1;
if verb == '%' {
out.push('%');
continue;
}
if !good_arg_num {
out.push_str(&format!("%!{verb}(BADINDEX)"));
continue;
}
let Some(v) = operands.get(next) else {
out.push_str("%!");
out.push(verb);
out.push_str("(MISSING)");
continue;
};
next += 1;
match verb {
'T' => out.push_str(&pad_text(&go_type_name(v), &spec)),
'v' | 'w' => out.push_str(&render_v(v, &spec)),
_ if is_verb(verb) => out.push_str(&render_verb(v, verb, &spec, 0)),
_ if matches!(v, Value::Undef) => out.push_str(&format!("%!{verb}(<nil>)")),
_ => out.push_str(&format!(
"%!{verb}({}={})",
go_type_name(v),
render_v(v, &spec)
)),
}
}
if !reordered && next < operands.len() {
let extra: Vec<String> = operands[next..]
.iter()
.map(|v| format!("{}={}", go_type_name(v), go_str(v)))
.collect();
out.push_str(&format!("%!(EXTRA {})", extra.join(", ")));
}
out
}
fn arg_number(
chars: &[char],
i: &mut usize,
next: &mut usize,
num_args: usize,
reordered: &mut bool,
good: &mut bool,
) -> bool {
if chars.get(*i) != Some(&'[') {
return false;
}
*reordered = true;
let (index, width, ok) = parse_arg_number(&chars[*i..]);
*i += width;
if ok && index < num_args {
*next = index;
return true;
}
*good = false;
ok
}
fn parse_arg_number(chars: &[char]) -> (usize, usize, bool) {
if chars.len() < 3 {
return (0, 1, false);
}
let Some(close) = chars.iter().position(|&c| c == ']') else {
return (0, 1, false);
};
let digits = &chars[1..close];
if digits.is_empty() || !digits.iter().all(|c| c.is_ascii_digit()) {
return (0, close + 1, false);
}
let mut n = 0usize;
for c in digits {
n = n * 10 + (*c as usize - '0' as usize);
}
match n.checked_sub(1) {
Some(index) => (index, close + 1, true),
None => (0, close + 1, false),
}
}
fn star_arg(operands: &[Value], next: &mut usize) -> Option<i64> {
let v = operands.get(*next)?;
*next += 1;
match unname(v) {
Value::Int(n) => Some(n),
_ => None,
}
}
fn render_v(v: &Value, spec: &Spec) -> String {
let numeric = spec.prec.is_some() || spec.zero || spec.space;
if numeric && !spec.plus && !spec.sharp && is_int_operand(v) {
return pad_number(&scalar_verb(v, 'd', spec), 'd', spec);
}
let mode = if spec.sharp {
FmtMode::SharpV
} else if spec.plus {
FmtMode::PlusV
} else {
FmtMode::V
};
if matches!(mode, FmtMode::V) && (spec.width.is_some() || spec.zero) {
if let Some(walked) = distribute_v(v, spec) {
return walked;
}
}
let mut s = go_str_mode(v, mode);
if let Some(p) = spec.prec {
if s.chars().count() > p {
s = s.chars().take(p).collect();
}
}
if is_num_operand(v) {
pad_number(&s, 'v', spec)
} else {
pad_text(&s, spec)
}
}
fn distribute_v(v: &Value, spec: &Spec) -> Option<String> {
if let Some(es) = slice_elems(v) {
let body: Vec<String> = es.iter().map(|e| render_v(e, spec)).collect();
return Some(format!("[{}]", body.join(" ")));
}
if let Some(pairs) = map_pairs(v) {
let mut rows: Vec<(String, String)> = pairs
.iter()
.map(|(k, val)| {
(
go_str(k),
format!("{}:{}", render_v(k, spec), render_v(val, spec)),
)
})
.collect();
rows.sort_by(|a, b| map_key_cmp(&a.0, &b.0));
let body: Vec<String> = rows.into_iter().map(|(_, r)| r).collect();
return Some(format!("map[{}]", body.join(" ")));
}
if let Some(fields) = struct_fields_of(v) {
let body: Vec<String> = fields.iter().map(|(_, f)| render_v(f, spec)).collect();
return Some(format!("{{{}}}", body.join(" ")));
}
match nil_composite_kind(v)? {
NilKind::Slice => Some("[]".to_string()),
NilKind::Map => Some("map[]".to_string()),
}
}
fn is_int_operand(v: &Value) -> bool {
arg_uint(v).is_some() || matches!(unname(v), Value::Int(_))
}
fn is_verb(c: char) -> bool {
matches!(
c,
't' | 'q'
| 'f'
| 'F'
| 'e'
| 'E'
| 'g'
| 'G'
| 'd'
| 'x'
| 'X'
| 'o'
| 'b'
| 'c'
| 'U'
| 's'
)
}
fn render_verb(v: &Value, verb: char, spec: &Spec, depth: usize) -> String {
let unnamed = unname(v);
let v = &unnamed;
if matches!(verb, 's' | 'q' | 'x' | 'X') {
if let Some(b) = slice_bytes(v) {
let text = Value::str(String::from_utf8_lossy(&b).into_owned());
return pad_text(&scalar_verb(&text, verb, spec), spec);
}
}
if let Some(es) = slice_elems(v) {
let body: Vec<String> = es
.iter()
.map(|e| render_verb(e, verb, spec, depth + 1))
.collect();
return format!("[{}]", body.join(" "));
}
if let Some(pairs) = map_pairs(v) {
let mut rows: Vec<(String, String)> = pairs
.iter()
.map(|(k, val)| {
(
go_str(k),
format!(
"{}:{}",
render_verb(k, verb, spec, depth + 1),
render_verb(val, verb, spec, depth + 1)
),
)
})
.collect();
rows.sort_by(|a, b| map_key_cmp(&a.0, &b.0));
let body: Vec<String> = rows.into_iter().map(|(_, r)| r).collect();
return format!("map[{}]", body.join(" "));
}
if let Some(fields) = struct_fields_of(v) {
let body: Vec<String> = fields
.iter()
.map(|(_, f)| render_verb(f, verb, spec, depth + 1))
.collect();
return format!("{{{}}}", body.join(" "));
}
if let Some(kind) = nil_composite_kind(v) {
return match kind {
NilKind::Slice => "[]".to_string(),
NilKind::Map => "map[]".to_string(),
};
}
if let Some(bad) = bad_verb(v, verb, spec, depth) {
return bad;
}
let body = scalar_verb(v, verb, spec);
match verb {
'd' | 'o' | 'b' | 'x' | 'X' | 'f' | 'F' | 'e' | 'E' | 'g' | 'G' => {
pad_number(&body, verb, spec)
}
'U' => pad_text(
&body,
&Spec {
zero: false,
..*spec
},
),
_ => pad_text(&body, spec),
}
}
fn slice_bytes(v: &Value) -> Option<Vec<u8>> {
if let Value::Obj(id) = v {
let nil_ty = HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Nil { kind, ty }) => Some((*kind, ty.clone())),
_ => None,
});
if let Some((kind, ty)) = nil_ty {
let bytes =
kind == NilKind::Slice && elem_ty_spelling(&ty).is_some_and(|e| is_byte_elem(&e));
return bytes.then(Vec::new);
}
}
let tagged = slice_elem_tag(v);
if matches!(&tagged, Some(t) if !is_byte_elem(t)) {
return None;
}
let es = slice_elems(v)?;
if tagged.is_none() && es.is_empty() {
return None;
}
es.iter()
.map(|e| match e {
Value::Int(n) if (0..=255).contains(n) => Some(*n as u8),
_ => None,
})
.collect()
}
fn is_byte_elem(t: &str) -> bool {
matches!(t, "byte" | "uint8")
}
fn slice_elem_tag(v: &Value) -> Option<String> {
let Value::Obj(id) = v else { return None };
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Slice { elem_ty, .. }) => elem_ty.clone(),
_ => None,
})
}
fn nil_composite_kind(v: &Value) -> Option<NilKind> {
let Value::Obj(id) = v else { return None };
HEAP.with(|h| match h.borrow().get(*id as usize) {
Some(HostObj::Nil { kind, .. }) => Some(*kind),
_ => None,
})
}
fn struct_fields_of(v: &Value) -> Option<Vec<(String, Value)>> {
let Value::Obj(id) = v else { return None };
HEAP.with(|h| match h.borrow().get(follow(*id) as usize) {
Some(HostObj::Struct { fields, .. }) => Some(fields.clone()),
_ => None,
})
}
fn scalar_verb(v: &Value, verb: char, spec: &Spec) -> String {
match verb {
't' => go_str(v),
'q' => match v {
Value::Int(n) => go_quote_rune(*n),
_ => {
let mut s = go_str(v);
if let Some(p) = spec.prec {
if s.chars().count() > p {
s = s.chars().take(p).collect();
}
}
if spec.sharp && !s.contains('`') && !s.contains('\n') {
format!("`{s}`")
} else {
go_quote(&s)
}
}
},
'f' | 'F' => {
let x = arg_float(v);
let s = if x.is_nan() {
"NaN".to_string()
} else if x.is_infinite() {
if x < 0.0 { "-Inf" } else { "+Inf" }.to_string()
} else {
format!("{:.*}", spec.prec.unwrap_or(6), x)
};
signed(s, spec)
}
'e' | 'E' => signed(
format_float_e(arg_float(v), Some(spec.prec.unwrap_or(6)), verb == 'E'),
spec,
),
'g' | 'G' => {
let s = match (spec.prec, unbox_f32(v)) {
(None, Some(f)) => {
let g = format_float32(f);
if verb == 'G' {
g.to_uppercase()
} else {
g
}
}
_ => format_float_g(arg_float(v), spec.prec, verb == 'G'),
};
signed(s, spec)
}
'd' => {
let (sign, digits) = match arg_uint(v) {
Some(u) => (sign_of(false, spec), u.to_string()),
None => {
let n = arg_int(v);
(sign_of(n < 0, spec), n.unsigned_abs().to_string())
}
};
int_precision(sign, "", &digits, spec.prec)
}
'x' | 'X' if matches!(v, Value::Str(_)) => {
let upper = verb == 'X';
let bytes: Vec<String> = go_str(v)
.bytes()
.map(|b| {
if upper {
format!("{b:02X}")
} else {
format!("{b:02x}")
}
})
.collect();
let body = bytes.join(if spec.space { " " } else { "" });
if spec.sharp {
format!("{}{body}", if upper { "0X" } else { "0x" })
} else {
body
}
}
'x' | 'X' | 'o' | 'b' => {
let (neg, mag) = match arg_uint(v) {
Some(u) => (false, u),
None => {
let n = arg_int(v);
(n < 0, n.unsigned_abs())
}
};
let mut digits = match verb {
'x' => format!("{mag:x}"),
'X' => format!("{mag:X}"),
'o' => format!("{mag:o}"),
_ => format!("{mag:b}"),
};
let prefix = match (spec.sharp, verb) {
(false, _) => "",
(true, 'x') => "0x",
(true, 'X') => "0X",
(true, 'b') => "0b",
(true, _) => {
if !digits.starts_with('0') {
digits.insert(0, '0');
}
""
}
};
int_precision(sign_of(neg, spec), prefix, &digits, spec.prec)
}
'c' => u32::try_from(arg_int(v))
.ok()
.and_then(char::from_u32)
.unwrap_or('\u{fffd}')
.to_string(),
'U' => format!("U+{:04X}", v.to_int() as u64),
's' => {
let mut s = match v {
Value::Str(s) => s.as_str().to_string(),
v => match bytes_of(v) {
Some(b) => String::from_utf8_lossy(&b).into_owned(),
None => go_str(v),
},
};
if let Some(p) = spec.prec {
if s.chars().count() > p {
s = s.chars().take(p).collect();
}
}
s
}
_ => go_str(v),
}
}
fn bad_verb(v: &Value, verb: char, spec: &Spec, depth: usize) -> Option<String> {
if matches!(v, Value::Undef) {
return Some(if depth == 0 {
format!("%!{verb}(<nil>)")
} else {
"<nil>".to_string()
});
}
let bad = match verb {
'd' | 'o' | 'c' | 'U' => matches!(v, Value::Str(_) | Value::Bool(_) | Value::Float(_)),
'b' => matches!(v, Value::Str(_) | Value::Bool(_)),
'x' | 'X' => matches!(v, Value::Bool(_)),
'f' | 'F' | 'e' | 'E' | 'g' | 'G' => matches!(v, Value::Str(_) | Value::Bool(_)),
'q' => matches!(v, Value::Bool(_) | Value::Float(_)),
's' => matches!(v, Value::Bool(_) | Value::Int(_) | Value::Float(_)),
't' => !matches!(v, Value::Bool(_)),
_ => false,
};
if !bad {
return None;
}
let mut text = go_str(v);
if let Some(p) = spec.prec {
if text.chars().count() > p {
text = text.chars().take(p).collect();
}
}
let inner = if is_num_operand(v) {
pad_number(&text, 'v', spec)
} else {
pad_text(&text, spec)
};
Some(format!("%!{verb}({}={})", go_type_name(v), inner))
}
fn int_precision(sign: &str, prefix: &str, digits: &str, prec: Option<usize>) -> String {
let Some(p) = prec else {
return format!("{sign}{prefix}{digits}");
};
if p == 0 && digits == "0" {
return format!("{sign}{prefix}");
}
let zeros = p.saturating_sub(digits.chars().count());
format!("{sign}{prefix}{}{digits}", "0".repeat(zeros))
}
fn signed(s: String, spec: &Spec) -> String {
if s.starts_with('-') {
return s;
}
format!("{}{s}", sign_of(false, spec))
}
fn pad_room(body: &str, spec: &Spec) -> Option<usize> {
let width = spec.width?;
let len = body.chars().count();
(len < width).then(|| width - len)
}
fn pad_text(body: &str, spec: &Spec) -> String {
let Some(fill) = pad_room(body, spec) else {
return body.to_string();
};
if spec.left {
return format!("{body}{}", " ".repeat(fill));
}
let fill_char = if spec.zero { "0" } else { " " };
format!("{}{body}", fill_char.repeat(fill))
}
fn pad_number(body: &str, verb: char, spec: &Spec) -> String {
let Some(fill) = pad_room(body, spec) else {
return body.to_string();
};
if spec.left {
return format!("{body}{}", " ".repeat(fill));
}
let zero = spec.zero && !(spec.prec.is_some() && matches!(verb, 'd' | 'x' | 'X' | 'o' | 'b'));
if !zero {
return format!("{}{body}", " ".repeat(fill));
}
let (sign, rest) = match body.strip_prefix(['-', '+', ' ']) {
Some(d) => (&body[..1], d),
None => ("", body),
};
let (prefix, digits) = match rest.get(..2) {
Some(p @ ("0x" | "0X" | "0b")) => (p, &rest[2..]),
_ => ("", rest),
};
format!("{sign}{prefix}{}{digits}", "0".repeat(fill + prefix.len()))
}
fn is_num_operand(v: &Value) -> bool {
arg_uint(v).is_some() || matches!(unname(v), Value::Int(_) | Value::Float(_))
}
pub mod stdlib {
use super::{go_str, heap_alloc, pop_args, HostObj, HEAP};
use fusevm::{Value, VM};
use std::cell::RefCell;
pub const TO_UPPER: u16 = 830;
pub const TO_LOWER: u16 = 831;
pub const CONTAINS: u16 = 832;
pub const HAS_PREFIX: u16 = 833;
pub const HAS_SUFFIX: u16 = 834;
pub const TRIM_SPACE: u16 = 835;
pub const SPLIT: u16 = 836;
pub const JOIN: u16 = 837;
pub const REPEAT: u16 = 838;
pub const INDEX: u16 = 839;
pub const REPLACE_ALL: u16 = 840;
pub const FIELDS: u16 = 841;
pub const COUNT: u16 = 842;
pub const TRIM_PREFIX: u16 = 843;
pub const TRIM_SUFFIX: u16 = 844;
pub const TRIM: u16 = 845;
pub const TITLE: u16 = 846;
pub const EQUAL_FOLD: u16 = 847;
pub const LAST_INDEX: u16 = 848;
pub const REPLACE: u16 = 849;
pub const ITOA: u16 = 850;
pub const ATOI: u16 = 851;
pub const PARSE_INT: u16 = 852;
pub const PARSE_FLOAT: u16 = 853;
pub const FORMAT_INT: u16 = 854;
pub const QUOTE: u16 = 855;
pub const STRCONV_ERR: u16 = 856;
pub const ABS: u16 = 860;
pub const SQRT: u16 = 861;
pub const POW: u16 = 862;
pub const FLOOR: u16 = 863;
pub const CEIL: u16 = 864;
pub const ROUND: u16 = 865;
pub const TRUNC: u16 = 866;
pub const MOD_F: u16 = 867;
pub const HYPOT: u16 = 868;
pub const MAX_F: u16 = 869;
pub const MIN_F: u16 = 870;
pub const SIN: u16 = 907;
pub const COS: u16 = 908;
pub const TAN: u16 = 909;
pub const ASIN: u16 = 910;
pub const ACOS: u16 = 911;
pub const ATAN: u16 = 912;
pub const ATAN2: u16 = 913;
pub const SINH: u16 = 914;
pub const COSH: u16 = 915;
pub const TANH: u16 = 916;
pub const EXP: u16 = 917;
pub const LOG: u16 = 918;
pub const LOG2: u16 = 919;
pub const LOG10: u16 = 920;
pub const CBRT: u16 = 921;
pub const CONTAINS_RUNE: u16 = 972;
pub const CONTAINS_ANY: u16 = 973;
pub const INDEX_BYTE: u16 = 974;
pub const INDEX_RUNE: u16 = 975;
pub const INDEX_ANY: u16 = 976;
pub const LAST_INDEX_BYTE: u16 = 977;
pub const SPLIT_N: u16 = 978;
pub const TRIM_LEFT: u16 = 979;
pub const TRIM_RIGHT: u16 = 980;
pub const COMPARE: u16 = 981;
pub const PARSE_BOOL: u16 = 982;
pub const FORMAT_BOOL: u16 = 983;
pub const FORMAT_FLOAT: u16 = 984;
pub const QUOTE_RUNE: u16 = 985;
pub const SORT_INTS: u16 = 875;
pub const SORT_STRINGS: u16 = 876;
pub const SORT_FLOAT64S: u16 = 877;
pub const GETENV: u16 = 880;
pub fn resolve(pkg: &str, func: &str) -> Option<u16> {
Some(match (pkg, func) {
("strings", "ToUpper") => TO_UPPER,
("strings", "ToLower") => TO_LOWER,
("strings", "Contains") => CONTAINS,
("strings", "HasPrefix") => HAS_PREFIX,
("strings", "HasSuffix") => HAS_SUFFIX,
("strings", "TrimSpace") => TRIM_SPACE,
("strings", "Split") => SPLIT,
("strings", "Join") => JOIN,
("strings", "Repeat") => REPEAT,
("strings", "Index") => INDEX,
("strings", "Replace") => REPLACE,
("strings", "ReplaceAll") => REPLACE_ALL,
("strings", "Fields") => FIELDS,
("strings", "Count") => COUNT,
("strings", "TrimPrefix") => TRIM_PREFIX,
("strings", "TrimSuffix") => TRIM_SUFFIX,
("strings", "Trim") => TRIM,
("strings", "Title") => TITLE,
("strings", "EqualFold") => EQUAL_FOLD,
("strings", "LastIndex") => LAST_INDEX,
("strings", "ContainsRune") => CONTAINS_RUNE,
("strings", "ContainsAny") => CONTAINS_ANY,
("strings", "IndexByte") => INDEX_BYTE,
("strings", "IndexRune") => INDEX_RUNE,
("strings", "IndexAny") => INDEX_ANY,
("strings", "LastIndexByte") => LAST_INDEX_BYTE,
("strings", "SplitN") => SPLIT_N,
("strings", "TrimLeft") => TRIM_LEFT,
("strings", "TrimRight") => TRIM_RIGHT,
("strings", "Compare") => COMPARE,
("strconv", "ParseBool") => PARSE_BOOL,
("strconv", "FormatBool") => FORMAT_BOOL,
("strconv", "FormatFloat") => FORMAT_FLOAT,
("strconv", "QuoteRune") => QUOTE_RUNE,
("strconv", "Itoa") => ITOA,
("strconv", "Atoi") => ATOI,
("strconv", "ParseInt") => PARSE_INT,
("strconv", "ParseFloat") => PARSE_FLOAT,
("strconv", "FormatInt") => FORMAT_INT,
("strconv", "Quote") => QUOTE,
("math", "Abs") => ABS,
("math", "Sqrt") => SQRT,
("math", "Pow") => POW,
("math", "Floor") => FLOOR,
("math", "Ceil") => CEIL,
("math", "Round") => ROUND,
("math", "Trunc") => TRUNC,
("math", "Mod") => MOD_F,
("math", "Hypot") => HYPOT,
("math", "Max") => MAX_F,
("math", "Min") => MIN_F,
("math", "Sin") => SIN,
("math", "Cos") => COS,
("math", "Tan") => TAN,
("math", "Asin") => ASIN,
("math", "Acos") => ACOS,
("math", "Atan") => ATAN,
("math", "Atan2") => ATAN2,
("math", "Sinh") => SINH,
("math", "Cosh") => COSH,
("math", "Tanh") => TANH,
("math", "Exp") => EXP,
("math", "Log") => LOG,
("math", "Log2") => LOG2,
("math", "Log10") => LOG10,
("math", "Cbrt") => CBRT,
("sort", "Ints") => SORT_INTS,
("sort", "Strings") => SORT_STRINGS,
("sort", "Float64s") => SORT_FLOAT64S,
("os", "Getenv") => GETENV,
_ => return None,
})
}
pub fn returns_error(pkg: &str, func: &str) -> bool {
matches!(
(pkg, func),
("strconv", "Atoi")
| ("strconv", "ParseInt")
| ("strconv", "ParseFloat")
| ("strconv", "ParseBool")
)
}
pub fn resolve_const(pkg: &str, name: &str) -> Option<Value> {
Some(match (pkg, name) {
("math", "Pi") => Value::Float(std::f64::consts::PI),
("math", "E") => Value::Float(std::f64::consts::E),
("math", "Sqrt2") => Value::Float(std::f64::consts::SQRT_2),
("math", "MaxInt64") => Value::Int(i64::MAX),
("math", "MinInt64") => Value::Int(i64::MIN),
("math", "MaxInt") => Value::Int(i64::MAX),
("math", "MinInt") => Value::Int(i64::MIN),
_ => return None,
})
}
pub fn install(vm: &mut VM) {
vm.register_builtin(TO_UPPER, |vm, a| s1(vm, a, |s| s.to_uppercase()));
vm.register_builtin(TO_LOWER, |vm, a| s1(vm, a, |s| s.to_lowercase()));
vm.register_builtin(TRIM_SPACE, |vm, a| s1(vm, a, |s| s.trim().to_string()));
vm.register_builtin(CONTAINS, |vm, a| b2(vm, a, |s, p| s.contains(p)));
vm.register_builtin(HAS_PREFIX, |vm, a| b2(vm, a, |s, p| s.starts_with(p)));
vm.register_builtin(HAS_SUFFIX, |vm, a| b2(vm, a, |s, p| s.ends_with(p)));
vm.register_builtin(INDEX, b_index);
vm.register_builtin(REPEAT, b_repeat);
vm.register_builtin(REPLACE, b_replace);
vm.register_builtin(REPLACE_ALL, b_replace_all);
vm.register_builtin(SPLIT, b_split);
vm.register_builtin(FIELDS, b_fields);
vm.register_builtin(JOIN, b_join);
vm.register_builtin(ITOA, b_itoa);
vm.register_builtin(ATOI, b_atoi);
vm.register_builtin(COUNT, b_count);
vm.register_builtin(TRIM_PREFIX, |vm, a| {
two_str(vm, a, |s, p| s.strip_prefix(p).unwrap_or(s).to_string())
});
vm.register_builtin(TRIM_SUFFIX, |vm, a| {
two_str(vm, a, |s, p| s.strip_suffix(p).unwrap_or(s).to_string())
});
vm.register_builtin(TRIM, |vm, a| {
two_str(vm, a, |s, cut| {
s.trim_matches(|c| cut.contains(c)).to_string()
})
});
vm.register_builtin(TITLE, |vm, a| s1(vm, a, title_case));
vm.register_builtin(EQUAL_FOLD, |vm, a| {
b2(vm, a, |s, t| s.eq_ignore_ascii_case(t))
});
vm.register_builtin(LAST_INDEX, b_last_index);
vm.register_builtin(CONTAINS_RUNE, |vm, a| {
let args = pop_args(vm, a);
let s = args.first().map(go_str).unwrap_or_default();
Value::bool(rune_of(args.get(1)).is_some_and(|r| s.contains(r)))
});
vm.register_builtin(INDEX_RUNE, |vm, a| {
let args = pop_args(vm, a);
let s = args.first().map(go_str).unwrap_or_default();
let at = rune_of(args.get(1)).and_then(|r| s.find(r));
Value::Int(at.map(|b| b as i64).unwrap_or(-1))
});
vm.register_builtin(CONTAINS_ANY, |vm, a| {
b2(vm, a, |s, chars| s.contains(|c| chars.contains(c)))
});
vm.register_builtin(INDEX_BYTE, |vm, a| {
let args = pop_args(vm, a);
let s = args.first().map(go_str).unwrap_or_default();
let b = args.get(1).map(|v| v.to_int()).unwrap_or(-1);
let at = u8::try_from(b)
.ok()
.and_then(|b| s.bytes().position(|x| x == b));
Value::Int(at.map(|i| i as i64).unwrap_or(-1))
});
vm.register_builtin(LAST_INDEX_BYTE, |vm, a| {
let args = pop_args(vm, a);
let s = args.first().map(go_str).unwrap_or_default();
let b = args.get(1).map(|v| v.to_int()).unwrap_or(-1);
let at = u8::try_from(b)
.ok()
.and_then(|b| s.bytes().rposition(|x| x == b));
Value::Int(at.map(|i| i as i64).unwrap_or(-1))
});
vm.register_builtin(INDEX_ANY, |vm, a| {
let args = pop_args(vm, a);
let s = args.first().map(go_str).unwrap_or_default();
let chars = args.get(1).map(go_str).unwrap_or_default();
let at = s.find(|c| chars.contains(c));
Value::Int(at.map(|b| b as i64).unwrap_or(-1))
});
vm.register_builtin(SPLIT_N, b_split_n);
vm.register_builtin(TRIM_LEFT, |vm, a| {
two_str(vm, a, |s, cut| {
s.trim_start_matches(|c| cut.contains(c)).to_string()
})
});
vm.register_builtin(TRIM_RIGHT, |vm, a| {
two_str(vm, a, |s, cut| {
s.trim_end_matches(|c| cut.contains(c)).to_string()
})
});
vm.register_builtin(COMPARE, |vm, a| {
let args = pop_args(vm, a);
let s = args.first().map(go_str).unwrap_or_default();
let t = args.get(1).map(go_str).unwrap_or_default();
Value::Int(match s.cmp(&t) {
std::cmp::Ordering::Less => -1,
std::cmp::Ordering::Equal => 0,
std::cmp::Ordering::Greater => 1,
})
});
vm.register_builtin(PARSE_BOOL, b_parse_bool);
vm.register_builtin(FORMAT_BOOL, |vm, a| {
let args = pop_args(vm, a);
let b = matches!(args.first(), Some(Value::Bool(true)));
Value::str(if b { "true" } else { "false" })
});
vm.register_builtin(FORMAT_FLOAT, b_format_float);
vm.register_builtin(QUOTE_RUNE, |vm, a| {
let args = pop_args(vm, a);
Value::str(super::go_quote_rune(
args.first().map(|v| v.to_int()).unwrap_or(0),
))
});
vm.register_builtin(PARSE_INT, b_parse_int);
vm.register_builtin(PARSE_FLOAT, b_parse_float);
vm.register_builtin(FORMAT_INT, b_format_int);
vm.register_builtin(QUOTE, |vm, a| s1(vm, a, super::go_quote));
vm.register_builtin(STRCONV_ERR, b_strconv_err);
vm.register_builtin(ABS, |vm, a| math1(vm, a, f64::abs));
vm.register_builtin(SQRT, |vm, a| math1(vm, a, f64::sqrt));
vm.register_builtin(FLOOR, |vm, a| math1(vm, a, f64::floor));
vm.register_builtin(CEIL, |vm, a| math1(vm, a, f64::ceil));
vm.register_builtin(ROUND, |vm, a| math1(vm, a, f64::round));
vm.register_builtin(TRUNC, |vm, a| math1(vm, a, f64::trunc));
vm.register_builtin(POW, |vm, a| math2(vm, a, f64::powf));
vm.register_builtin(MOD_F, |vm, a| math2(vm, a, |x, y| x % y));
vm.register_builtin(HYPOT, |vm, a| math2(vm, a, f64::hypot));
vm.register_builtin(MAX_F, |vm, a| math2(vm, a, f64::max));
vm.register_builtin(MIN_F, |vm, a| math2(vm, a, f64::min));
vm.register_builtin(SIN, |vm, a| math1(vm, a, f64::sin));
vm.register_builtin(COS, |vm, a| math1(vm, a, f64::cos));
vm.register_builtin(TAN, |vm, a| math1(vm, a, f64::tan));
vm.register_builtin(ASIN, |vm, a| math1(vm, a, f64::asin));
vm.register_builtin(ACOS, |vm, a| math1(vm, a, f64::acos));
vm.register_builtin(ATAN, |vm, a| math1(vm, a, f64::atan));
vm.register_builtin(ATAN2, |vm, a| math2(vm, a, f64::atan2));
vm.register_builtin(SINH, |vm, a| math1(vm, a, f64::sinh));
vm.register_builtin(COSH, |vm, a| math1(vm, a, f64::cosh));
vm.register_builtin(TANH, |vm, a| math1(vm, a, f64::tanh));
vm.register_builtin(EXP, |vm, a| math1(vm, a, f64::exp));
vm.register_builtin(LOG, |vm, a| math1(vm, a, f64::ln));
vm.register_builtin(LOG2, |vm, a| math1(vm, a, f64::log2));
vm.register_builtin(LOG10, |vm, a| math1(vm, a, f64::log10));
vm.register_builtin(CBRT, |vm, a| math1(vm, a, f64::cbrt));
vm.register_builtin(SORT_INTS, |vm, a| {
sort_slice(vm, a, |x, y| x.to_int().cmp(&y.to_int()))
});
vm.register_builtin(SORT_FLOAT64S, |vm, a| {
sort_slice(vm, a, |x, y| {
x.to_float()
.partial_cmp(&y.to_float())
.unwrap_or(std::cmp::Ordering::Equal)
})
});
vm.register_builtin(SORT_STRINGS, |vm, a| {
sort_slice(vm, a, |x, y| go_str(x).cmp(&go_str(y)))
});
vm.register_builtin(GETENV, |vm, a| {
let args = pop_args(vm, a);
let k = args.first().map(go_str).unwrap_or_default();
Value::str(std::env::var(&k).unwrap_or_default())
});
}
fn two_str(vm: &mut VM, argc: u8, f: impl Fn(&str, &str) -> String) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
let p = args.get(1).map(go_str).unwrap_or_default();
Value::str(f(&s, &p))
}
fn math1(vm: &mut VM, argc: u8, f: impl Fn(f64) -> f64) -> Value {
let args = pop_args(vm, argc);
Value::Float(f(args.first().map(|v| v.to_float()).unwrap_or(0.0)))
}
fn math2(vm: &mut VM, argc: u8, f: impl Fn(f64, f64) -> f64) -> Value {
let args = pop_args(vm, argc);
let a = args.first().map(|v| v.to_float()).unwrap_or(0.0);
let b = args.get(1).map(|v| v.to_float()).unwrap_or(0.0);
Value::Float(f(a, b))
}
fn sort_slice(
vm: &mut VM,
argc: u8,
cmp: impl Fn(&Value, &Value) -> std::cmp::Ordering,
) -> Value {
let args = pop_args(vm, argc);
if let Some(Value::Obj(id)) = args.first() {
if let Some((backing, offset, len)) = super::slice_backing(*id) {
HEAP.with(|h| {
if let Some(HostObj::Slice { elems: a, .. }) =
h.borrow_mut().get_mut(backing as usize)
{
a[offset..offset + len].sort_by(cmp);
}
});
}
}
Value::Undef
}
fn title_case(s: &str) -> String {
s.split(' ')
.map(|w| {
let mut c = w.chars();
match c.next() {
Some(f) => f.to_uppercase().chain(c).collect::<String>(),
None => String::new(),
}
})
.collect::<Vec<_>>()
.join(" ")
}
fn b_count(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
let sub = args.get(1).map(go_str).unwrap_or_default();
Value::Int(if sub.is_empty() {
s.chars().count() as i64 + 1
} else {
s.matches(&sub).count() as i64
})
}
fn b_last_index(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
let sub = args.get(1).map(go_str).unwrap_or_default();
Value::Int(s.rfind(&sub).map(|b| b as i64).unwrap_or(-1))
}
fn b_parse_int(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
let base = args.get(1).map(|v| v.to_int()).unwrap_or(10).max(2) as u32;
parse_signed(&s, base, "ParseInt")
}
fn b_parse_float(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
match s.parse::<f64>() {
Ok(f)
if f.is_infinite()
&& !s.trim_start_matches(['+', '-']).eq_ignore_ascii_case("inf") =>
{
parsed(Value::Float(f), Some(num_error("ParseFloat", &s, RANGE)))
}
Ok(f) => parsed(Value::Float(f), None),
Err(_) => parsed(Value::Float(0.0), Some(num_error("ParseFloat", &s, SYNTAX))),
}
}
fn b_format_int(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let n = args.first().map(|v| v.to_int()).unwrap_or(0);
let base = args.get(1).map(|v| v.to_int()).unwrap_or(10);
Value::str(match base {
2 => format!("{n:b}"),
8 => format!("{n:o}"),
16 => format!("{n:x}"),
_ => n.to_string(),
})
}
fn s1(vm: &mut VM, argc: u8, f: impl Fn(&str) -> String) -> Value {
let args = pop_args(vm, argc);
Value::str(f(&args.first().map(go_str).unwrap_or_default()))
}
fn b2(vm: &mut VM, argc: u8, f: impl Fn(&str, &str) -> bool) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
let p = args.get(1).map(go_str).unwrap_or_default();
Value::bool(f(&s, &p))
}
fn b_index(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
let sub = args.get(1).map(go_str).unwrap_or_default();
Value::Int(s.find(&sub).map(|b| b as i64).unwrap_or(-1))
}
fn b_repeat(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
let n = args.get(1).map(|v| v.to_int()).unwrap_or(0).max(0) as usize;
Value::str(s.repeat(n))
}
fn b_replace(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
let old = args.get(1).map(go_str).unwrap_or_default();
let new = args.get(2).map(go_str).unwrap_or_default();
let n = args.get(3).map(|v| v.to_int()).unwrap_or(-1);
if old.is_empty() {
return Value::str(s);
}
Value::str(if n < 0 {
s.replace(&old, &new)
} else {
s.replacen(&old, &new, n as usize)
})
}
fn b_replace_all(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
let old = args.get(1).map(go_str).unwrap_or_default();
let new = args.get(2).map(go_str).unwrap_or_default();
Value::str(if old.is_empty() {
s
} else {
s.replace(&old, &new)
})
}
fn b_split(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
let sep = args.get(1).map(go_str).unwrap_or_default();
let parts: Vec<Value> = if sep.is_empty() {
s.chars().map(|c| Value::str(c.to_string())).collect()
} else {
s.split(&sep).map(Value::str).collect()
};
Value::Obj(heap_alloc(HostObj::slice(parts)))
}
fn b_split_n(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
let sep = args.get(1).map(go_str).unwrap_or_default();
let n = args.get(2).map(|v| v.to_int()).unwrap_or(-1);
if n == 0 {
return super::typed_nil("[]string");
}
let parts: Vec<Value> = match (sep.is_empty(), usize::try_from(n).ok()) {
(true, Some(k)) => {
let mut rest = s.as_str();
let mut out = Vec::new();
while out.len() + 1 < k && !rest.is_empty() {
let c = rest.chars().next().expect("non-empty");
out.push(Value::str(c.to_string()));
rest = &rest[c.len_utf8()..];
}
if k > 0 && !rest.is_empty() {
out.push(Value::str(rest.to_string()));
}
out
}
(true, None) => s.chars().map(|c| Value::str(c.to_string())).collect(),
(false, Some(k)) => s.splitn(k, &sep).map(Value::str).collect(),
(false, None) => s.split(&sep).map(Value::str).collect(),
};
Value::Obj(heap_alloc(HostObj::slice(parts)))
}
fn b_parse_bool(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
match s.as_str() {
"1" | "t" | "T" | "TRUE" | "true" | "True" => parsed(Value::bool(true), None),
"0" | "f" | "F" | "FALSE" | "false" | "False" => parsed(Value::bool(false), None),
_ => parsed(Value::bool(false), Some(num_error("ParseBool", &s, SYNTAX))),
}
}
fn rune_of(v: Option<&Value>) -> Option<char> {
char::from_u32(u32::try_from(v?.to_int()).ok()?)
}
fn shortest_fixed(f: f64, narrowed: bool) -> String {
if narrowed {
format!("{}", f as f32)
} else {
format!("{f}")
}
}
fn shortest_sci32(f: f32, upper: bool) -> String {
let s = format!("{f:e}");
let e = if upper { 'E' } else { 'e' };
match s.split_once('e') {
Some((mant, exp)) => super::format_e(mant, exp.parse().unwrap_or(0), e),
None => s,
}
}
fn b_format_float(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let f = args.first().map(|v| v.to_float()).unwrap_or(0.0);
let verb =
char::from_u32(args.get(1).map(|v| v.to_int()).unwrap_or(0) as u32).unwrap_or('\0');
let prec = args.get(2).map(|v| v.to_int()).unwrap_or(-1);
let bits = args.get(3).map(|v| v.to_int()).unwrap_or(64);
let prec = usize::try_from(prec).ok();
let narrowed = bits == 32;
let f = if narrowed { f as f32 as f64 } else { f };
if f.is_nan() {
return Value::str("NaN");
}
if f.is_infinite() {
return Value::str(if f < 0.0 { "-Inf" } else { "+Inf" });
}
let out = match verb {
'f' | 'F' => match prec {
Some(p) => format!("{:.*}", p, f),
None => shortest_fixed(f, narrowed),
},
'e' | 'E' => match (prec, narrowed) {
(None, true) => shortest_sci32(f as f32, verb == 'E'),
_ => super::format_float_e(f, prec, verb == 'E'),
},
'g' | 'G' => match (prec, narrowed) {
(None, true) => {
let g = super::format_float32(f as f32);
if verb == 'G' {
g.to_uppercase()
} else {
g
}
}
_ => super::format_float_g(f, prec, verb == 'G'),
},
'b' | 'x' | 'X' => {
super::ffi_fault(
vm,
format!("go-rs: strconv.FormatFloat: fmt '{verb}' is not implemented"),
);
return Value::Undef;
}
other => format!("%{other}"),
};
Value::str(out)
}
fn b_fields(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
let parts: Vec<Value> = s.split_whitespace().map(Value::str).collect();
Value::Obj(heap_alloc(HostObj::slice(parts)))
}
fn b_join(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let sep = args.get(1).map(go_str).unwrap_or_default();
let joined = match args.first() {
Some(Value::Obj(id)) => HEAP.with(|h| {
let h = h.borrow();
let elems: &[Value] = match h.get(*id as usize) {
Some(HostObj::Slice { elems: a, .. }) => a,
Some(HostObj::SliceView {
backing,
offset,
len,
..
}) => match h.get(*backing as usize) {
Some(HostObj::Slice { elems: a, .. }) => &a[*offset..*offset + *len],
_ => &[],
},
_ => &[],
};
elems.iter().map(go_str).collect::<Vec<_>>().join(&sep)
}),
_ => String::new(),
};
Value::str(joined)
}
fn b_itoa(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
Value::str(args.first().map(|v| v.to_int()).unwrap_or(0).to_string())
}
fn parsed(value: Value, err: Option<Value>) -> Value {
let e = err.unwrap_or(Value::Undef);
Value::Obj(heap_alloc(HostObj::slice(vec![value, e])))
}
thread_local! {
static SENTINELS: RefCell<std::collections::HashMap<&'static str, Value>> =
RefCell::new(std::collections::HashMap::new());
}
pub(super) fn sentinels_reset() {
SENTINELS.with(|s| s.borrow_mut().clear());
}
fn sentinel(reason: &'static str) -> Value {
SENTINELS.with(|s| {
s.borrow_mut()
.entry(reason)
.or_insert_with(|| super::make_error(reason.to_string()))
.clone()
})
}
fn b_strconv_err(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
match args.first().map(go_str).unwrap_or_default().as_str() {
"ErrRange" => sentinel(RANGE),
_ => sentinel(SYNTAX),
}
}
fn num_error(func: &str, num: &str, reason: &'static str) -> Value {
Value::Obj(heap_alloc(HostObj::Struct {
type_name: NUM_ERROR.to_string(),
fields: vec![
("Func".to_string(), Value::str(func.to_string())),
("Num".to_string(), Value::str(num.to_string())),
("Err".to_string(), sentinel(reason)),
],
by_ref: true,
}))
}
pub const NUM_ERROR: &str = "strconv.NumError";
const SYNTAX: &str = "invalid syntax";
const RANGE: &str = "value out of range";
fn parse_signed(s: &str, base: u32, func: &str) -> Value {
match i64::from_str_radix(s, base) {
Ok(n) => parsed(Value::Int(n), None),
Err(e) => {
let (v, reason) = match e.kind() {
std::num::IntErrorKind::PosOverflow => (i64::MAX, RANGE),
std::num::IntErrorKind::NegOverflow => (i64::MIN, RANGE),
_ => (0, SYNTAX),
};
parsed(Value::Int(v), Some(num_error(func, s, reason)))
}
}
}
fn b_atoi(vm: &mut VM, argc: u8) -> Value {
let args = pop_args(vm, argc);
let s = args.first().map(go_str).unwrap_or_default();
parse_signed(&s, 10, "Atoi")
}
}
fn int_pair(a: &Value, b: &Value) -> Option<(i64, i64)> {
match (a, b) {
(Value::Int(x), Value::Int(y)) => Some((*x, *y)),
_ => None,
}
}
fn mixed_num_pair(a: &Value, b: &Value) -> bool {
matches!(
(a, b),
(Value::Int(_), Value::Float(_)) | (Value::Float(_), Value::Int(_))
)
}
pub fn numeric_hook(op: NumOp, a: &Value, b: &Value) -> Result<Value, String> {
match op {
NumOp::Add if matches!(a, Value::Undef) => Ok(b.clone()),
NumOp::Add if matches!(b, Value::Undef) => Ok(a.clone()),
NumOp::Add | NumOp::Sub | NumOp::Mul if int_pair(a, b).is_some() => {
let (x, y) = int_pair(a, b).unwrap_or((0, 0));
Ok(Value::Int(match op {
NumOp::Add => x.wrapping_add(y),
NumOp::Sub => x.wrapping_sub(y),
_ => x.wrapping_mul(y),
}))
}
NumOp::Neg if matches!(a, Value::Int(_)) => Ok(Value::Int(a.to_int().wrapping_neg())),
NumOp::Eq | NumOp::Ne if mixed_num_pair(a, b) => Ok(Value::bool(op == NumOp::Ne)),
NumOp::Add
| NumOp::Sub
| NumOp::Mul
| NumOp::Div
| NumOp::Mod
| NumOp::Pow
| NumOp::Lt
| NumOp::Gt
| NumOp::Le
| NumOp::Ge
if mixed_num_pair(a, b) =>
{
let (x, y) = if matches!(a, Value::Int(_)) {
("int", "float64")
} else {
("float64", "int")
};
Err(format!(
"go-rs: invalid operation: operator {op:?} not defined on mismatched types {x} and {y}"
))
}
NumOp::Add => Ok(Value::str(format!("{}{}", go_str(a), go_str(b)))),
NumOp::Eq | NumOp::Ne if nil_kind(a).is_some() || nil_kind(b).is_some() => {
let same = matches!((a, b), (Value::Undef, _) | (_, Value::Undef))
|| matches!((a, b), (Value::Obj(x), Value::Obj(y)) if x == y);
Ok(Value::bool(if op == NumOp::Eq { same } else { !same }))
}
NumOp::Eq | NumOp::Ne if ptr_eq(a, b).is_some() => {
let same = ptr_eq(a, b).unwrap_or(false);
Ok(Value::bool(if op == NumOp::Eq { same } else { !same }))
}
NumOp::Eq => Ok(Value::bool(go_str(a) == go_str(b))),
NumOp::Ne => Ok(Value::bool(go_str(a) != go_str(b))),
NumOp::Lt => Ok(Value::bool(go_str(a) < go_str(b))),
NumOp::Gt => Ok(Value::bool(go_str(a) > go_str(b))),
NumOp::Le => Ok(Value::bool(go_str(a) <= go_str(b))),
NumOp::Ge => Ok(Value::bool(go_str(a) >= go_str(b))),
NumOp::Sub | NumOp::Mul | NumOp::Div | NumOp::Mod | NumOp::Pow => Err(format!(
"go-rs: invalid operation: operator {op:?} not defined on `{}`",
go_str(a)
)),
NumOp::Neg => Err(format!(
"go-rs: invalid operation: unary `-` not defined on `{}`",
go_str(a)
)),
}
}