create prometeu-bytecode

This commit is contained in:
Nilton Constantino
2026-01-20 10:17:58 +00:00
parent 481deacc65
commit 84d57897b1
16 changed files with 559 additions and 109 deletions
+2 -1
View File
@@ -6,4 +6,5 @@ license.workspace = true
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_json = "1.0"
prometeu-bytecode = { path = "../prometeu-bytecode" }
@@ -1,12 +1,11 @@
mod virtual_machine;
mod value;
mod opcode;
mod call_frame;
mod scope_frame;
mod program;
pub mod native_interface;
pub use opcode::OpCode;
pub use prometeu_bytecode::opcode::OpCode;
pub use program::Program;
pub use value::Value;
pub use virtual_machine::{BudgetReport, LogicalFrameEndingReason, VirtualMachine};
@@ -1,204 +0,0 @@
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum OpCode {
// 6.1 Execution Control
Nop = 0x00,
Halt = 0x01,
Jmp = 0x02,
JmpIfFalse = 0x03,
JmpIfTrue = 0x04,
Trap = 0x05,
// 6.2 Stack
PushConst = 0x10,
Pop = 0x11,
Dup = 0x12,
Swap = 0x13,
PushI64 = 0x14,
PushF64 = 0x15,
PushBool = 0x16,
PushI32 = 0x17,
PopN = 0x18,
// 6.3 Arithmetic
Add = 0x20,
Sub = 0x21,
Mul = 0x22,
Div = 0x23,
// 6.4 Comparison and Logic
Eq = 0x30,
Neq = 0x31,
Lt = 0x32,
Gt = 0x33,
And = 0x34,
Or = 0x35,
Not = 0x36,
BitAnd = 0x37,
BitOr = 0x38,
BitXor = 0x39,
Shl = 0x3A,
Shr = 0x3B,
Lte = 0x3C,
Gte = 0x3D,
Neg = 0x3E,
// 6.5 Variables
GetGlobal = 0x40,
SetGlobal = 0x41,
GetLocal = 0x42,
SetLocal = 0x43,
// 6.6 Functions
Call = 0x50,
Ret = 0x51,
PushScope = 0x52,
PopScope = 0x53,
// 6.7 Heap
Alloc = 0x60,
LoadRef = 0x61,
StoreRef = 0x62,
// 6.8 Peripherals and System
Syscall = 0x70,
FrameSync = 0x80,
}
impl TryFrom<u16> for OpCode {
type Error = String;
fn try_from(value: u16) -> Result<Self, Self::Error> {
match value {
0x00 => Ok(OpCode::Nop),
0x01 => Ok(OpCode::Halt),
0x02 => Ok(OpCode::Jmp),
0x03 => Ok(OpCode::JmpIfFalse),
0x04 => Ok(OpCode::JmpIfTrue),
0x05 => Ok(OpCode::Trap),
0x10 => Ok(OpCode::PushConst),
0x11 => Ok(OpCode::Pop),
0x12 => Ok(OpCode::Dup),
0x13 => Ok(OpCode::Swap),
0x14 => Ok(OpCode::PushI64),
0x15 => Ok(OpCode::PushF64),
0x16 => Ok(OpCode::PushBool),
0x17 => Ok(OpCode::PushI32),
0x18 => Ok(OpCode::PopN),
0x20 => Ok(OpCode::Add),
0x21 => Ok(OpCode::Sub),
0x22 => Ok(OpCode::Mul),
0x23 => Ok(OpCode::Div),
0x30 => Ok(OpCode::Eq),
0x31 => Ok(OpCode::Neq),
0x32 => Ok(OpCode::Lt),
0x33 => Ok(OpCode::Gt),
0x34 => Ok(OpCode::And),
0x35 => Ok(OpCode::Or),
0x36 => Ok(OpCode::Not),
0x37 => Ok(OpCode::BitAnd),
0x38 => Ok(OpCode::BitOr),
0x39 => Ok(OpCode::BitXor),
0x3A => Ok(OpCode::Shl),
0x3B => Ok(OpCode::Shr),
0x3C => Ok(OpCode::Lte),
0x3D => Ok(OpCode::Gte),
0x3E => Ok(OpCode::Neg),
0x40 => Ok(OpCode::GetGlobal),
0x41 => Ok(OpCode::SetGlobal),
0x42 => Ok(OpCode::GetLocal),
0x43 => Ok(OpCode::SetLocal),
0x50 => Ok(OpCode::Call),
0x51 => Ok(OpCode::Ret),
0x52 => Ok(OpCode::PushScope),
0x53 => Ok(OpCode::PopScope),
0x60 => Ok(OpCode::Alloc),
0x61 => Ok(OpCode::LoadRef),
0x62 => Ok(OpCode::StoreRef),
0x70 => Ok(OpCode::Syscall),
0x80 => Ok(OpCode::FrameSync),
_ => Err(format!("Invalid OpCode: 0x{:04X}", value)),
}
}
}
impl OpCode {
pub fn cycles(&self) -> u64 {
match self {
OpCode::Nop => 1,
OpCode::Halt => 1,
OpCode::Jmp => 2,
OpCode::JmpIfFalse => 3,
OpCode::JmpIfTrue => 3,
OpCode::Trap => 1,
OpCode::PushConst => 2,
OpCode::Pop => 1,
OpCode::PopN => 2,
OpCode::Dup => 1,
OpCode::Swap => 1,
OpCode::PushI64 => 2,
OpCode::PushF64 => 2,
OpCode::PushBool => 2,
OpCode::PushI32 => 2,
OpCode::Add => 2,
OpCode::Sub => 2,
OpCode::Mul => 4,
OpCode::Div => 6,
OpCode::Eq => 2,
OpCode::Neq => 2,
OpCode::Lt => 2,
OpCode::Gt => 2,
OpCode::And => 2,
OpCode::Or => 2,
OpCode::Not => 1,
OpCode::BitAnd => 2,
OpCode::BitOr => 2,
OpCode::BitXor => 2,
OpCode::Shl => 2,
OpCode::Shr => 2,
OpCode::Lte => 2,
OpCode::Gte => 2,
OpCode::Neg => 1,
OpCode::GetGlobal => 3,
OpCode::SetGlobal => 3,
OpCode::GetLocal => 2,
OpCode::SetLocal => 2,
OpCode::Call => 5,
OpCode::Ret => 4,
OpCode::PushScope => 3,
OpCode::PopScope => 3,
OpCode::Alloc => 10,
OpCode::LoadRef => 3,
OpCode::StoreRef => 3,
OpCode::Syscall => 1, // Variable, but we'll use 1 as base or define via ID
OpCode::FrameSync => 1,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_opcode_decoding() {
assert_eq!(OpCode::try_from(0x00).unwrap(), OpCode::Nop);
assert_eq!(OpCode::try_from(0x05).unwrap(), OpCode::Trap);
assert_eq!(OpCode::try_from(0x10).unwrap(), OpCode::PushConst);
assert_eq!(OpCode::try_from(0x18).unwrap(), OpCode::PopN);
assert_eq!(OpCode::try_from(0x20).unwrap(), OpCode::Add);
assert_eq!(OpCode::try_from(0x70).unwrap(), OpCode::Syscall);
assert_eq!(OpCode::try_from(0x80).unwrap(), OpCode::FrameSync);
assert!(OpCode::try_from(0xFFFF).is_err());
}
#[test]
fn test_opcode_cycles() {
assert_eq!(OpCode::Nop.cycles(), 1);
assert_eq!(OpCode::Add.cycles(), 2);
assert_eq!(OpCode::Mul.cycles(), 4);
assert_eq!(OpCode::Div.cycles(), 6);
assert_eq!(OpCode::Alloc.cycles(), 10);
}
}
@@ -2,9 +2,10 @@ use crate::hardware::HardwareBridge;
use crate::prometeu_os::NativeInterface;
use crate::virtual_machine::call_frame::CallFrame;
use crate::virtual_machine::scope_frame::ScopeFrame;
use crate::virtual_machine::opcode::OpCode;
use crate::virtual_machine::value::Value;
use crate::virtual_machine::Program;
use prometeu_bytecode::opcode::OpCode;
use prometeu_bytecode::pbc::{self, ConstantPoolEntry};
/// 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
@@ -84,8 +85,16 @@ impl VirtualMachine {
// 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);
if let Ok(pbc_file) = pbc::parse_pbc(&program_bytes) {
let cp = pbc_file.cp.into_iter().map(|entry| match entry {
ConstantPoolEntry::Int32(v) => Value::Int32(v),
ConstantPoolEntry::Int64(v) => Value::Int64(v),
ConstantPoolEntry::Float64(v) => Value::Float(v),
ConstantPoolEntry::Boolean(v) => Value::Boolean(v),
ConstantPoolEntry::String(v) => Value::String(v),
ConstantPoolEntry::Null => Value::Null,
}).collect();
self.program = Program::new(pbc_file.rom, cp);
} else {
// Fallback for raw bytes if PBC parsing fails
self.program = Program::new(program_bytes, vec![]);
@@ -111,81 +120,6 @@ impl VirtualMachine {
self.cycles = 0;
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" 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);
for _ in 0..cp_count {
if cursor >= bytes.len() { return Err("Unexpected end of PBC".into()); }
let tag = bytes[cursor];
cursor += 1;
match tag {
1 => { // Int64 (64-bit)
let val = self.read_i64_at(bytes, &mut cursor)?;
cp.push(Value::Int64(val));
}
2 => { // Float (64-bit)
let val = self.read_f64_at(bytes, &mut cursor)?;
cp.push(Value::Float(val));
}
3 => { // Boolean
if cursor >= bytes.len() { return Err("Unexpected end of PBC".into()); }
let val = bytes[cursor] != 0;
cursor += 1;
cp.push(Value::Boolean(val));
}
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();
cursor += len;
cp.push(Value::String(s));
}
5 => { // Int32 (32-bit)
let val = self.read_u32_at(bytes, &mut cursor)? as i32;
cp.push(Value::Int32(val));
}
_ => cp.push(Value::Null),
}
}
// 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());
}
let rom = bytes[cursor..cursor + rom_size].to_vec();
Ok((rom, cp))
}
fn read_u32_at(&self, bytes: &[u8], cursor: &mut usize) -> Result<u32, String> {
if *cursor + 4 > bytes.len() { return Err("Unexpected end of PBC".into()); }
let val = u32::from_le_bytes(bytes[*cursor..*cursor + 4].try_into().unwrap());
*cursor += 4;
Ok(val)
}
fn read_i64_at(&self, bytes: &[u8], cursor: &mut usize) -> Result<i64, String> {
if *cursor + 8 > bytes.len() { return Err("Unexpected end of PBC".into()); }
let val = i64::from_le_bytes(bytes[*cursor..*cursor + 8].try_into().unwrap());
*cursor += 8;
Ok(val)
}
fn read_f64_at(&self, bytes: &[u8], cursor: &mut usize) -> Result<f64, String> {
if *cursor + 8 > bytes.len() { return Err("Unexpected end of PBC".into()); }
let val = f64::from_le_bytes(bytes[*cursor..*cursor + 8].try_into().unwrap());
*cursor += 8;
Ok(val)
}
}
impl Default for VirtualMachine {