pr 50
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
use crate::common::symbols::Symbol;
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use anyhow::{Context, Result};
|
||||
use prometeu_bytecode::disasm::disasm;
|
||||
use prometeu_bytecode::v0::BytecodeLoader;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
@@ -29,14 +30,14 @@ impl Artifacts {
|
||||
if emit_disasm {
|
||||
let disasm_path = out.with_extension("disasm.txt");
|
||||
|
||||
// Extract the actual bytecode (stripping the PBC header if present)
|
||||
let rom_to_disasm = if let Ok(pbc) = prometeu_bytecode::pbc::parse_pbc(&self.rom) {
|
||||
pbc.rom
|
||||
// Extract the actual bytecode (stripping the industrial PBS\0 header)
|
||||
let rom_to_disasm = if let Ok(module) = BytecodeLoader::load(&self.rom) {
|
||||
module.code
|
||||
} else {
|
||||
self.rom.clone()
|
||||
};
|
||||
|
||||
let instructions = disasm(&rom_to_disasm).map_err(|e| anyhow!("Disassembly failed: {}", e))?;
|
||||
let instructions = disasm(&rom_to_disasm).map_err(|e| anyhow::anyhow!("Disassembly failed: {}", e))?;
|
||||
|
||||
let mut disasm_text = String::new();
|
||||
for instr in instructions {
|
||||
|
||||
@@ -15,7 +15,8 @@ use crate::ir_core::ConstantValue;
|
||||
use anyhow::{anyhow, Result};
|
||||
use prometeu_bytecode::asm::{assemble, update_pc_by_operand, Asm, Operand};
|
||||
use prometeu_bytecode::opcode::OpCode;
|
||||
use prometeu_bytecode::pbc::{write_pbc, ConstantPoolEntry, PbcFile};
|
||||
use prometeu_bytecode::v0::{BytecodeModule, FunctionMeta, DebugInfo, ConstantPoolEntry};
|
||||
use prometeu_bytecode::abi::SourceSpan;
|
||||
|
||||
/// The final output of the code generation phase.
|
||||
pub struct EmitResult {
|
||||
@@ -68,34 +69,30 @@ impl<'a> BytecodeEmitter<'a> {
|
||||
self.add_constant(entry)
|
||||
}
|
||||
|
||||
/// Transforms an IR module into a binary PBC file.
|
||||
fn emit(&mut self, module: &ir_vm::Module) -> Result<EmitResult> {
|
||||
let mut asm_instrs = Vec::new();
|
||||
let mut ir_instr_map = Vec::new(); // Maps Asm index to IR instruction (for symbols)
|
||||
|
||||
// Pre-populate constant pool from IR and create a mapping for ConstIds
|
||||
let mut mapped_const_ids = Vec::with_capacity(module.const_pool.constants.len());
|
||||
for val in &module.const_pool.constants {
|
||||
mapped_const_ids.push(self.add_ir_constant(val));
|
||||
}
|
||||
|
||||
// Map FunctionIds to names for call resolution
|
||||
fn lower_instrs<'b>(
|
||||
&mut self,
|
||||
module: &'b ir_vm::Module,
|
||||
asm_instrs: &mut Vec<Asm>,
|
||||
ir_instr_map: &mut Vec<Option<&'b ir_vm::Instruction>>,
|
||||
mapped_const_ids: &[u32]
|
||||
) -> Result<Vec<(usize, usize)>> {
|
||||
let mut func_names = std::collections::HashMap::new();
|
||||
for func in &module.functions {
|
||||
func_names.insert(func.id, func.name.clone());
|
||||
}
|
||||
|
||||
// --- PHASE 1: Lowering IR to Assembly-like structures ---
|
||||
let mut ranges = Vec::new();
|
||||
|
||||
for function in &module.functions {
|
||||
let start_idx = asm_instrs.len();
|
||||
// Each function starts with a label for its entry point.
|
||||
asm_instrs.push(Asm::Label(function.name.clone()));
|
||||
ir_instr_map.push(None);
|
||||
|
||||
for instr in &function.body {
|
||||
let start_idx = asm_instrs.len();
|
||||
let op_start_idx = asm_instrs.len();
|
||||
|
||||
// Translate each IR instruction to its equivalent Bytecode OpCode.
|
||||
// Note: IR instructions are high-level, while Bytecode is low-level.
|
||||
match &instr.kind {
|
||||
InstrKind::Nop => asm_instrs.push(Asm::Op(OpCode::Nop, vec![])),
|
||||
InstrKind::Halt => asm_instrs.push(Asm::Op(OpCode::Halt, vec![])),
|
||||
@@ -147,17 +144,17 @@ impl<'a> BytecodeEmitter<'a> {
|
||||
asm_instrs.push(Asm::Op(OpCode::SetGlobal, vec![Operand::U32(*slot)]));
|
||||
}
|
||||
InstrKind::Jmp(label) => {
|
||||
asm_instrs.push(Asm::Op(OpCode::Jmp, vec![Operand::Label(label.0.clone())]));
|
||||
asm_instrs.push(Asm::Op(OpCode::Jmp, vec![Operand::RelLabel(label.0.clone(), function.name.clone())]));
|
||||
}
|
||||
InstrKind::JmpIfFalse(label) => {
|
||||
asm_instrs.push(Asm::Op(OpCode::JmpIfFalse, vec![Operand::Label(label.0.clone())]));
|
||||
asm_instrs.push(Asm::Op(OpCode::JmpIfFalse, vec![Operand::RelLabel(label.0.clone(), function.name.clone())]));
|
||||
}
|
||||
InstrKind::Label(label) => {
|
||||
asm_instrs.push(Asm::Label(label.0.clone()));
|
||||
}
|
||||
InstrKind::Call { func_id, arg_count } => {
|
||||
InstrKind::Call { func_id, .. } => {
|
||||
let name = func_names.get(func_id).ok_or_else(|| anyhow!("Undefined function ID: {:?}", func_id))?;
|
||||
asm_instrs.push(Asm::Op(OpCode::Call, vec![Operand::Label(name.clone()), Operand::U32(*arg_count)]));
|
||||
asm_instrs.push(Asm::Op(OpCode::Call, vec![Operand::Label(name.clone())]));
|
||||
}
|
||||
InstrKind::Ret => asm_instrs.push(Asm::Op(OpCode::Ret, vec![])),
|
||||
InstrKind::Syscall(id) => {
|
||||
@@ -183,24 +180,75 @@ impl<'a> BytecodeEmitter<'a> {
|
||||
InstrKind::GateRelease => asm_instrs.push(Asm::Op(OpCode::GateRelease, vec![])),
|
||||
}
|
||||
|
||||
let end_idx = asm_instrs.len();
|
||||
for _ in start_idx..end_idx {
|
||||
let op_end_idx = asm_instrs.len();
|
||||
for _ in op_start_idx..op_end_idx {
|
||||
ir_instr_map.push(Some(instr));
|
||||
}
|
||||
}
|
||||
let end_idx = asm_instrs.len();
|
||||
ranges.push((start_idx, end_idx));
|
||||
}
|
||||
Ok(ranges)
|
||||
}
|
||||
|
||||
fn calculate_pcs(asm_instrs: &[Asm]) -> Vec<u32> {
|
||||
let mut pcs = Vec::with_capacity(asm_instrs.len());
|
||||
let mut current_pc = 0u32;
|
||||
for instr in asm_instrs {
|
||||
pcs.push(current_pc);
|
||||
match instr {
|
||||
Asm::Label(_) => {}
|
||||
Asm::Op(_opcode, operands) => {
|
||||
current_pc += 2;
|
||||
current_pc = update_pc_by_operand(current_pc, operands);
|
||||
}
|
||||
}
|
||||
}
|
||||
pcs
|
||||
}
|
||||
|
||||
/// Transforms an IR module into a binary PBC file (v0 industrial format).
|
||||
pub fn emit(&mut self, module: &ir_vm::Module) -> Result<EmitResult> {
|
||||
let mut mapped_const_ids = Vec::with_capacity(module.const_pool.constants.len());
|
||||
for val in &module.const_pool.constants {
|
||||
mapped_const_ids.push(self.add_ir_constant(val));
|
||||
}
|
||||
|
||||
// --- PHASE 2: Assembly (Label Resolution) ---
|
||||
// Converts the list of Ops and Labels into raw bytes, calculating jump offsets.
|
||||
let mut asm_instrs = Vec::new();
|
||||
let mut ir_instr_map = Vec::new();
|
||||
let function_ranges = self.lower_instrs(module, &mut asm_instrs, &mut ir_instr_map, &mapped_const_ids)?;
|
||||
|
||||
let pcs = Self::calculate_pcs(&asm_instrs);
|
||||
let bytecode = assemble(&asm_instrs).map_err(|e| anyhow!(e))?;
|
||||
|
||||
// --- PHASE 3: Symbol Generation ---
|
||||
// Associates each bytecode offset with a line/column in the source file.
|
||||
|
||||
let mut functions = Vec::new();
|
||||
for (i, function) in module.functions.iter().enumerate() {
|
||||
let (start_idx, end_idx) = function_ranges[i];
|
||||
let start_pc = pcs[start_idx];
|
||||
let end_pc = if end_idx < pcs.len() { pcs[end_idx] } else { bytecode.len() as u32 };
|
||||
|
||||
functions.push(FunctionMeta {
|
||||
code_offset: start_pc,
|
||||
code_len: end_pc - start_pc,
|
||||
param_slots: function.param_slots,
|
||||
local_slots: function.local_slots,
|
||||
return_slots: function.return_slots,
|
||||
max_stack_slots: 0, // Will be filled by verifier
|
||||
});
|
||||
}
|
||||
|
||||
let mut pc_to_span = Vec::new();
|
||||
let mut symbols = Vec::new();
|
||||
let mut current_pc = 0u32;
|
||||
for (i, asm) in asm_instrs.iter().enumerate() {
|
||||
if let Some(ir_instr) = ir_instr_map[i] {
|
||||
if let Some(span) = ir_instr.span {
|
||||
for (i, instr_opt) in ir_instr_map.iter().enumerate() {
|
||||
let current_pc = pcs[i];
|
||||
if let Some(instr) = instr_opt {
|
||||
if let Some(span) = &instr.span {
|
||||
pc_to_span.push((current_pc, SourceSpan {
|
||||
file_id: span.file_id as u32,
|
||||
start: span.start,
|
||||
end: span.end,
|
||||
}));
|
||||
|
||||
let (line, col) = self.file_manager.lookup_pos(span.file_id, span.start);
|
||||
let file_path = self.file_manager.get_path(span.file_id)
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
@@ -214,30 +262,35 @@ impl<'a> BytecodeEmitter<'a> {
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
pc_to_span.sort_by_key(|(pc, _)| *pc);
|
||||
pc_to_span.dedup_by_key(|(pc, _)| *pc);
|
||||
|
||||
// Track the Program Counter (PC) as we iterate through instructions.
|
||||
match asm {
|
||||
Asm::Label(_) => {}
|
||||
Asm::Op(_opcode, operands) => {
|
||||
// Each OpCode takes 2 bytes (1 for opcode, 1 for padding/metadata)
|
||||
current_pc += 2;
|
||||
// Operands take additional space depending on their type.
|
||||
current_pc = update_pc_by_operand(current_pc, operands);
|
||||
}
|
||||
}
|
||||
let mut exports = Vec::new();
|
||||
let mut function_names = Vec::new();
|
||||
for (i, func) in module.functions.iter().enumerate() {
|
||||
exports.push(prometeu_bytecode::v0::Export {
|
||||
symbol: func.name.clone(),
|
||||
func_idx: i as u32,
|
||||
});
|
||||
function_names.push((i as u32, func.name.clone()));
|
||||
}
|
||||
|
||||
// --- PHASE 4: Serialization ---
|
||||
// Packages the constant pool and bytecode into the final PBC format.
|
||||
let pbc = PbcFile {
|
||||
let bytecode_module = BytecodeModule {
|
||||
version: 0,
|
||||
cp: self.constant_pool.clone(),
|
||||
rom: bytecode,
|
||||
const_pool: self.constant_pool.clone(),
|
||||
functions,
|
||||
code: bytecode,
|
||||
debug_info: Some(DebugInfo {
|
||||
pc_to_span,
|
||||
function_names,
|
||||
}),
|
||||
exports,
|
||||
imports: vec![],
|
||||
};
|
||||
|
||||
let out = write_pbc(&pbc).map_err(|e| anyhow!(e))?;
|
||||
Ok(EmitResult {
|
||||
rom: out,
|
||||
rom: bytecode_module.serialize(),
|
||||
symbols,
|
||||
})
|
||||
}
|
||||
@@ -252,7 +305,7 @@ mod tests {
|
||||
use crate::ir_core::ids::FunctionId;
|
||||
use crate::ir_core::const_pool::ConstantValue;
|
||||
use crate::common::files::FileManager;
|
||||
use prometeu_bytecode::pbc::{parse_pbc, ConstantPoolEntry};
|
||||
use prometeu_bytecode::v0::{BytecodeLoader, ConstantPoolEntry};
|
||||
|
||||
#[test]
|
||||
fn test_emit_module_with_const_pool() {
|
||||
@@ -271,6 +324,9 @@ mod tests {
|
||||
Instruction::new(InstrKind::PushConst(ir_vm::ConstId(id_str.0)), None),
|
||||
Instruction::new(InstrKind::Ret, None),
|
||||
],
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
};
|
||||
|
||||
module.functions.push(function);
|
||||
@@ -278,11 +334,11 @@ mod tests {
|
||||
let file_manager = FileManager::new();
|
||||
let result = emit_module(&module, &file_manager).expect("Failed to emit module");
|
||||
|
||||
let pbc = parse_pbc(&result.rom).expect("Failed to parse emitted PBC");
|
||||
let pbc = BytecodeLoader::load(&result.rom).expect("Failed to parse emitted PBC");
|
||||
|
||||
assert_eq!(pbc.cp.len(), 3);
|
||||
assert_eq!(pbc.cp[0], ConstantPoolEntry::Null);
|
||||
assert_eq!(pbc.cp[1], ConstantPoolEntry::Int64(12345));
|
||||
assert_eq!(pbc.cp[2], ConstantPoolEntry::String("hello".to_string()));
|
||||
assert_eq!(pbc.const_pool.len(), 3);
|
||||
assert_eq!(pbc.const_pool[0], ConstantPoolEntry::Null);
|
||||
assert_eq!(pbc.const_pool[1], ConstantPoolEntry::Int64(12345));
|
||||
assert_eq!(pbc.const_pool[2], ConstantPoolEntry::String("hello".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,3 +2,5 @@ pub mod emit_bytecode;
|
||||
pub mod artifacts;
|
||||
|
||||
pub use emit_bytecode::emit_module;
|
||||
pub use artifacts::Artifacts;
|
||||
pub use emit_bytecode::EmitResult;
|
||||
|
||||
@@ -106,7 +106,7 @@ mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use tempfile::tempdir;
|
||||
use prometeu_bytecode::pbc::parse_pbc;
|
||||
use prometeu_bytecode::v0::BytecodeLoader;
|
||||
use prometeu_bytecode::disasm::disasm;
|
||||
use prometeu_bytecode::opcode::OpCode;
|
||||
|
||||
@@ -152,8 +152,8 @@ mod tests {
|
||||
fs::write(project_dir.join("main.pbs"), code).unwrap();
|
||||
|
||||
let unit = compile(project_dir).expect("Failed to compile");
|
||||
let pbc = parse_pbc(&unit.rom).expect("Failed to parse PBC");
|
||||
let instrs = disasm(&pbc.rom).expect("Failed to disassemble");
|
||||
let pbc = BytecodeLoader::load(&unit.rom).expect("Failed to parse PBC");
|
||||
let instrs = disasm(&pbc.code).expect("Failed to disassemble");
|
||||
|
||||
let opcodes: Vec<_> = instrs.iter().map(|i| i.opcode).collect();
|
||||
|
||||
@@ -202,8 +202,8 @@ mod tests {
|
||||
fs::write(project_dir.join("main.pbs"), code).unwrap();
|
||||
|
||||
let unit = compile(project_dir).expect("Failed to compile");
|
||||
let pbc = parse_pbc(&unit.rom).expect("Failed to parse PBC");
|
||||
let instrs = disasm(&pbc.rom).expect("Failed to disassemble");
|
||||
let pbc = BytecodeLoader::load(&unit.rom).expect("Failed to parse PBC");
|
||||
let instrs = disasm(&pbc.code).expect("Failed to disassemble");
|
||||
|
||||
let mut disasm_text = String::new();
|
||||
for instr in instrs {
|
||||
@@ -230,37 +230,36 @@ mod tests {
|
||||
0028 GetLocal U32(0)
|
||||
002E PushConst U32(4)
|
||||
0034 Gt
|
||||
0036 JmpIfFalse U32(94)
|
||||
003C Jmp U32(66)
|
||||
0036 JmpIfFalse U32(74)
|
||||
003C Jmp U32(50)
|
||||
0042 GetLocal U32(0)
|
||||
0048 Call U32(0) U32(1)
|
||||
0052 SetLocal U32(1)
|
||||
0058 Jmp U32(100)
|
||||
005E Jmp U32(100)
|
||||
0064 Alloc U32(2) U32(1)
|
||||
006E SetLocal U32(1)
|
||||
0074 GetLocal U32(1)
|
||||
007A GateRetain
|
||||
007C SetLocal U32(2)
|
||||
0082 GetLocal U32(2)
|
||||
0088 GateRetain
|
||||
008A GateBeginMutate
|
||||
008C GetLocal U32(2)
|
||||
0092 GateRetain
|
||||
0094 GateLoad U32(0)
|
||||
009A SetLocal U32(3)
|
||||
00A0 GetLocal U32(3)
|
||||
00A6 PushConst U32(5)
|
||||
00AC Add
|
||||
00AE SetLocal U32(4)
|
||||
00B4 GateEndMutate
|
||||
00B6 GateRelease
|
||||
00B8 GetLocal U32(1)
|
||||
00BE GateRelease
|
||||
00C0 GetLocal U32(2)
|
||||
00C6 GateRelease
|
||||
00C8 PushConst U32(0)
|
||||
00CE Ret
|
||||
0048 Call U32(0)
|
||||
004E SetLocal U32(1)
|
||||
0054 Jmp U32(80)
|
||||
005A Jmp U32(80)
|
||||
0060 Alloc U32(2) U32(1)
|
||||
006A SetLocal U32(1)
|
||||
0070 GetLocal U32(1)
|
||||
0076 GateRetain
|
||||
0078 SetLocal U32(2)
|
||||
007E GetLocal U32(2)
|
||||
0084 GateRetain
|
||||
0086 GateBeginMutate
|
||||
0088 GetLocal U32(2)
|
||||
008E GateRetain
|
||||
0090 GateLoad U32(0)
|
||||
0096 SetLocal U32(3)
|
||||
009C GetLocal U32(3)
|
||||
00A2 PushConst U32(5)
|
||||
00A8 Add
|
||||
00AA SetLocal U32(4)
|
||||
00B0 GateEndMutate
|
||||
00B2 GateRelease
|
||||
00B4 GetLocal U32(1)
|
||||
00BA GateRelease
|
||||
00BC GetLocal U32(2)
|
||||
00C2 GateRelease
|
||||
00C4 Ret
|
||||
"#;
|
||||
|
||||
assert_eq!(disasm_text, expected_disasm);
|
||||
@@ -269,7 +268,6 @@ mod tests {
|
||||
#[test]
|
||||
fn test_hip_conformance_v0() {
|
||||
use crate::ir_core::*;
|
||||
use crate::ir_core::ids::*;
|
||||
use crate::lowering::lower_program;
|
||||
use crate::backend;
|
||||
use std::collections::HashMap;
|
||||
@@ -294,6 +292,9 @@ mod tests {
|
||||
functions: vec![Function {
|
||||
id: FunctionId(1),
|
||||
name: "main".to_string(),
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
params: vec![],
|
||||
return_type: Type::Void,
|
||||
blocks: vec![Block {
|
||||
@@ -351,23 +352,22 @@ mod tests {
|
||||
|
||||
let rom = emit_result.rom;
|
||||
|
||||
// --- 5. ASSERT GOLDEN BYTECODE (Exact Bytes) ---
|
||||
// Header: PPBC, Version: 0, Flags: 0
|
||||
assert_eq!(&rom[0..4], b"PPBC");
|
||||
assert_eq!(rom[4..6], [0, 0]); // Version 0
|
||||
assert_eq!(rom[6..8], [0, 0]); // Flags 0
|
||||
// --- 5. ASSERT INDUSTRIAL FORMAT ---
|
||||
use prometeu_bytecode::v0::BytecodeLoader;
|
||||
let pbc = BytecodeLoader::load(&rom).expect("Failed to parse industrial PBC");
|
||||
|
||||
// CP Count: 2 (Null, 42)
|
||||
assert_eq!(rom[8..12], [2, 0, 0, 0]);
|
||||
assert_eq!(&rom[0..4], b"PBS\0");
|
||||
assert_eq!(pbc.const_pool.len(), 2); // Null, 42
|
||||
|
||||
// ROM Data contains HIP opcodes:
|
||||
assert!(rom.contains(&0x60), "Bytecode must contain Alloc (0x60)");
|
||||
assert!(rom.contains(&0x67), "Bytecode must contain GateBeginMutate (0x67)");
|
||||
assert!(rom.contains(&0x62), "Bytecode must contain GateStore (0x62)");
|
||||
assert!(rom.contains(&0x63), "Bytecode must contain GateBeginPeek (0x63)");
|
||||
assert!(rom.contains(&0x61), "Bytecode must contain GateLoad (0x61)");
|
||||
assert!(rom.contains(&0x69), "Bytecode must contain GateRetain (0x69)");
|
||||
assert!(rom.contains(&0x6A), "Bytecode must contain GateRelease (0x6A)");
|
||||
let code = pbc.code;
|
||||
assert!(code.iter().any(|&b| b == 0x60), "Bytecode must contain Alloc (0x60)");
|
||||
assert!(code.iter().any(|&b| b == 0x67), "Bytecode must contain GateBeginMutate (0x67)");
|
||||
assert!(code.iter().any(|&b| b == 0x62), "Bytecode must contain GateStore (0x62)");
|
||||
assert!(code.iter().any(|&b| b == 0x63), "Bytecode must contain GateBeginPeek (0x63)");
|
||||
assert!(code.iter().any(|&b| b == 0x61), "Bytecode must contain GateLoad (0x61)");
|
||||
assert!(code.iter().any(|&b| b == 0x69), "Bytecode must contain GateRetain (0x69)");
|
||||
assert!(code.iter().any(|&b| b == 0x6A), "Bytecode must contain GateRelease (0x6A)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -30,6 +30,8 @@ pub enum Node {
|
||||
WhenArm(WhenArmNode),
|
||||
TypeName(TypeNameNode),
|
||||
TypeApp(TypeAppNode),
|
||||
ConstructorDecl(ConstructorDeclNode),
|
||||
ConstantDecl(ConstantDeclNode),
|
||||
Alloc(AllocNode),
|
||||
Mutate(MutateNode),
|
||||
Borrow(BorrowNode),
|
||||
@@ -98,13 +100,33 @@ pub struct TypeDeclNode {
|
||||
pub type_kind: String, // "struct" | "contract" | "error"
|
||||
pub name: String,
|
||||
pub is_host: bool,
|
||||
pub body: Box<Node>, // TypeBody
|
||||
pub params: Vec<ParamNode>, // fields for struct/error
|
||||
pub constructors: Vec<ConstructorDeclNode>, // [ ... ]
|
||||
pub constants: Vec<ConstantDeclNode>, // [[ ... ]]
|
||||
pub body: Option<Box<Node>>, // TypeBody (methods)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct ConstructorDeclNode {
|
||||
pub span: Span,
|
||||
pub params: Vec<ParamNode>,
|
||||
pub initializers: Vec<Node>,
|
||||
pub name: String,
|
||||
pub body: Box<Node>, // BlockNode
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct ConstantDeclNode {
|
||||
pub span: Span,
|
||||
pub name: String,
|
||||
pub value: Box<Node>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct TypeBodyNode {
|
||||
pub span: Span,
|
||||
pub members: Vec<TypeMemberNode>,
|
||||
pub methods: Vec<ServiceFnSigNode>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
|
||||
@@ -74,8 +74,22 @@ impl<'a> Lexer<'a> {
|
||||
')' => TokenKind::CloseParen,
|
||||
'{' => TokenKind::OpenBrace,
|
||||
'}' => TokenKind::CloseBrace,
|
||||
'[' => TokenKind::OpenBracket,
|
||||
']' => TokenKind::CloseBracket,
|
||||
'[' => {
|
||||
if self.peek() == Some('[') {
|
||||
self.next();
|
||||
TokenKind::OpenDoubleBracket
|
||||
} else {
|
||||
TokenKind::OpenBracket
|
||||
}
|
||||
}
|
||||
']' => {
|
||||
if self.peek() == Some(']') {
|
||||
self.next();
|
||||
TokenKind::CloseDoubleBracket
|
||||
} else {
|
||||
TokenKind::CloseBracket
|
||||
}
|
||||
}
|
||||
',' => TokenKind::Comma,
|
||||
'.' => TokenKind::Dot,
|
||||
':' => TokenKind::Colon,
|
||||
|
||||
@@ -26,8 +26,12 @@ pub struct Lowerer<'a> {
|
||||
function_ids: HashMap<String, FunctionId>,
|
||||
type_ids: HashMap<String, TypeId>,
|
||||
struct_slots: HashMap<String, u32>,
|
||||
struct_constructors: HashMap<String, HashMap<String, ConstructorDeclNode>>,
|
||||
type_constants: HashMap<String, HashMap<String, Node>>,
|
||||
current_type_context: Option<String>,
|
||||
contract_registry: ContractRegistry,
|
||||
diagnostics: Vec<Diagnostic>,
|
||||
max_slots_used: u32,
|
||||
}
|
||||
|
||||
impl<'a> Lowerer<'a> {
|
||||
@@ -58,8 +62,12 @@ impl<'a> Lowerer<'a> {
|
||||
function_ids: HashMap::new(),
|
||||
type_ids: HashMap::new(),
|
||||
struct_slots,
|
||||
struct_constructors: HashMap::new(),
|
||||
type_constants: HashMap::new(),
|
||||
current_type_context: None,
|
||||
contract_registry: ContractRegistry::new(),
|
||||
diagnostics: Vec::new(),
|
||||
max_slots_used: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,15 +92,92 @@ impl<'a> Lowerer<'a> {
|
||||
let id = TypeId(self.next_type_id);
|
||||
self.next_type_id += 1;
|
||||
self.type_ids.insert(n.name.clone(), id);
|
||||
}
|
||||
}
|
||||
|
||||
// Second pre-scan: calculate struct slots (recursive)
|
||||
let mut struct_nodes = HashMap::new();
|
||||
for decl in &file.decls {
|
||||
if let Node::TypeDecl(n) = decl {
|
||||
if n.type_kind == "struct" {
|
||||
if let Node::TypeBody(body) = &*n.body {
|
||||
self.struct_slots.insert(n.name.clone(), body.members.len() as u32);
|
||||
struct_nodes.insert(n.name.clone(), n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut changed = true;
|
||||
while changed {
|
||||
changed = false;
|
||||
for (name, node) in &struct_nodes {
|
||||
if !self.struct_slots.contains_key(name) {
|
||||
let mut slots = 0;
|
||||
let mut all_known = true;
|
||||
for param in &node.params {
|
||||
let member_ty = self.lower_type_node(¶m.ty);
|
||||
match &member_ty {
|
||||
Type::Struct(sname) => {
|
||||
if let Some(s_slots) = self.get_builtin_struct_slots(sname) {
|
||||
slots += s_slots;
|
||||
} else if let Some(s_slots) = self.struct_slots.get(sname) {
|
||||
slots += s_slots;
|
||||
} else {
|
||||
all_known = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => slots += self.get_type_slots(&member_ty),
|
||||
}
|
||||
}
|
||||
if all_known {
|
||||
self.struct_slots.insert(name.clone(), slots);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for decl in &file.decls {
|
||||
if let Node::TypeDecl(n) = decl {
|
||||
let mut constants = HashMap::new();
|
||||
for c in &n.constants {
|
||||
constants.insert(c.name.clone(), *c.value.clone());
|
||||
}
|
||||
self.type_constants.insert(n.name.clone(), constants);
|
||||
|
||||
let mut ctors = HashMap::new();
|
||||
|
||||
// Default constructor: TypeName(...)
|
||||
if n.type_kind == "struct" {
|
||||
let mut params = Vec::new();
|
||||
let mut initializers = Vec::new();
|
||||
for p in &n.params {
|
||||
params.push(p.clone());
|
||||
initializers.push(Node::Ident(IdentNode {
|
||||
span: p.span,
|
||||
name: p.name.clone(),
|
||||
}));
|
||||
}
|
||||
let default_ctor = ConstructorDeclNode {
|
||||
span: n.span,
|
||||
params,
|
||||
initializers,
|
||||
name: n.name.clone(),
|
||||
body: Box::new(Node::Block(BlockNode {
|
||||
span: n.span,
|
||||
stmts: Vec::new(),
|
||||
tail: None,
|
||||
})),
|
||||
};
|
||||
ctors.insert(n.name.clone(), default_ctor);
|
||||
}
|
||||
|
||||
for ctor in &n.constructors {
|
||||
ctors.insert(ctor.name.clone(), ctor.clone());
|
||||
}
|
||||
self.struct_constructors.insert(n.name.clone(), ctors);
|
||||
}
|
||||
}
|
||||
|
||||
let mut module = Module {
|
||||
name: module_name.to_string(),
|
||||
functions: Vec::new(),
|
||||
@@ -118,24 +203,32 @@ impl<'a> Lowerer<'a> {
|
||||
let func_id = *self.function_ids.get(&n.name).unwrap();
|
||||
self.next_block_id = 0;
|
||||
self.local_vars = vec![HashMap::new()];
|
||||
self.max_slots_used = 0;
|
||||
|
||||
let mut params = Vec::new();
|
||||
let mut local_types = HashMap::new();
|
||||
for (i, param) in n.params.iter().enumerate() {
|
||||
let mut param_slots = 0u32;
|
||||
for param in &n.params {
|
||||
let ty = self.lower_type_node(¶m.ty);
|
||||
let slots = self.get_type_slots(&ty);
|
||||
params.push(Param {
|
||||
name: param.name.clone(),
|
||||
ty: ty.clone(),
|
||||
});
|
||||
self.local_vars[0].insert(param.name.clone(), LocalInfo { slot: i as u32, ty: ty.clone() });
|
||||
local_types.insert(i as u32, ty);
|
||||
self.local_vars[0].insert(param.name.clone(), LocalInfo { slot: param_slots, ty: ty.clone() });
|
||||
for i in 0..slots {
|
||||
local_types.insert(param_slots + i, ty.clone());
|
||||
}
|
||||
param_slots += slots;
|
||||
}
|
||||
self.max_slots_used = param_slots;
|
||||
|
||||
let ret_ty = if let Some(ret) = &n.ret {
|
||||
self.lower_type_node(ret)
|
||||
} else {
|
||||
Type::Void
|
||||
};
|
||||
let return_slots = self.get_type_slots(&ret_ty);
|
||||
|
||||
let func = Function {
|
||||
id: func_id,
|
||||
@@ -144,6 +237,9 @@ impl<'a> Lowerer<'a> {
|
||||
return_type: ret_ty,
|
||||
blocks: Vec::new(),
|
||||
local_types,
|
||||
param_slots: param_slots as u16,
|
||||
local_slots: 0,
|
||||
return_slots: return_slots as u16,
|
||||
};
|
||||
|
||||
self.current_function = Some(func);
|
||||
@@ -160,7 +256,9 @@ impl<'a> Lowerer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
Ok(self.current_function.take().unwrap())
|
||||
let mut final_func = self.current_function.take().unwrap();
|
||||
final_func.local_slots = (self.max_slots_used - param_slots) as u16;
|
||||
Ok(final_func)
|
||||
}
|
||||
|
||||
fn lower_node(&mut self, node: &Node) -> Result<(), ()> {
|
||||
@@ -258,8 +356,7 @@ impl<'a> Lowerer<'a> {
|
||||
self.lower_node(&n.target)?;
|
||||
|
||||
// 2. Preserve gate identity
|
||||
let gate_slot = self.get_next_local_slot();
|
||||
self.local_vars.last_mut().unwrap().insert(format!("$gate_{}", gate_slot), LocalInfo { slot: gate_slot, ty: Type::Int });
|
||||
let gate_slot = self.add_local_to_scope(format!("$gate_{}", self.get_next_local_slot()), Type::Int);
|
||||
self.emit(Instr::SetLocal(gate_slot));
|
||||
|
||||
// 3. Begin Operation
|
||||
@@ -268,8 +365,7 @@ impl<'a> Lowerer<'a> {
|
||||
|
||||
// 4. Bind view to local
|
||||
self.local_vars.push(HashMap::new());
|
||||
let view_slot = self.get_next_local_slot();
|
||||
self.local_vars.last_mut().unwrap().insert(n.binding.to_string(), LocalInfo { slot: view_slot, ty: Type::Int });
|
||||
let view_slot = self.add_local_to_scope(n.binding.to_string(), Type::Int);
|
||||
self.emit(Instr::SetLocal(view_slot));
|
||||
|
||||
// 5. Body
|
||||
@@ -287,8 +383,7 @@ impl<'a> Lowerer<'a> {
|
||||
self.lower_node(&n.target)?;
|
||||
|
||||
// 2. Preserve gate identity
|
||||
let gate_slot = self.get_next_local_slot();
|
||||
self.local_vars.last_mut().unwrap().insert(format!("$gate_{}", gate_slot), LocalInfo { slot: gate_slot, ty: Type::Int });
|
||||
let gate_slot = self.add_local_to_scope(format!("$gate_{}", self.get_next_local_slot()), Type::Int);
|
||||
self.emit(Instr::SetLocal(gate_slot));
|
||||
|
||||
// 3. Begin Operation
|
||||
@@ -297,8 +392,7 @@ impl<'a> Lowerer<'a> {
|
||||
|
||||
// 4. Bind view to local
|
||||
self.local_vars.push(HashMap::new());
|
||||
let view_slot = self.get_next_local_slot();
|
||||
self.local_vars.last_mut().unwrap().insert(n.binding.to_string(), LocalInfo { slot: view_slot, ty: Type::Int });
|
||||
let view_slot = self.add_local_to_scope(n.binding.to_string(), Type::Int);
|
||||
self.emit(Instr::SetLocal(view_slot));
|
||||
|
||||
// 5. Body
|
||||
@@ -316,8 +410,7 @@ impl<'a> Lowerer<'a> {
|
||||
self.lower_node(&n.target)?;
|
||||
|
||||
// 2. Preserve gate identity
|
||||
let gate_slot = self.get_next_local_slot();
|
||||
self.local_vars.last_mut().unwrap().insert(format!("$gate_{}", gate_slot), LocalInfo { slot: gate_slot, ty: Type::Int });
|
||||
let gate_slot = self.add_local_to_scope(format!("$gate_{}", self.get_next_local_slot()), Type::Int);
|
||||
self.emit(Instr::SetLocal(gate_slot));
|
||||
|
||||
// 3. Begin Operation
|
||||
@@ -326,8 +419,7 @@ impl<'a> Lowerer<'a> {
|
||||
|
||||
// 4. Bind view to local
|
||||
self.local_vars.push(HashMap::new());
|
||||
let view_slot = self.get_next_local_slot();
|
||||
self.local_vars.last_mut().unwrap().insert(n.binding.to_string(), LocalInfo { slot: view_slot, ty: Type::Int });
|
||||
let view_slot = self.add_local_to_scope(n.binding.to_string(), Type::Int);
|
||||
self.emit(Instr::SetLocal(view_slot));
|
||||
|
||||
// 5. Body
|
||||
@@ -372,10 +464,8 @@ impl<'a> Lowerer<'a> {
|
||||
} else { Type::Int }
|
||||
};
|
||||
|
||||
let slot = self.get_next_local_slot();
|
||||
let slots = self.get_type_slots(&ty);
|
||||
|
||||
self.local_vars.last_mut().unwrap().insert(n.name.clone(), LocalInfo { slot, ty });
|
||||
let slot = self.add_local_to_scope(n.name.clone(), ty);
|
||||
|
||||
for i in (0..slots).rev() {
|
||||
self.emit(Instr::SetLocal(slot + i));
|
||||
@@ -434,6 +524,15 @@ impl<'a> Lowerer<'a> {
|
||||
|
||||
fn lower_member_access(&mut self, n: &MemberAccessNode) -> Result<(), ()> {
|
||||
if let Node::Ident(id) = &*n.object {
|
||||
if let Some(constants) = self.type_constants.get(&id.name).cloned() {
|
||||
if let Some(const_val) = constants.get(&n.member) {
|
||||
let old_ctx = self.current_type_context.replace(id.name.clone());
|
||||
let res = self.lower_node(const_val);
|
||||
self.current_type_context = old_ctx;
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
if id.name == "Color" {
|
||||
let val = match n.member.as_str() {
|
||||
"BLACK" => 0x0000,
|
||||
@@ -539,6 +638,25 @@ impl<'a> Lowerer<'a> {
|
||||
fn lower_call(&mut self, n: &CallNode) -> Result<(), ()> {
|
||||
match &*n.callee {
|
||||
Node::Ident(id_node) => {
|
||||
// 1. Check for constructor call: TypeName(...)
|
||||
let ctor = self.struct_constructors.get(&id_node.name)
|
||||
.and_then(|ctors| ctors.get(&id_node.name))
|
||||
.cloned();
|
||||
|
||||
if let Some(ctor) = ctor {
|
||||
return self.lower_constructor_call(&ctor, &n.args);
|
||||
}
|
||||
|
||||
if let Some(ctx) = &self.current_type_context {
|
||||
let ctor = self.struct_constructors.get(ctx)
|
||||
.and_then(|ctors| ctors.get(&id_node.name))
|
||||
.cloned();
|
||||
|
||||
if let Some(ctor) = ctor {
|
||||
return self.lower_constructor_call(&ctor, &n.args);
|
||||
}
|
||||
}
|
||||
|
||||
for arg in &n.args {
|
||||
self.lower_node(arg)?;
|
||||
}
|
||||
@@ -559,6 +677,19 @@ impl<'a> Lowerer<'a> {
|
||||
}
|
||||
}
|
||||
Node::MemberAccess(ma) => {
|
||||
// Check if it's a constructor alias: TypeName.Alias(...)
|
||||
let ctor = if let Node::Ident(obj_id) = &*ma.object {
|
||||
self.struct_constructors.get(&obj_id.name)
|
||||
.and_then(|ctors| ctors.get(&ma.member))
|
||||
.cloned()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(ctor) = ctor {
|
||||
return self.lower_constructor_call(&ctor, &n.args);
|
||||
}
|
||||
|
||||
// Check for Pad.any()
|
||||
if ma.member == "any" {
|
||||
if let Node::Ident(obj_id) = &*ma.object {
|
||||
@@ -647,6 +778,56 @@ impl<'a> Lowerer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn lower_constructor_call(&mut self, ctor: &ConstructorDeclNode, args: &[Node]) -> Result<(), ()> {
|
||||
let mut param_map = HashMap::new();
|
||||
for (i, param) in ctor.params.iter().enumerate() {
|
||||
if i < args.len() {
|
||||
param_map.insert(param.name.clone(), args[i].clone());
|
||||
}
|
||||
}
|
||||
|
||||
for init in &ctor.initializers {
|
||||
let substituted = self.substitute_node(init, ¶m_map);
|
||||
self.lower_node(&substituted)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn substitute_node(&self, node: &Node, param_map: &HashMap<String, Node>) -> Node {
|
||||
match node {
|
||||
Node::Ident(id) => {
|
||||
if let Some(arg) = param_map.get(&id.name) {
|
||||
arg.clone()
|
||||
} else {
|
||||
node.clone()
|
||||
}
|
||||
}
|
||||
Node::Binary(bin) => {
|
||||
Node::Binary(BinaryNode {
|
||||
span: bin.span,
|
||||
left: Box::new(self.substitute_node(&bin.left, param_map)),
|
||||
right: Box::new(self.substitute_node(&bin.right, param_map)),
|
||||
op: bin.op.clone(),
|
||||
})
|
||||
}
|
||||
Node::Unary(un) => {
|
||||
Node::Unary(UnaryNode {
|
||||
span: un.span,
|
||||
op: un.op.clone(),
|
||||
expr: Box::new(self.substitute_node(&un.expr, param_map)),
|
||||
})
|
||||
}
|
||||
Node::Call(call) => {
|
||||
Node::Call(CallNode {
|
||||
span: call.span,
|
||||
callee: Box::new(self.substitute_node(&call.callee, param_map)),
|
||||
args: call.args.iter().map(|a| self.substitute_node(a, param_map)).collect(),
|
||||
})
|
||||
}
|
||||
_ => node.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn lower_pad_any(&mut self, base_slot: u32) {
|
||||
for i in 0..12 {
|
||||
let btn_base = base_slot + (i * 4);
|
||||
@@ -808,6 +989,24 @@ impl<'a> Lowerer<'a> {
|
||||
self.local_vars.iter().flat_map(|s| s.values()).map(|info| self.get_type_slots(&info.ty)).sum()
|
||||
}
|
||||
|
||||
fn add_local_to_scope(&mut self, name: String, ty: Type) -> u32 {
|
||||
let slot = self.get_next_local_slot();
|
||||
let slots = self.get_type_slots(&ty);
|
||||
|
||||
if slot + slots > self.max_slots_used {
|
||||
self.max_slots_used = slot + slots;
|
||||
}
|
||||
|
||||
self.local_vars.last_mut().unwrap().insert(name, LocalInfo { slot, ty: ty.clone() });
|
||||
|
||||
if let Some(func) = &mut self.current_function {
|
||||
for i in 0..slots {
|
||||
func.local_types.insert(slot + i, ty.clone());
|
||||
}
|
||||
}
|
||||
slot
|
||||
}
|
||||
|
||||
fn find_local(&self, name: &str) -> Option<LocalInfo> {
|
||||
for scope in self.local_vars.iter().rev() {
|
||||
if let Some(info) = scope.get(name) {
|
||||
@@ -817,10 +1016,26 @@ impl<'a> Lowerer<'a> {
|
||||
None
|
||||
}
|
||||
|
||||
fn get_builtin_struct_slots(&self, name: &str) -> Option<u32> {
|
||||
match name {
|
||||
"Pad" => Some(48),
|
||||
"ButtonState" => Some(4),
|
||||
"Color" => Some(1),
|
||||
"Touch" => Some(6),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_type_slots(&self, ty: &Type) -> u32 {
|
||||
match ty {
|
||||
Type::Void => 0,
|
||||
Type::Struct(name) => self.struct_slots.get(name).cloned().unwrap_or(1),
|
||||
Type::Struct(name) => {
|
||||
if let Some(slots) = self.get_builtin_struct_slots(name) {
|
||||
slots
|
||||
} else {
|
||||
self.struct_slots.get(name).cloned().unwrap_or(1)
|
||||
}
|
||||
}
|
||||
Type::Array(_, size) => *size,
|
||||
_ => 1,
|
||||
}
|
||||
@@ -1127,11 +1342,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_alloc_struct_slots() {
|
||||
let code = "
|
||||
declare struct Vec3 {
|
||||
x: int,
|
||||
y: int,
|
||||
z: int
|
||||
}
|
||||
declare struct Vec3(x: int, y: int, z: int)
|
||||
fn main() {
|
||||
let v = alloc Vec3;
|
||||
}
|
||||
|
||||
@@ -225,49 +225,107 @@ impl Parser {
|
||||
};
|
||||
let name = self.expect_identifier()?;
|
||||
|
||||
let mut params = Vec::new();
|
||||
if self.peek().kind == TokenKind::OpenParen {
|
||||
params = self.parse_param_list()?;
|
||||
}
|
||||
|
||||
let mut constructors = Vec::new();
|
||||
if self.peek().kind == TokenKind::OpenBracket {
|
||||
constructors = self.parse_constructor_list()?;
|
||||
}
|
||||
|
||||
let mut is_host = false;
|
||||
if self.peek().kind == TokenKind::Host {
|
||||
self.advance();
|
||||
is_host = true;
|
||||
}
|
||||
|
||||
let body = self.parse_type_body()?;
|
||||
let mut constants = Vec::new();
|
||||
if self.peek().kind == TokenKind::OpenDoubleBracket {
|
||||
self.advance();
|
||||
while self.peek().kind != TokenKind::CloseDoubleBracket && self.peek().kind != TokenKind::Eof {
|
||||
let c_start = self.peek().span.start;
|
||||
let c_name = self.expect_identifier()?;
|
||||
self.consume(TokenKind::Colon)?;
|
||||
let c_value = self.parse_expr(0)?;
|
||||
constants.push(ConstantDeclNode {
|
||||
span: Span::new(self.file_id, c_start, c_value.span().end),
|
||||
name: c_name,
|
||||
value: Box::new(c_value),
|
||||
});
|
||||
if self.peek().kind == TokenKind::Comma {
|
||||
self.advance();
|
||||
}
|
||||
}
|
||||
self.consume(TokenKind::CloseDoubleBracket)?;
|
||||
}
|
||||
|
||||
let mut body = None;
|
||||
if self.peek().kind == TokenKind::OpenBrace {
|
||||
body = Some(Box::new(self.parse_type_body()?));
|
||||
}
|
||||
|
||||
let body_span = body.span();
|
||||
let mut end_pos = start_span.end;
|
||||
if let Some(b) = &body {
|
||||
end_pos = b.span().end;
|
||||
} else if !constants.is_empty() {
|
||||
// We should use the CloseDoubleBracket span here, but I don't have it easily
|
||||
// Let's just use the last constant's end
|
||||
end_pos = constants.last().unwrap().span.end;
|
||||
} else if !params.is_empty() {
|
||||
end_pos = params.last().unwrap().span.end;
|
||||
}
|
||||
|
||||
Ok(Node::TypeDecl(TypeDeclNode {
|
||||
span: Span::new(self.file_id, start_span.start, body_span.end),
|
||||
span: Span::new(self.file_id, start_span.start, end_pos),
|
||||
vis,
|
||||
type_kind,
|
||||
name,
|
||||
is_host,
|
||||
body: Box::new(body),
|
||||
params,
|
||||
constructors,
|
||||
constants,
|
||||
body,
|
||||
}))
|
||||
}
|
||||
|
||||
fn parse_type_body(&mut self) -> Result<Node, DiagnosticBundle> {
|
||||
let start_span = self.consume(TokenKind::OpenBrace)?.span;
|
||||
let mut members = Vec::new();
|
||||
let mut methods = Vec::new();
|
||||
while self.peek().kind != TokenKind::CloseBrace && self.peek().kind != TokenKind::Eof {
|
||||
let m_start = self.peek().span.start;
|
||||
let name = self.expect_identifier()?;
|
||||
self.consume(TokenKind::Colon)?;
|
||||
let ty = self.parse_type_ref()?;
|
||||
let m_end = ty.span().end;
|
||||
members.push(TypeMemberNode {
|
||||
span: Span::new(self.file_id, m_start, m_end),
|
||||
name,
|
||||
ty: Box::new(ty)
|
||||
});
|
||||
if self.peek().kind == TokenKind::Comma {
|
||||
self.advance();
|
||||
if self.peek().kind == TokenKind::Fn {
|
||||
let sig_node = self.parse_service_member()?;
|
||||
if let Node::ServiceFnSig(sig) = sig_node {
|
||||
methods.push(sig);
|
||||
}
|
||||
if self.peek().kind == TokenKind::Semicolon {
|
||||
self.advance();
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
let m_start = self.peek().span.start;
|
||||
let name = self.expect_identifier()?;
|
||||
self.consume(TokenKind::Colon)?;
|
||||
let ty = self.parse_type_ref()?;
|
||||
let m_end = ty.span().end;
|
||||
members.push(TypeMemberNode {
|
||||
span: Span::new(self.file_id, m_start, m_end),
|
||||
name,
|
||||
ty: Box::new(ty)
|
||||
});
|
||||
if self.peek().kind == TokenKind::Comma {
|
||||
self.advance();
|
||||
} else if self.peek().kind == TokenKind::Semicolon {
|
||||
self.advance();
|
||||
}
|
||||
}
|
||||
}
|
||||
let end_span = self.consume(TokenKind::CloseBrace)?.span;
|
||||
Ok(Node::TypeBody(TypeBodyNode {
|
||||
span: Span::new(self.file_id, start_span.start, end_span.end),
|
||||
members,
|
||||
methods,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -344,6 +402,22 @@ impl Parser {
|
||||
self.advance();
|
||||
"bounded".to_string()
|
||||
}
|
||||
TokenKind::None => {
|
||||
self.advance();
|
||||
"none".to_string()
|
||||
}
|
||||
TokenKind::Some => {
|
||||
self.advance();
|
||||
"some".to_string()
|
||||
}
|
||||
TokenKind::Ok => {
|
||||
self.advance();
|
||||
"ok".to_string()
|
||||
}
|
||||
TokenKind::Err => {
|
||||
self.advance();
|
||||
"err".to_string()
|
||||
}
|
||||
_ => return Err(self.error_with_code("Expected type name", Some("E_PARSE_EXPECTED_TOKEN"))),
|
||||
};
|
||||
let mut node = if self.peek().kind == TokenKind::Lt {
|
||||
@@ -819,6 +893,10 @@ impl Parser {
|
||||
self.advance();
|
||||
Ok("err".to_string())
|
||||
}
|
||||
TokenKind::Bounded => {
|
||||
self.advance();
|
||||
Ok("bounded".to_string())
|
||||
}
|
||||
TokenKind::Invalid(msg) => {
|
||||
let code = if msg.contains("Unterminated string") {
|
||||
"E_LEX_UNTERMINATED_STRING"
|
||||
@@ -827,7 +905,7 @@ impl Parser {
|
||||
};
|
||||
Err(self.error_with_code(&msg, Some(code)))
|
||||
}
|
||||
_ => Err(self.error_with_code("Expected identifier", Some("E_PARSE_EXPECTED_TOKEN"))),
|
||||
_ => Err(self.error_with_code(&format!("Expected identifier, found {:?}", peeked_kind), Some("E_PARSE_EXPECTED_TOKEN"))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -845,6 +923,45 @@ impl Parser {
|
||||
self.errors.push(diag.clone());
|
||||
DiagnosticBundle::from(diag)
|
||||
}
|
||||
|
||||
fn parse_constructor_list(&mut self) -> Result<Vec<ConstructorDeclNode>, DiagnosticBundle> {
|
||||
self.consume(TokenKind::OpenBracket)?;
|
||||
let mut constructors = Vec::new();
|
||||
while self.peek().kind != TokenKind::CloseBracket && self.peek().kind != TokenKind::Eof {
|
||||
let start_span = self.peek().span;
|
||||
let params = self.parse_param_list()?;
|
||||
self.consume(TokenKind::Colon)?;
|
||||
|
||||
let mut initializers = Vec::new();
|
||||
if self.peek().kind == TokenKind::OpenParen {
|
||||
self.advance();
|
||||
while self.peek().kind != TokenKind::CloseParen && self.peek().kind != TokenKind::Eof {
|
||||
initializers.push(self.parse_expr(0)?);
|
||||
if self.peek().kind == TokenKind::Comma {
|
||||
self.advance();
|
||||
}
|
||||
}
|
||||
self.consume(TokenKind::CloseParen)?;
|
||||
} else {
|
||||
initializers.push(self.parse_expr(0)?);
|
||||
}
|
||||
|
||||
self.consume(TokenKind::As)?;
|
||||
let name = self.expect_identifier()?;
|
||||
|
||||
let body = self.parse_block()?;
|
||||
|
||||
constructors.push(ConstructorDeclNode {
|
||||
span: Span::new(self.file_id, start_span.start, body.span().end),
|
||||
params,
|
||||
initializers,
|
||||
name,
|
||||
body: Box::new(body),
|
||||
});
|
||||
}
|
||||
self.consume(TokenKind::CloseBracket)?;
|
||||
Ok(constructors)
|
||||
}
|
||||
}
|
||||
|
||||
impl Node {
|
||||
@@ -876,6 +993,8 @@ impl Node {
|
||||
Node::WhenArm(n) => n.span,
|
||||
Node::TypeName(n) => n.span,
|
||||
Node::TypeApp(n) => n.span,
|
||||
Node::ConstructorDecl(n) => n.span,
|
||||
Node::ConstantDecl(n) => n.span,
|
||||
Node::Alloc(n) => n.span,
|
||||
Node::Mutate(n) => n.span,
|
||||
Node::Borrow(n) => n.span,
|
||||
|
||||
@@ -146,6 +146,8 @@ impl<'a> Resolver<'a> {
|
||||
self.resolve_type_ref(arg);
|
||||
}
|
||||
}
|
||||
Node::ConstructorDecl(n) => self.resolve_constructor_decl(n),
|
||||
Node::ConstantDecl(n) => self.resolve_node(&n.value),
|
||||
Node::Alloc(n) => {
|
||||
self.resolve_type_ref(&n.ty);
|
||||
}
|
||||
@@ -217,13 +219,48 @@ impl<'a> Resolver<'a> {
|
||||
}
|
||||
|
||||
fn resolve_type_decl(&mut self, n: &TypeDeclNode) {
|
||||
if let Node::TypeBody(body) = &*n.body {
|
||||
for member in &body.members {
|
||||
self.resolve_type_ref(&member.ty);
|
||||
for param in &n.params {
|
||||
self.resolve_type_ref(¶m.ty);
|
||||
}
|
||||
for constructor in &n.constructors {
|
||||
self.resolve_constructor_decl(constructor);
|
||||
}
|
||||
self.enter_scope();
|
||||
for ctor in &n.constructors {
|
||||
self.define_local(&ctor.name, ctor.span, SymbolKind::Local);
|
||||
}
|
||||
for constant in &n.constants {
|
||||
self.resolve_node(&constant.value);
|
||||
}
|
||||
self.exit_scope();
|
||||
if let Some(body_node) = &n.body {
|
||||
if let Node::TypeBody(body) = &**body_node {
|
||||
for member in &body.members {
|
||||
self.resolve_type_ref(&member.ty);
|
||||
}
|
||||
for method in &body.methods {
|
||||
for param in &method.params {
|
||||
self.resolve_type_ref(¶m.ty);
|
||||
}
|
||||
self.resolve_type_ref(&method.ret);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_constructor_decl(&mut self, n: &ConstructorDeclNode) {
|
||||
self.enter_scope();
|
||||
for param in &n.params {
|
||||
self.resolve_type_ref(¶m.ty);
|
||||
self.define_local(¶m.name, param.span, SymbolKind::Local);
|
||||
}
|
||||
for init in &n.initializers {
|
||||
self.resolve_node(init);
|
||||
}
|
||||
self.resolve_node(&n.body);
|
||||
self.exit_scope();
|
||||
}
|
||||
|
||||
fn resolve_block(&mut self, n: &BlockNode) {
|
||||
self.enter_scope();
|
||||
for stmt in &n.stmts {
|
||||
@@ -311,6 +348,20 @@ impl<'a> Resolver<'a> {
|
||||
return Some(sym.clone());
|
||||
}
|
||||
|
||||
// 5. Fallback for constructor calls: check Type namespace if looking for a Value
|
||||
if namespace == Namespace::Value {
|
||||
if let Some(sym) = self.current_module.type_symbols.get(name) {
|
||||
if sym.kind == SymbolKind::Struct {
|
||||
return Some(sym.clone());
|
||||
}
|
||||
}
|
||||
if let Some(sym) = self.imported_symbols.type_symbols.get(name) {
|
||||
if sym.kind == SymbolKind::Struct {
|
||||
return Some(sym.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +52,8 @@ pub enum TokenKind {
|
||||
CloseBrace, // }
|
||||
OpenBracket, // [
|
||||
CloseBracket, // ]
|
||||
OpenDoubleBracket, // [[
|
||||
CloseDoubleBracket, // ]]
|
||||
Comma, // ,
|
||||
Dot, // .
|
||||
Colon, // :
|
||||
|
||||
@@ -13,6 +13,9 @@ pub struct TypeChecker<'a> {
|
||||
scopes: Vec<HashMap<String, PbsType>>,
|
||||
mut_bindings: Vec<HashMap<String, bool>>,
|
||||
current_return_type: Option<PbsType>,
|
||||
struct_constructors: HashMap<String, HashMap<String, PbsType>>,
|
||||
struct_constants: HashMap<String, HashMap<String, PbsType>>,
|
||||
struct_methods: HashMap<String, HashMap<String, PbsType>>,
|
||||
diagnostics: Vec<Diagnostic>,
|
||||
contract_registry: ContractRegistry,
|
||||
}
|
||||
@@ -28,6 +31,9 @@ impl<'a> TypeChecker<'a> {
|
||||
scopes: Vec::new(),
|
||||
mut_bindings: Vec::new(),
|
||||
current_return_type: None,
|
||||
struct_constructors: HashMap::new(),
|
||||
struct_constants: HashMap::new(),
|
||||
struct_methods: HashMap::new(),
|
||||
diagnostics: Vec::new(),
|
||||
contract_registry: ContractRegistry::new(),
|
||||
}
|
||||
@@ -86,8 +92,62 @@ impl<'a> TypeChecker<'a> {
|
||||
_ => PbsType::Void,
|
||||
};
|
||||
if let Some(sym) = self.module_symbols.type_symbols.symbols.get_mut(&n.name) {
|
||||
sym.ty = Some(ty);
|
||||
sym.ty = Some(ty.clone());
|
||||
}
|
||||
|
||||
// Resolve constructors
|
||||
let mut ctors = HashMap::new();
|
||||
|
||||
// Default constructor: TypeName(...)
|
||||
if n.type_kind == "struct" {
|
||||
let mut params = Vec::new();
|
||||
let mut initializers = Vec::new();
|
||||
for p in &n.params {
|
||||
let p_ty = self.resolve_type_node(&p.ty);
|
||||
params.push(p_ty);
|
||||
initializers.push(Node::Ident(IdentNode {
|
||||
span: p.span,
|
||||
name: p.name.clone(),
|
||||
}));
|
||||
}
|
||||
let default_ctor_ty = PbsType::Function {
|
||||
params: params.clone(),
|
||||
return_type: Box::new(ty.clone()),
|
||||
};
|
||||
ctors.insert(n.name.clone(), default_ctor_ty);
|
||||
}
|
||||
|
||||
for ctor in &n.constructors {
|
||||
let mut params = Vec::new();
|
||||
for p in &ctor.params {
|
||||
params.push(self.resolve_type_node(&p.ty));
|
||||
}
|
||||
let ctor_ty = PbsType::Function {
|
||||
params,
|
||||
return_type: Box::new(ty.clone()),
|
||||
};
|
||||
ctors.insert(ctor.name.clone(), ctor_ty);
|
||||
}
|
||||
self.struct_constructors.insert(n.name.clone(), ctors);
|
||||
|
||||
// Resolve methods
|
||||
let mut methods = HashMap::new();
|
||||
if let Some(body_node) = &n.body {
|
||||
if let Node::TypeBody(body) = &**body_node {
|
||||
for m in &body.methods {
|
||||
let mut params = Vec::new();
|
||||
for p in &m.params {
|
||||
params.push(self.resolve_type_node(&p.ty));
|
||||
}
|
||||
let m_ty = PbsType::Function {
|
||||
params,
|
||||
return_type: Box::new(self.resolve_type_node(&m.ret)),
|
||||
};
|
||||
methods.insert(m.name.clone(), m_ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.struct_methods.insert(n.name.clone(), methods);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -100,6 +160,15 @@ impl<'a> TypeChecker<'a> {
|
||||
self.check_fn_decl(n);
|
||||
PbsType::Void
|
||||
}
|
||||
Node::TypeDecl(n) => {
|
||||
self.check_type_decl(n);
|
||||
PbsType::Void
|
||||
}
|
||||
Node::ConstructorDecl(n) => {
|
||||
self.check_constructor_decl(n);
|
||||
PbsType::Void
|
||||
}
|
||||
Node::ConstantDecl(n) => self.check_node(&n.value),
|
||||
Node::Block(n) => self.check_block(n),
|
||||
Node::LetStmt(n) => {
|
||||
self.check_let_stmt(n);
|
||||
@@ -166,26 +235,45 @@ impl<'a> TypeChecker<'a> {
|
||||
}
|
||||
|
||||
// Builtin Struct Associated Members (Static/Constants)
|
||||
match id.name.as_str() {
|
||||
"Color" => {
|
||||
match n.member.as_str() {
|
||||
"BLACK" | "WHITE" | "RED" | "GREEN" | "BLUE" | "MAGENTA" | "TRANSPARENT" | "COLOR_KEY" => {
|
||||
return PbsType::Struct("Color".to_string());
|
||||
}
|
||||
"rgb" => {
|
||||
return PbsType::Function {
|
||||
params: vec![PbsType::Int, PbsType::Int, PbsType::Int],
|
||||
return_type: Box::new(PbsType::Struct("Color".to_string())),
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(constants) = self.struct_constants.get(&id.name) {
|
||||
if let Some(ty) = constants.get(&n.member) {
|
||||
return ty.clone();
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for constructors if used as Type.alias(...)
|
||||
if let Some(ctors) = self.struct_constructors.get(&id.name) {
|
||||
if let Some(ty) = ctors.get(&n.member) {
|
||||
return ty.clone();
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for static methods if used as Type.method(...)
|
||||
if let Some(methods) = self.struct_methods.get(&id.name) {
|
||||
if let Some(ty) = methods.get(&n.member) {
|
||||
return ty.clone();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let obj_ty = self.check_node(&n.object);
|
||||
if let PbsType::Struct(ref name) = obj_ty {
|
||||
if let Some(methods) = self.struct_methods.get(name) {
|
||||
if let Some(ty) = methods.get(&n.member) {
|
||||
// If it's a method call on an instance, the first parameter (self) is implicit
|
||||
if let PbsType::Function { mut params, return_type } = ty.clone() {
|
||||
if !params.is_empty() {
|
||||
// Check if first param is the struct itself (simple heuristic for self)
|
||||
// In a real compiler we'd check the parameter name or a flag
|
||||
params.remove(0);
|
||||
return PbsType::Function { params, return_type };
|
||||
}
|
||||
}
|
||||
return ty.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match obj_ty {
|
||||
PbsType::Struct(ref name) => {
|
||||
match name.as_str() {
|
||||
@@ -234,10 +322,11 @@ impl<'a> TypeChecker<'a> {
|
||||
}
|
||||
|
||||
if obj_ty != PbsType::Void {
|
||||
let msg = format!("Member '{}' not found on type {:?}", n.member, obj_ty);
|
||||
self.diagnostics.push(Diagnostic {
|
||||
level: DiagnosticLevel::Error,
|
||||
code: Some("E_RESOLVE_UNDEFINED".to_string()),
|
||||
message: format!("Member '{}' not found on type {}", n.member, obj_ty),
|
||||
message: msg,
|
||||
span: Some(n.span),
|
||||
});
|
||||
}
|
||||
@@ -360,6 +449,13 @@ impl<'a> TypeChecker<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for default constructor: check if it's a struct name
|
||||
if let Some(ctors) = self.struct_constructors.get(&n.name) {
|
||||
if let Some(ty) = ctors.get(&n.name) {
|
||||
return ty.clone();
|
||||
}
|
||||
}
|
||||
|
||||
// Built-ins (some, none, ok, err might be handled as calls or special keywords)
|
||||
// For v0, let's treat none as a special literal or identifier
|
||||
if n.name == "none" {
|
||||
@@ -544,6 +640,49 @@ impl<'a> TypeChecker<'a> {
|
||||
first_ty.unwrap_or(PbsType::Void)
|
||||
}
|
||||
|
||||
fn check_type_decl(&mut self, n: &TypeDeclNode) {
|
||||
for constructor in &n.constructors {
|
||||
self.check_constructor_decl(constructor);
|
||||
}
|
||||
|
||||
let struct_ty = PbsType::Struct(n.name.clone());
|
||||
let mut constants_scope = HashMap::new();
|
||||
if let Some(ctors) = self.struct_constructors.get(&n.name) {
|
||||
for (name, ty) in ctors {
|
||||
constants_scope.insert(name.clone(), ty.clone());
|
||||
}
|
||||
}
|
||||
|
||||
let mut constants_map = HashMap::new();
|
||||
self.scopes.push(constants_scope);
|
||||
for constant in &n.constants {
|
||||
let val_ty = self.check_node(&constant.value);
|
||||
if !self.is_assignable(&struct_ty, &val_ty) {
|
||||
self.error_type_mismatch(&struct_ty, &val_ty, constant.span);
|
||||
}
|
||||
constants_map.insert(constant.name.clone(), struct_ty.clone());
|
||||
}
|
||||
self.scopes.pop();
|
||||
self.struct_constants.insert(n.name.clone(), constants_map);
|
||||
|
||||
if let Some(body) = &n.body {
|
||||
self.check_node(body);
|
||||
}
|
||||
}
|
||||
|
||||
fn check_constructor_decl(&mut self, n: &ConstructorDeclNode) {
|
||||
self.enter_scope();
|
||||
for param in &n.params {
|
||||
let ty = self.resolve_type_node(¶m.ty);
|
||||
self.define_local(¶m.name, ty, false);
|
||||
}
|
||||
for init in &n.initializers {
|
||||
self.check_node(init);
|
||||
}
|
||||
self.check_node(&n.body);
|
||||
self.exit_scope();
|
||||
}
|
||||
|
||||
fn resolve_type_node(&mut self, node: &Node) -> PbsType {
|
||||
match node {
|
||||
Node::TypeName(tn) => {
|
||||
@@ -705,7 +844,21 @@ mod tests {
|
||||
let mut file_manager = FileManager::new();
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let file_path = temp_dir.path().join("test.pbs");
|
||||
fs::write(&file_path, code).unwrap();
|
||||
|
||||
// Inject industrial base definitions for tests
|
||||
let mut full_code = String::new();
|
||||
if !code.contains("struct Color") {
|
||||
full_code.push_str("declare struct Color(raw: bounded) [[ BLACK: Color(0b), WHITE: Color(65535b), RED: Color(63488b), GREEN: Color(2016b), BLUE: Color(31b) ]] { fn raw(self: Color): bounded; fn rgb(r: int, g: int, b: int): Color; } \n");
|
||||
}
|
||||
if !code.contains("struct ButtonState") {
|
||||
full_code.push_str("declare struct ButtonState(pressed: bool, released: bool, down: bool, hold_frames: bounded) \n");
|
||||
}
|
||||
if !code.contains("struct Pad") {
|
||||
full_code.push_str("declare struct Pad(up: ButtonState, down: ButtonState, left: ButtonState, right: ButtonState, a: ButtonState, b: ButtonState, x: ButtonState, y: ButtonState, l: ButtonState, r: ButtonState, start: ButtonState, select: ButtonState) { fn any(self: Pad): bool; } \n");
|
||||
}
|
||||
full_code.push_str(code);
|
||||
|
||||
fs::write(&file_path, full_code).unwrap();
|
||||
|
||||
let frontend = PbsFrontend;
|
||||
match frontend.compile_to_ir(&file_path, &mut file_manager) {
|
||||
|
||||
@@ -21,4 +21,8 @@ pub struct Function {
|
||||
pub blocks: Vec<Block>,
|
||||
#[serde(default)]
|
||||
pub local_types: HashMap<u32, Type>,
|
||||
|
||||
pub param_slots: u16,
|
||||
pub local_slots: u16,
|
||||
pub return_slots: u16,
|
||||
}
|
||||
|
||||
@@ -37,6 +37,9 @@ mod tests {
|
||||
functions: vec![Function {
|
||||
id: FunctionId(10),
|
||||
name: "entry".to_string(),
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
params: vec![],
|
||||
return_type: Type::Void,
|
||||
blocks: vec![Block {
|
||||
@@ -90,7 +93,10 @@ mod tests {
|
||||
"terminator": "Return"
|
||||
}
|
||||
],
|
||||
"local_types": {}
|
||||
"local_types": {},
|
||||
"param_slots": 0,
|
||||
"local_slots": 0,
|
||||
"return_slots": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -158,6 +158,9 @@ mod tests {
|
||||
Function {
|
||||
id: FunctionId(1),
|
||||
name: "test".to_string(),
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
params: vec![],
|
||||
return_type: Type::Void,
|
||||
blocks,
|
||||
|
||||
@@ -51,6 +51,9 @@ mod tests {
|
||||
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![
|
||||
@@ -99,7 +102,10 @@ mod tests {
|
||||
"kind": "Ret",
|
||||
"span": null
|
||||
}
|
||||
]
|
||||
],
|
||||
"param_slots": 0,
|
||||
"local_slots": 0,
|
||||
"return_slots": 0
|
||||
}
|
||||
],
|
||||
"globals": []
|
||||
@@ -122,6 +128,9 @@ mod tests {
|
||||
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 {
|
||||
@@ -146,7 +155,7 @@ mod tests {
|
||||
assert_eq!(func.name, "start");
|
||||
assert_eq!(func.id, FunctionId(10));
|
||||
|
||||
assert_eq!(func.body.len(), 4);
|
||||
assert_eq!(func.body.len(), 3);
|
||||
match &func.body[0].kind {
|
||||
InstrKind::Label(Label(l)) => assert!(l.contains("block_0")),
|
||||
_ => panic!("Expected label"),
|
||||
@@ -156,10 +165,6 @@ mod tests {
|
||||
_ => panic!("Expected PushConst"),
|
||||
}
|
||||
match &func.body[2].kind {
|
||||
InstrKind::PushNull => (),
|
||||
_ => panic!("Expected PushNull"),
|
||||
}
|
||||
match &func.body[3].kind {
|
||||
InstrKind::Ret => (),
|
||||
_ => panic!("Expected Ret"),
|
||||
}
|
||||
|
||||
@@ -40,6 +40,10 @@ pub struct Function {
|
||||
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.
|
||||
|
||||
@@ -52,6 +52,9 @@ pub fn lower_function(
|
||||
}).collect(),
|
||||
return_type: lower_type(&core_func.return_type),
|
||||
body: vec![],
|
||||
param_slots: core_func.param_slots,
|
||||
local_slots: core_func.local_slots,
|
||||
return_slots: core_func.return_slots,
|
||||
};
|
||||
|
||||
// Type tracking for RC insertion
|
||||
@@ -320,12 +323,8 @@ pub fn lower_function(
|
||||
}
|
||||
}
|
||||
|
||||
// If the function is Void, we must push a Null value to satisfy the VM's RET instruction.
|
||||
// The VM always pops one value from the stack to be the return value.
|
||||
if vm_func.return_type == ir_vm::Type::Void {
|
||||
vm_func.body.push(ir_vm::Instruction::new(ir_vm::InstrKind::PushNull, None));
|
||||
}
|
||||
|
||||
// If the function is Void, we don't need to push anything.
|
||||
// The VM's Ret opcode handles zero return slots correctly.
|
||||
vm_func.body.push(ir_vm::Instruction::new(ir_vm::InstrKind::Ret, None));
|
||||
}
|
||||
ir_core::Terminator::Jump(target) => {
|
||||
@@ -424,6 +423,9 @@ mod tests {
|
||||
},
|
||||
],
|
||||
local_types: HashMap::new(),
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
}],
|
||||
}],
|
||||
field_offsets: std::collections::HashMap::new(),
|
||||
@@ -436,7 +438,7 @@ mod tests {
|
||||
let func = &vm_module.functions[0];
|
||||
assert_eq!(func.name, "main");
|
||||
|
||||
assert_eq!(func.body.len(), 8);
|
||||
assert_eq!(func.body.len(), 7);
|
||||
|
||||
match &func.body[0].kind {
|
||||
InstrKind::Label(Label(l)) => assert_eq!(l, "block_0"),
|
||||
@@ -466,10 +468,6 @@ mod tests {
|
||||
_ => panic!("Expected HostCall 42"),
|
||||
}
|
||||
match &func.body[6].kind {
|
||||
InstrKind::PushNull => (),
|
||||
_ => panic!("Expected PushNull"),
|
||||
}
|
||||
match &func.body[7].kind {
|
||||
InstrKind::Ret => (),
|
||||
_ => panic!("Expected Ret"),
|
||||
}
|
||||
@@ -500,6 +498,9 @@ mod tests {
|
||||
terminator: Terminator::Return,
|
||||
}],
|
||||
local_types: HashMap::new(),
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
}],
|
||||
}],
|
||||
field_offsets,
|
||||
@@ -518,7 +519,7 @@ mod tests {
|
||||
// GateStore 100 (offset)
|
||||
// Ret
|
||||
|
||||
assert_eq!(func.body.len(), 10);
|
||||
assert_eq!(func.body.len(), 9);
|
||||
match &func.body[1].kind {
|
||||
ir_vm::InstrKind::LocalLoad { slot } => assert_eq!(*slot, 0),
|
||||
_ => panic!("Expected LocalLoad 0"),
|
||||
@@ -536,10 +537,6 @@ mod tests {
|
||||
_ => panic!("Expected GateStore 100"),
|
||||
}
|
||||
match &func.body[8].kind {
|
||||
ir_vm::InstrKind::PushNull => (),
|
||||
_ => panic!("Expected PushNull"),
|
||||
}
|
||||
match &func.body[9].kind {
|
||||
ir_vm::InstrKind::Ret => (),
|
||||
_ => panic!("Expected Ret"),
|
||||
}
|
||||
@@ -564,6 +561,9 @@ mod tests {
|
||||
terminator: Terminator::Return,
|
||||
}],
|
||||
local_types: HashMap::new(),
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
}],
|
||||
}],
|
||||
field_offsets: std::collections::HashMap::new(),
|
||||
@@ -609,6 +609,9 @@ mod tests {
|
||||
terminator: Terminator::Return,
|
||||
}],
|
||||
local_types: HashMap::new(),
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
}],
|
||||
}],
|
||||
field_offsets: HashMap::new(),
|
||||
@@ -635,10 +638,10 @@ mod tests {
|
||||
assert!(found_overwrite, "Should have emitted release-then-store sequence for overwrite");
|
||||
|
||||
// Check Ret cleanup:
|
||||
// LocalLoad 1, GateRelease, PushNull, Ret
|
||||
// LocalLoad 1, GateRelease, Ret
|
||||
let mut found_cleanup = false;
|
||||
for i in 0..kinds.len() - 3 {
|
||||
if let (InstrKind::LocalLoad { slot: 1 }, InstrKind::GateRelease, InstrKind::PushNull, InstrKind::Ret) = (kinds[i], kinds[i+1], kinds[i+2], kinds[i+3]) {
|
||||
for i in 0..kinds.len() - 2 {
|
||||
if let (InstrKind::LocalLoad { slot: 1 }, InstrKind::GateRelease, InstrKind::Ret) = (kinds[i], kinds[i+1], kinds[i+2]) {
|
||||
found_cleanup = true;
|
||||
break;
|
||||
}
|
||||
@@ -671,6 +674,9 @@ mod tests {
|
||||
terminator: Terminator::Return,
|
||||
}],
|
||||
local_types: HashMap::new(),
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
}],
|
||||
}],
|
||||
field_offsets: HashMap::new(),
|
||||
|
||||
Reference in New Issue
Block a user