//! Function-local branches and validated return boundaries share one completion path. use super::*; impl VirtualMachine { pub(super) fn jump_to( &mut self, target: usize, opcode: OpCode, pc: u32, ) -> Result<(), LogicalFrameEndingReason> { let function = self.call_stack.last().map(|f| &self.program.functions[f.func_idx]); if self.validated_image.is_some() && function.is_some_and(|f| target == f.code_len as usize) { return self.finish_return(opcode, pc); } self.pc = function.map_or(0, |f| f.code_offset as usize) + target; Ok(()) } pub(super) fn finish_return( &mut self, opcode: OpCode, pc: u32, ) -> Result<(), LogicalFrameEndingReason> { let frame = self.call_stack.last().cloned().ok_or_else(|| { self.trap(TRAP_STACK_UNDERFLOW, opcode as u16, "RET with empty call stack".into(), pc) })?; let func = &self.program.functions[frame.func_idx]; let return_slots = func.return_slots as usize; let current_height = self.operand_stack.len(); let expected_height = frame.stack_base + func.param_slots as usize + func.local_slots as usize + return_slots; if current_height != expected_height { return Err(self.trap(TRAP_BAD_RET_SLOTS, opcode as u16, format!( "Incorrect stack height at RET in func {}: expected {} slots (stack_base={} + params={} + locals={} + returns={}), got {}", frame.func_idx, expected_height, frame.stack_base, func.param_slots, func.local_slots, return_slots, current_height ), pc)); } self.check_signature_group( frame.func_idx, true, &self.operand_stack[current_height - return_slots..], ) .map_err(|(_, error)| self.value_trap(error, opcode, pc))?; // Validation is complete. Move the ordered result suffix ahead of this // frame's parameters/locals without cloning owners or reserving scratch. if return_slots != 0 { self.operand_stack[frame.stack_base..].rotate_right(return_slots); } self.operand_stack.truncate(frame.stack_base + return_slots); self.call_stack.pop(); self.pc = frame.return_pc as usize; if self.call_stack.is_empty() { self.handle_safepoint().map_err(|e| self.resource_trap(e, opcode, pc))?; } Ok(()) } }