//! 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( module: &JoinModule, entry: JoinFuncId, args: &[JoinValue], ) -> Result { execute_function(module, entry, args.to_vec()) } fn execute_function( 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(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(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(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: BoxCall → VM method_router 経由(ガードレール設計) // - 制御フロー: JoinIR Runner が担当 // - Box/Plugin 実装: Rust VM に委譲(VM 2号機を避ける) MirLikeInst::BoxCall { dst, box_name, method, args, } => { if box_name != "StringBox" { return Err(JoinRuntimeError::new(format!( "Unsupported box call target: {}", box_name ))); } match method.as_str() { "length" => { let arg = expect_str(&read_var(locals, args[0])?)?; // S-5.2: VM の StringBox.length() 実装を使用(hardcoded 削除) let string_box = crate::boxes::basic::StringBox::new(arg); let result_box = string_box.length(); let result_value = box_to_join_value(result_box)?; let dst_var = dst.ok_or_else(|| { JoinRuntimeError::new("length call requires destination") })?; locals.insert(dst_var, result_value); } "substring" => { if args.len() != 3 { return Err(JoinRuntimeError::new( "substring expects 3 arguments (s, start, end)", )); } let s = expect_str(&read_var(locals, args[0])?)?; let start = expect_int(&read_var(locals, args[1])?)? as usize; let end = expect_int(&read_var(locals, args[2])?)? as usize; // S-5.2: VM の StringBox.substring() 実装を使用(hardcoded 削除) let string_box = crate::boxes::basic::StringBox::new(s); let result_box = string_box.substring(start, end); let result_value = box_to_join_value(result_box)?; let dst_var = dst.ok_or_else(|| { JoinRuntimeError::new("substring call requires destination") })?; locals.insert(dst_var, result_value); } _ => { return Err(JoinRuntimeError::new(format!( "Unsupported StringBox method: {}", method ))) } } } } 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 ))), } } fn expect_int(value: &JoinValue) -> Result { match value { JoinValue::Int(i) => Ok(*i), other => Err(JoinRuntimeError::new(format!( "Expected int, got {:?}", other ))), } } fn expect_str(value: &JoinValue) -> Result { match value { JoinValue::Str(s) => Ok(s.clone()), other => Err(JoinRuntimeError::new(format!( "Expected string, got {:?}", other ))), } } /// S-5.2: Convert Box from VM to JoinValue /// /// Tries to downcast to known primitive types first (IntegerBox, BoolBox, StringBox), /// otherwise wraps as BoxRef for future use. fn box_to_join_value(nyash_box: Box) -> Result { use std::sync::Arc; // Try to downcast to known primitive types first if let Some(int_box) = nyash_box.as_any().downcast_ref::() { return Ok(JoinValue::Int(int_box.value)); } if let Some(bool_box) = nyash_box.as_any().downcast_ref::() { return Ok(JoinValue::Bool(bool_box.value)); } if let Some(str_box) = nyash_box.as_any().downcast_ref::() { return Ok(JoinValue::Str(str_box.value.clone())); } // Otherwise, wrap as BoxRef (for S-5.3/S-5.4 future use) Ok(JoinValue::BoxRef(Arc::from(nyash_box))) }