/*! * Minimal MIR Interpreter * * Executes a subset of MIR instructions for fast iteration without LLVM/JIT. * Supported: Const, BinOp(Add/Sub/Mul/Div/Mod), Compare, Load/Store, Branch, Jump, Return, * Print/Debug (best-effort), Barrier/Safepoint (no-op). */ use std::collections::HashMap; use crate::box_trait::NyashBox; pub(super) use crate::backend::abi_util::{eq_vm, to_bool_vm}; pub(super) use crate::backend::vm::{VMError, VMValue}; pub(super) use crate::mir::{ BasicBlockId, BinaryOp, Callee, CompareOp, ConstValue, MirFunction, MirInstruction, MirModule, ValueId, }; mod exec; mod handlers; mod helpers; mod method_router; mod utils; pub struct MirInterpreter { pub(super) regs: HashMap, pub(super) mem: HashMap, // Object field storage keyed by stable object identity (Arc ptr addr fallback) pub(super) obj_fields: HashMap>, pub(super) functions: HashMap, pub(super) cur_fn: Option, // Trace context (dev-only; enabled with NYASH_VM_TRACE=1) pub(super) last_block: Option, pub(super) last_inst: Option, // Static box singleton instances (persistent across method calls) pub(super) static_boxes: HashMap, // Static box declarations (metadata for creating instances) pub(super) static_box_decls: HashMap, } impl MirInterpreter { pub fn new() -> Self { Self { regs: HashMap::new(), mem: HashMap::new(), obj_fields: HashMap::new(), functions: HashMap::new(), cur_fn: None, last_block: None, last_inst: None, static_boxes: HashMap::new(), static_box_decls: HashMap::new(), } } /// Register static box declarations (called from vm.rs during setup) pub fn register_static_box_decl(&mut self, name: String, decl: crate::core::model::BoxDeclaration) { self.static_box_decls.insert(name, decl); } /// Ensure static box singleton instance exists, create if not /// Returns mutable reference to the singleton instance fn ensure_static_box_instance(&mut self, box_name: &str) -> Result<&mut crate::instance_v2::InstanceBox, VMError> { // Check if instance already exists if !self.static_boxes.contains_key(box_name) { // Get declaration let decl = self.static_box_decls.get(box_name) .ok_or_else(|| VMError::InvalidInstruction( format!("static box declaration not found: {}", box_name) ))? .clone(); // Create instance from declaration let instance = crate::instance_v2::InstanceBox::from_declaration( box_name.to_string(), decl.fields.clone(), decl.methods.clone(), ); self.static_boxes.insert(box_name.to_string(), instance); if std::env::var("NYASH_VM_STATIC_TRACE").ok().as_deref() == Some("1") { eprintln!("[vm-static] created singleton instance for static box: {}", box_name); } } // Return mutable reference self.static_boxes.get_mut(box_name) .ok_or_else(|| VMError::InvalidInstruction( format!("static box instance not found after creation: {}", box_name) )) } /// Check if a function name represents a static box method /// Format: "BoxName.method/Arity" fn is_static_box_method(&self, func_name: &str) -> Option { if let Some((box_name, _rest)) = func_name.split_once('.') { if self.static_box_decls.contains_key(box_name) { return Some(box_name.to_string()); } } None } /// Execute module entry (main) and return boxed result pub fn execute_module(&mut self, module: &MirModule) -> Result, VMError> { // Snapshot functions for call resolution self.functions = module.functions.clone(); let func = module .functions .get("main") .ok_or_else(|| VMError::InvalidInstruction("missing main".into()))?; let ret = self.execute_function(func)?; Ok(ret.to_nyash_box()) } fn execute_function(&mut self, func: &MirFunction) -> Result { self.exec_function_inner(func, None) } }