added comments extensively
This commit is contained in:
@@ -5,35 +5,61 @@ use crate::virtual_machine::opcode::OpCode;
|
||||
use crate::virtual_machine::value::Value;
|
||||
use crate::virtual_machine::Program;
|
||||
|
||||
/// Reason why the Virtual Machine stopped execution during a specific run.
|
||||
/// This allows the system to decide if it should continue execution in the next tick
|
||||
/// or if the frame is finalized.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LogicalFrameEndingReason {
|
||||
/// Execution reached a `FRAME_SYNC` instruction, marking the end of the logical frame.
|
||||
FrameSync,
|
||||
/// The cycle budget for the current host tick was exhausted before reaching `FRAME_SYNC`.
|
||||
BudgetExhausted,
|
||||
/// A `HALT` instruction was executed, terminating the program.
|
||||
Halted,
|
||||
/// The Program Counter (PC) reached the end of the available bytecode.
|
||||
EndOfRom,
|
||||
/// Execution hit a registered breakpoint.
|
||||
Breakpoint,
|
||||
}
|
||||
|
||||
/// A report detailing the results of an execution slice (run_budget).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct BudgetReport {
|
||||
/// Total virtual cycles consumed during this run.
|
||||
pub cycles_used: u64,
|
||||
/// Number of VM instructions executed.
|
||||
pub steps_executed: u32,
|
||||
/// The reason why this execution slice ended.
|
||||
pub reason: LogicalFrameEndingReason,
|
||||
}
|
||||
|
||||
/// The PVM (PROMETEU Virtual Machine).
|
||||
///
|
||||
/// A deterministic, stack-based virtual machine designed for educational purposes.
|
||||
/// It models execution through fixed-cost cycles and explicit memory management.
|
||||
pub struct VirtualMachine {
|
||||
/// Program Counter: points to the next byte in the ROM to be executed.
|
||||
pub pc: usize,
|
||||
/// Operand Stack: used for intermediate calculations and passing arguments to opcodes.
|
||||
pub operand_stack: Vec<Value>,
|
||||
/// Call Stack: stores execution frames for function calls and local variables.
|
||||
pub call_stack: Vec<CallFrame>,
|
||||
/// Globals: storage for persistent variables that survive between frames.
|
||||
pub globals: Vec<Value>,
|
||||
/// The currently loaded program (Bytecode + Constant Pool).
|
||||
pub program: Program,
|
||||
pub heap: Vec<Value>, // Simplified for demo, future real RAM/Heap
|
||||
/// Dynamic memory region for complex structures (Simplified in current version).
|
||||
pub heap: Vec<Value>,
|
||||
/// Total accumulated execution cycles since the last reset.
|
||||
pub cycles: u64,
|
||||
/// Flag indicating if the VM has been stopped by a `HALT` instruction.
|
||||
pub halted: bool,
|
||||
/// A set of PC addresses where execution should pause.
|
||||
pub breakpoints: std::collections::HashSet<usize>,
|
||||
}
|
||||
|
||||
impl VirtualMachine {
|
||||
/// Creates a new VM instance with the provided bytecode and constants.
|
||||
pub fn new(rom: Vec<u8>, constant_pool: Vec<Value>) -> Self {
|
||||
Self {
|
||||
pc: 0,
|
||||
@@ -48,26 +74,31 @@ impl VirtualMachine {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the VM state and loads a new program.
|
||||
/// This is typically called by the Firmware when starting a new App/Cartridge.
|
||||
pub fn initialize(&mut self, program_bytes: Vec<u8>, entrypoint: &str) {
|
||||
// PBC (Prometeu ByteCode) is a binary format that includes a header,
|
||||
// constant pool, and the raw ROM (bytecode).
|
||||
if program_bytes.starts_with(b"PPBC") {
|
||||
if let Ok((rom, cp)) = self.parse_pbc(&program_bytes) {
|
||||
self.program = Program::new(rom, cp);
|
||||
} else {
|
||||
// Fallback for raw bytes if PBC parsing fails
|
||||
self.program = Program::new(program_bytes, vec![]);
|
||||
}
|
||||
} else {
|
||||
// For now, we treat the bytes as the ROM directly.
|
||||
// If it doesn't have the PPBC signature, treat it as raw bytecode.
|
||||
self.program = Program::new(program_bytes, vec![]);
|
||||
}
|
||||
|
||||
// If the entrypoint is numeric, we can try to use it as the initial PC.
|
||||
// If not, for now we ignore it or start from 0.
|
||||
// Resolve the entrypoint. Currently supports numeric addresses.
|
||||
if let Ok(addr) = entrypoint.parse::<usize>() {
|
||||
self.pc = addr;
|
||||
} else {
|
||||
self.pc = 0;
|
||||
}
|
||||
|
||||
// Full state reset to ensure a clean start for the App
|
||||
self.operand_stack.clear();
|
||||
self.call_stack.clear();
|
||||
self.globals.clear();
|
||||
@@ -76,9 +107,12 @@ impl VirtualMachine {
|
||||
self.halted = false;
|
||||
}
|
||||
|
||||
/// Parses the PROMETEU binary format.
|
||||
/// Format: "PPBC" (4) | CP_COUNT (u32) | CP_ENTRIES[...] | ROM_SIZE (u32) | ROM_BYTES[...]
|
||||
fn parse_pbc(&self, bytes: &[u8]) -> Result<(Vec<u8>, Vec<Value>), String> {
|
||||
let mut cursor = 4; // Skip "PPBC"
|
||||
let mut cursor = 4; // Skip "PPBC" signature
|
||||
|
||||
// 1. Parse Constant Pool (literals like strings, ints, floats used in the program)
|
||||
let cp_count = self.read_u32_at(bytes, &mut cursor)? as usize;
|
||||
let mut cp = Vec::with_capacity(cp_count);
|
||||
|
||||
@@ -88,11 +122,11 @@ impl VirtualMachine {
|
||||
cursor += 1;
|
||||
|
||||
match tag {
|
||||
1 => { // Integer
|
||||
1 => { // Integer (64-bit)
|
||||
let val = self.read_i64_at(bytes, &mut cursor)?;
|
||||
cp.push(Value::Integer(val));
|
||||
}
|
||||
2 => { // Float
|
||||
2 => { // Float (64-bit)
|
||||
let val = self.read_f64_at(bytes, &mut cursor)?;
|
||||
cp.push(Value::Float(val));
|
||||
}
|
||||
@@ -102,7 +136,7 @@ impl VirtualMachine {
|
||||
cursor += 1;
|
||||
cp.push(Value::Boolean(val));
|
||||
}
|
||||
4 => { // String
|
||||
4 => { // String (UTF-8)
|
||||
let len = self.read_u32_at(bytes, &mut cursor)? as usize;
|
||||
if cursor + len > bytes.len() { return Err("Unexpected end of PBC".into()); }
|
||||
let s = String::from_utf8_lossy(&bytes[cursor..cursor + len]).into_owned();
|
||||
@@ -113,6 +147,7 @@ impl VirtualMachine {
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Parse ROM (executable bytecode)
|
||||
let rom_size = self.read_u32_at(bytes, &mut cursor)? as usize;
|
||||
if cursor + rom_size > bytes.len() {
|
||||
return Err("Invalid ROM size in PBC".into());
|
||||
@@ -151,6 +186,16 @@ impl Default for VirtualMachine {
|
||||
}
|
||||
|
||||
impl VirtualMachine {
|
||||
/// Executes the VM for a limited number of cycles (budget).
|
||||
///
|
||||
/// This is the heart of the deterministic execution model. Instead of running
|
||||
/// indefinitely, the VM runs until it consumes its allocated budget or reaches
|
||||
/// a synchronization point (`FRAME_SYNC`).
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `budget` - Maximum number of cycles allowed for this execution slice.
|
||||
/// * `native` - Interface for handling syscalls (Firmware/OS).
|
||||
/// * `hw` - Access to virtual hardware peripherals.
|
||||
pub fn run_budget(
|
||||
&mut self,
|
||||
budget: u64,
|
||||
@@ -165,6 +210,9 @@ impl VirtualMachine {
|
||||
&& !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.
|
||||
if steps_executed > 0 && self.breakpoints.contains(&self.pc) {
|
||||
ending_reason = Some(LogicalFrameEndingReason::Breakpoint);
|
||||
break;
|
||||
@@ -173,26 +221,31 @@ impl VirtualMachine {
|
||||
let pc_before = self.pc;
|
||||
let cycles_before = self.cycles;
|
||||
|
||||
// Fast-path: FRAME_SYNC ends the logical frame
|
||||
// Fast-path for FRAME_SYNC:
|
||||
// This instruction is special because it marks the end of a logical game frame.
|
||||
// We peak ahead to handle it efficiently.
|
||||
let opcode_val = self.peek_u16()?;
|
||||
let opcode = OpCode::try_from(opcode_val)?;
|
||||
if opcode == OpCode::FrameSync {
|
||||
self.pc += 2;
|
||||
self.pc += 2; // Advance PC past the opcode
|
||||
self.cycles += OpCode::FrameSync.cycles();
|
||||
steps_executed += 1;
|
||||
ending_reason = Some(LogicalFrameEndingReason::FrameSync);
|
||||
break;
|
||||
}
|
||||
|
||||
// Execute a single step (Fetch-Decode-Execute)
|
||||
self.step(native, hw)?;
|
||||
steps_executed += 1;
|
||||
|
||||
// ensures real progress
|
||||
// Integrity check: ensure real progress is being made to avoid infinite loops
|
||||
// caused by zero-cycle instructions or stuck PC.
|
||||
if self.pc == pc_before && self.cycles == cycles_before && !self.halted {
|
||||
return Err(format!("VM stuck at PC 0x{:08X}", self.pc));
|
||||
}
|
||||
}
|
||||
|
||||
// Determine why we stopped if no explicit reason (FrameSync/Breakpoint) was set.
|
||||
if ending_reason.is_none() {
|
||||
if self.halted {
|
||||
ending_reason = Some(LogicalFrameEndingReason::Halted);
|
||||
@@ -210,6 +263,7 @@ impl VirtualMachine {
|
||||
})
|
||||
}
|
||||
|
||||
/// Peeks at the next 16-bit value in the ROM without advancing the PC.
|
||||
fn peek_u16(&self) -> Result<u16, String> {
|
||||
if self.pc + 2 > self.program.rom.len() {
|
||||
return Err("Unexpected end of ROM".into());
|
||||
@@ -221,14 +275,22 @@ impl VirtualMachine {
|
||||
Ok(u16::from_le_bytes(bytes))
|
||||
}
|
||||
|
||||
/// Executes a single instruction at the current Program Counter (PC).
|
||||
///
|
||||
/// This follows the classic CPU cycle:
|
||||
/// 1. Fetch: Read the opcode from memory.
|
||||
/// 2. Decode: Identify what operation to perform.
|
||||
/// 3. Execute: Perform the operation, updating stacks, memory, or calling peripherals.
|
||||
pub fn step(&mut self, native: &mut dyn NativeInterface, hw: &mut dyn HardwareBridge) -> Result<(), String> {
|
||||
if self.halted || self.pc >= self.program.rom.len() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Fetch & Decode
|
||||
let opcode_val = self.read_u16()?;
|
||||
let opcode = OpCode::try_from(opcode_val)?;
|
||||
|
||||
// Execute
|
||||
match opcode {
|
||||
OpCode::Nop => {}
|
||||
OpCode::Halt => {
|
||||
@@ -369,6 +431,8 @@ impl VirtualMachine {
|
||||
self.operand_stack[stack_idx] = val;
|
||||
}
|
||||
OpCode::Call => {
|
||||
// addr: destination instruction address
|
||||
// args_count: how many values from the operand stack become locals in the new frame
|
||||
let addr = self.read_u32()? as usize;
|
||||
let args_count = self.read_u32()? as usize;
|
||||
let stack_base = self.operand_stack.len() - args_count;
|
||||
@@ -382,18 +446,21 @@ impl VirtualMachine {
|
||||
OpCode::Ret => {
|
||||
let frame = self.call_stack.pop().ok_or("Call stack underflow")?;
|
||||
let return_val = self.pop()?;
|
||||
// Clean up the operand stack, removing the frame's locals
|
||||
self.operand_stack.truncate(frame.stack_base);
|
||||
// Return the result of the function
|
||||
self.push(return_val);
|
||||
self.pc = frame.return_address;
|
||||
}
|
||||
OpCode::PushScope => {
|
||||
// Used for blocks within a function that have their own locals
|
||||
let locals_count = self.read_u32()? as usize;
|
||||
let stack_base = self.operand_stack.len();
|
||||
for _ in 0..locals_count {
|
||||
self.push(Value::Null);
|
||||
}
|
||||
self.call_stack.push(CallFrame {
|
||||
return_address: 0,
|
||||
return_address: 0, // Scope blocks don't return via PC jump
|
||||
stack_base,
|
||||
locals_count,
|
||||
});
|
||||
@@ -403,6 +470,7 @@ impl VirtualMachine {
|
||||
self.operand_stack.truncate(frame.stack_base);
|
||||
}
|
||||
OpCode::Alloc => {
|
||||
// Allocates 'size' values on the heap and pushes a reference to the stack
|
||||
let size = self.read_u32()? as usize;
|
||||
let ref_idx = self.heap.len();
|
||||
for _ in 0..size {
|
||||
@@ -411,6 +479,7 @@ impl VirtualMachine {
|
||||
self.push(Value::Ref(ref_idx));
|
||||
}
|
||||
OpCode::LoadRef => {
|
||||
// Reads a value from a heap reference at a specific offset
|
||||
let offset = self.read_u32()? as usize;
|
||||
let ref_val = self.pop()?;
|
||||
if let Value::Ref(base) = ref_val {
|
||||
@@ -421,6 +490,7 @@ impl VirtualMachine {
|
||||
}
|
||||
}
|
||||
OpCode::StoreRef => {
|
||||
// Writes a value to a heap reference at a specific offset
|
||||
let offset = self.read_u32()? as usize;
|
||||
let val = self.pop()?;
|
||||
let ref_val = self.pop()?;
|
||||
@@ -434,15 +504,18 @@ impl VirtualMachine {
|
||||
}
|
||||
}
|
||||
OpCode::Syscall => {
|
||||
// Calls a native function implemented by the Firmware/OS
|
||||
let id = self.read_u32()?;
|
||||
let native_cycles = native.syscall(id, self, hw).map_err(|e| format!("syscall 0x{:08X} failed: {}", id, e))?;
|
||||
self.cycles += native_cycles;
|
||||
}
|
||||
OpCode::FrameSync => {
|
||||
// Already handled in the run_budget loop for performance
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
// Apply the instruction cost to the cycle counter
|
||||
self.cycles += opcode.cycles();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user