This commit is contained in:
Nilton Constantino
2026-01-27 13:51:12 +00:00
parent 8240785160
commit 4bd3484c85
9 changed files with 185 additions and 67 deletions
@@ -0,0 +1,85 @@
use crate::ir;
use crate::ir_core;
use anyhow::Result;
/// Lowers a Core IR program into a VM IR module.
pub fn lower_program(program: &ir_core::Program) -> Result<ir::Module> {
// For now, we assume a single module program or lower the first one.
// In the future, we might want to lower all modules and link them.
if let Some(core_module) = program.modules.first() {
lower_module(core_module, &program.const_pool)
} else {
anyhow::bail!("No modules in core program")
}
}
/// Lowers a single Core IR module into a VM IR module.
pub fn lower_module(core_module: &ir_core::Module, const_pool: &ir_core::ConstPool) -> Result<ir::Module> {
let mut vm_module = ir::Module::new(core_module.name.clone());
vm_module.const_pool = const_pool.clone();
for core_func in &core_module.functions {
vm_module.functions.push(lower_function(core_func)?);
}
Ok(vm_module)
}
/// Lowers a Core IR function into a VM IR function.
pub fn lower_function(core_func: &ir_core::Function) -> Result<ir::Function> {
let mut vm_func = ir::Function {
id: core_func.id,
name: core_func.name.clone(),
params: vec![], // Params are not yet represented in Core IR Function
return_type: ir::Type::Null, // Return type is not yet represented in Core IR Function
body: vec![],
};
for block in &core_func.blocks {
// Core blocks map to labels in the flat VM IR instruction list.
vm_func.body.push(ir::Instruction::new(
ir::InstrKind::Label(ir::Label(format!("block_{}", block.id))),
None,
));
for instr in &block.instrs {
match instr {
ir_core::Instr::PushConst(id) => {
vm_func.body.push(ir::Instruction::new(
ir::InstrKind::PushConst(*id),
None,
));
}
ir_core::Instr::Call(func_id, arg_count) => {
vm_func.body.push(ir::Instruction::new(
ir::InstrKind::Call {
func_id: *func_id,
arg_count: *arg_count
},
None,
));
}
ir_core::Instr::Syscall(id) => {
vm_func.body.push(ir::Instruction::new(
ir::InstrKind::Syscall(*id),
None,
));
}
}
}
match &block.terminator {
ir_core::Terminator::Return => {
vm_func.body.push(ir::Instruction::new(ir::InstrKind::Ret, None));
}
ir_core::Terminator::Jump(target) => {
vm_func.body.push(ir::Instruction::new(
ir::InstrKind::Jmp(ir::Label(format!("block_{}", target))),
None,
));
}
}
}
Ok(vm_func)
}
@@ -0,0 +1,3 @@
pub mod core_to_vm;
pub use core_to_vm::lower_program;