haku2: add stats + fix crash w uninit vm

This commit is contained in:
りき萌 2025-06-16 16:39:54 +02:00
parent e667c6336a
commit 00a48527ca
12 changed files with 88 additions and 71 deletions

View file

@ -134,9 +134,15 @@ extern "C" {
) -> *mut DefsC;
fn haku2_defs_destroy(defs: *mut DefsC);
fn haku2_vm_new(s: *mut ScratchC, defs: *const DefsC, limits: *const LimitsC) -> *mut VmC;
fn haku2_vm_new() -> *mut VmC;
fn haku2_vm_destroy(vm: *mut VmC);
fn haku2_vm_reset(vm: *mut VmC, fuel: u32);
fn haku2_vm_reset(
vm: *mut VmC,
s: *mut ScratchC,
defs: *const DefsC,
limits: *const LimitsC,
fuel: u32,
);
fn haku2_vm_run_main(
vm: *mut VmC,
scratch: *mut ScratchC,
@ -296,6 +302,7 @@ impl Code {
pub struct Vm {
scratch: Scratch,
code: Code,
limits: Limits,
inner: VmInner,
}
@ -318,15 +325,10 @@ pub struct Dotter {
}
impl Vm {
pub fn new(scratch: Scratch, code: Code, limits: &Limits) -> Self {
let raw = NonNull::new(unsafe {
haku2_vm_new(
scratch.raw.as_ptr(),
code.defs.raw.as_ptr(),
limits.raw.as_ptr(),
)
})
.expect("out of memory");
pub fn new(scratch: Scratch, code: Code, limits: Limits) -> Self {
// SAFETY: haku2_vm_new cannot fail.
// Do note that this returns an uninitialized VM, which must be reset before use.
let raw = NonNull::new(unsafe { haku2_vm_new() }).expect("out of memory");
trace!("Vm::new({scratch:?}, {code:?}, {limits:?}) -> {raw:?}");
Self {
// SAFETY:
@ -336,6 +338,7 @@ impl Vm {
inner: VmInner { raw },
scratch,
code,
limits,
}
}
@ -346,8 +349,15 @@ impl Vm {
/// continuation being stack on top of the old one---at the expense of a stack slot.
pub fn begin(&mut self, fuel: u32) -> Result<(), Exception> {
trace!("Vm::begin({self:?}, {fuel})");
self.scratch.reset();
let ok = unsafe {
haku2_vm_reset(self.inner.raw.as_ptr(), fuel);
haku2_vm_reset(
self.inner.raw.as_ptr(),
self.scratch.raw.as_ptr(),
self.code.defs.raw.as_ptr(),
self.limits.raw.as_ptr(),
fuel,
);
haku2_vm_run_main(
self.inner.raw.as_ptr(),
self.scratch.raw.as_ptr(),
@ -422,6 +432,7 @@ impl Vm {
mut scratch,
code: _,
inner: _,
limits: _,
} = self;
scratch.reset();
scratch