clean up, debugger, add comments

This commit is contained in:
2026-03-24 13:40:20 +00:00
parent 28df72417b
commit 31080ea40d
60 changed files with 1033 additions and 557 deletions
+71 -71
View File
@@ -1,116 +1,116 @@
# prometeu-bytecode
Contrato oficial (ABI) do ecossistema PROMETEU. Este crate define o conjunto de instruções (ISA), o formato de arquivo `.pbc` (Prometeu ByteCode) e ferramentas básicas de montagem (Assembler) e desmontagem (Disassembler).
Official contract (ABI) of the PROMETEU ecosystem. This crate defines the Instruction Set Architecture (ISA), the `.pbc` file format (Prometeu ByteCode), and basic tools for assembly (Assembler) and disassembly (Disassembler).
## Design
A PVM (Prometeu Virtual Machine) é uma máquina baseada em pilha (**stack-based**). A maioria das instruções opera nos valores do topo da pilha de operandos. O formato de dados padrão para multi-byte na ROM é **Little-Endian**.
The PVM (Prometeu Virtual Machine) is a **stack-based** machine. Most instructions operate on values at the top of the operand stack. The default multi-byte data format in ROM is **Little-Endian**.
### Convenção de Notação da Pilha
Nas tabelas abaixo, usamos a seguinte notação para representar o estado da pilha:
### Stack Notation Convention
In the tables below, we use the following notation to represent the state of the stack:
`[a, b] -> [c]`
Significa que a instrução remove `a` e `b` da pilha (onde `b` estava no topo) e insere `c` no topo.
Means the instruction removes `a` and `b` from the stack (where `b` was at the top) and pushes `c` to the top.
---
## Conjunto de Instruções (ISA)
## Instruction Set Architecture (ISA)
### 6.1 Controle de Execução
### 6.1 Execution Control
| OpCode | Valor | Operandos | Pilha | Descrição |
| OpCode | Value | Operands | Stack | Description |
| :--- | :--- | :--- | :--- | :--- |
| `Nop` | `0x00` | - | `[] -> []` | Nenhuma operação. |
| `Halt` | `0x01` | - | `[] -> []` | Interrompe a execução da VM permanentemente. |
| `Jmp` | `0x02` | `addr: u32` | `[] -> []` | Salto incondicional para o endereço absoluto `addr`. |
| `JmpIfFalse`| `0x03` | `addr: u32` | `[bool] -> []` | Salta para `addr` se o valor desempilhado for `false`. |
| `JmpIfTrue` | `0x04` | `addr: u32` | `[bool] -> []` | Salta para `addr` se o valor desempilhado for `true`. |
| `Trap` | `0x05` | - | `[] -> []` | Interrupção para debugger (breakpoint). |
| `Nop` | `0x00` | - | `[] -> []` | No operation. |
| `Halt` | `0x01` | - | `[] -> []` | Permanently halts VM execution. |
| `Jmp` | `0x02` | `addr: u32` | `[] -> []` | Unconditional jump to absolute address `addr`. |
| `JmpIfFalse`| `0x03` | `addr: u32` | `[bool] -> []` | Jumps to `addr` if the popped value is `false`. |
| `JmpIfTrue` | `0x04` | `addr: u32` | `[bool] -> []` | Jumps to `addr` if the popped value is `true`. |
| `Trap` | `0x05` | - | `[] -> []` | Debugger interruption (breakpoint). |
### 6.2 Manipulação da Pilha
### 6.2 Stack Manipulation
| OpCode | Valor | Operandos | Pilha | Descrição |
| OpCode | Value | Operands | Stack | Description |
| :--- | :--- | :--- | :--- | :--- |
| `PushConst` | `0x10` | `idx: u32` | `[] -> [val]` | Carrega a constante do índice `idx` da Constant Pool. |
| `Pop` | `0x11` | - | `[val] -> []` | Remove e descarta o valor do topo da pilha. |
| `Dup` | `0x12` | - | `[val] -> [val, val]` | Duplica o valor no topo da pilha. |
| `Swap` | `0x13` | - | `[a, b] -> [b, a]` | Inverte a posição dos dois valores no topo. |
| `PushI64` | `0x14` | `val: i64` | `[] -> [i64]` | Empilha um inteiro de 64 bits imediato. |
| `PushF64` | `0x15` | `val: f64` | `[] -> [f64]` | Empilha um ponto flutuante de 64 bits imediato. |
| `PushBool` | `0x16` | `val: u8` | `[] -> [bool]` | Empilha um booleano (0=false, 1=true). |
| `PushI32` | `0x17` | `val: i32` | `[] -> [i32]` | Empilha um inteiro de 32 bits imediato. |
| `PopN` | `0x18` | `n: u16` | `[...] -> [...]` | Remove `n` valores da pilha de uma vez. |
| `PushConst` | `0x10` | `idx: u32` | `[] -> [val]` | Loads the constant at index `idx` from the Constant Pool. |
| `Pop` | `0x11` | - | `[val] -> []` | Removes and discards the top value of the stack. |
| `Dup` | `0x12` | - | `[val] -> [val, val]` | Duplicates the value at the top of the stack. |
| `Swap` | `0x13` | - | `[a, b] -> [b, a]` | Swaps the positions of the two values at the top. |
| `PushI64` | `0x14` | `val: i64` | `[] -> [i64]` | Pushes an immediate 64-bit integer. |
| `PushF64` | `0x15` | `val: f64` | `[] -> [f64]` | Pushes an immediate 64-bit floating point. |
| `PushBool` | `0x16` | `val: u8` | `[] -> [bool]` | Pushes a boolean (0=false, 1=true). |
| `PushI32` | `0x17` | `val: i32` | `[] -> [i32]` | Pushes an immediate 32-bit integer. |
| `PopN` | `0x18` | `n: u16` | `[...] -> [...]` | Removes `n` values from the stack at once. |
### 6.3 Aritmética
A VM realiza promoção automática de tipos (ex: `i32` + `f64` resulta em `f64`).
### 6.3 Arithmetic
The VM performs automatic type promotion (e.g., `i32` + `f64` results in `f64`).
| OpCode | Valor | Pilha | Descrição |
| OpCode | Value | Stack | Description |
| :--- | :--- | :--- | :--- |
| `Add` | `0x20` | `[a, b] -> [a + b]` | Soma os dois valores do topo. |
| `Sub` | `0x21` | `[a, b] -> [a - b]` | Subtrai `b` de `a`. |
| `Mul` | `0x22` | `[a, b] -> [a * b]` | Multiplica os dois valores do topo. |
| `Div` | `0x23` | `[a, b] -> [a / b]` | Divide `a` por `b`. Erro se `b == 0`. |
| `Neg` | `0x3E` | `[a] -> [-a]` | Inverte o sinal numérico. |
| `Add` | `0x20` | `[a, b] -> [a + b]` | Adds the two top values. |
| `Sub` | `0x21` | `[a, b] -> [a - b]` | Subtracts `b` from `a`. |
| `Mul` | `0x22` | `[a, b] -> [a * b]` | Multiplies the two top values. |
| `Div` | `0x23` | `[a, b] -> [a / b]` | Divides `a` by `b`. Error if `b == 0`. |
| `Neg` | `0x3E` | `[a] -> [-a]` | Negates the numeric sign. |
### 6.4 Lógica e Comparação
### 6.4 Logic and Comparison
| OpCode | Valor | Pilha | Descrição |
| OpCode | Value | Stack | Description |
| :--- | :--- | :--- | :--- |
| `Eq` | `0x30` | `[a, b] -> [bool]` | Testa igualdade. |
| `Neq` | `0x31` | `[a, b] -> [bool]` | Testa desigualdade. |
| `Eq` | `0x30` | `[a, b] -> [bool]` | Tests equality. |
| `Neq` | `0x31` | `[a, b] -> [bool]` | Tests inequality. |
| `Lt` | `0x32` | `[a, b] -> [bool]` | `a < b` |
| `Gt` | `0x33` | `[a, b] -> [bool]` | `a > b` |
| `Lte` | `0x3C` | `[a, b] -> [bool]` | `a <= b` |
| `Gte` | `0x3D` | `[a, b] -> [bool]` | `a >= b` |
| `And` | `0x34` | `[a, b] -> [bool]` | AND lógico (booleano). |
| `Or` | `0x35` | `[a, b] -> [bool]` | OR lógico (booleano). |
| `Not` | `0x36` | `[a] -> [!a]` | NOT lógico. |
| `BitAnd` | `0x37` | `[a, b] -> [int]` | AND bit a bit. |
| `BitOr` | `0x38` | `[a, b] -> [int]` | OR bit a bit. |
| `BitXor` | `0x39` | `[a, b] -> [int]` | XOR bit a bit. |
| `And` | `0x34` | `[a, b] -> [bool]` | Logical AND (boolean). |
| `Or` | `0x35` | `[a, b] -> [bool]` | Logical OR (boolean). |
| `Not` | `0x36` | `[a] -> [!a]` | Logical NOT. |
| `BitAnd` | `0x37` | `[a, b] -> [int]` | Bitwise AND. |
| `BitOr` | `0x38` | `[a, b] -> [int]` | Bitwise OR. |
| `BitXor` | `0x39` | `[a, b] -> [int]` | Bitwise XOR. |
| `Shl` | `0x3A` | `[a, b] -> [int]` | Shift Left: `a << b`. |
| `Shr` | `0x3B` | `[a, b] -> [int]` | Shift Right: `a >> b`. |
### 6.5 Variáveis e Memória
### 6.5 Variables and Memory
| OpCode | Valor | Operandos | Pilha | Descrição |
| OpCode | Value | Operands | Stack | Description |
| :--- | :--- | :--- | :--- | :--- |
| `GetGlobal`| `0x40` | `idx: u32` | `[] -> [val]` | Carrega valor da global `idx`. |
| `SetGlobal`| `0x41` | `idx: u32` | `[val] -> []` | Armazena topo na global `idx`. |
| `GetLocal` | `0x42` | `idx: u32` | `[] -> [val]` | Carrega local `idx` do frame atual. |
| `SetLocal` | `0x43` | `idx: u32` | `[val] -> []` | Armazena topo na local `idx` do frame atual. |
| `GetGlobal`| `0x40` | `idx: u32` | `[] -> [val]` | Loads value from global `idx`. |
| `SetGlobal`| `0x41` | `idx: u32` | `[val] -> []` | Stores top of stack in global `idx`. |
| `GetLocal` | `0x42` | `idx: u32` | `[] -> [val]` | Loads local `idx` from the current frame. |
| `SetLocal` | `0x43` | `idx: u32` | `[val] -> []` | Stores top of stack in local `idx` of the current frame. |
### 6.6 Funções e Escopo
### 6.6 Functions and Scope
| OpCode | Valor | Operandos | Pilha | Descrição |
| OpCode | Value | Operands | Stack | Description |
| :--- | :--- | :--- | :--- | :--- |
| `Call` | `0x50` | `addr: u32, args: u32` | `[a1, a2] -> [...]` | Chama `addr`. Os `args` valores no topo viram locais do novo frame. |
| `Ret` | `0x51` | - | `[val] -> [val]` | Retorna da função atual, limpando o frame e devolvendo o valor do topo. |
| `PushScope`| `0x52` | - | `[] -> []` | Inicia um sub-escopo (bloco) para locais temporários. |
| `PopScope` | `0x53` | - | `[] -> []` | Finaliza sub-escopo, removendo locais criados nele da pilha. |
| `Call` | `0x50` | `addr: u32, args: u32` | `[a1, a2] -> [...]` | Calls `addr`. The `args` values at the top become locals of the new frame. |
| `Ret` | `0x51` | - | `[val] -> [val]` | Returns from the current function, clearing the frame and returning the top value. |
| `PushScope`| `0x52` | - | `[] -> []` | Starts a sub-scope (block) for temporary locals. |
| `PopScope` | `0x53` | - | `[] -> []` | Ends sub-scope, removing locals created in it from the stack. |
### 6.7 Heap (Memória Dinâmica)
### 6.7 Heap (Dynamic Memory)
| OpCode | Valor | Operandos | Pilha | Descrição |
| OpCode | Value | Operands | Stack | Description |
| :--- | :--- | :--- | :--- | :--- |
| `Alloc` | `0x60` | `size: u32` | `[] -> [ref]` | Aloca `size` slots no heap e retorna uma referência. |
| `LoadRef` | `0x61` | `offset: u32`| `[ref] -> [val]` | Lê valor do heap no endereço `ref + offset`. |
| `StoreRef`| `0x62` | `offset: u32`| `[ref, val] -> []` | Escreve `val` no heap no endereço `ref + offset`. |
| `Alloc` | `0x60` | `size: u32` | `[] -> [ref]` | Allocates `size` slots on the heap and returns a reference. |
| `LoadRef` | `0x61` | `offset: u32`| `[ref] -> [val]` | Reads value from the heap at address `ref + offset`. |
| `StoreRef`| `0x62` | `offset: u32`| `[ref, val] -> []` | Writes `val` to the heap at address `ref + offset`. |
### 6.8 Sistema e Sincronização
### 6.8 System and Synchronization
| OpCode | Valor | Operandos | Pilha | Descrição |
| OpCode | Value | Operands | Stack | Description |
| :--- | :--- | :--- | :--- | :--- |
| `Syscall` | `0x70` | `id: u32` | `[...] -> [...]` | Invoca uma função do sistema/firmware. A pilha depende da syscall. |
| `FrameSync`| `0x80` | - | `[] -> []` | Marca o fim do processamento do frame lógico atual (60 FPS). |
| `Syscall` | `0x70` | `id: u32` | `[...] -> [...]` | Invokes a system/firmware function. The stack depends on the syscall. |
| `FrameSync`| `0x80` | - | `[] -> []` | Marks the end of processing for the current logical frame (60 FPS). |
---
## Estrutura do PBC (Prometeu ByteCode)
## PBC Structure (Prometeu ByteCode)
O PBC é o formato binário oficial para programas Prometeu.
PBC is the official binary format for Prometeu programs.
```rust
// Exemplo de como carregar um arquivo PBC
// Example of how to load a PBC file
let bytes = std::fs::read("game.pbc")?;
let pbc = prometeu_bytecode::pbc::parse_pbc(&bytes)?;
@@ -120,11 +120,11 @@ println!("Constants: {}", pbc.cp.len());
---
## Assembler e Disassembler
## Assembler and Disassembler
Este crate fornece ferramentas para facilitar a geração e inspeção de código.
This crate provides tools to facilitate code generation and inspection.
### Montagem (Assembler)
### Assembly (Assembler)
```rust
use prometeu_bytecode::asm::{assemble, Asm, Operand};
use prometeu_bytecode::opcode::OpCode;
@@ -139,7 +139,7 @@ let instructions = vec![
let rom_bytes = assemble(&instructions).unwrap();
```
### Desmontagem (Disassembler)
### Disassembly (Disassembler)
```rust
use prometeu_bytecode::disasm::disasm;
+9
View File
@@ -1,5 +1,12 @@
//! This module defines the Application Binary Interface (ABI) of the Prometeu Virtual Machine.
//! It specifies how instructions are encoded in bytes and how they interact with memory.
use crate::opcode::OpCode;
/// Returns the size in bytes of the operands for a given OpCode.
///
/// Note: This does NOT include the 2 bytes of the OpCode itself.
/// For example, `PushI32` has a size of 4, but occupies 6 bytes in ROM (2 for OpCode + 4 for value).
pub fn operand_size(opcode: OpCode) -> usize {
match opcode {
OpCode::PushConst => 4,
@@ -17,6 +24,7 @@ pub fn operand_size(opcode: OpCode) -> usize {
}
}
/// Checks if an instruction is a jump (branch) instruction.
pub fn is_jump(opcode: OpCode) -> bool {
match opcode {
OpCode::Jmp | OpCode::JmpIfFalse | OpCode::JmpIfTrue => true,
@@ -24,6 +32,7 @@ pub fn is_jump(opcode: OpCode) -> bool {
}
}
/// Checks if an instruction has any immediate operands in the instruction stream.
pub fn has_immediate(opcode: OpCode) -> bool {
operand_size(opcode) > 0
}
+18
View File
@@ -2,22 +2,33 @@ use crate::opcode::OpCode;
use crate::readwrite::*;
use std::collections::HashMap;
/// Represents an operand for an instruction.
#[derive(Debug, Clone)]
pub enum Operand {
/// 32-bit unsigned integer (e.g., indices, addresses).
U32(u32),
/// 32-bit signed integer.
I32(i32),
/// 64-bit signed integer.
I64(i64),
/// 64-bit floating point.
F64(f64),
/// Boolean (true/false).
Bool(bool),
/// A symbolic label that will be resolved to an absolute PC address.
Label(String),
}
/// Represents an assembly-level element (either an instruction or a label).
#[derive(Debug, Clone)]
pub enum Asm {
/// An OpCode followed by its operands. The mnemonics represent the operation to be performed.
Op(OpCode, Vec<Operand>),
/// A named marker in the code (e.g., "start:").
Label(String),
}
/// Internal helper to calculate the next PC based on the operands' sizes.
pub fn update_pc_by_operand(initial_pc: u32, operands: &Vec<Operand>) -> u32 {
let mut pcp: u32 = initial_pc;
for operand in operands {
@@ -30,6 +41,13 @@ pub fn update_pc_by_operand(initial_pc: u32, operands: &Vec<Operand>) -> u32 {
pcp
}
/// Converts a list of assembly instructions into raw ROM bytes.
///
/// The assembly process is done in two passes:
/// 1. **Label Resolution**: Iterates through all instructions to calculate the PC (Program Counter)
/// of each label and stores them in a map.
/// 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 mut labels = HashMap::new();
let mut current_pc = 0u32;
+10
View File
@@ -2,13 +2,18 @@ use crate::opcode::OpCode;
use crate::readwrite::*;
use std::io::{Cursor, Read};
/// Represents a disassembled instruction.
#[derive(Debug, Clone)]
pub struct Instr {
/// The absolute address (PC) where this instruction starts in ROM.
pub pc: u32,
/// The decoded OpCode.
pub opcode: OpCode,
/// The list of operands extracted from the byte stream.
pub operands: Vec<DisasmOperand>,
}
/// Represents an operand decoded from the byte stream.
#[derive(Debug, Clone)]
pub enum DisasmOperand {
U32(u32),
@@ -18,6 +23,11 @@ pub enum DisasmOperand {
Bool(bool),
}
/// Translates raw ROM bytes back into a human-readable list of instructions.
///
/// This is the inverse of the assembly process. It reads the bytes sequentially,
/// identifies the OpCode, and then reads the correct number of operand bytes
/// based on the ISA rules.
pub fn disasm(rom: &[u8]) -> Result<Vec<Instr>, String> {
let mut instructions = Vec::new();
let mut cursor = Cursor::new(rom);
+16 -45
View File
@@ -1,51 +1,22 @@
//! # Prometeu Bytecode (PBC)
//!
//! This crate defines the core Application Binary Interface (ABI) and Instruction Set Architecture (ISA)
//! for the Prometeu Virtual Machine (PVM).
//!
//! It serves as the "source of truth" for how programs are structured, encoded, and executed
//! within the ecosystem.
//!
//! ## 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.
//! - [`readwrite`]: Internal utilities for Little-Endian binary I/O.
pub mod opcode;
pub mod abi;
pub mod pbc;
pub mod readwrite;
pub mod asm;
pub mod disasm;
#[cfg(test)]
mod tests {
use crate::opcode::OpCode;
use crate::asm::{self, Asm, Operand};
use crate::pbc::{self, PbcFile, ConstantPoolEntry};
use crate::disasm;
#[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);
}
}
+123 -8
View File
@@ -1,67 +1,180 @@
/// Represents a single instruction in the Prometeu Virtual Machine.
///
/// Each OpCode is encoded as a 16-bit unsigned integer (u16) in the bytecode.
/// The PVM is a stack-based machine, meaning most instructions take their
/// operands from the top of the stack and push their results back onto it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum OpCode {
// 6.1 Execution Control
// --- 6.1 Execution Control ---
/// No operation. Does nothing for 1 cycle.
Nop = 0x00,
/// Stops the Virtual Machine execution immediately.
Halt = 0x01,
/// Unconditional jump to a specific PC (Program Counter) address.
/// Operand: addr (u32)
Jmp = 0x02,
/// Jumps to `addr` if the value at the top of the stack is `false`.
/// Operand: addr (u32)
/// Stack: [bool] -> []
JmpIfFalse = 0x03,
/// Jumps to `addr` if the value at the top of the stack is `true`.
/// Operand: addr (u32)
/// Stack: [bool] -> []
JmpIfTrue = 0x04,
/// Triggers a software breakpoint. Used for debugging.
Trap = 0x05,
// 6.2 Stack
// --- 6.2 Stack Manipulation ---
/// Loads a constant from the Constant Pool into the stack.
/// Operand: index (u32)
/// Stack: [] -> [value]
PushConst = 0x10,
/// Removes the top value from the stack.
/// Stack: [val] -> []
Pop = 0x11,
/// Duplicates the top value of the stack.
/// Stack: [val] -> [val, val]
Dup = 0x12,
/// Swaps the two top values of the stack.
/// Stack: [a, b] -> [b, a]
Swap = 0x13,
/// Pushes a 64-bit integer literal onto the stack.
/// Operand: value (i64)
PushI64 = 0x14,
/// Pushes a 64-bit float literal onto the stack.
/// Operand: value (f64)
PushF64 = 0x15,
/// Pushes a boolean literal onto the stack (0=false, 1=true).
/// Operand: value (u8)
PushBool = 0x16,
/// Pushes a 32-bit integer literal onto the stack.
/// Operand: value (i32)
PushI32 = 0x17,
/// Removes `n` values from the stack.
/// Operand: n (u16)
PopN = 0x18,
// 6.3 Arithmetic
// --- 6.3 Arithmetic ---
/// Adds the two top values (a + b).
/// Stack: [a, b] -> [result]
Add = 0x20,
/// Subtracts the top value from the second one (a - b).
/// Stack: [a, b] -> [result]
Sub = 0x21,
/// Multiplies the two top values (a * b).
/// Stack: [a, b] -> [result]
Mul = 0x22,
/// Divides the second top value by the top one (a / b).
/// Stack: [a, b] -> [result]
Div = 0x23,
// 6.4 Comparison and Logic
// --- 6.4 Comparison and Logic ---
/// Checks if a equals b.
/// Stack: [a, b] -> [bool]
Eq = 0x30,
/// Checks if a is not equal to b.
/// Stack: [a, b] -> [bool]
Neq = 0x31,
/// Checks if a is less than b.
/// Stack: [a, b] -> [bool]
Lt = 0x32,
/// Checks if a is greater than b.
/// Stack: [a, b] -> [bool]
Gt = 0x33,
/// Logical AND.
/// Stack: [bool, bool] -> [bool]
And = 0x34,
/// Logical OR.
/// Stack: [bool, bool] -> [bool]
Or = 0x35,
/// Logical NOT.
/// Stack: [bool] -> [bool]
Not = 0x36,
/// Bitwise AND.
/// Stack: [int, int] -> [int]
BitAnd = 0x37,
/// Bitwise OR.
/// Stack: [int, int] -> [int]
BitOr = 0x38,
/// Bitwise XOR.
/// Stack: [int, int] -> [int]
BitXor = 0x39,
/// Bitwise Shift Left.
/// Stack: [int, count] -> [int]
Shl = 0x3A,
/// Bitwise Shift Right.
/// Stack: [int, count] -> [int]
Shr = 0x3B,
/// Checks if a is less than or equal to b.
/// Stack: [a, b] -> [bool]
Lte = 0x3C,
/// Checks if a is greater than or equal to b.
/// Stack: [a, b] -> [bool]
Gte = 0x3D,
/// Negates a number (-a).
/// Stack: [num] -> [num]
Neg = 0x3E,
// 6.5 Variables
// --- 6.5 Variables ---
/// Loads a value from a global variable slot.
/// Operand: slot_index (u32)
/// Stack: [] -> [value]
GetGlobal = 0x40,
/// Stores the top value into a global variable slot.
/// Operand: slot_index (u32)
/// Stack: [value] -> []
SetGlobal = 0x41,
/// Loads a value from a local variable slot in the current frame.
/// Operand: slot_index (u32)
/// Stack: [] -> [value]
GetLocal = 0x42,
/// Stores the top value into a local variable slot in the current frame.
/// Operand: slot_index (u32)
/// Stack: [value] -> []
SetLocal = 0x43,
// 6.6 Functions
// --- 6.6 Functions ---
/// Calls a function at a specific address.
/// Operands: addr (u32), args_count (u32)
/// Stack: [arg0, arg1, ...] -> [return_value]
Call = 0x50,
/// Returns from the current function.
/// Stack: [return_val] -> [return_val]
Ret = 0x51,
/// Starts a new local scope (for blocks/loops).
PushScope = 0x52,
/// Ends the current local scope, discarding its local variables.
PopScope = 0x53,
// 6.7 Heap
// --- 6.7 Heap ---
/// Allocates `size` slots on the heap.
/// Stack: [size] -> [reference]
Alloc = 0x60,
/// Reads a value from the heap at `reference + offset`.
/// Operand: offset (u32)
/// Stack: [reference] -> [value]
LoadRef = 0x61,
/// Writes a value to the heap at `reference + offset`.
/// Operand: offset (u32)
/// Stack: [reference, value] -> []
StoreRef = 0x62,
// 6.8 Peripherals and System
// --- 6.8 Peripherals and System ---
/// Invokes a system function (Firmware/OS).
/// Operand: syscall_id (u32)
/// Stack: [args...] -> [results...] (depends on syscall)
Syscall = 0x70,
/// Synchronizes the VM with the hardware frame (usually 60Hz).
/// Execution pauses until the next VSync.
FrameSync = 0x80,
}
@@ -123,6 +236,8 @@ impl TryFrom<u16> for OpCode {
}
impl OpCode {
/// Returns the cost of the instruction in VM cycles.
/// This is used for performance monitoring and resource limiting (Certification).
pub fn cycles(&self) -> u64 {
match self {
OpCode::Nop => 1,
+73
View File
@@ -1,22 +1,47 @@
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());
@@ -68,6 +93,9 @@ pub fn parse_pbc(bytes: &[u8]) -> Result<PbcFile, 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())?;
@@ -109,3 +137,48 @@ pub fn write_pbc(pbc: &PbcFile) -> Result<Vec<u8>, 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);
}
}
+11
View File
@@ -1,41 +1,52 @@
//! Binary I/O utilities for the Prometeu ecosystem.
//! All multi-byte data is encoded in Little-Endian format.
use std::io::{self, Read, Write};
/// Reads a 16-bit unsigned integer from a reader.
pub fn read_u16_le<R: Read>(mut reader: R) -> io::Result<u16> {
let mut buf = [0u8; 2];
reader.read_exact(&mut buf)?;
Ok(u16::from_le_bytes(buf))
}
/// Reads a 32-bit unsigned integer from a reader.
pub fn read_u32_le<R: Read>(mut reader: R) -> io::Result<u32> {
let mut buf = [0u8; 4];
reader.read_exact(&mut buf)?;
Ok(u32::from_le_bytes(buf))
}
/// Reads a 64-bit signed integer from a reader.
pub fn read_i64_le<R: Read>(mut reader: R) -> io::Result<i64> {
let mut buf = [0u8; 8];
reader.read_exact(&mut buf)?;
Ok(i64::from_le_bytes(buf))
}
/// Reads a 64-bit floating point from a reader.
pub fn read_f64_le<R: Read>(mut reader: R) -> io::Result<f64> {
let mut buf = [0u8; 8];
reader.read_exact(&mut buf)?;
Ok(f64::from_le_bytes(buf))
}
/// Writes a 16-bit unsigned integer to a writer.
pub fn write_u16_le<W: Write>(mut writer: W, val: u16) -> io::Result<()> {
writer.write_all(&val.to_le_bytes())
}
/// Writes a 32-bit unsigned integer to a writer.
pub fn write_u32_le<W: Write>(mut writer: W, val: u32) -> io::Result<()> {
writer.write_all(&val.to_le_bytes())
}
/// Writes a 64-bit signed integer to a writer.
pub fn write_i64_le<W: Write>(mut writer: W, val: i64) -> io::Result<()> {
writer.write_all(&val.to_le_bytes())
}
/// Writes a 64-bit floating point to a writer.
pub fn write_f64_le<W: Write>(mut writer: W, val: f64) -> io::Result<()> {
writer.write_all(&val.to_le_bytes())
}