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
+409
View File
@@ -0,0 +1,409 @@
//! # IR Instructions
//!
//! This module defines the set of instructions used in the Intermediate Representation (IR).
//! These instructions are designed to be easy to generate from a high-level AST and
//! easy to lower into VM-specific bytecode.
use crate::common::spans::Span;
use crate::ir_core::ids::FunctionId;
use crate::ir_vm::types::{ConstId, TypeId};
/// An `Instruction` combines an instruction's behavior (`kind`) with its
/// source code location (`span`) for debugging and error reporting.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Instruction {
pub kind: InstrKind,
/// The location in the original source code that generated this instruction.
pub span: Option<Span>,
}
impl Instruction {
/// Creates a new instruction with an optional source span.
pub fn new(kind: InstrKind, span: Option<Span>) -> Self {
Self { kind, span }
}
}
/// A `Label` represents a destination for a jump instruction.
/// During the assembly phase, labels are resolved into actual memory offsets.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct Label(pub String);
/// The various types of operations that can be performed in the IR.
///
/// The IR uses a stack-based model, similar to the final Prometeu ByteCode.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum InstrKind {
/// Does nothing.
Nop,
/// Terminates program execution.
Halt,
// --- Literals ---
// These instructions push a constant value from the pool onto the stack.
/// Pushes a constant from the pool onto the stack.
PushConst(ConstId),
/// Pushes a bounded value (0..0xFFFF) onto the stack.
PushBounded(u32),
/// Pushes a boolean onto the stack.
PushBool(bool),
/// Pushes a `null` value onto the stack.
PushNull,
// --- Stack Operations ---
/// Removes the top value from the stack.
Pop,
/// Duplicates the top value on the stack.
Dup,
/// Swaps the top two values on the stack.
Swap,
// --- Arithmetic ---
// These take two values from the stack and push the result.
/// Addition: `a + b`
Add,
/// Subtraction: `a - b`
Sub,
/// Multiplication: `a * b`
Mul,
/// Division: `a / b`
Div,
/// Negation: `-a` (takes one value)
Neg,
// --- Logical/Comparison ---
/// Equality: `a == b`
Eq,
/// Inequality: `a != b`
Neq,
/// Less than: `a < b`
Lt,
/// Greater than: `a > b`
Gt,
/// Less than or equal: `a <= b`
Lte,
/// Greater than or equal: `a >= b`
Gte,
/// Logical AND: `a && b`
And,
/// Logical OR: `a || b`
Or,
/// Logical NOT: `!a`
Not,
// --- Bitwise Operations ---
/// Bitwise AND: `a & b`
BitAnd,
/// Bitwise OR: `a | b`
BitOr,
/// Bitwise XOR: `a ^ b`
BitXor,
/// Shift Left: `a << b`
Shl,
/// Shift Right: `a >> b`
Shr,
// --- Variable Access ---
/// Retrieves a value from a local variable slot and pushes it onto the stack.
LocalLoad { slot: u32 },
/// Pops a value from the stack and stores it in a local variable slot.
LocalStore { slot: u32 },
/// Retrieves a value from a global variable slot and pushes it onto the stack.
GetGlobal(u32),
/// Pops a value from the stack and stores it in a global variable slot.
SetGlobal(u32),
// --- Control Flow ---
/// Unconditionally jumps to the specified label.
Jmp(Label),
/// Pops a boolean from the stack. If false, jumps to the specified label.
JmpIfFalse(Label),
/// Defines a location that can be jumped to. Does not emit code by itself.
Label(Label),
/// Calls a function by ID with the specified number of arguments.
/// Arguments should be pushed onto the stack before calling.
Call { func_id: FunctionId, arg_count: u32 },
/// Calls a function from another project.
ImportCall {
dep_alias: String,
module_path: String,
symbol_name: String,
arg_count: u32,
},
/// Returns from the current function. The return value (if any) should be on top of the stack.
Ret,
// --- OS / System ---
/// Triggers a system call (e.g., drawing to the screen, reading input).
Syscall(u32),
/// Special instruction to synchronize with the hardware frame clock.
FrameSync,
// --- HIP / Memory ---
/// Allocates memory on the heap.
Alloc { type_id: TypeId, slots: u32 },
/// Reads from heap at gate + offset. Pops gate, pushes value.
GateLoad { offset: u32 },
/// Writes to heap at gate + offset. Pops gate and value.
GateStore { offset: u32 },
// --- Scope Markers ---
GateBeginPeek,
GateEndPeek,
GateBeginBorrow,
GateEndBorrow,
GateBeginMutate,
GateEndMutate,
// --- Reference Counting ---
/// Increments the reference count of a gate handle on the stack.
/// Stack: [..., Gate(g)] -> [..., Gate(g)]
GateRetain,
/// Decrements the reference count of a gate handle and pops it from the stack.
/// Stack: [..., Gate(g)] -> [...]
GateRelease,
}
/// List of instructions that are sensitive to Reference Counting (RC).
/// These instructions must trigger retain/release operations on gate handles.
pub const RC_SENSITIVE_OPS: &[&str] = &[
"LocalStore",
"GateStore",
"GateLoad",
"Pop",
"Ret",
"FrameSync",
];
#[cfg(test)]
mod tests {
use super::*;
use crate::ir_vm::types::{ConstId, TypeId};
#[test]
fn test_instr_kind_is_cloneable() {
let instr = InstrKind::Alloc { type_id: TypeId(1), slots: 2 };
let cloned = instr.clone();
match cloned {
InstrKind::Alloc { type_id, slots } => {
assert_eq!(type_id, TypeId(1));
assert_eq!(slots, 2);
}
_ => panic!("Clone failed"),
}
}
#[test]
fn test_isa_surface_snapshot() {
// This test ensures that the instruction set surface remains stable.
// If you add/remove/change instructions, this test will fail,
// prompting an explicit review of the ISA change.
let instructions = vec![
InstrKind::Nop,
InstrKind::Halt,
InstrKind::PushConst(ConstId(0)),
InstrKind::PushBounded(0),
InstrKind::PushBool(true),
InstrKind::PushNull,
InstrKind::Pop,
InstrKind::Dup,
InstrKind::Swap,
InstrKind::Add,
InstrKind::Sub,
InstrKind::Mul,
InstrKind::Div,
InstrKind::Neg,
InstrKind::Eq,
InstrKind::Neq,
InstrKind::Lt,
InstrKind::Gt,
InstrKind::Lte,
InstrKind::Gte,
InstrKind::And,
InstrKind::Or,
InstrKind::Not,
InstrKind::BitAnd,
InstrKind::BitOr,
InstrKind::BitXor,
InstrKind::Shl,
InstrKind::Shr,
InstrKind::LocalLoad { slot: 0 },
InstrKind::LocalStore { slot: 0 },
InstrKind::GetGlobal(0),
InstrKind::SetGlobal(0),
InstrKind::Jmp(Label("target".to_string())),
InstrKind::JmpIfFalse(Label("target".to_string())),
InstrKind::Label(Label("target".to_string())),
InstrKind::Call { func_id: FunctionId(0), arg_count: 0 },
InstrKind::ImportCall {
dep_alias: "std".to_string(),
module_path: "math".to_string(),
symbol_name: "abs".to_string(),
arg_count: 1,
},
InstrKind::Ret,
InstrKind::Syscall(0),
InstrKind::FrameSync,
InstrKind::Alloc { type_id: TypeId(0), slots: 0 },
InstrKind::GateLoad { offset: 0 },
InstrKind::GateStore { offset: 0 },
InstrKind::GateBeginPeek,
InstrKind::GateEndPeek,
InstrKind::GateBeginBorrow,
InstrKind::GateEndBorrow,
InstrKind::GateBeginMutate,
InstrKind::GateEndMutate,
InstrKind::GateRetain,
InstrKind::GateRelease,
];
let serialized = serde_json::to_string_pretty(&instructions).unwrap();
// This is a "lock" on the ISA surface.
// If the structure of InstrKind changes, the serialization will change.
let expected_json = r#"[
"Nop",
"Halt",
{
"PushConst": 0
},
{
"PushBounded": 0
},
{
"PushBool": true
},
"PushNull",
"Pop",
"Dup",
"Swap",
"Add",
"Sub",
"Mul",
"Div",
"Neg",
"Eq",
"Neq",
"Lt",
"Gt",
"Lte",
"Gte",
"And",
"Or",
"Not",
"BitAnd",
"BitOr",
"BitXor",
"Shl",
"Shr",
{
"LocalLoad": {
"slot": 0
}
},
{
"LocalStore": {
"slot": 0
}
},
{
"GetGlobal": 0
},
{
"SetGlobal": 0
},
{
"Jmp": "target"
},
{
"JmpIfFalse": "target"
},
{
"Label": "target"
},
{
"Call": {
"func_id": 0,
"arg_count": 0
}
},
{
"ImportCall": {
"dep_alias": "std",
"module_path": "math",
"symbol_name": "abs",
"arg_count": 1
}
},
"Ret",
{
"Syscall": 0
},
"FrameSync",
{
"Alloc": {
"type_id": 0,
"slots": 0
}
},
{
"GateLoad": {
"offset": 0
}
},
{
"GateStore": {
"offset": 0
}
},
"GateBeginPeek",
"GateEndPeek",
"GateBeginBorrow",
"GateEndBorrow",
"GateBeginMutate",
"GateEndMutate",
"GateRetain",
"GateRelease"
]"#;
assert_eq!(serialized, expected_json);
}
#[test]
fn test_no_ref_leakage_in_instr_names() {
// Enforce the rule that "Ref" must never refer to HIP memory in ir_vm.
// The snapshot test above already locks the names, but this test
// explicitly asserts the absence of the "Ref" substring in HIP-related instructions.
let instructions = [
"GateLoad", "GateStore", "Alloc",
"GateBeginPeek", "GateEndPeek",
"GateBeginBorrow", "GateEndBorrow",
"GateBeginMutate", "GateEndMutate",
"GateRetain", "GateRelease"
];
for name in instructions {
assert!(!name.contains("Ref"), "Instruction {} contains forbidden 'Ref' terminology", name);
}
}
#[test]
fn test_rc_sensitive_list_exists() {
// Required by PR-06: Documentation test or unit assertion that the RC-sensitive list exists
assert!(!RC_SENSITIVE_OPS.is_empty(), "RC-sensitive instructions list must not be empty");
let expected = ["LocalStore", "GateStore", "GateLoad", "Pop", "Ret", "FrameSync"];
for op in expected {
assert!(RC_SENSITIVE_OPS.contains(&op), "RC-sensitive list must contain {}", op);
}
}
}
+172
View File
@@ -0,0 +1,172 @@
//! # VM Intermediate Representation (ir_vm)
//!
//! This module defines the Intermediate Representation for the Prometeu VM.
//!
//! ## Memory Model
//!
//! * Heap is never directly addressable.
//! * All HIP (Heap) access is mediated via Gate Pool resolution.
//! * `Gate(GateId)` is the only HIP pointer form in `ir_vm`.
//!
//! ## Reference Counting (RC)
//!
//! The VM uses Reference Counting to manage HIP memory.
//!
//! ### RC Rules:
//! * **Retain**: Increment `strong_rc` when a gate handle is copied.
//! * **Release**: Decrement `strong_rc` when a gate handle is overwritten or dropped.
//!
//! ### RC-Sensitive Instructions:
//! The following instructions are RC-sensitive and must trigger RC updates:
//! * `LocalStore`: Release old value, retain new value.
//! * `GateStore`: Release old value, retain new value.
//! * `Pop`: Release the popped value.
//! * `Ret`: Release all live locals in the frame.
//! * `FrameSync`: Safe point; reclamation occurs after this point.
pub mod types;
pub mod module;
pub mod instr;
pub mod validate;
pub use instr::{InstrKind, Instruction, Label};
pub use module::{Function, Global, Module, Param};
pub use types::{ConstId, GateId, Type, TypeId, Value};
#[cfg(test)]
mod tests {
use super::*;
use crate::ir_core::const_pool::{ConstPool, ConstantValue};
use crate::ir_core::ids::{ConstId, FunctionId};
use serde_json;
#[test]
fn test_vm_ir_serialization() {
let mut const_pool = ConstPool::new();
const_pool.insert(ConstantValue::String("Hello VM".to_string()));
let module = Module {
name: "test_module".to_string(),
const_pool,
functions: vec![Function {
id: FunctionId(1),
name: "main".to_string(),
param_slots: 0,
local_slots: 0,
return_slots: 0,
params: vec![],
return_type: Type::Null,
body: vec![
Instruction::new(InstrKind::PushConst(crate::ir_vm::types::ConstId(0)), None),
Instruction::new(InstrKind::Call { func_id: FunctionId(2), arg_count: 1 }, None),
Instruction::new(InstrKind::Ret, None),
],
}],
globals: vec![],
};
let json = serde_json::to_string_pretty(&module).unwrap();
let expected = r#"{
"name": "test_module",
"const_pool": {
"constants": [
{
"String": "Hello VM"
}
]
},
"functions": [
{
"id": 1,
"name": "main",
"params": [],
"return_type": "Null",
"body": [
{
"kind": {
"PushConst": 0
},
"span": null
},
{
"kind": {
"Call": {
"func_id": 2,
"arg_count": 1
}
},
"span": null
},
{
"kind": "Ret",
"span": null
}
],
"param_slots": 0,
"local_slots": 0,
"return_slots": 0
}
],
"globals": []
}"#;
assert_eq!(json, expected);
}
#[test]
fn test_lowering_smoke() {
use crate::ir_core;
use crate::lowering::lower_program;
let mut const_pool = ir_core::ConstPool::new();
const_pool.insert(ir_core::ConstantValue::Int(42));
let program = ir_core::Program {
const_pool,
modules: vec![ir_core::Module {
name: "test_core".to_string(),
functions: vec![ir_core::Function {
id: FunctionId(10),
name: "start".to_string(),
param_slots: 0,
local_slots: 0,
return_slots: 0,
params: vec![],
return_type: ir_core::Type::Void,
blocks: vec![ir_core::Block {
id: 0,
instrs: vec![
ir_core::Instr::from(ir_core::InstrKind::PushConst(ConstId(0))),
],
terminator: ir_core::Terminator::Return,
}],
local_types: std::collections::HashMap::new(),
}],
}],
field_offsets: std::collections::HashMap::new(),
field_types: std::collections::HashMap::new(),
};
let vm_module = lower_program(&program).expect("Lowering failed");
assert_eq!(vm_module.name, "test_core");
assert_eq!(vm_module.functions.len(), 1);
let func = &vm_module.functions[0];
assert_eq!(func.name, "start");
assert_eq!(func.id, FunctionId(10));
assert_eq!(func.body.len(), 3);
match &func.body[0].kind {
InstrKind::Label(Label(l)) => assert!(l.contains("block_0")),
_ => panic!("Expected label"),
}
match &func.body[1].kind {
InstrKind::PushConst(id) => assert_eq!(id.0, 0),
_ => panic!("Expected PushConst"),
}
match &func.body[2].kind {
InstrKind::Ret => (),
_ => panic!("Expected Ret"),
}
}
}
@@ -0,0 +1,79 @@
//! # IR Module Structure
//!
//! This module defines the structure of the Intermediate Representation (IR).
//! The IR is a higher-level representation of the program than bytecode, but lower
//! than the source code AST. It is organized into Modules, Functions, and Globals.
use crate::ir_core::const_pool::ConstPool;
use crate::ir_core::ids::FunctionId;
use crate::ir_vm::instr::Instruction;
use crate::ir_vm::types::Type;
use serde::{Deserialize, Serialize};
/// A `Module` is the top-level container for a compiled program or library.
/// It contains a collection of global variables, functions, and a constant pool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Module {
/// The name of the module (usually derived from the project name).
pub name: String,
/// Shared constant pool for this module.
pub const_pool: ConstPool,
/// List of all functions defined in this module.
pub functions: Vec<Function>,
/// List of all global variables available in this module.
pub globals: Vec<Global>,
}
/// Represents a function in the IR.
///
/// Functions consist of a signature (name, parameters, return type) and a body
/// which is a flat list of IR instructions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Function {
/// The unique identifier of the function.
pub id: FunctionId,
/// The unique name of the function.
pub name: String,
/// The list of input parameters.
pub params: Vec<Param>,
/// The type of value this function returns.
pub return_type: Type,
/// The sequence of instructions that make up the function's logic.
pub body: Vec<Instruction>,
pub param_slots: u16,
pub local_slots: u16,
pub return_slots: u16,
}
/// A parameter passed to a function.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Param {
/// The name of the parameter (useful for debugging and symbols).
pub name: String,
/// The data type of the parameter.
pub r#type: Type,
}
/// A global variable accessible by any function in the module.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Global {
/// The name of the global variable.
pub name: String,
/// The data type of the variable.
pub r#type: Type,
/// The unique memory slot index assigned to this global variable.
pub slot: u32,
}
impl Module {
/// Creates a new, empty module with the given name.
pub fn new(name: String) -> Self {
Self {
name,
const_pool: ConstPool::new(),
functions: Vec::new(),
globals: Vec::new(),
}
}
}
@@ -0,0 +1,88 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct GateId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ConstId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct TypeId(pub u32);
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Value {
Int(i64),
Float(f64),
Bounded(u32),
Bool(bool),
Unit,
Const(ConstId),
Gate(GateId),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Type {
Any,
Null,
Bool,
Int,
Bounded,
Float,
String,
Color,
Array(Box<Type>),
Object,
Function,
Void,
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
#[test]
fn test_ids_implement_required_traits() {
fn assert_copy<T: Copy>() {}
fn assert_eq_hash<T: Eq + std::hash::Hash>() {}
assert_copy::<GateId>();
assert_eq_hash::<GateId>();
assert_copy::<ConstId>();
assert_eq_hash::<ConstId>();
assert_copy::<TypeId>();
assert_eq_hash::<TypeId>();
}
#[test]
fn test_gate_id_usage() {
let id1 = GateId(1);
let id2 = GateId(1);
let id3 = GateId(2);
assert_eq!(id1, id2);
assert_ne!(id1, id3);
let mut set = HashSet::new();
set.insert(id1);
assert!(set.contains(&id2));
}
#[test]
fn test_value_gate_exists_and_is_clonable() {
let gate_id = GateId(42);
let val = Value::Gate(gate_id);
let cloned_val = val.clone();
if let Value::Gate(id) = cloned_val {
assert_eq!(id, gate_id);
} else {
panic!("Expected Value::Gate");
}
}
}
@@ -0,0 +1,10 @@
use crate::common::diagnostics::DiagnosticBundle;
use crate::ir_vm::module::Module;
pub fn validate_module(_module: &Module) -> Result<(), DiagnosticBundle> {
// TODO: Implement common IR validations:
// - Type checking rules
// - HostCall signatures
// - VM invariants
Ok(())
}