//! JoinIR 実験用のミニ実行器(Phase 27.2) //! //! 目的: hand-written / minimal JoinIR を VM と A/B 比較するための軽量ランナー。 //! - 対応値: i64 / bool / String / Unit //! - 対応命令: Const / BinOp / Compare / BoxCall(StringBox: length, substring) / //! Call / Jump / Ret //! //! Phase 27.8: ops box 統合 //! - JoinValue / JoinIrOpError は join_ir_ops から再エクスポート //! - eval_binop() / eval_compare() を使用(実装を一箇所に集約) use std::collections::HashMap; use crate::mir::join_ir::{ ConstValue, JoinFuncId, JoinInst, JoinModule, MirLikeInst, VarId, }; // Phase 27.8: ops box からの再エクスポート pub use crate::mir::join_ir_ops::{JoinIrOpError, JoinValue}; // Phase 27.8: 互換性のため JoinRuntimeError を JoinIrOpError の別名として保持 pub type JoinRuntimeError = JoinIrOpError; pub fn run_joinir_function( vm: &mut crate::backend::mir_interpreter::MirInterpreter, module: &JoinModule, entry: JoinFuncId, args: &[JoinValue], ) -> Result { execute_function(vm, module, entry, args.to_vec()) } fn execute_function( vm: &mut crate::backend::mir_interpreter::MirInterpreter, module: &JoinModule, mut current_func: JoinFuncId, mut current_args: Vec, ) -> Result { 'exec: loop { let func = module .functions .get(¤t_func) .ok_or_else(|| JoinRuntimeError::new(format!("Function {:?} not found", current_func)))?; if func.params.len() != current_args.len() { return Err(JoinRuntimeError::new(format!( "Arity mismatch for {:?}: expected {}, got {}", func.id, func.params.len(), current_args.len() ))); } let mut locals: HashMap = HashMap::new(); for (param, arg) in func.params.iter().zip(current_args.iter()) { locals.insert(*param, arg.clone()); } let mut ip = 0usize; while ip < func.body.len() { match &func.body[ip] { JoinInst::Compute(inst) => { eval_compute(vm, inst, &mut locals)?; ip += 1; } JoinInst::Call { func: target, args, k_next, dst, } => { if k_next.is_some() { return Err(JoinRuntimeError::new( "Join continuation (k_next) is not supported in the experimental runner", )); } let resolved_args = materialize_args(args, &locals)?; if let Some(dst_var) = dst { let value = execute_function(vm, module, *target, resolved_args)?; locals.insert(*dst_var, value); ip += 1; } else { current_func = *target; current_args = resolved_args; continue 'exec; } } JoinInst::Jump { cont: _, args, cond } => { let should_jump = match cond { Some(var) => as_bool(&read_var(&locals, *var)?)?, None => true, }; if should_jump { let ret = if let Some(first) = args.first() { read_var(&locals, *first)? } else { JoinValue::Unit }; return Ok(ret); } ip += 1; } JoinInst::Ret { value } => { let ret = match value { Some(var) => read_var(&locals, *var)?, None => JoinValue::Unit, }; return Ok(ret); } } } // fallthrough without explicit return return Ok(JoinValue::Unit); } } fn eval_compute( vm: &mut crate::backend::mir_interpreter::MirInterpreter, inst: &MirLikeInst, locals: &mut HashMap, ) -> Result<(), JoinRuntimeError> { match inst { MirLikeInst::Const { dst, value } => { let v = match value { ConstValue::Integer(i) => JoinValue::Int(*i), ConstValue::Bool(b) => JoinValue::Bool(*b), ConstValue::String(s) => JoinValue::Str(s.clone()), ConstValue::Null => JoinValue::Unit, }; locals.insert(*dst, v); } MirLikeInst::BinOp { dst, op, lhs, rhs } => { // Phase 27.8: ops box の eval_binop() を使用 let l = read_var(locals, *lhs)?; let r = read_var(locals, *rhs)?; let v = crate::mir::join_ir_ops::eval_binop(*op, &l, &r)?; locals.insert(*dst, v); } MirLikeInst::Compare { dst, op, lhs, rhs } => { // Phase 27.8: ops box の eval_compare() を使用 let l = read_var(locals, *lhs)?; let r = read_var(locals, *rhs)?; let v = crate::mir::join_ir_ops::eval_compare(*op, &l, &r)?; locals.insert(*dst, v); } // S-5.2-improved: BoxCall → VM execute_box_call ラッパー経由 // - 制御フロー: JoinIR Runner が担当 // - Box/Plugin 実装: Rust VM に完全委譲(VM 2号機を避ける) // - VM の完全な BoxCall 意味論を使用: // * Void guards (Void.length() → 0) // * PluginBox サポート (FileBox, NetBox) // * InstanceBox policy checks // * object_fields handling // * Method re-routing (toString→str) MirLikeInst::BoxCall { dst, box_name: _, // box_name は VM が内部で判定するため不要 method, args, } => { // First argument is the receiver (box instance) if args.is_empty() { return Err(JoinRuntimeError::new( "BoxCall requires at least a receiver argument", )); } // Convert receiver to VMValue let receiver_jv = read_var(locals, args[0])?; let receiver_vm = receiver_jv.to_vm_value(); // Convert remaining arguments to VMValue let method_args_vm: Vec = args[1..] .iter() .map(|&var_id| read_var(locals, var_id).map(|jv| jv.to_vm_value())) .collect::, _>>()?; // Invoke VM's execute_box_call for complete semantics let result_vm = vm.execute_box_call(receiver_vm, method, method_args_vm) .map_err(|e| JoinRuntimeError::new(format!("BoxCall failed: {}", e)))?; // Convert result back to JoinValue let result_jv = crate::mir::join_ir_ops::JoinValue::from_vm_value(&result_vm)?; // Store result if destination is specified if let Some(dst_var) = dst { locals.insert(*dst_var, result_jv); } } } Ok(()) } fn read_var(locals: &HashMap, var: VarId) -> Result { locals .get(&var) .cloned() .ok_or_else(|| JoinRuntimeError::new(format!("Variable {:?} not bound", var))) } fn materialize_args( args: &[VarId], locals: &HashMap, ) -> Result, JoinRuntimeError> { args.iter().map(|v| read_var(locals, *v)).collect() } fn as_bool(value: &JoinValue) -> Result { match value { JoinValue::Bool(b) => Ok(*b), JoinValue::Int(i) => Ok(*i != 0), JoinValue::Unit => Ok(false), other => Err(JoinRuntimeError::new(format!( "Expected bool-compatible value, got {:?}", other ))), } }