change ir to ir_vm and make it feature frozen
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
//! # 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::{ConstId, FunctionId};
|
||||
|
||||
/// 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, 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 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.
|
||||
GetLocal(u32),
|
||||
/// Pops a value from the stack and stores it in a local variable slot.
|
||||
SetLocal(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 },
|
||||
/// 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. Pops size from stack.
|
||||
Alloc,
|
||||
/// Reads from heap at reference + offset. Pops reference, pushes value.
|
||||
LoadRef(u32),
|
||||
/// Writes to heap at reference + offset. Pops reference and value.
|
||||
StoreRef(u32),
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
pub mod types;
|
||||
pub mod module;
|
||||
pub mod instr;
|
||||
pub mod validate;
|
||||
|
||||
pub use instr::{Instruction, InstrKind, Label};
|
||||
pub use module::{Module, Function, Global, Param};
|
||||
pub use types::Type;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ir_core::ids::{ConstId, FunctionId};
|
||||
use crate::ir_core::const_pool::{ConstPool, ConstantValue};
|
||||
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(),
|
||||
params: vec![],
|
||||
return_type: Type::Null,
|
||||
body: vec![
|
||||
Instruction::new(InstrKind::PushConst(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
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"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(),
|
||||
params: vec![],
|
||||
return_type: ir_core::Type::Void,
|
||||
blocks: vec![ir_core::Block {
|
||||
id: 0,
|
||||
instrs: vec![
|
||||
ir_core::Instr::PushConst(ConstId(0)),
|
||||
],
|
||||
terminator: ir_core::Terminator::Return,
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
};
|
||||
|
||||
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,75 @@
|
||||
//! # 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_vm::instr::Instruction;
|
||||
use crate::ir_vm::types::Type;
|
||||
use crate::ir_core::const_pool::ConstPool;
|
||||
use crate::ir_core::ids::FunctionId;
|
||||
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>,
|
||||
}
|
||||
|
||||
/// 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,16 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Type {
|
||||
Any,
|
||||
Null,
|
||||
Bool,
|
||||
Int,
|
||||
Float,
|
||||
String,
|
||||
Color,
|
||||
Array(Box<Type>),
|
||||
Object,
|
||||
Function,
|
||||
Void,
|
||||
}
|
||||
@@ -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
|
||||
// - Syscall signatures
|
||||
// - VM invariants
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user