removed bounded from VM, bytecode and specs

This commit is contained in:
2026-03-24 13:40:44 +00:00
parent a04f462939
commit cfdca93160
18 changed files with 894 additions and 507 deletions
+332 -246
View File
@@ -1,19 +1,19 @@
use crate::call_frame::CallFrame;
use crate::heap::{CoroutineState, Heap};
use crate::object::ObjectKind;
use crate::roots::{RootVisitor, visit_value_for_roots};
use crate::scheduler::Scheduler;
use crate::verifier::Verifier;
use crate::vm_init_error::VmInitError;
use crate::{HostContext, NativeInterface};
use prometeu_bytecode::isa::core::CoreOpCode as OpCode;
use prometeu_bytecode::HeapRef;
use prometeu_bytecode::ProgramImage;
use prometeu_bytecode::Value;
use crate::roots::{RootVisitor, visit_value_for_roots};
use crate::heap::{Heap, CoroutineState};
use crate::object::ObjectKind;
use crate::scheduler::Scheduler;
use prometeu_bytecode::isa::core::CoreOpCode as OpCode;
use prometeu_bytecode::{
TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_INVALID_FUNC, TRAP_INVALID_SYSCALL, TRAP_OOB,
TRAP_STACK_UNDERFLOW, TRAP_TYPE, TrapInfo,
};
use prometeu_bytecode::HeapRef;
use prometeu_hal::syscalls::caps::ALL;
use prometeu_hal::vm_fault::VmFault;
@@ -109,7 +109,6 @@ pub struct VirtualMachine {
current_coro: Option<HeapRef>,
}
impl Default for VirtualMachine {
fn default() -> Self {
Self::new(vec![], vec![])
@@ -118,10 +117,14 @@ impl Default for VirtualMachine {
impl VirtualMachine {
/// Returns the current program counter.
pub fn pc(&self) -> usize { self.pc }
pub fn pc(&self) -> usize {
self.pc
}
/// Returns true if there are no active call frames.
pub fn call_stack_is_empty(&self) -> bool { self.call_stack.is_empty() }
pub fn call_stack_is_empty(&self) -> bool {
self.call_stack.is_empty()
}
/// Returns up to `n` values from the top of the operand stack (top-first order).
pub fn operand_stack_top(&self, n: usize) -> Vec<Value> {
@@ -131,20 +134,30 @@ impl VirtualMachine {
}
/// Returns true if the VM has executed a HALT and is not currently running.
pub fn is_halted(&self) -> bool { self.halted }
pub fn is_halted(&self) -> bool {
self.halted
}
/// Adds a software breakpoint at the given PC.
pub fn insert_breakpoint(&mut self, pc: usize) { let _ = self.breakpoints.insert(pc); }
pub fn insert_breakpoint(&mut self, pc: usize) {
let _ = self.breakpoints.insert(pc);
}
/// Removes a software breakpoint at the given PC, if present.
pub fn remove_breakpoint(&mut self, pc: usize) { let _ = self.breakpoints.remove(&pc); }
pub fn remove_breakpoint(&mut self, pc: usize) {
let _ = self.breakpoints.remove(&pc);
}
/// Returns the list of currently configured breakpoints.
pub fn breakpoints_list(&self) -> Vec<usize> { self.breakpoints.iter().cloned().collect() }
pub fn breakpoints_list(&self) -> Vec<usize> {
self.breakpoints.iter().cloned().collect()
}
// Test-only helpers for internal unit tests within this crate.
#[cfg(test)]
pub(crate) fn push_operand_for_test(&mut self, v: Value) { self.operand_stack.push(v); }
pub(crate) fn push_operand_for_test(&mut self, v: Value) {
self.operand_stack.push(v);
}
/// Creates a new VM instance with the provided bytecode and constants.
pub fn new(rom: Vec<u8>, constant_pool: Vec<Value>) -> Self {
Self {
@@ -340,7 +353,10 @@ impl VirtualMachine {
let mut steps_executed = 0;
let mut ending_reason: Option<LogicalFrameEndingReason> = None;
while (self.cycles - start_cycles) < budget && !self.halted && self.pc < self.program.rom.len() {
while (self.cycles - start_cycles) < budget
&& !self.halted
&& self.pc < self.program.rom.len()
{
// Debugger support: stop before executing an instruction if there's a breakpoint.
// Note: we skip the check for the very first step of a slice to avoid
// getting stuck on the same breakpoint repeatedly.
@@ -388,7 +404,6 @@ impl VirtualMachine {
})
}
/// Harness: run exactly `frames` logical frames deterministically.
///
/// This repeatedly calls `run_budget` with the provided `budget_per_slice` until
@@ -465,12 +480,13 @@ impl VirtualMachine {
| LogicalFrameEndingReason::Breakpoint
);
out.push(rep);
if terminal { break; }
if terminal {
break;
}
}
Ok(out)
}
/// Executes a single instruction at the current Program Counter (PC).
///
/// This follows the classic CPU cycle:
@@ -628,14 +644,23 @@ impl VirtualMachine {
args.reverse();
// Build operand stack for the new coroutine: params followed by zeroed locals
let mut new_stack: Vec<Value> = Vec::with_capacity((param_slots + local_slots) as usize);
let mut new_stack: Vec<Value> =
Vec::with_capacity((param_slots + local_slots) as usize);
// Place user args as parameters
for v in args { new_stack.push(v); }
for v in args {
new_stack.push(v);
}
// Zero-init locals
for _ in 0..local_slots { new_stack.push(Value::Null); }
for _ in 0..local_slots {
new_stack.push(Value::Null);
}
// Initial frame for the coroutine (sentinel-like return to end-of-rom)
let frames = vec![CallFrame { return_pc: self.program.rom.len() as u32, stack_base: 0, func_idx: fn_id }];
let frames = vec![CallFrame {
return_pc: self.program.rom.len() as u32,
stack_base: 0,
func_idx: fn_id,
}];
let href = self.heap.allocate_coroutine(
entry_pc,
@@ -663,11 +688,9 @@ impl VirtualMachine {
// wake_tick = current_tick + duration + 1
let duration = instr
.imm_u32()
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))? as u64;
let wake = self
.current_tick
.saturating_add(duration)
.saturating_add(1);
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?
as u64;
let wake = self.current_tick.saturating_add(duration).saturating_add(1);
self.sleep_requested_until = Some(wake);
// End the logical frame right after the instruction completes
@@ -716,7 +739,7 @@ impl VirtualMachine {
other
),
start_pc as u32,
))
));
}
};
@@ -733,10 +756,7 @@ impl VirtualMachine {
return Err(self.trap(
TRAP_TYPE,
opcode as u16,
format!(
"CALL_CLOSURE on non-closure object kind {:?}",
header.kind
),
format!("CALL_CLOSURE on non-closure object kind {:?}", header.kind),
start_pc as u32,
));
}
@@ -785,7 +805,9 @@ impl VirtualMachine {
// Prepare the operand stack to match the direct CALL convention:
// push hidden arg0 (closure_ref) followed by arg1..argN.
self.push(Value::HeapRef(href));
for v in user_args.into_iter() { self.push(v); }
for v in user_args.into_iter() {
self.push(v);
}
let stack_base = self
.operand_stack
@@ -794,9 +816,15 @@ impl VirtualMachine {
.ok_or_else(|| LogicalFrameEndingReason::Panic("Stack underflow".into()))?;
// Allocate and zero-init local slots
for _ in 0..callee_local_slots { self.operand_stack.push(Value::Null); }
for _ in 0..callee_local_slots {
self.operand_stack.push(Value::Null);
}
self.call_stack.push(CallFrame { return_pc: self.pc as u32, stack_base, func_idx: fn_id });
self.call_stack.push(CallFrame {
return_pc: self.pc as u32,
stack_base,
func_idx: fn_id,
});
self.pc = callee_code_offset;
}
OpCode::PushConst => {
@@ -821,20 +849,6 @@ impl VirtualMachine {
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?;
self.push(Value::Int32(val));
}
OpCode::PushBounded => {
let val = instr
.imm_u32()
.map_err(|e| LogicalFrameEndingReason::Panic(format!("{:?}", e)))?;
if val > 0xFFFF {
return Err(self.trap(
TRAP_OOB,
opcode as u16,
format!("Bounded value overflow: {} > 0xFFFF", val),
start_pc as u32,
));
}
self.push(Value::Bounded(val));
}
OpCode::PushF64 => {
let val = instr
.imm_f64()
@@ -883,17 +897,6 @@ impl VirtualMachine {
(Value::Float(a), Value::Int32(b)) => Ok(Value::Float(a + *b as f64)),
(Value::Int64(a), Value::Float(b)) => Ok(Value::Float(*a as f64 + b)),
(Value::Float(a), Value::Int64(b)) => Ok(Value::Float(a + *b as f64)),
(Value::Bounded(a), Value::Bounded(b)) => {
let res = a.saturating_add(*b);
if res > 0xFFFF {
Err(OpError::Trap(
TRAP_OOB,
format!("Bounded addition overflow: {} + {} = {}", a, b, res),
))
} else {
Ok(Value::Bounded(res))
}
}
_ => Err(OpError::Panic("Invalid types for ADD".into())),
})?,
OpCode::Sub => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
@@ -906,16 +909,6 @@ impl VirtualMachine {
(Value::Float(a), Value::Int32(b)) => Ok(Value::Float(a - b as f64)),
(Value::Int64(a), Value::Float(b)) => Ok(Value::Float(a as f64 - b)),
(Value::Float(a), Value::Int64(b)) => Ok(Value::Float(a - b as f64)),
(Value::Bounded(a), Value::Bounded(b)) => {
if a < b {
Err(OpError::Trap(
TRAP_OOB,
format!("Bounded subtraction underflow: {} - {} < 0", a, b),
))
} else {
Ok(Value::Bounded(a - b))
}
}
_ => Err(OpError::Panic("Invalid types for SUB".into())),
})?,
OpCode::Mul => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
@@ -928,17 +921,6 @@ impl VirtualMachine {
(Value::Float(a), Value::Int32(b)) => Ok(Value::Float(a * b as f64)),
(Value::Int64(a), Value::Float(b)) => Ok(Value::Float(a as f64 * b)),
(Value::Float(a), Value::Int64(b)) => Ok(Value::Float(a * b as f64)),
(Value::Bounded(a), Value::Bounded(b)) => {
let res = a as u64 * b as u64;
if res > 0xFFFF {
Err(OpError::Trap(
TRAP_OOB,
format!("Bounded multiplication overflow: {} * {} = {}", a, b, res),
))
} else {
Ok(Value::Bounded(res as u32))
}
}
_ => Err(OpError::Panic("Invalid types for MUL".into())),
})?,
OpCode::Div => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
@@ -1008,15 +990,6 @@ impl VirtualMachine {
}
Ok(Value::Float(a / b as f64))
}
(Value::Bounded(a), Value::Bounded(b)) => {
if b == 0 {
return Err(OpError::Trap(
TRAP_DIV_ZERO,
"Bounded division by zero".into(),
));
}
Ok(Value::Bounded(a / b))
}
_ => Err(OpError::Panic("Invalid types for DIV".into())),
})?,
OpCode::Mod => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
@@ -1032,41 +1005,8 @@ impl VirtualMachine {
}
Ok(Value::Int64(a % b))
}
(Value::Bounded(a), Value::Bounded(b)) => {
if b == 0 {
return Err(OpError::Trap(TRAP_DIV_ZERO, "Bounded modulo by zero".into()));
}
Ok(Value::Bounded(a % b))
}
_ => Err(OpError::Panic("Invalid types for MOD".into())),
})?,
OpCode::BoundToInt => {
let val = self.pop().map_err(LogicalFrameEndingReason::Panic)?;
if let Value::Bounded(b) = val {
self.push(Value::Int64(b as i64));
} else {
return Err(LogicalFrameEndingReason::Panic(
"Expected bounded for BOUND_TO_INT".into(),
));
}
}
OpCode::IntToBoundChecked => {
let val = self.pop().map_err(LogicalFrameEndingReason::Panic)?;
let int_val = val.as_integer().ok_or_else(|| {
LogicalFrameEndingReason::Panic(
"Expected integer for INT_TO_BOUND_CHECKED".into(),
)
})?;
if !(0..=0xFFFF).contains(&int_val) {
return Err(self.trap(
TRAP_OOB,
OpCode::IntToBoundChecked as u16,
format!("Integer to bounded conversion out of range: {}", int_val),
start_pc as u32,
));
}
self.push(Value::Bounded(int_val as u32));
}
OpCode::Eq => {
self.binary_op(opcode, start_pc as u32, |a, b| Ok(Value::Boolean(a == b)))?
}
@@ -1323,7 +1263,8 @@ impl VirtualMachine {
OpCode::Syscall as u16,
format!(
"Missing capability for syscall {} (required=0x{:X})",
syscall.name(), meta.caps
syscall.name(),
meta.caps
),
pc_at_syscall,
));
@@ -1394,12 +1335,16 @@ impl VirtualMachine {
// Collect GC roots from VM state
struct CollectRoots(Vec<prometeu_bytecode::HeapRef>);
impl crate::roots::RootVisitor for CollectRoots {
fn visit_heap_ref(&mut self, r: prometeu_bytecode::HeapRef) { self.0.push(r); }
fn visit_heap_ref(&mut self, r: prometeu_bytecode::HeapRef) {
self.0.push(r);
}
}
let mut collector = CollectRoots(Vec::new());
self.visit_roots(&mut collector);
// Add current coroutine and all suspended (ready/sleeping) coroutines as GC roots
if let Some(cur) = self.current_coro { collector.0.push(cur); }
if let Some(cur) = self.current_coro {
collector.0.push(cur);
}
let mut coro_roots = self.heap.suspended_coroutine_handles();
collector.0.append(&mut coro_roots);
@@ -1583,10 +1528,13 @@ impl VirtualMachine {
for frame in &self.call_stack {
if let Some(func_meta) = self.program.functions.get(frame.func_idx) {
let start = frame.stack_base;
let frame_slots = (func_meta.param_slots as usize) + (func_meta.local_slots as usize);
let frame_slots =
(func_meta.param_slots as usize) + (func_meta.local_slots as usize);
let mut end = start.saturating_add(frame_slots);
// Clamp to current stack height just in case
if end > self.operand_stack.len() { end = self.operand_stack.len(); }
if end > self.operand_stack.len() {
end = self.operand_stack.len();
}
for i in start..end {
if let Some(v) = self.operand_stack.get(i) {
visit_value_for_roots(v, visitor);
@@ -1727,13 +1675,25 @@ mod tests {
for _ in 0..10 {
if !vm1.halted {
let rep = vm1.run_budget(4, &mut native, &mut ctx1).expect("vm1 ok");
trace1.push((vm1.pc, vm1.current_tick, vm1.operand_stack.len(), format!("{:?}", rep.reason)));
trace1.push((
vm1.pc,
vm1.current_tick,
vm1.operand_stack.len(),
format!("{:?}", rep.reason),
));
}
if !vm2.halted {
let rep = vm2.run_budget(4, &mut native, &mut ctx2).expect("vm2 ok");
trace2.push((vm2.pc, vm2.current_tick, vm2.operand_stack.len(), format!("{:?}", rep.reason)));
trace2.push((
vm2.pc,
vm2.current_tick,
vm2.operand_stack.len(),
format!("{:?}", rep.reason),
));
}
if vm1.halted && vm2.halted {
break;
}
if vm1.halted && vm2.halted { break; }
}
assert!(vm1.halted && vm2.halted, "Both VMs should reach HALT deterministically");
@@ -1801,7 +1761,7 @@ mod tests {
#[test]
fn test_gc_many_coroutines_and_wake_order_determinism() {
use crate::heap::{CoroutineState};
use crate::heap::CoroutineState;
use crate::object::ObjectKind;
// ROM: FrameSync; FrameSync; Halt (two deterministic safepoints back-to-back)
@@ -1824,7 +1784,10 @@ mod tests {
}
// Sanity: allocations present
assert!(vm.heap.len() as u32 >= coro_count, "heap should contain coroutine objects and bytes");
assert!(
vm.heap.len() as u32 >= coro_count,
"heap should contain coroutine objects and bytes"
);
let mut native = MockNative;
let mut ctx = HostContext::new(None);
@@ -1902,54 +1865,6 @@ mod tests {
}
}
#[test]
fn test_int_to_bound_checked_trap() {
let mut native = MockNative;
let mut ctx = HostContext::new(None);
let mut rom = Vec::new();
rom.extend_from_slice(&(OpCode::PushI32 as u16).to_le_bytes());
rom.extend_from_slice(&70000i32.to_le_bytes()); // > 65535
rom.extend_from_slice(&(OpCode::IntToBoundChecked as u16).to_le_bytes());
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
let mut vm = new_test_vm(rom.clone(), vec![]);
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
match report.reason {
LogicalFrameEndingReason::Trap(trap) => {
assert_eq!(trap.code, TRAP_OOB);
assert_eq!(trap.opcode, OpCode::IntToBoundChecked as u16);
}
_ => panic!("Expected Trap, got {:?}", report.reason),
}
}
#[test]
fn test_bounded_add_overflow_trap() {
let mut native = MockNative;
let mut ctx = HostContext::new(None);
let mut rom = Vec::new();
rom.extend_from_slice(&(OpCode::PushBounded as u16).to_le_bytes());
rom.extend_from_slice(&60000u32.to_le_bytes());
rom.extend_from_slice(&(OpCode::PushBounded as u16).to_le_bytes());
rom.extend_from_slice(&10000u32.to_le_bytes());
rom.extend_from_slice(&(OpCode::Add as u16).to_le_bytes());
rom.extend_from_slice(&(OpCode::Halt as u16).to_le_bytes());
let mut vm = new_test_vm(rom.clone(), vec![]);
let report = vm.run_budget(100, &mut native, &mut ctx).unwrap();
match report.reason {
LogicalFrameEndingReason::Trap(trap) => {
assert_eq!(trap.code, TRAP_OOB);
assert_eq!(trap.opcode, OpCode::Add as u16);
}
_ => panic!("Expected Trap, got {:?}", report.reason),
}
}
#[test]
fn test_comparisons_polymorphic() {
let mut native = MockNative;
@@ -2377,7 +2292,6 @@ mod tests {
assert!(vm.pop().is_err()); // Stack should be empty
}
#[test]
fn test_entry_point_ret_with_prepare_call() {
// PushI32 0 (0x17), then Ret (0x51)
@@ -2431,7 +2345,7 @@ mod tests {
) -> Result<(), VmFault> {
ret.push_bool(true);
ret.push_int(42);
ret.push_bounded(255)?;
ret.push_int(255);
Ok(())
}
}
@@ -2688,20 +2602,6 @@ mod tests {
}
}
#[test]
fn test_host_return_bounded_overflow_trap() {
let mut stack = Vec::new();
let mut ret = HostReturn::new(&mut stack);
let res = ret.push_bounded(65536);
assert!(res.is_err());
match res.err().unwrap() {
VmFault::Trap(code, _) => {
assert_eq!(code, TRAP_OOB);
}
_ => panic!("Expected Trap"),
}
}
#[test]
fn test_loader_hardening_invalid_magic() {
let mut vm = VirtualMachine::default();
@@ -3441,13 +3341,17 @@ mod tests {
other => panic!("Expected FrameSync, got {:?}", other),
}
assert_eq!(vm.heap.len(), 1, "All short-lived objects except main coroutine must be reclaimed deterministically");
assert_eq!(
vm.heap.len(),
1,
"All short-lived objects except main coroutine must be reclaimed deterministically"
);
}
#[test]
fn test_gc_keeps_objects_captured_by_suspended_coroutines() {
use crate::object::ObjectKind;
use crate::heap::CoroutineState;
use crate::object::ObjectKind;
// ROM: FRAME_SYNC; HALT (trigger GC at safepoint)
let mut rom = Vec::new();
@@ -3474,7 +3378,11 @@ mod tests {
vec![],
);
assert_eq!(vm.heap.len(), 3, "object + suspended coroutine + main coroutine must be allocated");
assert_eq!(
vm.heap.len(),
3,
"object + suspended coroutine + main coroutine must be allocated"
);
let mut native = MockNative;
let mut ctx = HostContext::new(None);
@@ -3572,9 +3480,30 @@ mod tests {
// VM with three functions (0=main, 1=A, 2=B)
let mut vm = new_test_vm(rom.clone(), vec![]);
vm.program.functions = std::sync::Arc::from(vec![
FunctionMeta { code_offset: off_main as u32, code_len: main.len() as u32, param_slots: 0, local_slots: 0, return_slots: 0, max_stack_slots: 8 },
FunctionMeta { code_offset: off_a as u32, code_len: fn_a.len() as u32, param_slots: 0, local_slots: 0, return_slots: 0, max_stack_slots: 8 },
FunctionMeta { code_offset: off_b as u32, code_len: fn_b.len() as u32, param_slots: 0, local_slots: 0, return_slots: 0, max_stack_slots: 8 },
FunctionMeta {
code_offset: off_main as u32,
code_len: main.len() as u32,
param_slots: 0,
local_slots: 0,
return_slots: 0,
max_stack_slots: 8,
},
FunctionMeta {
code_offset: off_a as u32,
code_len: fn_a.len() as u32,
param_slots: 0,
local_slots: 0,
return_slots: 0,
max_stack_slots: 8,
},
FunctionMeta {
code_offset: off_b as u32,
code_len: fn_b.len() as u32,
param_slots: 0,
local_slots: 0,
return_slots: 0,
max_stack_slots: 8,
},
]);
let mut native = MockNative;
@@ -3589,16 +3518,24 @@ mod tests {
// Consider currently running coroutine
if let Some(cur) = vm.current_coro {
if let Some(f) = vm.call_stack.last() {
if f.func_idx == 1 { a_href = Some(cur); }
if f.func_idx == 2 { b_href = Some(cur); }
if f.func_idx == 1 {
a_href = Some(cur);
}
if f.func_idx == 2 {
b_href = Some(cur);
}
}
}
// And also consider suspended (Ready/Sleeping) coroutines
for h in vm.heap.suspended_coroutine_handles() {
if let Some(co) = vm.heap.coroutine_data(h) {
if let Some(f) = co.frames.last() {
if f.func_idx == 1 { a_href = Some(h); }
if f.func_idx == 2 { b_href = Some(h); }
if f.func_idx == 1 {
a_href = Some(h);
}
if f.func_idx == 2 {
b_href = Some(h);
}
}
}
}
@@ -3613,10 +3550,15 @@ mod tests {
let _ = vm.run_budget(100, &mut native, &mut ctx).unwrap();
let a_now = vm.heap.coroutine_data(a_href).unwrap().stack.len();
let b_now = vm.heap.coroutine_data(b_href).unwrap().stack.len();
if a_now > prev_a { trace.push(1); }
else if b_now > prev_b { trace.push(2); }
else { panic!("no coroutine progress detected this frame"); }
prev_a = a_now; prev_b = b_now;
if a_now > prev_a {
trace.push(1);
} else if b_now > prev_b {
trace.push(2);
} else {
panic!("no coroutine progress detected this frame");
}
prev_a = a_now;
prev_b = b_now;
}
assert_eq!(trace, vec![1, 2, 1, 2, 1, 2], "Coroutines must strictly alternate under Yield");
@@ -3668,9 +3610,30 @@ mod tests {
let mut vm = new_test_vm(rom.clone(), vec![]);
vm.program.functions = std::sync::Arc::from(vec![
FunctionMeta { code_offset: off_main as u32, code_len: main.len() as u32, param_slots: 0, local_slots: 0, return_slots: 0, max_stack_slots: 8 },
FunctionMeta { code_offset: off_a as u32, code_len: fn_a.len() as u32, param_slots: 0, local_slots: 0, return_slots: 0, max_stack_slots: 8 },
FunctionMeta { code_offset: off_b as u32, code_len: fn_b.len() as u32, param_slots: 0, local_slots: 0, return_slots: 0, max_stack_slots: 8 },
FunctionMeta {
code_offset: off_main as u32,
code_len: main.len() as u32,
param_slots: 0,
local_slots: 0,
return_slots: 0,
max_stack_slots: 8,
},
FunctionMeta {
code_offset: off_a as u32,
code_len: fn_a.len() as u32,
param_slots: 0,
local_slots: 0,
return_slots: 0,
max_stack_slots: 8,
},
FunctionMeta {
code_offset: off_b as u32,
code_len: fn_b.len() as u32,
param_slots: 0,
local_slots: 0,
return_slots: 0,
max_stack_slots: 8,
},
]);
let mut native = MockNative;
@@ -3685,15 +3648,23 @@ mod tests {
let mut b_href = None;
if let Some(cur) = vm.current_coro {
if let Some(f) = vm.call_stack.last() {
if f.func_idx == 1 { a_href = Some(cur); }
if f.func_idx == 2 { b_href = Some(cur); }
if f.func_idx == 1 {
a_href = Some(cur);
}
if f.func_idx == 2 {
b_href = Some(cur);
}
}
}
for h in vm.heap.suspended_coroutine_handles() {
if let Some(co) = vm.heap.coroutine_data(h) {
if let Some(f) = co.frames.last() {
if f.func_idx == 1 { a_href = Some(h); }
if f.func_idx == 2 { b_href = Some(h); }
if f.func_idx == 1 {
a_href = Some(h);
}
if f.func_idx == 2 {
b_href = Some(h);
}
}
}
}
@@ -3728,7 +3699,10 @@ mod tests {
// in the following frame, and we observe its heap stack update at end tick = wake_tick + 1.
// A executes SLEEP at its first run (tick 1), so wake_tick = 1 + N + 1, observed tick = +1.
let expected_observed_end_tick = 1u64 + sleep_n as u64 + 2u64;
assert_eq!(woke_at_tick, expected_observed_end_tick, "A must wake at the exact tick (+1 frame to observe)");
assert_eq!(
woke_at_tick, expected_observed_end_tick,
"A must wake at the exact tick (+1 frame to observe)"
);
// And B must have produced at least N items (one per frame) before A's wake.
assert!(ones_before as u64 >= sleep_n as u64, "B must keep running while A sleeps");
}
@@ -3776,9 +3750,30 @@ mod tests {
let mut vm1 = new_test_vm(rom.clone(), vec![]);
let mut vm2 = new_test_vm(rom.clone(), vec![]);
let fm: std::sync::Arc<[prometeu_bytecode::FunctionMeta]> = std::sync::Arc::from(vec![
FunctionMeta { code_offset: off_main as u32, code_len: main.len() as u32, param_slots: 0, local_slots: 0, return_slots: 0, max_stack_slots: 8 },
FunctionMeta { code_offset: off_a as u32, code_len: fn_a.len() as u32, param_slots: 0, local_slots: 0, return_slots: 0, max_stack_slots: 8 },
FunctionMeta { code_offset: off_b as u32, code_len: fn_b.len() as u32, param_slots: 0, local_slots: 0, return_slots: 0, max_stack_slots: 8 },
FunctionMeta {
code_offset: off_main as u32,
code_len: main.len() as u32,
param_slots: 0,
local_slots: 0,
return_slots: 0,
max_stack_slots: 8,
},
FunctionMeta {
code_offset: off_a as u32,
code_len: fn_a.len() as u32,
param_slots: 0,
local_slots: 0,
return_slots: 0,
max_stack_slots: 8,
},
FunctionMeta {
code_offset: off_b as u32,
code_len: fn_b.len() as u32,
param_slots: 0,
local_slots: 0,
return_slots: 0,
max_stack_slots: 8,
},
]);
vm1.program.functions = fm.clone();
vm2.program.functions = fm;
@@ -3793,20 +3788,29 @@ mod tests {
// Discover A/B handles in both VMs
let find_ab = |vm: &VirtualMachine| {
let mut a = None; let mut b = None;
let mut a = None;
let mut b = None;
// running
if let Some(cur) = vm.current_coro {
if let Some(f) = vm.call_stack.last() {
if f.func_idx == 1 { a = Some(cur); }
if f.func_idx == 2 { b = Some(cur); }
if f.func_idx == 1 {
a = Some(cur);
}
if f.func_idx == 2 {
b = Some(cur);
}
}
}
// suspended
for h in vm.heap.suspended_coroutine_handles() {
if let Some(co) = vm.heap.coroutine_data(h) {
if let Some(f) = co.frames.last() {
if f.func_idx == 1 { a = Some(h); }
if f.func_idx == 2 { b = Some(h); }
if f.func_idx == 1 {
a = Some(h);
}
if f.func_idx == 2 {
b = Some(h);
}
}
}
}
@@ -3826,17 +3830,34 @@ mod tests {
let _ = vm1.run_budget(100, &mut native, &mut c1).unwrap();
let a_now = vm1.heap.coroutine_data(a1).unwrap().stack.len();
let b_now = vm1.heap.coroutine_data(b1).unwrap().stack.len();
if a_now > a1_prev { trace1.push(1); } else if b_now > b1_prev { trace1.push(2); } else { panic!("no progress 1"); }
a1_prev = a_now; b1_prev = b_now;
if a_now > a1_prev {
trace1.push(1);
} else if b_now > b1_prev {
trace1.push(2);
} else {
panic!("no progress 1");
}
a1_prev = a_now;
b1_prev = b_now;
let _ = vm2.run_budget(100, &mut native, &mut c2).unwrap();
let a2_now = vm2.heap.coroutine_data(a2).unwrap().stack.len();
let b2_now = vm2.heap.coroutine_data(b2).unwrap().stack.len();
if a2_now > a2_prev { trace2.push(1); } else if b2_now > b2_prev { trace2.push(2); } else { panic!("no progress 2"); }
a2_prev = a2_now; b2_prev = b2_now;
if a2_now > a2_prev {
trace2.push(1);
} else if b2_now > b2_prev {
trace2.push(2);
} else {
panic!("no progress 2");
}
a2_prev = a2_now;
b2_prev = b2_now;
}
assert_eq!(trace1, trace2, "Execution trace (coroutine IDs) must match exactly across runs");
assert_eq!(
trace1, trace2,
"Execution trace (coroutine IDs) must match exactly across runs"
);
}
#[test]
@@ -3867,9 +3888,23 @@ mod tests {
let mut vm = new_test_vm(rom.clone(), vec![]);
vm.program.functions = std::sync::Arc::from(vec![
FunctionMeta { code_offset: off_main as u32, code_len: main.len() as u32, param_slots: 0, local_slots: 0, return_slots: 0, max_stack_slots: 8 },
FunctionMeta {
code_offset: off_main as u32,
code_len: main.len() as u32,
param_slots: 0,
local_slots: 0,
return_slots: 0,
max_stack_slots: 8,
},
// Function F takes 1 parameter (the HeapRef) which stays on its stack while sleeping
FunctionMeta { code_offset: off_f as u32, code_len: fn_f.len() as u32, param_slots: 1, local_slots: 0, return_slots: 0, max_stack_slots: 8 },
FunctionMeta {
code_offset: off_f as u32,
code_len: fn_f.len() as u32,
param_slots: 1,
local_slots: 0,
return_slots: 0,
max_stack_slots: 8,
},
]);
// Force GC at first safepoint to stress retention
@@ -3887,7 +3922,10 @@ mod tests {
assert!(matches!(rep.reason, LogicalFrameEndingReason::FrameSync));
// The captured object must remain alive because it is referenced by the sleeping coroutine's stack
assert!(vm.heap.is_valid(captured), "captured object must remain alive while coroutine sleeps");
assert!(
vm.heap.is_valid(captured),
"captured object must remain alive while coroutine sleeps"
);
}
#[test]
@@ -3918,7 +3956,10 @@ mod tests {
assert!(vm.halted);
assert_eq!(vm.operand_stack.len(), 1);
let top = vm.peek().unwrap().clone();
let href = match top { Value::HeapRef(h) => h, _ => panic!("Expected HeapRef on stack") };
let href = match top {
Value::HeapRef(h) => h,
_ => panic!("Expected HeapRef on stack"),
};
assert!(vm.heap.is_valid(href));
assert_eq!(vm.heap.closure_fn_id(href), Some(7));
let env = vm.heap.closure_env_slice(href).expect("env slice");
@@ -3961,7 +4002,10 @@ mod tests {
// After HALT, stack must contain only the closure ref
assert_eq!(vm.operand_stack.len(), 1);
let href = match vm.pop().unwrap() { Value::HeapRef(h) => h, _ => panic!("Expected HeapRef") };
let href = match vm.pop().unwrap() {
Value::HeapRef(h) => h,
_ => panic!("Expected HeapRef"),
};
assert_eq!(vm.heap.closure_fn_id(href), Some(9));
let env = vm.heap.closure_env_slice(href).expect("env slice");
assert_eq!(env.len(), 3);
@@ -3995,8 +4039,18 @@ mod tests {
let mut vm = new_test_vm(rom.clone(), vec![]);
vm.program.functions = std::sync::Arc::from(vec![
FunctionMeta { code_offset: f0_start as u32, code_len: f0_len as u32, ..Default::default() },
FunctionMeta { code_offset: f1_start, code_len: f1_len, param_slots: 1, return_slots: 1, ..Default::default() },
FunctionMeta {
code_offset: f0_start as u32,
code_len: f0_len as u32,
..Default::default()
},
FunctionMeta {
code_offset: f1_start,
code_len: f1_len,
param_slots: 1,
return_slots: 1,
..Default::default()
},
]);
let mut native = MockNative;
@@ -4034,8 +4088,18 @@ mod tests {
let mut vm = new_test_vm(rom.clone(), vec![]);
vm.program.functions = std::sync::Arc::from(vec![
FunctionMeta { code_offset: f0_start as u32, code_len: f0_len as u32, ..Default::default() },
FunctionMeta { code_offset: f1_start, code_len: f1_len, param_slots: 1, return_slots: 1, ..Default::default() },
FunctionMeta {
code_offset: f0_start as u32,
code_len: f0_len as u32,
..Default::default()
},
FunctionMeta {
code_offset: f1_start,
code_len: f1_len,
param_slots: 1,
return_slots: 1,
..Default::default()
},
]);
let mut native = MockNative;
@@ -4062,7 +4126,11 @@ mod tests {
let f0_len = rom.len() - f0_start;
let mut vm = new_test_vm(rom.clone(), vec![]);
vm.program.functions = std::sync::Arc::from(vec![FunctionMeta { code_offset: f0_start as u32, code_len: f0_len as u32, ..Default::default() }]);
vm.program.functions = std::sync::Arc::from(vec![FunctionMeta {
code_offset: f0_start as u32,
code_len: f0_len as u32,
..Default::default()
}]);
let mut native = MockNative;
let mut ctx = HostContext::new(None);
@@ -4073,7 +4141,9 @@ mod tests {
assert_eq!(info.code, TRAP_TYPE);
assert_eq!(info.opcode, OpCode::CallClosure as u16);
}
other => panic!("Expected Trap(TYPE) from CALL_CLOSURE on non-closure, got {:?}", other),
other => {
panic!("Expected Trap(TYPE) from CALL_CLOSURE on non-closure, got {:?}", other)
}
}
}
@@ -4114,9 +4184,25 @@ mod tests {
let mut vm = new_test_vm(rom.clone(), vec![]);
vm.program.functions = std::sync::Arc::from(vec![
FunctionMeta { code_offset: f0_start as u32, code_len: f0_len as u32, ..Default::default() },
FunctionMeta { code_offset: f1_start, code_len: f1_len, param_slots: 1, return_slots: 1, ..Default::default() },
FunctionMeta { code_offset: f2_start, code_len: f2_len, param_slots: 1, return_slots: 1, ..Default::default() },
FunctionMeta {
code_offset: f0_start as u32,
code_len: f0_len as u32,
..Default::default()
},
FunctionMeta {
code_offset: f1_start,
code_len: f1_len,
param_slots: 1,
return_slots: 1,
..Default::default()
},
FunctionMeta {
code_offset: f2_start,
code_len: f2_len,
param_slots: 1,
return_slots: 1,
..Default::default()
},
]);
let mut native = MockNative;