Co-authored-by: Nilton Constantino <nilton.constantino@visma.com>
Reviewed-on: #8
This commit is contained in:
2026-03-24 13:40:22 +00:00
co-authored by Nilton Constantino
parent 05838d10b0
commit f9120e740b
128 changed files with 19414 additions and 4567 deletions
+1 -1
View File
@@ -6,4 +6,4 @@ license.workspace = true
repository.workspace = true
[dependencies]
# No dependencies for now
serde = { version = "1.0", features = ["derive"] }
+111 -1
View File
@@ -11,6 +11,7 @@ pub fn operand_size(opcode: OpCode) -> usize {
match opcode {
OpCode::PushConst => 4,
OpCode::PushI32 => 4,
OpCode::PushBounded => 4,
OpCode::PushI64 => 8,
OpCode::PushF64 => 8,
OpCode::PushBool => 1,
@@ -18,12 +19,62 @@ pub fn operand_size(opcode: OpCode) -> usize {
OpCode::Jmp | OpCode::JmpIfFalse | OpCode::JmpIfTrue => 4,
OpCode::GetGlobal | OpCode::SetGlobal => 4,
OpCode::GetLocal | OpCode::SetLocal => 4,
OpCode::Call => 8, // addr(u32) + args_count(u32)
OpCode::Call => 4, // func_id(u32)
OpCode::Syscall => 4,
OpCode::Alloc => 8, // type_id(u32) + slots(u32)
OpCode::GateLoad | OpCode::GateStore => 4, // offset(u32)
_ => 0,
}
}
// --- HIP Trap Codes ---
/// Attempted to access a gate that does not exist or has been recycled incorrectly.
pub const TRAP_INVALID_GATE: u32 = 0x01;
/// Attempted to access a gate that has been explicitly released (RC=0).
pub const TRAP_DEAD_GATE: u32 = 0x02;
/// Attempted to access a field or index beyond the allocated slots for a gate.
pub const TRAP_OOB: u32 = 0x03;
/// Attempted a typed operation on a gate whose storage type does not match.
pub const TRAP_TYPE: u32 = 0x04;
/// The syscall ID provided is not recognized by the system.
pub const TRAP_INVALID_SYSCALL: u32 = 0x0000_0007;
/// Not enough arguments on the stack for the requested syscall.
pub const TRAP_STACK_UNDERFLOW: u32 = 0x0000_0008;
/// Attempted to access a local slot that is out of bounds for the current frame.
pub const TRAP_INVALID_LOCAL: u32 = 0x0000_0009;
/// Division or modulo by zero.
pub const TRAP_DIV_ZERO: u32 = 0x0000_000A;
/// Attempted to call a function that does not exist in the function table.
pub const TRAP_INVALID_FUNC: u32 = 0x0000_000B;
/// Executed RET with an incorrect stack height (mismatch with function metadata).
pub const TRAP_BAD_RET_SLOTS: u32 = 0x0000_000C;
use serde::{Deserialize, Serialize};
/// Detailed information about a source code span.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct SourceSpan {
pub file_id: u32,
pub start: u32,
pub end: u32,
}
/// Detailed information about a runtime trap.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TrapInfo {
/// The specific trap code (e.g., TRAP_OOB).
pub code: u32,
/// The numeric value of the opcode that triggered the trap.
pub opcode: u16,
/// A human-readable message explaining the trap.
pub message: String,
/// The absolute Program Counter (PC) address where the trap occurred.
pub pc: u32,
/// Optional source span information if debug symbols are available.
pub span: Option<SourceSpan>,
}
/// Checks if an instruction is a jump (branch) instruction.
pub fn is_jump(opcode: OpCode) -> bool {
match opcode {
@@ -36,3 +87,62 @@ pub fn is_jump(opcode: OpCode) -> bool {
pub fn has_immediate(opcode: OpCode) -> bool {
operand_size(opcode) > 0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_trap_code_stability() {
// These numeric values are normative and must not change.
assert_eq!(TRAP_INVALID_GATE, 0x01);
assert_eq!(TRAP_DEAD_GATE, 0x02);
assert_eq!(TRAP_OOB, 0x03);
assert_eq!(TRAP_TYPE, 0x04);
assert_eq!(TRAP_INVALID_SYSCALL, 0x07);
assert_eq!(TRAP_STACK_UNDERFLOW, 0x08);
assert_eq!(TRAP_INVALID_LOCAL, 0x09);
assert_eq!(TRAP_DIV_ZERO, 0x0A);
assert_eq!(TRAP_INVALID_FUNC, 0x0B);
assert_eq!(TRAP_BAD_RET_SLOTS, 0x0C);
}
#[test]
fn test_abi_documentation_snapshot() {
// Snapshot of the ABI rules for traps and operands.
let abi_info = r#"
HIP Traps:
- INVALID_GATE (0x01): Non-existent gate handle.
- DEAD_GATE (0x02): Gate handle with RC=0.
- OOB (0x03): Access beyond allocated slots.
- TYPE (0x04): Type mismatch during heap access.
System Traps:
- INVALID_SYSCALL (0x07): Unknown syscall ID.
- STACK_UNDERFLOW (0x08): Missing syscall arguments.
- INVALID_LOCAL (0x09): Local slot out of bounds.
- DIV_ZERO (0x0A): Division by zero.
- INVALID_FUNC (0x0B): Function table index out of bounds.
- BAD_RET_SLOTS (0x0C): Stack height mismatch at RET.
Operand Sizes:
- Alloc: 8 bytes (u32 type_id, u32 slots)
- GateLoad: 4 bytes (u32 offset)
- GateStore: 4 bytes (u32 offset)
- PopN: 4 bytes (u32 count)
"#;
// This test serves as a "doc-lock".
// If you change the ABI, you must update this string.
let current_info = format!(
"\nHIP Traps:\n- INVALID_GATE (0x{:02X}): Non-existent gate handle.\n- DEAD_GATE (0x{:02X}): Gate handle with RC=0.\n- OOB (0x{:02X}): Access beyond allocated slots.\n- TYPE (0x{:02X}): Type mismatch during heap access.\n\nSystem Traps:\n- INVALID_SYSCALL (0x{:02X}): Unknown syscall ID.\n- STACK_UNDERFLOW (0x{:02X}): Missing syscall arguments.\n- INVALID_LOCAL (0x{:02X}): Local slot out of bounds.\n- DIV_ZERO (0x{:02X}): Division by zero.\n- INVALID_FUNC (0x{:02X}): Function table index out of bounds.\n- BAD_RET_SLOTS (0x{:02X}): Stack height mismatch at RET.\n\nOperand Sizes:\n- Alloc: {} bytes (u32 type_id, u32 slots)\n- GateLoad: {} bytes (u32 offset)\n- GateStore: {} bytes (u32 offset)\n- PopN: {} bytes (u32 count)\n",
TRAP_INVALID_GATE, TRAP_DEAD_GATE, TRAP_OOB, TRAP_TYPE,
TRAP_INVALID_SYSCALL, TRAP_STACK_UNDERFLOW, TRAP_INVALID_LOCAL, TRAP_DIV_ZERO, TRAP_INVALID_FUNC, TRAP_BAD_RET_SLOTS,
operand_size(OpCode::Alloc),
operand_size(OpCode::GateLoad),
operand_size(OpCode::GateStore),
operand_size(OpCode::PopN)
);
assert_eq!(current_info.trim(), abi_info.trim());
}
}
+58 -8
View File
@@ -17,6 +17,8 @@ pub enum Operand {
Bool(bool),
/// A symbolic label that will be resolved to an absolute PC address.
Label(String),
/// A symbolic label that will be resolved to a PC address relative to another label.
RelLabel(String, String),
}
/// Represents an assembly-level element (either an instruction or a label).
@@ -33,7 +35,7 @@ pub fn update_pc_by_operand(initial_pc: u32, operands: &Vec<Operand>) -> u32 {
let mut pcp: u32 = initial_pc;
for operand in operands {
match operand {
Operand::U32(_) | Operand::I32(_) | Operand::Label(_) => pcp += 4,
Operand::U32(_) | Operand::I32(_) | Operand::Label(_) | Operand::RelLabel(_, _) => pcp += 4,
Operand::I64(_) | Operand::F64(_) => pcp += 8,
Operand::Bool(_) => pcp += 1,
}
@@ -41,6 +43,11 @@ pub fn update_pc_by_operand(initial_pc: u32, operands: &Vec<Operand>) -> u32 {
pcp
}
pub struct AssembleResult {
pub code: Vec<u8>,
pub unresolved_labels: HashMap<String, Vec<u32>>,
}
/// Converts a list of assembly instructions into raw ROM bytes.
///
/// The assembly process is done in two passes:
@@ -49,6 +56,15 @@ pub fn update_pc_by_operand(initial_pc: u32, operands: &Vec<Operand>) -> u32 {
/// 2. **Code Generation**: Translates each OpCode and its operands (resolving labels using the map)
/// into the final binary format.
pub fn assemble(instructions: &[Asm]) -> Result<Vec<u8>, String> {
let res = assemble_with_unresolved(instructions)?;
if !res.unresolved_labels.is_empty() {
let labels: Vec<_> = res.unresolved_labels.keys().cloned().collect();
return Err(format!("Undefined labels: {:?}", labels));
}
Ok(res.code)
}
pub fn assemble_with_unresolved(instructions: &[Asm]) -> Result<AssembleResult, String> {
let mut labels = HashMap::new();
let mut current_pc = 0u32;
@@ -67,21 +83,52 @@ pub fn assemble(instructions: &[Asm]) -> Result<Vec<u8>, String> {
// Second pass: generate bytes
let mut rom = Vec::new();
let mut unresolved_labels: HashMap<String, Vec<u32>> = HashMap::new();
let mut pc = 0u32;
for instr in instructions {
match instr {
Asm::Label(_) => {}
Asm::Op(opcode, operands) => {
write_u16_le(&mut rom, *opcode as u16).map_err(|e| e.to_string())?;
pc += 2;
for operand in operands {
match operand {
Operand::U32(v) => write_u32_le(&mut rom, *v).map_err(|e| e.to_string())?,
Operand::I32(v) => write_u32_le(&mut rom, *v as u32).map_err(|e| e.to_string())?,
Operand::I64(v) => write_i64_le(&mut rom, *v).map_err(|e| e.to_string())?,
Operand::F64(v) => write_f64_le(&mut rom, *v).map_err(|e| e.to_string())?,
Operand::Bool(v) => rom.push(if *v { 1 } else { 0 }),
Operand::U32(v) => {
write_u32_le(&mut rom, *v).map_err(|e| e.to_string())?;
pc += 4;
}
Operand::I32(v) => {
write_u32_le(&mut rom, *v as u32).map_err(|e| e.to_string())?;
pc += 4;
}
Operand::I64(v) => {
write_i64_le(&mut rom, *v).map_err(|e| e.to_string())?;
pc += 8;
}
Operand::F64(v) => {
write_f64_le(&mut rom, *v).map_err(|e| e.to_string())?;
pc += 8;
}
Operand::Bool(v) => {
rom.push(if *v { 1 } else { 0 });
pc += 1;
}
Operand::Label(name) => {
if let Some(addr) = labels.get(name) {
write_u32_le(&mut rom, *addr).map_err(|e| e.to_string())?;
} else {
unresolved_labels.entry(name.clone()).or_default().push(pc);
write_u32_le(&mut rom, 0).map_err(|e| e.to_string())?; // Placeholder
}
pc += 4;
}
Operand::RelLabel(name, base) => {
let addr = labels.get(name).ok_or(format!("Undefined label: {}", name))?;
write_u32_le(&mut rom, *addr).map_err(|e| e.to_string())?;
let base_addr = labels.get(base).ok_or(format!("Undefined base label: {}", base))?;
let rel_addr = (*addr as i64) - (*base_addr as i64);
write_u32_le(&mut rom, rel_addr as u32).map_err(|e| e.to_string())?;
pc += 4;
}
}
}
@@ -89,5 +136,8 @@ pub fn assemble(instructions: &[Asm]) -> Result<Vec<u8>, String> {
}
}
Ok(rom)
Ok(AssembleResult {
code: rom,
unresolved_labels,
})
}
+8 -12
View File
@@ -39,30 +39,26 @@ pub fn disasm(rom: &[u8]) -> Result<Vec<Instr>, String> {
let mut operands = Vec::new();
match opcode {
OpCode::PushConst | OpCode::PushI32 | OpCode::Jmp | OpCode::JmpIfFalse | OpCode::JmpIfTrue
OpCode::PushConst | OpCode::PushI32 | OpCode::PushBounded | OpCode::Jmp | OpCode::JmpIfFalse | OpCode::JmpIfTrue
| OpCode::GetGlobal | OpCode::SetGlobal | OpCode::GetLocal | OpCode::SetLocal
| OpCode::PopN | OpCode::Syscall => {
| OpCode::PopN | OpCode::Syscall | OpCode::GateLoad | OpCode::GateStore | OpCode::Call => {
let v = read_u32_le(&mut cursor).map_err(|e| e.to_string())?;
operands.push(DisasmOperand::U32(v));
}
OpCode::PushI64 => {
OpCode::PushI64 | OpCode::PushF64 => {
let v = read_i64_le(&mut cursor).map_err(|e| e.to_string())?;
operands.push(DisasmOperand::I64(v));
}
OpCode::PushF64 => {
let v = read_f64_le(&mut cursor).map_err(|e| e.to_string())?;
operands.push(DisasmOperand::F64(v));
}
OpCode::PushBool => {
let mut b_buf = [0u8; 1];
cursor.read_exact(&mut b_buf).map_err(|e| e.to_string())?;
operands.push(DisasmOperand::Bool(b_buf[0] != 0));
}
OpCode::Call => {
let addr = read_u32_le(&mut cursor).map_err(|e| e.to_string())?;
let args = read_u32_le(&mut cursor).map_err(|e| e.to_string())?;
operands.push(DisasmOperand::U32(addr));
operands.push(DisasmOperand::U32(args));
OpCode::Alloc => {
let v1 = read_u32_le(&mut cursor).map_err(|e| e.to_string())?;
let v2 = read_u32_le(&mut cursor).map_err(|e| e.to_string())?;
operands.push(DisasmOperand::U32(v1));
operands.push(DisasmOperand::U32(v2));
}
_ => {}
}
+4 -2
View File
@@ -8,7 +8,6 @@
//!
//! ## Core Components:
//! - [`opcode`]: Defines the available instructions and their performance characteristics.
//! - [`pbc`]: Handles the serialization and deserialization of `.pbc` files.
//! - [`abi`]: Specifies the binary rules for operands and stack behavior.
//! - [`asm`]: Provides a programmatic Assembler to convert high-level instructions to bytes.
//! - [`disasm`]: Provides a Disassembler to inspect compiled bytecode.
@@ -16,7 +15,10 @@
pub mod opcode;
pub mod abi;
pub mod pbc;
pub mod readwrite;
pub mod asm;
pub mod disasm;
mod model;
pub use model::*;
+651
View File
@@ -0,0 +1,651 @@
use crate::abi::SourceSpan;
use crate::opcode::OpCode;
use serde::{Deserialize, Serialize};
/// An entry in the Constant Pool.
///
/// The Constant Pool is a table of unique values used by the program.
/// Instead of embedding large data (like strings) directly in the instruction stream,
/// the bytecode uses `PushConst <index>` to load these values onto the stack.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ConstantPoolEntry {
/// Reserved index (0). Represents a null/undefined value.
Null,
/// A 64-bit integer constant.
Int64(i64),
/// A 64-bit floating point constant.
Float64(f64),
/// A boolean constant.
Boolean(bool),
/// A UTF-8 string constant.
String(String),
/// A 32-bit integer constant.
Int32(i32),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LoadError {
InvalidMagic,
InvalidVersion,
InvalidEndianness,
OverlappingSections,
SectionOutOfBounds,
InvalidOpcode,
InvalidConstIndex,
InvalidFunctionIndex,
MalformedHeader,
MalformedSection,
UnexpectedEof,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct FunctionMeta {
pub code_offset: u32,
pub code_len: u32,
pub param_slots: u16,
pub local_slots: u16,
pub return_slots: u16,
pub max_stack_slots: u16,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct DebugInfo {
pub pc_to_span: Vec<(u32, SourceSpan)>, // Sorted by PC
pub function_names: Vec<(u32, String)>, // (func_idx, name)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Export {
pub symbol: String,
pub func_idx: u32,
}
/// Represents the final serialized format of a PBS v0 module.
///
/// This structure is a pure data container for the PBS format. It does NOT
/// contain any linker-like logic (symbol resolution, patching, etc.).
/// All multi-module programs must be flattened and linked by the compiler
/// before being serialized into this format.
#[derive(Debug, Clone, PartialEq)]
pub struct BytecodeModule {
pub version: u16,
pub const_pool: Vec<ConstantPoolEntry>,
pub functions: Vec<FunctionMeta>,
pub code: Vec<u8>,
pub debug_info: Option<DebugInfo>,
pub exports: Vec<Export>,
}
impl BytecodeModule {
pub fn serialize(&self) -> Vec<u8> {
let cp_data = self.serialize_const_pool();
let func_data = self.serialize_functions();
let code_data = self.code.clone();
let debug_data = self.debug_info.as_ref().map(|di| self.serialize_debug(di)).unwrap_or_default();
let export_data = self.serialize_exports();
let mut final_sections = Vec::new();
if !cp_data.is_empty() { final_sections.push((0, cp_data)); }
if !func_data.is_empty() { final_sections.push((1, func_data)); }
if !code_data.is_empty() { final_sections.push((2, code_data)); }
if !debug_data.is_empty() { final_sections.push((3, debug_data)); }
if !export_data.is_empty() { final_sections.push((4, export_data)); }
let mut out = Vec::new();
// Magic "PBS\0"
out.extend_from_slice(b"PBS\0");
// Version 0
out.extend_from_slice(&0u16.to_le_bytes());
// Endianness 0 (Little Endian), Reserved
out.extend_from_slice(&[0u8, 0u8]);
// section_count
out.extend_from_slice(&(final_sections.len() as u32).to_le_bytes());
// padding to 32 bytes
out.extend_from_slice(&[0u8; 20]);
let mut current_offset = 32 + (final_sections.len() as u32 * 12);
// Write section table
for (kind, data) in &final_sections {
let k: u32 = *kind;
out.extend_from_slice(&k.to_le_bytes());
out.extend_from_slice(&current_offset.to_le_bytes());
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
current_offset += data.len() as u32;
}
// Write section data
for (_, data) in final_sections {
out.extend_from_slice(&data);
}
out
}
fn serialize_const_pool(&self) -> Vec<u8> {
if self.const_pool.is_empty() { return Vec::new(); }
let mut data = Vec::new();
data.extend_from_slice(&(self.const_pool.len() as u32).to_le_bytes());
for entry in &self.const_pool {
match entry {
ConstantPoolEntry::Null => data.push(0),
ConstantPoolEntry::Int64(v) => {
data.push(1);
data.extend_from_slice(&v.to_le_bytes());
}
ConstantPoolEntry::Float64(v) => {
data.push(2);
data.extend_from_slice(&v.to_le_bytes());
}
ConstantPoolEntry::Boolean(v) => {
data.push(3);
data.push(if *v { 1 } else { 0 });
}
ConstantPoolEntry::String(v) => {
data.push(4);
let s_bytes = v.as_bytes();
data.extend_from_slice(&(s_bytes.len() as u32).to_le_bytes());
data.extend_from_slice(s_bytes);
}
ConstantPoolEntry::Int32(v) => {
data.push(5);
data.extend_from_slice(&v.to_le_bytes());
}
}
}
data
}
fn serialize_functions(&self) -> Vec<u8> {
if self.functions.is_empty() { return Vec::new(); }
let mut data = Vec::new();
data.extend_from_slice(&(self.functions.len() as u32).to_le_bytes());
for f in &self.functions {
data.extend_from_slice(&f.code_offset.to_le_bytes());
data.extend_from_slice(&f.code_len.to_le_bytes());
data.extend_from_slice(&f.param_slots.to_le_bytes());
data.extend_from_slice(&f.local_slots.to_le_bytes());
data.extend_from_slice(&f.return_slots.to_le_bytes());
data.extend_from_slice(&f.max_stack_slots.to_le_bytes());
}
data
}
fn serialize_debug(&self, di: &DebugInfo) -> Vec<u8> {
let mut data = Vec::new();
data.extend_from_slice(&(di.pc_to_span.len() as u32).to_le_bytes());
for (pc, span) in &di.pc_to_span {
data.extend_from_slice(&pc.to_le_bytes());
data.extend_from_slice(&span.file_id.to_le_bytes());
data.extend_from_slice(&span.start.to_le_bytes());
data.extend_from_slice(&span.end.to_le_bytes());
}
data.extend_from_slice(&(di.function_names.len() as u32).to_le_bytes());
for (idx, name) in &di.function_names {
data.extend_from_slice(&idx.to_le_bytes());
let n_bytes = name.as_bytes();
data.extend_from_slice(&(n_bytes.len() as u32).to_le_bytes());
data.extend_from_slice(n_bytes);
}
data
}
fn serialize_exports(&self) -> Vec<u8> {
if self.exports.is_empty() { return Vec::new(); }
let mut data = Vec::new();
data.extend_from_slice(&(self.exports.len() as u32).to_le_bytes());
for exp in &self.exports {
data.extend_from_slice(&exp.func_idx.to_le_bytes());
let s_bytes = exp.symbol.as_bytes();
data.extend_from_slice(&(s_bytes.len() as u32).to_le_bytes());
data.extend_from_slice(s_bytes);
}
data
}
}
pub struct BytecodeLoader;
impl BytecodeLoader {
pub fn load(bytes: &[u8]) -> Result<BytecodeModule, LoadError> {
if bytes.len() < 32 {
return Err(LoadError::UnexpectedEof);
}
// Magic "PBS\0"
if &bytes[0..4] != b"PBS\0" {
return Err(LoadError::InvalidMagic);
}
let version = u16::from_le_bytes([bytes[4], bytes[5]]);
if version != 0 {
return Err(LoadError::InvalidVersion);
}
let endianness = bytes[6];
if endianness != 0 { // 0 = Little Endian
return Err(LoadError::InvalidEndianness);
}
let section_count = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
let mut sections = Vec::new();
let mut pos = 32;
for _ in 0..section_count {
if pos + 12 > bytes.len() {
return Err(LoadError::UnexpectedEof);
}
let kind = u32::from_le_bytes([bytes[pos], bytes[pos+1], bytes[pos+2], bytes[pos+3]]);
let offset = u32::from_le_bytes([bytes[pos+4], bytes[pos+5], bytes[pos+6], bytes[pos+7]]);
let length = u32::from_le_bytes([bytes[pos+8], bytes[pos+9], bytes[pos+10], bytes[pos+11]]);
// Basic bounds check
if (offset as usize) + (length as usize) > bytes.len() {
return Err(LoadError::SectionOutOfBounds);
}
sections.push((kind, offset, length));
pos += 12;
}
// Check for overlapping sections
for i in 0..sections.len() {
for j in i + 1..sections.len() {
let (_, o1, l1) = sections[i];
let (_, o2, l2) = sections[j];
if (o1 < o2 + l2) && (o2 < o1 + l1) {
return Err(LoadError::OverlappingSections);
}
}
}
let mut module = BytecodeModule {
version,
const_pool: Vec::new(),
functions: Vec::new(),
code: Vec::new(),
debug_info: None,
exports: Vec::new(),
};
for (kind, offset, length) in sections {
let section_data = &bytes[offset as usize..(offset + length) as usize];
match kind {
0 => { // Const Pool
module.const_pool = parse_const_pool(section_data)?;
}
1 => { // Functions
module.functions = parse_functions(section_data)?;
}
2 => { // Code
module.code = section_data.to_vec();
}
3 => { // Debug Info
module.debug_info = Some(parse_debug_section(section_data)?);
}
4 => { // Exports
module.exports = parse_exports(section_data)?;
}
_ => {} // Skip unknown or optional sections
}
}
// Additional validations
validate_module(&module)?;
Ok(module)
}
}
fn parse_const_pool(data: &[u8]) -> Result<Vec<ConstantPoolEntry>, LoadError> {
if data.is_empty() {
return Ok(Vec::new());
}
if data.len() < 4 {
return Err(LoadError::MalformedSection);
}
let count = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
let mut cp = Vec::with_capacity(count);
let mut pos = 4;
for _ in 0..count {
if pos >= data.len() {
return Err(LoadError::UnexpectedEof);
}
let tag = data[pos];
pos += 1;
match tag {
0 => cp.push(ConstantPoolEntry::Null),
1 => { // Int64
if pos + 8 > data.len() { return Err(LoadError::UnexpectedEof); }
let val = i64::from_le_bytes(data[pos..pos+8].try_into().unwrap());
cp.push(ConstantPoolEntry::Int64(val));
pos += 8;
}
2 => { // Float64
if pos + 8 > data.len() { return Err(LoadError::UnexpectedEof); }
let val = f64::from_le_bytes(data[pos..pos+8].try_into().unwrap());
cp.push(ConstantPoolEntry::Float64(val));
pos += 8;
}
3 => { // Boolean
if pos >= data.len() { return Err(LoadError::UnexpectedEof); }
cp.push(ConstantPoolEntry::Boolean(data[pos] != 0));
pos += 1;
}
4 => { // String
if pos + 4 > data.len() { return Err(LoadError::UnexpectedEof); }
let len = u32::from_le_bytes(data[pos..pos+4].try_into().unwrap()) as usize;
pos += 4;
if pos + len > data.len() { return Err(LoadError::UnexpectedEof); }
let s = String::from_utf8_lossy(&data[pos..pos+len]).into_owned();
cp.push(ConstantPoolEntry::String(s));
pos += len;
}
5 => { // Int32
if pos + 4 > data.len() { return Err(LoadError::UnexpectedEof); }
let val = i32::from_le_bytes(data[pos..pos+4].try_into().unwrap());
cp.push(ConstantPoolEntry::Int32(val));
pos += 4;
}
_ => return Err(LoadError::MalformedSection),
}
}
Ok(cp)
}
fn parse_functions(data: &[u8]) -> Result<Vec<FunctionMeta>, LoadError> {
if data.is_empty() {
return Ok(Vec::new());
}
if data.len() < 4 {
return Err(LoadError::MalformedSection);
}
let count = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
let mut functions = Vec::with_capacity(count);
let mut pos = 4;
for _ in 0..count {
if pos + 16 > data.len() {
return Err(LoadError::UnexpectedEof);
}
let code_offset = u32::from_le_bytes(data[pos..pos+4].try_into().unwrap());
let code_len = u32::from_le_bytes(data[pos+4..pos+8].try_into().unwrap());
let param_slots = u16::from_le_bytes(data[pos+8..pos+10].try_into().unwrap());
let local_slots = u16::from_le_bytes(data[pos+10..pos+12].try_into().unwrap());
let return_slots = u16::from_le_bytes(data[pos+12..pos+14].try_into().unwrap());
let max_stack_slots = u16::from_le_bytes(data[pos+14..pos+16].try_into().unwrap());
functions.push(FunctionMeta {
code_offset,
code_len,
param_slots,
local_slots,
return_slots,
max_stack_slots,
});
pos += 16;
}
Ok(functions)
}
fn parse_debug_section(data: &[u8]) -> Result<DebugInfo, LoadError> {
if data.is_empty() {
return Ok(DebugInfo::default());
}
if data.len() < 8 {
return Err(LoadError::MalformedSection);
}
let mut pos = 0;
// PC to Span table
let span_count = u32::from_le_bytes(data[pos..pos+4].try_into().unwrap()) as usize;
pos += 4;
let mut pc_to_span = Vec::with_capacity(span_count);
for _ in 0..span_count {
if pos + 16 > data.len() {
return Err(LoadError::UnexpectedEof);
}
let pc = u32::from_le_bytes(data[pos..pos+4].try_into().unwrap());
let file_id = u32::from_le_bytes(data[pos+4..pos+8].try_into().unwrap());
let start = u32::from_le_bytes(data[pos+8..pos+12].try_into().unwrap());
let end = u32::from_le_bytes(data[pos+12..pos+16].try_into().unwrap());
pc_to_span.push((pc, SourceSpan { file_id, start, end }));
pos += 16;
}
// Function names table
if pos + 4 > data.len() {
return Err(LoadError::UnexpectedEof);
}
let func_name_count = u32::from_le_bytes(data[pos..pos+4].try_into().unwrap()) as usize;
pos += 4;
let mut function_names = Vec::with_capacity(func_name_count);
for _ in 0..func_name_count {
if pos + 8 > data.len() {
return Err(LoadError::UnexpectedEof);
}
let func_idx = u32::from_le_bytes(data[pos..pos+4].try_into().unwrap());
let name_len = u32::from_le_bytes(data[pos+4..pos+8].try_into().unwrap()) as usize;
pos += 8;
if pos + name_len > data.len() {
return Err(LoadError::UnexpectedEof);
}
let name = String::from_utf8_lossy(&data[pos..pos+name_len]).into_owned();
function_names.push((func_idx, name));
pos += name_len;
}
Ok(DebugInfo { pc_to_span, function_names })
}
fn parse_exports(data: &[u8]) -> Result<Vec<Export>, LoadError> {
if data.is_empty() {
return Ok(Vec::new());
}
if data.len() < 4 {
return Err(LoadError::MalformedSection);
}
let count = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
let mut exports = Vec::with_capacity(count);
let mut pos = 4;
for _ in 0..count {
if pos + 8 > data.len() {
return Err(LoadError::UnexpectedEof);
}
let func_idx = u32::from_le_bytes(data[pos..pos+4].try_into().unwrap());
let name_len = u32::from_le_bytes(data[pos+4..pos+8].try_into().unwrap()) as usize;
pos += 8;
if pos + name_len > data.len() {
return Err(LoadError::UnexpectedEof);
}
let symbol = String::from_utf8_lossy(&data[pos..pos+name_len]).into_owned();
exports.push(Export { symbol, func_idx });
pos += name_len;
}
Ok(exports)
}
fn validate_module(module: &BytecodeModule) -> Result<(), LoadError> {
for func in &module.functions {
// Opcode stream bounds
if (func.code_offset as usize) + (func.code_len as usize) > module.code.len() {
return Err(LoadError::InvalidFunctionIndex);
}
}
// Basic opcode scan for const pool indices
let mut pos = 0;
while pos < module.code.len() {
if pos + 2 > module.code.len() {
break; // Unexpected EOF in middle of opcode, maybe should be error
}
let op_val = u16::from_le_bytes([module.code[pos], module.code[pos+1]]);
let opcode = OpCode::try_from(op_val).map_err(|_| LoadError::InvalidOpcode)?;
pos += 2;
match opcode {
OpCode::PushConst => {
if pos + 4 > module.code.len() { return Err(LoadError::UnexpectedEof); }
let idx = u32::from_le_bytes(module.code[pos..pos+4].try_into().unwrap()) as usize;
if idx >= module.const_pool.len() {
return Err(LoadError::InvalidConstIndex);
}
pos += 4;
}
OpCode::PushI32 | OpCode::PushBounded | OpCode::Jmp | OpCode::JmpIfFalse | OpCode::JmpIfTrue
| OpCode::GetGlobal | OpCode::SetGlobal | OpCode::GetLocal | OpCode::SetLocal
| OpCode::PopN | OpCode::Syscall | OpCode::GateLoad | OpCode::GateStore => {
pos += 4;
}
OpCode::PushI64 | OpCode::PushF64 => {
pos += 8;
}
OpCode::PushBool => {
pos += 1;
}
OpCode::Call => {
pos += 4;
}
OpCode::Alloc => {
pos += 8;
}
_ => {}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn create_header(section_count: u32) -> Vec<u8> {
let mut h = vec![0u8; 32];
h[0..4].copy_from_slice(b"PBS\0");
h[4..6].copy_from_slice(&0u16.to_le_bytes()); // version
h[6] = 0; // endianness
h[8..12].copy_from_slice(&section_count.to_le_bytes());
h
}
#[test]
fn test_invalid_magic() {
let mut data = create_header(0);
data[0] = b'X';
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidMagic));
}
#[test]
fn test_invalid_version() {
let mut data = create_header(0);
data[4] = 1;
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidVersion));
}
#[test]
fn test_invalid_endianness() {
let mut data = create_header(0);
data[6] = 1;
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidEndianness));
}
#[test]
fn test_overlapping_sections() {
let mut data = create_header(2);
// Section 1: Kind 0, Offset 64, Length 32
data.extend_from_slice(&0u32.to_le_bytes());
data.extend_from_slice(&64u32.to_le_bytes());
data.extend_from_slice(&32u32.to_le_bytes());
// Section 2: Kind 1, Offset 80, Length 32 (Overlaps with Section 1)
data.extend_from_slice(&1u32.to_le_bytes());
data.extend_from_slice(&80u32.to_le_bytes());
data.extend_from_slice(&32u32.to_le_bytes());
// Ensure data is long enough for the offsets
data.resize(256, 0);
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::OverlappingSections));
}
#[test]
fn test_section_out_of_bounds() {
let mut data = create_header(1);
// Section 1: Kind 0, Offset 64, Length 1000
data.extend_from_slice(&0u32.to_le_bytes());
data.extend_from_slice(&64u32.to_le_bytes());
data.extend_from_slice(&1000u32.to_le_bytes());
data.resize(256, 0);
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::SectionOutOfBounds));
}
#[test]
fn test_invalid_function_code_offset() {
let mut data = create_header(2);
// Section 1: Functions, Kind 1, Offset 64, Length 20 (Header 4 + 1 entry 16)
data.extend_from_slice(&1u32.to_le_bytes());
data.extend_from_slice(&64u32.to_le_bytes());
data.extend_from_slice(&20u32.to_le_bytes());
// Section 2: Code, Kind 2, Offset 128, Length 10
data.extend_from_slice(&2u32.to_le_bytes());
data.extend_from_slice(&128u32.to_le_bytes());
data.extend_from_slice(&10u32.to_le_bytes());
data.resize(256, 0);
// Setup functions section
let func_data_start = 64;
data[func_data_start..func_data_start+4].copy_from_slice(&1u32.to_le_bytes()); // 1 function
let entry_start = func_data_start + 4;
data[entry_start..entry_start+4].copy_from_slice(&5u32.to_le_bytes()); // code_offset = 5
data[entry_start+4..entry_start+8].copy_from_slice(&10u32.to_le_bytes()); // code_len = 10
// 5 + 10 = 15 > 10 (code section length)
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidFunctionIndex));
}
#[test]
fn test_invalid_const_index() {
let mut data = create_header(2);
// Section 1: Const Pool, Kind 0, Offset 64, Length 4 (Empty CP)
data.extend_from_slice(&0u32.to_le_bytes());
data.extend_from_slice(&64u32.to_le_bytes());
data.extend_from_slice(&4u32.to_le_bytes());
// Section 2: Code, Kind 2, Offset 128, Length 6 (PushConst 0)
data.extend_from_slice(&2u32.to_le_bytes());
data.extend_from_slice(&128u32.to_le_bytes());
data.extend_from_slice(&6u32.to_le_bytes());
data.resize(256, 0);
// Setup empty CP
data[64..68].copy_from_slice(&0u32.to_le_bytes());
// Setup code with PushConst 0
data[128..130].copy_from_slice(&(OpCode::PushConst as u16).to_le_bytes());
data[130..134].copy_from_slice(&0u32.to_le_bytes());
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidConstIndex));
}
#[test]
fn test_valid_minimal_load() {
let data = create_header(0);
let module = BytecodeLoader::load(&data).unwrap();
assert_eq!(module.version, 0);
assert!(module.const_pool.is_empty());
assert!(module.functions.is_empty());
assert!(module.code.is_empty());
}
}
+139 -17
View File
@@ -54,8 +54,12 @@ pub enum OpCode {
/// Operand: value (i32)
PushI32 = 0x17,
/// Removes `n` values from the stack.
/// Operand: n (u16)
/// Operand: n (u32)
PopN = 0x18,
/// Pushes a 16-bit bounded integer literal onto the stack.
/// Operand: value (u32, must be <= 0xFFFF)
/// Stack: [] -> [bounded]
PushBounded = 0x19,
// --- 6.3 Arithmetic ---
@@ -71,6 +75,15 @@ pub enum OpCode {
/// Divides the second top value by the top one (a / b).
/// Stack: [a, b] -> [result]
Div = 0x23,
/// Remainder of the division of the second top value by the top one (a % b).
/// Stack: [a, b] -> [result]
Mod = 0x24,
/// Converts a bounded value to a 64-bit integer.
/// Stack: [bounded] -> [int64]
BoundToInt = 0x25,
/// Converts an integer to a bounded value, trapping if out of range (0..65535).
/// Stack: [int] -> [bounded]
IntToBoundChecked = 0x26,
// --- 6.4 Comparison and Logic ---
@@ -141,9 +154,9 @@ pub enum OpCode {
// --- 6.6 Functions ---
/// Calls a function at a specific address.
/// Operands: addr (u32), args_count (u32)
/// Stack: [arg0, arg1, ...] -> [return_value]
/// Calls a function by its index in the function table.
/// Operand: func_id (u32)
/// Stack: [arg0, arg1, ...] -> [return_slots...]
Call = 0x50,
/// Returns from the current function.
/// Stack: [return_val] -> [return_val]
@@ -153,19 +166,46 @@ pub enum OpCode {
/// Ends the current local scope, discarding its local variables.
PopScope = 0x53,
// --- 6.7 Heap ---
// --- 6.7 HIP (Heap Interface Protocol) ---
/// Allocates `size` slots on the heap.
/// Stack: [size] -> [reference]
/// Allocates `slots` slots on the heap with the given `type_id`.
/// Operands: type_id (u32), slots (u32)
/// Stack: [] -> [gate]
Alloc = 0x60,
/// Reads a value from the heap at `reference + offset`.
/// Reads a value from the heap at `gate + offset`.
/// Operand: offset (u32)
/// Stack: [reference] -> [value]
LoadRef = 0x61,
/// Writes a value to the heap at `reference + offset`.
/// Stack: [gate] -> [value]
GateLoad = 0x61,
/// Writes a value to the heap at `gate + offset`.
/// Operand: offset (u32)
/// Stack: [reference, value] -> []
StoreRef = 0x62,
/// Stack: [gate, value] -> []
GateStore = 0x62,
/// Marks the beginning of a Peek scope for a gate.
/// Stack: [gate] -> [gate]
GateBeginPeek = 0x63,
/// Marks the end of a Peek scope for a gate.
/// Stack: [gate] -> [gate]
GateEndPeek = 0x64,
/// Marks the beginning of a Borrow scope for a gate.
/// Stack: [gate] -> [gate]
GateBeginBorrow = 0x65,
/// Marks the end of a Borrow scope for a gate.
/// Stack: [gate] -> [gate]
GateEndBorrow = 0x66,
/// Marks the beginning of a Mutate scope for a gate.
/// Stack: [gate] -> [gate]
GateBeginMutate = 0x67,
/// Marks the end of a Mutate scope for a gate.
/// Stack: [gate] -> [gate]
GateEndMutate = 0x68,
/// Increments the reference count of a gate.
/// Stack: [gate] -> [gate]
GateRetain = 0x69,
/// Decrements the reference count of a gate.
/// Stack: [gate] -> []
GateRelease = 0x6A,
// --- 6.8 Peripherals and System ---
@@ -198,10 +238,14 @@ impl TryFrom<u16> for OpCode {
0x16 => Ok(OpCode::PushBool),
0x17 => Ok(OpCode::PushI32),
0x18 => Ok(OpCode::PopN),
0x19 => Ok(OpCode::PushBounded),
0x20 => Ok(OpCode::Add),
0x21 => Ok(OpCode::Sub),
0x22 => Ok(OpCode::Mul),
0x23 => Ok(OpCode::Div),
0x24 => Ok(OpCode::Mod),
0x25 => Ok(OpCode::BoundToInt),
0x26 => Ok(OpCode::IntToBoundChecked),
0x30 => Ok(OpCode::Eq),
0x31 => Ok(OpCode::Neq),
0x32 => Ok(OpCode::Lt),
@@ -226,8 +270,16 @@ impl TryFrom<u16> for OpCode {
0x52 => Ok(OpCode::PushScope),
0x53 => Ok(OpCode::PopScope),
0x60 => Ok(OpCode::Alloc),
0x61 => Ok(OpCode::LoadRef),
0x62 => Ok(OpCode::StoreRef),
0x61 => Ok(OpCode::GateLoad),
0x62 => Ok(OpCode::GateStore),
0x63 => Ok(OpCode::GateBeginPeek),
0x64 => Ok(OpCode::GateEndPeek),
0x65 => Ok(OpCode::GateBeginBorrow),
0x66 => Ok(OpCode::GateEndBorrow),
0x67 => Ok(OpCode::GateBeginMutate),
0x68 => Ok(OpCode::GateEndMutate),
0x69 => Ok(OpCode::GateRetain),
0x6A => Ok(OpCode::GateRelease),
0x70 => Ok(OpCode::Syscall),
0x80 => Ok(OpCode::FrameSync),
_ => Err(format!("Invalid OpCode: 0x{:04X}", value)),
@@ -255,10 +307,14 @@ impl OpCode {
OpCode::PushF64 => 2,
OpCode::PushBool => 2,
OpCode::PushI32 => 2,
OpCode::PushBounded => 2,
OpCode::Add => 2,
OpCode::Sub => 2,
OpCode::Mul => 4,
OpCode::Div => 6,
OpCode::Mod => 6,
OpCode::BoundToInt => 1,
OpCode::IntToBoundChecked => 1,
OpCode::Eq => 2,
OpCode::Neq => 2,
OpCode::Lt => 2,
@@ -283,10 +339,76 @@ impl OpCode {
OpCode::PushScope => 3,
OpCode::PopScope => 3,
OpCode::Alloc => 10,
OpCode::LoadRef => 3,
OpCode::StoreRef => 3,
OpCode::GateLoad => 3,
OpCode::GateStore => 3,
OpCode::GateBeginPeek => 1,
OpCode::GateEndPeek => 1,
OpCode::GateBeginBorrow => 1,
OpCode::GateEndBorrow => 1,
OpCode::GateBeginMutate => 1,
OpCode::GateEndMutate => 1,
OpCode::GateRetain => 1,
OpCode::GateRelease => 1,
OpCode::Syscall => 1,
OpCode::FrameSync => 1,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::asm::{assemble, Asm, Operand};
#[test]
fn test_opcode_stability() {
// Normative test: ensures opcode numeric values are frozen.
assert_eq!(OpCode::Nop as u16, 0x00);
assert_eq!(OpCode::PushConst as u16, 0x10);
assert_eq!(OpCode::Alloc as u16, 0x60);
assert_eq!(OpCode::GateLoad as u16, 0x61);
assert_eq!(OpCode::GateStore as u16, 0x62);
assert_eq!(OpCode::GateBeginPeek as u16, 0x63);
assert_eq!(OpCode::GateEndPeek as u16, 0x64);
assert_eq!(OpCode::GateBeginBorrow as u16, 0x65);
assert_eq!(OpCode::GateEndBorrow as u16, 0x66);
assert_eq!(OpCode::GateBeginMutate as u16, 0x67);
assert_eq!(OpCode::GateEndMutate as u16, 0x68);
assert_eq!(OpCode::GateRetain as u16, 0x69);
assert_eq!(OpCode::GateRelease as u16, 0x6A);
assert_eq!(OpCode::FrameSync as u16, 0x80);
}
#[test]
fn test_hip_bytecode_golden() {
// Golden test for HIP opcodes and their encodings.
// Rule: All multi-byte operands are little-endian.
let instructions = vec![
Asm::Op(OpCode::Alloc, vec![Operand::U32(0x11223344), Operand::U32(0x55667788)]),
Asm::Op(OpCode::GateLoad, vec![Operand::U32(0xAABBCCDD)]),
Asm::Op(OpCode::GateStore, vec![Operand::U32(0x11223344)]),
Asm::Op(OpCode::GateBeginPeek, vec![]),
Asm::Op(OpCode::GateRetain, vec![]),
Asm::Op(OpCode::GateRelease, vec![]),
];
let bytes = assemble(&instructions).unwrap();
let mut expected = Vec::new();
// Alloc (0x60, 0x00) + type_id (44 33 22 11) + slots (88 77 66 55)
expected.extend_from_slice(&[0x60, 0x00, 0x44, 0x33, 0x22, 0x11, 0x88, 0x77, 0x66, 0x55]);
// GateLoad (0x61, 0x00) + offset (DD CC BB AA)
expected.extend_from_slice(&[0x61, 0x00, 0xDD, 0xCC, 0xBB, 0xAA]);
// GateStore (0x62, 0x00) + offset (44 33 22 11)
expected.extend_from_slice(&[0x62, 0x00, 0x44, 0x33, 0x22, 0x11]);
// GateBeginPeek (0x63, 0x00)
expected.extend_from_slice(&[0x63, 0x00]);
// GateRetain (0x69, 0x00)
expected.extend_from_slice(&[0x69, 0x00]);
// GateRelease (0x6A, 0x00)
expected.extend_from_slice(&[0x6A, 0x00]);
assert_eq!(bytes, expected);
}
}
-184
View File
@@ -1,184 +0,0 @@
use crate::readwrite::*;
use std::io::{Cursor, Read, Write};
/// An entry in the Constant Pool.
///
/// The Constant Pool is a table of unique values used by the program.
/// Instead of embedding large data (like strings) directly in the instruction stream,
/// the bytecode uses `PushConst <index>` to load these values onto the stack.
#[derive(Debug, Clone, PartialEq)]
pub enum ConstantPoolEntry {
/// Reserved index (0). Represents a null/undefined value.
Null,
/// A 64-bit integer constant.
Int64(i64),
/// A 64-bit floating point constant.
Float64(f64),
/// A boolean constant.
Boolean(bool),
/// A UTF-8 string constant.
String(String),
/// A 32-bit integer constant.
Int32(i32),
}
/// Represents a compiled Prometeu ByteCode (.pbc) file.
///
/// The file format follows this structure (Little-Endian):
/// 1. Magic Header: "PPBC" (4 bytes)
/// 2. CP Count: u32
/// 3. CP Entries: [Tag (u8), Data...]
/// 4. ROM Size: u32
/// 5. ROM Data: [u16 OpCode, Operands...][]
#[derive(Debug, Clone, Default)]
pub struct PbcFile {
/// The list of constants used by the program.
pub cp: Vec<ConstantPoolEntry>,
/// The raw instruction bytes (ROM).
pub rom: Vec<u8>,
}
/// Parses a raw byte buffer into a `PbcFile` structure.
///
/// This function validates the "PPBC" signature and reconstructs the
/// Constant Pool and ROM data from the binary format.
pub fn parse_pbc(bytes: &[u8]) -> Result<PbcFile, String> {
if bytes.len() < 4 || &bytes[0..4] != b"PPBC" {
return Err("Invalid PBC signature".into());
}
let mut cursor = Cursor::new(&bytes[4..]);
let cp_count = read_u32_le(&mut cursor).map_err(|e| e.to_string())? as usize;
let mut cp = Vec::with_capacity(cp_count);
for _ in 0..cp_count {
let mut tag_buf = [0u8; 1];
cursor.read_exact(&mut tag_buf).map_err(|e| e.to_string())?;
let tag = tag_buf[0];
match tag {
1 => {
let val = read_i64_le(&mut cursor).map_err(|e| e.to_string())?;
cp.push(ConstantPoolEntry::Int64(val));
}
2 => {
let val = read_f64_le(&mut cursor).map_err(|e| e.to_string())?;
cp.push(ConstantPoolEntry::Float64(val));
}
3 => {
let mut bool_buf = [0u8; 1];
cursor.read_exact(&mut bool_buf).map_err(|e| e.to_string())?;
cp.push(ConstantPoolEntry::Boolean(bool_buf[0] != 0));
}
4 => {
let len = read_u32_le(&mut cursor).map_err(|e| e.to_string())? as usize;
let mut s_buf = vec![0u8; len];
cursor.read_exact(&mut s_buf).map_err(|e| e.to_string())?;
let s = String::from_utf8_lossy(&s_buf).into_owned();
cp.push(ConstantPoolEntry::String(s));
}
5 => {
let val = read_u32_le(&mut cursor).map_err(|e| e.to_string())? as i32;
cp.push(ConstantPoolEntry::Int32(val));
}
_ => cp.push(ConstantPoolEntry::Null),
}
}
let rom_size = read_u32_le(&mut cursor).map_err(|e| e.to_string())? as usize;
let mut rom = vec![0u8; rom_size];
cursor.read_exact(&mut rom).map_err(|e| e.to_string())?;
Ok(PbcFile { cp, rom })
}
/// Serializes a `PbcFile` structure into a binary buffer.
///
/// This is used by the compiler to generate the final .pbc file.
pub fn write_pbc(pbc: &PbcFile) -> Result<Vec<u8>, String> {
let mut out = Vec::new();
out.write_all(b"PPBC").map_err(|e| e.to_string())?;
write_u32_le(&mut out, pbc.cp.len() as u32).map_err(|e| e.to_string())?;
for entry in &pbc.cp {
match entry {
ConstantPoolEntry::Null => {
out.write_all(&[0]).map_err(|e| e.to_string())?;
}
ConstantPoolEntry::Int64(v) => {
out.write_all(&[1]).map_err(|e| e.to_string())?;
write_i64_le(&mut out, *v).map_err(|e| e.to_string())?;
}
ConstantPoolEntry::Float64(v) => {
out.write_all(&[2]).map_err(|e| e.to_string())?;
write_f64_le(&mut out, *v).map_err(|e| e.to_string())?;
}
ConstantPoolEntry::Boolean(v) => {
out.write_all(&[3]).map_err(|e| e.to_string())?;
out.write_all(&[if *v { 1 } else { 0 }]).map_err(|e| e.to_string())?;
}
ConstantPoolEntry::String(v) => {
out.write_all(&[4]).map_err(|e| e.to_string())?;
let bytes = v.as_bytes();
write_u32_le(&mut out, bytes.len() as u32).map_err(|e| e.to_string())?;
out.write_all(bytes).map_err(|e| e.to_string())?;
}
ConstantPoolEntry::Int32(v) => {
out.write_all(&[5]).map_err(|e| e.to_string())?;
write_u32_le(&mut out, *v as u32).map_err(|e| e.to_string())?;
}
}
}
write_u32_le(&mut out, pbc.rom.len() as u32).map_err(|e| e.to_string())?;
out.write_all(&pbc.rom).map_err(|e| e.to_string())?;
Ok(out)
}
#[cfg(test)]
mod tests {
use crate::asm::{self, Asm, Operand};
use crate::disasm;
use crate::opcode::OpCode;
use crate::pbc::{self, ConstantPoolEntry, PbcFile};
#[test]
fn test_golden_abi_roundtrip() {
// 1. Create a simple assembly program: PushI32 42; Halt
let instructions = vec![
Asm::Op(OpCode::PushI32, vec![Operand::I32(42)]),
Asm::Op(OpCode::Halt, vec![]),
];
let rom = asm::assemble(&instructions).expect("Failed to assemble");
// 2. Create a PBC file
let pbc_file = PbcFile {
cp: vec![ConstantPoolEntry::Int32(100)], // Random CP entry
rom,
};
let bytes = pbc::write_pbc(&pbc_file).expect("Failed to write PBC");
// 3. Parse it back
let parsed_pbc = pbc::parse_pbc(&bytes).expect("Failed to parse PBC");
assert_eq!(parsed_pbc.cp, pbc_file.cp);
assert_eq!(parsed_pbc.rom, pbc_file.rom);
// 4. Disassemble ROM
let dis_instrs = disasm::disasm(&parsed_pbc.rom).expect("Failed to disassemble");
assert_eq!(dis_instrs.len(), 2);
assert_eq!(dis_instrs[0].opcode, OpCode::PushI32);
if let disasm::DisasmOperand::U32(v) = dis_instrs[0].operands[0] {
assert_eq!(v, 42);
} else {
panic!("Wrong operand type");
}
assert_eq!(dis_instrs[1].opcode, OpCode::Halt);
}
}