Phase 12.7完了 + ChatGPT5によるVMリファクタリング

## 📚 Phase 12.7 ドキュメント整理
- ChatGPT5作成のANCP Token仕様書v1を整備
- フォルダ構造を機能別に再編成:
  - ancp-specs/ : ANCP圧縮技法仕様
  - grammar-specs/ : 文法改革仕様
  - implementation/ : 実装計画
  - ai-feedback/ : AIアドバイザーフィードバック
- 各フォルダにREADME.md作成で導線改善

## 🔧 ChatGPT5によるVMリファクタリング
- vm_instructions.rs (1927行) をモジュール分割:
  - boxcall.rs : Box呼び出し処理
  - call.rs : 関数呼び出し処理
  - extern_call.rs : 外部関数処理
  - function_new.rs : FunctionBox生成
  - newbox.rs : Box生成処理
  - plugin_invoke.rs : プラグイン呼び出し
- VM実行をファイル分割で整理:
  - vm_state.rs : 状態管理
  - vm_exec.rs : 実行エンジン
  - vm_control_flow.rs : 制御フロー
  - vm_gc.rs : GC処理
- plugin_loader_v2もモジュール化

##  新機能実装
- FunctionBox呼び出しのVM/MIR統一進捗
- ラムダ式のFunctionBox変換テスト追加
- 関数値の直接呼び出し基盤整備

次ステップ: ANCPプロトタイプ実装開始(Week 1)

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Moe Charm
2025-09-04 03:41:02 +09:00
parent 7455c9ec97
commit 6488b0542e
57 changed files with 3803 additions and 3871 deletions

View File

@ -67,6 +67,7 @@ pub(super) fn execute_instruction(vm: &mut VM, instruction: &MirInstruction, deb
// Complex operations
MirInstruction::Call { dst, func, args, effects: _ } => vm.execute_call(*dst, *func, args),
MirInstruction::FunctionNew { dst, params, body, captures, me } => vm.execute_function_new(*dst, params, body, captures, me),
MirInstruction::BoxCall { dst, box_val, method, method_id, args, effects: _ , .. } => vm.execute_boxcall(*dst, *box_val, method, *method_id, args),
MirInstruction::PluginInvoke { dst, box_val, method, args, effects: _ } => vm.execute_plugin_invoke(*dst, *box_val, method, args),
MirInstruction::NewBox { dst, box_type, args } => vm.execute_newbox(*dst, box_type, args),

View File

@ -7,6 +7,7 @@ use crate::mir::instruction::{MirInstruction, ConstValue, BinaryOp, UnaryOp, Com
use crate::mir::ValueId;
use crate::box_trait::{NyashBox, IntegerBox, StringBox, BoolBox};
use crate::boxes::math_box::FloatBox;
use crate::boxes::function_box::FunctionBox;
use crate::boxes::null_box::NullBox;
use super::context::CodegenContext;
use std::collections::HashMap;
@ -157,6 +158,50 @@ impl LLVMCompiler {
}
}
MirInstruction::FunctionNew { dst, params, body, captures, me } => {
// Minimal: build FunctionBox with empty captures unless provided
let mut env = crate::boxes::function_box::ClosureEnv::new();
// Materialize captures (by value) if any
for (name, vid) in captures.iter() {
let v = self.values.get(vid).ok_or_else(|| format!("Value %{} not found for capture {}", vid.0, name))?;
env.captures.insert(name.clone(), v.clone_box());
}
// me capture (weak) if provided and is a box
if let Some(m) = me {
if let Some(b) = self.values.get(m) {
if let Some(arc) = std::sync::Arc::downcast::<dyn NyashBox>({
let bx: std::sync::Arc<dyn NyashBox> = std::sync::Arc::from(b.clone_box());
bx
}).ok() {
env.me_value = Some(std::sync::Arc::downgrade(&arc));
}
}
}
let fun = FunctionBox::with_env(params.clone(), body.clone(), env);
self.values.insert(*dst, Box::new(fun));
println!(" 🧰 %{} = function_new (params={})", dst.0, params.len());
}
MirInstruction::Call { dst, func, args, .. } => {
// Resolve callee
let cal = self.values.get(func)
.ok_or_else(|| format!("Call target %{} not found", func.0))?;
if let Some(fb) = cal.as_any().downcast_ref::<FunctionBox>() {
// Collect args as NyashBox
let mut argv: Vec<Box<dyn NyashBox>> = Vec::new();
for a in args {
let av = self.values.get(a).ok_or_else(|| format!("Arg %{} not found", a.0))?;
argv.push(av.clone_box());
}
let out = crate::interpreter::run_function_box(fb, argv)
.map_err(|e| format!("FunctionBox call failed: {:?}", e))?;
if let Some(d) = dst { self.values.insert(*d, out); }
println!(" 📞 call %{} -> {}", func.0, dst.map(|v| v.0).unwrap_or(u32::MAX));
} else {
println!(" ⚠️ Skipping call: callee not FunctionBox");
}
}
_ => {
// Other instructions not yet implemented
println!(" ⚠️ Skipping instruction: {:?}", inst);

View File

@ -13,6 +13,10 @@ pub mod control_flow;
pub mod dispatch;
pub mod frame;
pub mod gc_helpers;
pub mod vm_control_flow;
mod vm_gc; // A3: GC roots & diagnostics extracted
mod vm_exec; // A3: execution loop extracted
mod vm_state; // A3: state & basic helpers extracted
pub mod abi_util; // Shared ABI/utility helpers
pub mod mir_interpreter; // Lightweight MIR interpreter

View File

@ -7,7 +7,7 @@
* Typical Callers: runner (VM backend), instruction handlers (vm_instructions)
*/
use crate::mir::{MirModule, MirFunction, MirInstruction, ConstValue, BinaryOp, CompareOp, UnaryOp, ValueId, BasicBlockId};
use crate::mir::{ConstValue, ValueId, BasicBlockId, MirModule, MirFunction, MirInstruction};
use crate::box_trait::{NyashBox, StringBox, IntegerBox, BoolBox, VoidBox};
use std::collections::HashMap;
use std::sync::Arc;
@ -183,13 +183,13 @@ impl From<&ConstValue> for VMValue {
/// Virtual Machine state
pub struct VM {
/// Value storage (uses ValueId as direct index into Vec for O(1) access)
values: Vec<Option<VMValue>>,
pub(super) values: Vec<Option<VMValue>>,
/// Current function being executed
current_function: Option<String>,
pub(super) current_function: Option<String>,
/// Frame state (current block, pc, last result)
frame: ExecutionFrame,
pub(super) frame: ExecutionFrame,
/// Previous basic block (for phi node resolution)
previous_block: Option<BasicBlockId>,
pub(super) previous_block: Option<BasicBlockId>,
/// Simple field storage for objects (maps reference -> field -> value)
pub(super) object_fields: HashMap<ValueId, HashMap<String, VMValue>>,
/// Class name mapping for objects (for visibility checks)
@ -197,13 +197,13 @@ pub struct VM {
/// Marks ValueIds that represent internal (me/this) references within the current function
pub(super) object_internal: std::collections::HashSet<ValueId>,
/// Loop executor for handling phi nodes and loop-specific logic
loop_executor: LoopExecutor,
pub(super) loop_executor: LoopExecutor,
/// Shared runtime for box creation and declarations
pub(super) runtime: NyashRuntime,
/// Scope tracker for calling fini on scope exit
scope_tracker: ScopeTracker,
pub(super) scope_tracker: ScopeTracker,
/// Active MIR module during execution (for function calls)
module: Option<MirModule>,
pub(super) module: Option<MirModule>,
/// Instruction execution counters (by MIR opcode)
pub(super) instr_counter: std::collections::HashMap<&'static str, usize>,
/// Execution start time for optional stats
@ -243,31 +243,9 @@ pub struct VM {
impl VM {
pub fn runtime_ref(&self) -> &NyashRuntime { &self.runtime }
/// Enter a GC root region and return a guard that leaves on drop
pub(super) fn enter_root_region(&mut self) {
self.scope_tracker.enter_root_region();
}
/// Pin a slice of VMValue as roots in the current region
pub(super) fn pin_roots<'a>(&mut self, values: impl IntoIterator<Item = &'a VMValue>) {
for v in values {
self.scope_tracker.pin_root(v);
}
}
/// Leave current GC root region
pub(super) fn leave_root_region(&mut self) { self.scope_tracker.leave_root_region(); }
/// Site info for GC logs: (func, bb, pc)
pub(super) fn gc_site_info(&self) -> (String, i64, i64) {
let func = self.current_function.as_deref().unwrap_or("<none>").to_string();
let bb = self.frame.current_block.map(|b| b.0 as i64).unwrap_or(-1);
let pc = self.frame.pc as i64;
(func, bb, pc)
}
/// Print a simple breakdown of root VMValue kinds and top BoxRef types
fn gc_print_roots_breakdown(&self) {
/// Print a simple breakdown of root VMValue kinds and top BoxRef types (old-moved placeholder)
pub(super) fn gc_print_roots_breakdown_old(&self) {
use std::collections::HashMap;
let roots = self.scope_tracker.roots_snapshot();
let mut kinds: HashMap<&'static str, u64> = HashMap::new();
@ -292,7 +270,7 @@ impl VM {
top.truncate(5);
eprintln!("[GC] roots_boxref_top5: {:?}", top);
}
fn gc_print_reachability_depth2(&self) {
pub(super) fn gc_print_reachability_depth2_old(&self) {
use std::collections::HashMap;
let roots = self.scope_tracker.roots_snapshot();
let mut child_types: HashMap<String, u64> = HashMap::new();
@ -327,106 +305,7 @@ impl VM {
top.truncate(5);
eprintln!("[GC] depth2_children: total={} top5={:?}", child_count, top);
}
fn jit_threshold_from_env() -> u32 {
std::env::var("NYASH_JIT_THRESHOLD")
.ok()
.and_then(|s| s.parse::<u32>().ok())
.filter(|&v| v > 0)
.unwrap_or(64)
}
/// Helper: execute phi via LoopExecutor with previous_block-based selection (Step2 skeleton)
pub(super) fn loop_execute_phi(&mut self, dst: ValueId, inputs: &[(BasicBlockId, ValueId)]) -> Result<VMValue, VMError> {
if inputs.is_empty() {
return Err(VMError::InvalidInstruction("Phi node has no inputs".to_string()));
}
let debug_phi = std::env::var("NYASH_VM_DEBUG").ok().as_deref() == Some("1")
|| std::env::var("NYASH_VM_DEBUG_PHI").ok().as_deref() == Some("1");
if debug_phi { eprintln!("[VM] phi-select (delegated) prev={:?} inputs={:?}", self.previous_block, inputs); }
// Borrow just the values storage immutably to avoid borrowing entire &self in closure
let values_ref = &self.values;
let res = self.loop_executor.execute_phi(dst, inputs, |val_id| {
let index = val_id.to_usize();
if index < values_ref.len() {
if let Some(ref value) = values_ref[index] {
Ok(value.clone())
} else {
Err(VMError::InvalidValue(format!("Value {} not set", val_id)))
}
} else {
Err(VMError::InvalidValue(format!("Value {} out of bounds", val_id)))
}
});
if debug_phi {
match &res {
Ok(v) => eprintln!("[VM] phi-result -> {:?}", v),
Err(e) => eprintln!("[VM] phi-error -> {:?}", e),
}
}
res
}
/// Create a new VM instance
pub fn new() -> Self {
Self {
values: Vec::new(),
current_function: None,
frame: ExecutionFrame::new(),
previous_block: None,
object_fields: HashMap::new(),
object_class: HashMap::new(),
object_internal: std::collections::HashSet::new(),
loop_executor: LoopExecutor::new(),
runtime: NyashRuntime::new(),
scope_tracker: ScopeTracker::new(),
module: None,
instr_counter: std::collections::HashMap::new(),
exec_start: None,
boxcall_hits_vtable: 0,
boxcall_hits_poly_pic: 0,
boxcall_hits_mono_pic: 0,
boxcall_hits_generic: 0,
boxcall_pic_hits: std::collections::HashMap::new(),
boxcall_pic_funcname: std::collections::HashMap::new(),
boxcall_poly_pic: std::collections::HashMap::new(),
boxcall_vtable_funcname: std::collections::HashMap::new(),
type_versions: std::collections::HashMap::new(),
jit_manager: Some(crate::jit::manager::JitManager::new(Self::jit_threshold_from_env())),
// TODO: Re-enable when interpreter refactoring is complete
// box_registry: Arc::new(UnifiedBoxRegistry::new()),
// #[cfg(all(feature = "plugins", not(target_arch = "wasm32")))]
// plugin_loader: None,
// scope_tracker: ScopeTracker::new(),
// box_declarations: Arc::new(RwLock::new(HashMap::new())),
}
}
/// Create a VM with an external runtime (dependency injection)
pub fn with_runtime(runtime: NyashRuntime) -> Self {
Self {
values: Vec::new(),
current_function: None,
frame: ExecutionFrame::new(),
previous_block: None,
object_fields: HashMap::new(),
object_class: HashMap::new(),
object_internal: std::collections::HashSet::new(),
loop_executor: LoopExecutor::new(),
runtime,
scope_tracker: ScopeTracker::new(),
module: None,
instr_counter: std::collections::HashMap::new(),
exec_start: None,
boxcall_hits_vtable: 0,
boxcall_hits_poly_pic: 0,
boxcall_hits_mono_pic: 0,
boxcall_hits_generic: 0,
boxcall_pic_hits: std::collections::HashMap::new(),
boxcall_pic_funcname: std::collections::HashMap::new(),
boxcall_poly_pic: std::collections::HashMap::new(),
boxcall_vtable_funcname: std::collections::HashMap::new(),
type_versions: std::collections::HashMap::new(),
jit_manager: Some(crate::jit::manager::JitManager::new(Self::jit_threshold_from_env())),
}
}
// TODO: Re-enable when interpreter refactoring is complete
/*
@ -451,58 +330,12 @@ impl VM {
}
*/
/// Execute a MIR module
pub fn execute_module(&mut self, module: &MirModule) -> Result<Box<dyn NyashBox>, VMError> {
// Store module for nested calls
self.module = Some(module.clone());
// Optional: dump registry for debugging
if std::env::var("NYASH_REG_DUMP").ok().as_deref() == Some("1") {
crate::runtime::type_meta::dump_registry();
}
// Reset stats
self.instr_counter.clear();
self.exec_start = Some(Instant::now());
// Find main function
let main_function = module.get_function("main")
.ok_or_else(|| VMError::InvalidInstruction("No main function found".to_string()))?;
// Execute main function
let result = self.execute_function(main_function)?;
// Optional: print VM stats
self.maybe_print_stats();
// Optional: print concise JIT unified stats
self.maybe_print_jit_unified_stats();
// Optional: print cache stats summary
if crate::config::env::vm_pic_stats() {
self.print_cache_stats_summary();
}
// Optional: print JIT detailed summary (top functions)
if let Some(jm) = &self.jit_manager { jm.print_summary(); }
// Optional: GC diagnostics if enabled
{
let lvl = crate::config::env::gc_trace_level();
if lvl > 0 {
if let Some((sp, rd, wr)) = self.runtime.gc.snapshot_counters() {
eprintln!("[GC] counters: safepoints={} read_barriers={} write_barriers={}", sp, rd, wr);
}
let roots_total = self.scope_tracker.root_count_total();
let root_regions = self.scope_tracker.root_regions();
let field_slots: usize = self.object_fields.values().map(|m| m.len()).sum();
eprintln!("[GC] mock_mark: roots_total={} regions={} object_field_slots={}", roots_total, root_regions, field_slots);
if lvl >= 2 { self.gc_print_roots_breakdown(); }
if lvl >= 3 { self.gc_print_reachability_depth2(); }
}
}
// Convert result to NyashBox
Ok(result.to_nyash_box())
/// Execute a MIR module (old placeholder; moved to vm_exec.rs)
pub fn execute_module_old_moved(&mut self, _module: &MirModule) -> Result<Box<dyn NyashBox>, VMError> {
Ok(Box::new(VoidBox::new()))
}
fn print_cache_stats_summary(&self) {
fn print_cache_stats_summary_old(&self) {
let sites_poly = self.boxcall_poly_pic.len();
let entries_poly: usize = self.boxcall_poly_pic.values().map(|v| v.len()).sum();
let avg_entries = if sites_poly > 0 { (entries_poly as f64) / (sites_poly as f64) } else { 0.0 };
@ -523,7 +356,7 @@ impl VM {
}
/// Call a MIR function by name with VMValue arguments
pub(super) fn call_function_by_name(&mut self, func_name: &str, args: Vec<VMValue>) -> Result<VMValue, VMError> {
pub(super) fn call_function_by_name_old(&mut self, func_name: &str, args: Vec<VMValue>) -> Result<VMValue, VMError> {
// Root region: ensure args stay rooted during nested call
self.enter_root_region();
self.pin_roots(args.iter());
@ -574,7 +407,7 @@ impl VM {
}
/// Execute a single function
fn execute_function(&mut self, function: &MirFunction) -> Result<VMValue, VMError> {
fn execute_function_old(&mut self, function: &MirFunction) -> Result<VMValue, VMError> {
self.current_function = Some(function.signature.name.clone());
// Phase 10_a: JIT profiling (function entry)
if let Some(jm) = &mut self.jit_manager {
@ -721,89 +554,15 @@ impl VM {
}
}
/// Execute a single instruction
fn execute_instruction(&mut self, instruction: &MirInstruction) -> Result<ControlFlow, VMError> {
// Record instruction for stats
let debug_global = std::env::var("NYASH_VM_DEBUG").ok().as_deref() == Some("1");
let debug_exec = debug_global || std::env::var("NYASH_VM_DEBUG_EXEC").ok().as_deref() == Some("1");
if debug_exec { eprintln!("[VM] execute_instruction: {:?}", instruction); }
self.record_instruction(instruction);
super::dispatch::execute_instruction(self, instruction, debug_global)
}
/// Execute a single instruction (old placeholder; moved to vm_exec.rs)
fn execute_instruction_old(&mut self, _instruction: &MirInstruction) -> Result<ControlFlow, VMError> { unreachable!("moved") }
/// Get a value from storage
pub(super) fn get_value(&self, value_id: ValueId) -> Result<VMValue, VMError> {
let index = value_id.to_usize();
if index < self.values.len() {
if let Some(ref value) = self.values[index] {
Ok(value.clone())
} else {
Err(VMError::InvalidValue(format!("Value {} not set", value_id)))
}
} else {
Err(VMError::InvalidValue(format!("Value {} out of bounds", value_id)))
}
}
/// Set a value in the VM storage
pub(super) fn set_value(&mut self, value_id: ValueId, value: VMValue) {
let index = value_id.to_usize();
// Resize Vec if necessary
if index >= self.values.len() {
self.values.resize(index + 1, None);
}
self.values[index] = Some(value);
}
/// Record an instruction execution for statistics
pub(super) fn record_instruction(&mut self, instruction: &MirInstruction) {
let key: &'static str = match instruction {
MirInstruction::Const { .. } => "Const",
MirInstruction::BinOp { .. } => "BinOp",
MirInstruction::UnaryOp { .. } => "UnaryOp",
MirInstruction::Compare { .. } => "Compare",
MirInstruction::Load { .. } => "Load",
MirInstruction::Store { .. } => "Store",
MirInstruction::Call { .. } => "Call",
MirInstruction::BoxCall { .. } => "BoxCall",
MirInstruction::Branch { .. } => "Branch",
MirInstruction::Jump { .. } => "Jump",
MirInstruction::Return { .. } => "Return",
MirInstruction::Phi { .. } => "Phi",
MirInstruction::NewBox { .. } => "NewBox",
MirInstruction::TypeCheck { .. } => "TypeCheck",
MirInstruction::Cast { .. } => "Cast",
MirInstruction::TypeOp { .. } => "TypeOp",
MirInstruction::ArrayGet { .. } => "ArrayGet",
MirInstruction::ArraySet { .. } => "ArraySet",
MirInstruction::Copy { .. } => "Copy",
MirInstruction::Debug { .. } => "Debug",
MirInstruction::Print { .. } => "Print",
MirInstruction::Nop => "Nop",
MirInstruction::Throw { .. } => "Throw",
MirInstruction::Catch { .. } => "Catch",
MirInstruction::Safepoint => "Safepoint",
MirInstruction::RefNew { .. } => "RefNew",
MirInstruction::RefGet { .. } => "RefGet",
MirInstruction::RefSet { .. } => "RefSet",
MirInstruction::WeakNew { .. } => "WeakNew",
MirInstruction::WeakLoad { .. } => "WeakLoad",
MirInstruction::BarrierRead { .. } => "BarrierRead",
MirInstruction::BarrierWrite { .. } => "BarrierWrite",
MirInstruction::WeakRef { .. } => "WeakRef",
MirInstruction::Barrier { .. } => "Barrier",
MirInstruction::FutureNew { .. } => "FutureNew",
MirInstruction::FutureSet { .. } => "FutureSet",
MirInstruction::Await { .. } => "Await",
MirInstruction::ExternCall { .. } => "ExternCall",
MirInstruction::PluginInvoke { .. } => "PluginInvoke",
};
*self.instr_counter.entry(key).or_insert(0) += 1;
}
/// Phase 9.78a: Unified method dispatch for all Box types
@ -1254,12 +1013,7 @@ impl VM {
/// RAII guard for GC root regions
// Root region guard removed in favor of explicit enter/leave to avoid borrow conflicts
/// Control flow result from instruction execution
pub(super) enum ControlFlow {
Continue,
Jump(BasicBlockId),
Return(VMValue),
}
pub(super) use crate::backend::vm_control_flow::ControlFlow;
impl Default for VM {
fn default() -> Self {

View File

@ -0,0 +1,9 @@
use crate::mir::BasicBlockId;
use crate::backend::vm::VMValue;
/// Control flow result from instruction execution
pub(crate) enum ControlFlow {
Continue,
Jump(BasicBlockId),
Return(VMValue),
}

317
src/backend/vm_exec.rs Normal file
View File

@ -0,0 +1,317 @@
/*!
* VM Execution Loop (extracted from vm.rs)
*
* Contains the high-level execution entrypoints and per-instruction dispatch glue:
* - VM::execute_module
* - VM::execute_function
* - VM::call_function_by_name
* - VM::execute_instruction (delegates to backend::dispatch)
* - VM::print_cache_stats_summary (stats helper)
*
* Behavior and public APIs are preserved. This is a pure move/refactor.
*/
use crate::mir::{MirModule, MirFunction, MirInstruction, ValueId, BasicBlockId};
use crate::box_trait::NyashBox;
use super::{vm::VM, vm::VMError, vm::VMValue};
use crate::backend::vm_control_flow::ControlFlow;
use std::sync::Arc;
impl VM {
/// Execute a MIR module
pub fn execute_module(&mut self, module: &MirModule) -> Result<Box<dyn NyashBox>, VMError> {
self.module = Some(module.clone());
if std::env::var("NYASH_REG_DUMP").ok().as_deref() == Some("1") {
crate::runtime::type_meta::dump_registry();
}
self.instr_counter.clear();
self.exec_start = Some(std::time::Instant::now());
let main_function = module
.get_function("main")
.ok_or_else(|| VMError::InvalidInstruction("No main function found".to_string()))?;
let result = self.execute_function(main_function)?;
self.maybe_print_stats();
self.maybe_print_jit_unified_stats();
if crate::config::env::vm_pic_stats() {
self.print_cache_stats_summary();
}
if let Some(jm) = &self.jit_manager { jm.print_summary(); }
{
let lvl = crate::config::env::gc_trace_level();
if lvl > 0 {
if let Some((sp, rd, wr)) = self.runtime.gc.snapshot_counters() {
eprintln!("[GC] counters: safepoints={} read_barriers={} write_barriers={}", sp, rd, wr);
}
let roots_total = self.scope_tracker.root_count_total();
let root_regions = self.scope_tracker.root_regions();
let field_slots: usize = self.object_fields.values().map(|m| m.len()).sum();
eprintln!(
"[GC] mock_mark: roots_total={} regions={} object_field_slots={}",
roots_total, root_regions, field_slots
);
if lvl >= 2 { self.gc_print_roots_breakdown(); }
if lvl >= 3 { self.gc_print_reachability_depth2(); }
}
}
Ok(result.to_nyash_box())
}
pub(super) fn print_cache_stats_summary(&self) {
let sites_poly = self.boxcall_poly_pic.len();
let entries_poly: usize = self.boxcall_poly_pic.values().map(|v| v.len()).sum();
let avg_entries = if sites_poly > 0 {
(entries_poly as f64) / (sites_poly as f64)
} else {
0.0
};
let sites_mono = self.boxcall_pic_funcname.len();
let hits_total: u64 = self.boxcall_pic_hits.values().map(|v| *v as u64).sum();
let vt_entries = self.boxcall_vtable_funcname.len();
eprintln!(
"[VM] PIC/VT summary: poly_sites={} avg_entries={:.2} mono_sites={} hits_total={} vt_entries={} | hits: vt={} poly={} mono={} generic={}",
sites_poly,
avg_entries,
sites_mono,
hits_total,
vt_entries,
self.boxcall_hits_vtable,
self.boxcall_hits_poly_pic,
self.boxcall_hits_mono_pic,
self.boxcall_hits_generic
);
let mut hits: Vec<(&String, &u32)> = self.boxcall_pic_hits.iter().collect();
hits.sort_by(|a, b| b.1.cmp(a.1));
for (i, (k, v)) in hits.into_iter().take(5).enumerate() {
eprintln!(" #{} {} hits={}", i + 1, k, v);
}
}
/// Call a MIR function by name with VMValue arguments
pub(super) fn call_function_by_name(
&mut self,
func_name: &str,
args: Vec<VMValue>,
) -> Result<VMValue, VMError> {
self.enter_root_region();
self.pin_roots(args.iter());
let module_ref = self
.module
.as_ref()
.ok_or_else(|| VMError::InvalidInstruction("No active module".to_string()))?;
let function_ref = module_ref
.get_function(func_name)
.ok_or_else(|| VMError::InvalidInstruction(format!("Function '{}' not found", func_name)))?;
let function = function_ref.clone();
let saved_values = std::mem::take(&mut self.values);
let saved_current_function = self.current_function.clone();
let saved_current_block = self.frame.current_block;
let saved_previous_block = self.previous_block;
let saved_pc = self.frame.pc;
let saved_last_result = self.frame.last_result;
for (i, param_id) in function.params.iter().enumerate() {
if let Some(arg) = args.get(i) {
self.set_value(*param_id, arg.clone());
}
}
if let Some(first) = function.params.get(0) {
if let Some((class_part, _rest)) = func_name.split_once('.') {
self.object_class.insert(*first, class_part.to_string());
self.object_internal.insert(*first);
}
}
let result = self.execute_function(&function);
self.values = saved_values;
self.current_function = saved_current_function;
self.frame.current_block = saved_current_block;
self.previous_block = saved_previous_block;
self.frame.pc = saved_pc;
self.frame.last_result = saved_last_result;
self.scope_tracker.leave_root_region();
result
}
/// Execute a single function
pub(super) fn execute_function(&mut self, function: &MirFunction) -> Result<VMValue, VMError> {
use crate::box_trait::{StringBox, IntegerBox, BoolBox, VoidBox};
use crate::runtime::global_hooks;
use crate::instance_v2::InstanceBox;
use super::control_flow;
self.current_function = Some(function.signature.name.clone());
if let Some(jm) = &mut self.jit_manager {
if let Ok(s) = std::env::var("NYASH_JIT_THRESHOLD") {
if let Ok(t) = s.parse::<u32>() { if t > 0 { jm.set_threshold(t); } }
}
jm.record_entry(&function.signature.name);
let _ = jm.maybe_compile(&function.signature.name, function);
if jm.is_compiled(&function.signature.name)
&& std::env::var("NYASH_JIT_STATS").ok().as_deref() == Some("1")
{
if let Some(h) = jm.handle_of(&function.signature.name) {
eprintln!(
"[JIT] dispatch would go to handle={} for {} (stub)",
h, function.signature.name
);
}
}
}
self.loop_executor.initialize();
self.scope_tracker.push_scope();
global_hooks::push_task_scope();
let args_vec: Vec<VMValue> = function
.params
.iter()
.filter_map(|pid| self.get_value(*pid).ok())
.collect();
if std::env::var("NYASH_JIT_EXEC").ok().as_deref() == Some("1") {
let jit_only = std::env::var("NYASH_JIT_ONLY").ok().as_deref() == Some("1");
self.enter_root_region();
self.pin_roots(args_vec.iter());
if let Some(compiled) = self
.jit_manager
.as_ref()
.map(|jm| jm.is_compiled(&function.signature.name))
{
if compiled {
crate::runtime::host_api::set_current_vm(self as *mut _);
let jit_val = if let Some(jm_mut) = self.jit_manager.as_mut() {
jm_mut.execute_compiled(
&function.signature.name,
&function.signature.return_type,
&args_vec,
)
} else {
None
};
crate::runtime::host_api::clear_current_vm();
if let Some(val) = jit_val {
self.leave_root_region();
self.scope_tracker.pop_scope();
global_hooks::pop_task_scope();
return Ok(val);
} else if std::env::var("NYASH_JIT_STATS").ok().as_deref() == Some("1")
|| std::env::var("NYASH_JIT_TRAP_LOG").ok().as_deref() == Some("1")
{
eprintln!("[JIT] fallback: VM path taken for {}", function.signature.name);
if jit_only {
self.leave_root_region();
self.scope_tracker.pop_scope();
global_hooks::pop_task_scope();
return Err(VMError::InvalidInstruction(format!(
"JIT-only enabled and JIT trap occurred for {}",
function.signature.name
)));
}
}
} else if jit_only {
if let Some(jm_mut) = self.jit_manager.as_mut() {
let _ = jm_mut.maybe_compile(&function.signature.name, function);
}
if self
.jit_manager
.as_ref()
.map(|jm| jm.is_compiled(&function.signature.name))
.unwrap_or(false)
{
crate::runtime::host_api::set_current_vm(self as *mut _);
let jit_val = if let Some(jm_mut) = self.jit_manager.as_mut() {
jm_mut.execute_compiled(
&function.signature.name,
&function.signature.return_type,
&args_vec,
)
} else {
None
};
crate::runtime::host_api::clear_current_vm();
if let Some(val) = jit_val {
self.leave_root_region();
self.scope_tracker.pop_scope();
global_hooks::pop_task_scope();
return Ok(val);
} else {
self.leave_root_region();
self.scope_tracker.pop_scope();
global_hooks::pop_task_scope();
return Err(VMError::InvalidInstruction(format!(
"JIT-only mode: compiled execution failed for {}",
function.signature.name
)));
}
} else {
self.leave_root_region();
self.scope_tracker.pop_scope();
global_hooks::pop_task_scope();
return Err(VMError::InvalidInstruction(format!(
"JIT-only mode: function {} not compiled",
function.signature.name
)));
}
}
}
}
let mut current_block = function.entry_block;
self.frame.current_block = Some(current_block);
self.frame.pc = 0;
let mut should_return: Option<VMValue> = None;
let mut next_block: Option<BasicBlockId> = None;
loop {
if let Some(block) = function.blocks.get(&current_block) {
for instruction in &block.instructions {
match self.execute_instruction(instruction)? {
ControlFlow::Continue => continue,
ControlFlow::Jump(target) => {
next_block = Some(target);
break;
}
ControlFlow::Return(value) => {
should_return = Some(value);
break;
}
}
}
} else {
return Err(VMError::InvalidBasicBlock(format!(
"Basic block {:?} not found",
current_block
)));
}
if let Some(return_value) = should_return {
self.scope_tracker.pop_scope();
global_hooks::pop_task_scope();
return Ok(return_value);
} else if let Some(target) = next_block {
control_flow::record_transition(
&mut self.previous_block,
&mut self.loop_executor,
current_block,
target,
)
.ok();
current_block = target;
} else {
self.scope_tracker.pop_scope();
global_hooks::pop_task_scope();
return Ok(VMValue::Void);
}
}
}
/// Execute a single instruction
pub(super) fn execute_instruction(&mut self, instruction: &MirInstruction) -> Result<ControlFlow, VMError> {
let debug_global = std::env::var("NYASH_VM_DEBUG").ok().as_deref() == Some("1");
let debug_exec = debug_global || std::env::var("NYASH_VM_DEBUG_EXEC").ok().as_deref() == Some("1");
if debug_exec { eprintln!("[VM] execute_instruction: {:?}", instruction); }
self.record_instruction(instruction);
super::dispatch::execute_instruction(self, instruction, debug_global)
}
}

99
src/backend/vm_gc.rs Normal file
View File

@ -0,0 +1,99 @@
/*!
* VM GC Roots & Diagnostics (extracted from vm.rs)
*
* - Root region helpers: enter_root_region / pin_roots / leave_root_region
* - Site info for GC logs
* - Debug prints for roots snapshot and shallow reachability
*/
use super::vm::{VM, VMError, VMValue};
impl VM {
/// Enter a GC root region and return a guard that leaves on drop
pub(super) fn enter_root_region(&mut self) {
self.scope_tracker.enter_root_region();
}
/// Pin a slice of VMValue as roots in the current region
pub(super) fn pin_roots<'a>(&mut self, values: impl IntoIterator<Item = &'a VMValue>) {
for v in values {
self.scope_tracker.pin_root(v);
}
}
/// Leave current GC root region
pub(super) fn leave_root_region(&mut self) { self.scope_tracker.leave_root_region(); }
/// Site info for GC logs: (func, bb, pc)
pub(super) fn gc_site_info(&self) -> (String, i64, i64) {
let func = self.current_function.as_deref().unwrap_or("<none>").to_string();
let bb = self.frame.current_block.map(|b| b.0 as i64).unwrap_or(-1);
let pc = self.frame.pc as i64;
(func, bb, pc)
}
/// Print a simple breakdown of root VMValue kinds and top BoxRef types
pub(super) fn gc_print_roots_breakdown(&self) {
use std::collections::HashMap;
let roots = self.scope_tracker.roots_snapshot();
let mut kinds: HashMap<&'static str, u64> = HashMap::new();
let mut box_types: HashMap<String, u64> = HashMap::new();
for v in &roots {
match v {
VMValue::Integer(_) => *kinds.entry("Integer").or_insert(0) += 1,
VMValue::Float(_) => *kinds.entry("Float").or_insert(0) += 1,
VMValue::Bool(_) => *kinds.entry("Bool").or_insert(0) += 1,
VMValue::String(_) => *kinds.entry("String").or_insert(0) += 1,
VMValue::Future(_) => *kinds.entry("Future").or_insert(0) += 1,
VMValue::Void => *kinds.entry("Void").or_insert(0) += 1,
VMValue::BoxRef(b) => {
let tn = b.type_name().to_string();
*box_types.entry(tn).or_insert(0) += 1;
}
}
}
eprintln!("[GC] roots_breakdown: kinds={:?}", kinds);
let mut top: Vec<(String, u64)> = box_types.into_iter().collect();
top.sort_by(|a, b| b.1.cmp(&a.1));
top.truncate(5);
eprintln!("[GC] roots_boxref_top5: {:?}", top);
}
/// Print shallow reachability from current roots into ArrayBox/MapBox values
pub(super) fn gc_print_reachability_depth2(&self) {
use std::collections::HashMap;
let roots = self.scope_tracker.roots_snapshot();
let mut child_types: HashMap<String, u64> = HashMap::new();
let mut child_count = 0u64;
for v in &roots {
if let VMValue::BoxRef(b) = v {
if let Some(arr) = b.as_any().downcast_ref::<crate::boxes::array::ArrayBox>() {
if let Ok(items) = arr.items.read() {
for item in items.iter() {
let tn = item.type_name().to_string();
*child_types.entry(tn).or_insert(0) += 1;
child_count += 1;
}
}
}
if let Some(map) = b.as_any().downcast_ref::<crate::boxes::map_box::MapBox>() {
let vals = map.values();
if let Some(arr2) = vals.as_any().downcast_ref::<crate::boxes::array::ArrayBox>() {
if let Ok(items) = arr2.items.read() {
for item in items.iter() {
let tn = item.type_name().to_string();
*child_types.entry(tn).or_insert(0) += 1;
child_count += 1;
}
}
}
}
}
}
let mut top: Vec<(String, u64)> = child_types.into_iter().collect();
top.sort_by(|a, b| b.1.cmp(&a.1));
top.truncate(5);
eprintln!("[GC] depth2_children: total={} top5={:?}", child_count, top);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,559 @@
use crate::box_trait::NyashBox;
use crate::mir::ValueId;
use crate::backend::vm::ControlFlow;
use crate::backend::{VM, VMError, VMValue};
impl VM {
/// Execute BoxCall instruction
pub(crate) fn execute_boxcall(&mut self, dst: Option<ValueId>, box_val: ValueId, method: &str, method_id: Option<u16>, args: &[ValueId]) -> Result<ControlFlow, VMError> {
let recv = self.get_value(box_val)?;
// Debug logging if enabled
let debug_boxcall = std::env::var("NYASH_VM_DEBUG_BOXCALL").is_ok();
// Fast-path: ConsoleBox.readLine — provide safe stdin fallback with EOF→Void
if let VMValue::BoxRef(arc_box) = &recv {
if let Some(p) = arc_box.as_any().downcast_ref::<crate::runtime::plugin_loader_v2::PluginBoxV2>() {
if p.box_type == "ConsoleBox" && method == "readLine" {
use std::io::Read;
let mut s = String::new();
let mut stdin = std::io::stdin();
let mut buf = [0u8; 1];
loop {
match stdin.read(&mut buf) {
Ok(0) => {
if let Some(dst_id) = dst { let nb = crate::boxes::null_box::NullBox::new(); self.set_value(dst_id, VMValue::from_nyash_box(Box::new(nb))); }
return Ok(ControlFlow::Continue);
}
Ok(_) => {
let ch = buf[0] as char;
if ch == '\n' { break; }
s.push(ch);
if s.len() > 1_000_000 { break; }
}
Err(_) => {
if let Some(dst_id) = dst { let nb = crate::boxes::null_box::NullBox::new(); self.set_value(dst_id, VMValue::from_nyash_box(Box::new(nb))); }
return Ok(ControlFlow::Continue);
}
}
}
if let Some(dst_id) = dst { self.set_value(dst_id, VMValue::String(s)); }
return Ok(ControlFlow::Continue);
}
}
}
// VTable-first stub path (optional)
if crate::config::env::abi_vtable() {
if let Some(res) = self.try_boxcall_vtable_stub(dst, &recv, method, method_id, args) { return res; }
}
// Record PIC hit (per-receiver-type × method)
let pic_key = self.build_pic_key(&recv, method, method_id);
self.pic_record_hit(&pic_key);
// Explicit fast-paths
if let VMValue::BoxRef(arc_box) = &recv {
// ArrayBox get/set
if arc_box.as_any().downcast_ref::<crate::boxes::array::ArrayBox>().is_some() {
let get_slot = crate::mir::slot_registry::resolve_slot_by_type_name("ArrayBox", "get");
let set_slot = crate::mir::slot_registry::resolve_slot_by_type_name("ArrayBox", "set");
let is_get = (method_id.is_some() && method_id == get_slot) || method == "get";
let is_set = (method_id.is_some() && method_id == set_slot) || method == "set";
if is_get && args.len() >= 1 {
let idx_val = self.get_value(args[0])?;
let idx_box = idx_val.to_nyash_box();
let arr = arc_box.as_any().downcast_ref::<crate::boxes::array::ArrayBox>().unwrap();
let out = arr.get(idx_box);
if let Some(dst_id) = dst { self.set_value(dst_id, VMValue::from_nyash_box(out)); }
return Ok(ControlFlow::Continue);
} else if is_set && args.len() >= 2 {
crate::backend::gc_helpers::gc_write_barrier_site(&self.runtime, "BoxCall.fastpath.Array.set");
let idx_val = self.get_value(args[0])?;
let val_val = self.get_value(args[1])?;
let idx_box = idx_val.to_nyash_box();
let val_box = val_val.to_nyash_box();
let arr = arc_box.as_any().downcast_ref::<crate::boxes::array::ArrayBox>().unwrap();
let out = arr.set(idx_box, val_box);
if let Some(dst_id) = dst { self.set_value(dst_id, VMValue::from_nyash_box(out)); }
return Ok(ControlFlow::Continue);
}
}
// InstanceBox getField/setField by name
if let Some(inst) = arc_box.as_any().downcast_ref::<crate::instance_v2::InstanceBox>() {
let is_getf = method == "getField";
let is_setf = method == "setField";
if (is_getf && args.len() >= 1) || (is_setf && args.len() >= 2) {
let name_val = self.get_value(args[0])?;
let field_name = match &name_val { VMValue::String(s) => s.clone(), _ => name_val.to_string(), };
if is_getf {
let out_opt = inst.get_field_unified(&field_name);
let out_vm = match out_opt {
Some(nv) => match nv {
crate::value::NyashValue::Integer(i) => VMValue::Integer(i),
crate::value::NyashValue::Float(f) => VMValue::Float(f),
crate::value::NyashValue::Bool(b) => VMValue::Bool(b),
crate::value::NyashValue::String(s) => VMValue::String(s),
crate::value::NyashValue::Void | crate::value::NyashValue::Null => VMValue::Void,
crate::value::NyashValue::Box(b) => { if let Ok(g) = b.lock() { VMValue::from_nyash_box(g.share_box()) } else { VMValue::Void } }
_ => VMValue::Void,
},
None => VMValue::Void,
};
if let Some(dst_id) = dst { self.set_value(dst_id, out_vm); }
return Ok(ControlFlow::Continue);
} else {
// setField
crate::backend::gc_helpers::gc_write_barrier_site(&self.runtime, "BoxCall.fastpath.Instance.setField");
let val_vm = self.get_value(args[1])?;
let nv_opt = match val_vm.clone() {
VMValue::Integer(i) => Some(crate::value::NyashValue::Integer(i)),
VMValue::Float(f) => Some(crate::value::NyashValue::Float(f)),
VMValue::Bool(b) => Some(crate::value::NyashValue::Bool(b)),
VMValue::String(s) => Some(crate::value::NyashValue::String(s)),
VMValue::Void => Some(crate::value::NyashValue::Void),
_ => None,
};
if let Some(nv) = nv_opt { let _ = inst.set_field_unified(field_name, nv); if let Some(dst_id) = dst { self.set_value(dst_id, VMValue::Void); } return Ok(ControlFlow::Continue); }
}
}
}
}
// VTable-like thunk path via TypeMeta and method_id
if let (Some(mid), VMValue::BoxRef(arc_box)) = (method_id, &recv) {
let mut class_label: Option<String> = None;
let mut is_instance = false;
let mut is_plugin = false;
let mut is_builtin = false;
if let Some(inst) = arc_box.as_any().downcast_ref::<crate::instance_v2::InstanceBox>() { class_label = Some(inst.class_name.clone()); is_instance = true; }
else if let Some(p) = arc_box.as_any().downcast_ref::<crate::runtime::plugin_loader_v2::PluginBoxV2>() { class_label = Some(p.box_type.clone()); is_plugin = true; }
else { class_label = Some(arc_box.type_name().to_string()); is_builtin = true; }
if let Some(label) = class_label {
let tm = crate::runtime::type_meta::get_or_create_type_meta(&label);
if let Some(th) = tm.get_thunk(mid as usize) {
if let Some(target) = th.get_target() {
match target {
crate::runtime::type_meta::ThunkTarget::MirFunction(func_name) => {
if std::env::var("NYASH_VM_VT_STATS").ok().as_deref() == Some("1") { eprintln!("[VT] hit class={} slot={} -> {}", label, mid, func_name); }
let mut vm_args = Vec::with_capacity(1 + args.len());
vm_args.push(recv.clone());
for a in args { vm_args.push(self.get_value(*a)?); }
let res = self.call_function_by_name(&func_name, vm_args)?;
self.record_poly_pic(&pic_key, &recv, &func_name);
let threshold = crate::config::env::vm_pic_threshold();
if self.pic_hits(&pic_key) >= threshold { self.boxcall_pic_funcname.insert(pic_key.clone(), func_name.clone()); }
if is_instance {
let vkey = self.build_vtable_key(&label, mid, args.len());
self.boxcall_vtable_funcname.entry(vkey).or_insert(func_name.clone());
}
if let Some(dst_id) = dst { self.set_value(dst_id, res); }
return Ok(ControlFlow::Continue);
}
crate::runtime::type_meta::ThunkTarget::PluginInvoke { method_id: mid2 } => {
if is_plugin {
if let Some(p) = arc_box.as_any().downcast_ref::<crate::runtime::plugin_loader_v2::PluginBoxV2>() {
self.enter_root_region();
let nyash_args: Vec<Box<dyn NyashBox>> = args.iter().map(|arg| { let val = self.get_value(*arg)?; Ok(val.to_nyash_box()) }).collect::<Result<Vec<_>, VMError>>()?;
self.pin_roots(std::iter::once(&recv));
let pinned_args: Vec<VMValue> = args.iter().filter_map(|a| self.get_value(*a).ok()).collect();
self.pin_roots(pinned_args.iter());
let mut tlv = crate::runtime::plugin_ffi_common::encode_tlv_header(nyash_args.len() as u16);
let mut enc_failed = false;
for a in &nyash_args {
if let Some(s) = a.as_any().downcast_ref::<crate::box_trait::StringBox>() { crate::runtime::plugin_ffi_common::encode::string(&mut tlv, &s.value); }
else if let Some(i) = a.as_any().downcast_ref::<crate::box_trait::IntegerBox>() { crate::runtime::plugin_ffi_common::encode::i32(&mut tlv, i.value as i32); }
else if let Some(h) = a.as_any().downcast_ref::<crate::runtime::plugin_loader_v2::PluginBoxV2>() { crate::runtime::plugin_ffi_common::encode::plugin_handle(&mut tlv, h.inner.type_id, h.inner.instance_id); }
else { enc_failed = true; break; }
}
if !enc_failed {
let mut out = vec![0u8; 4096];
let mut out_len: usize = out.len();
crate::runtime::host_api::set_current_vm(self as *mut _);
let code = unsafe { (p.inner.invoke_fn)(p.inner.type_id, mid2 as u32, p.inner.instance_id, tlv.as_ptr(), tlv.len(), out.as_mut_ptr(), &mut out_len) };
crate::runtime::host_api::clear_current_vm();
if code == 0 {
let vm_out = if let Some((tag, _sz, payload)) = crate::runtime::plugin_ffi_common::decode::tlv_first(&out[..out_len]) {
match tag {
6 | 7 => VMValue::String(crate::runtime::plugin_ffi_common::decode::string(payload)),
2 => crate::runtime::plugin_ffi_common::decode::i32(payload).map(|v| VMValue::Integer(v as i64)).unwrap_or(VMValue::Void),
9 => {
if let Some(h) = crate::runtime::plugin_ffi_common::decode::u64(payload) { if let Some(arc) = crate::runtime::host_handles::get(h) { VMValue::BoxRef(arc) } else { VMValue::Void } } else { VMValue::Void }
}
_ => VMValue::Void,
}
} else { VMValue::Void };
if let Some(dst_id) = dst { self.set_value(dst_id, vm_out); }
self.leave_root_region();
return Ok(ControlFlow::Continue);
}
self.leave_root_region();
}
}
}
}
crate::runtime::type_meta::ThunkTarget::BuiltinCall { method: ref m } => {
if is_builtin {
let nyash_args: Vec<Box<dyn NyashBox>> = args.iter().map(|arg| { let val = self.get_value(*arg)?; Ok(val.to_nyash_box()) }).collect::<Result<Vec<_>, VMError>>()?;
if crate::backend::gc_helpers::is_mutating_builtin_call(&recv, m) { crate::backend::gc_helpers::gc_write_barrier_site(&self.runtime, "BoxCall.builtin"); }
else if m == "setField" { crate::backend::gc_helpers::gc_write_barrier_site(&self.runtime, "BoxCall.setField"); }
let cloned_box = arc_box.share_box();
self.boxcall_hits_generic = self.boxcall_hits_generic.saturating_add(1);
let out = self.call_box_method(cloned_box, m, nyash_args)?;
let vm_out = VMValue::from_nyash_box(out);
if let Some(dst_id) = dst { self.set_value(dst_id, vm_out); }
return Ok(ControlFlow::Continue);
}
}
}
}
}
// Legacy vtable cache for InstanceBox
if is_instance {
let inst = arc_box.as_any().downcast_ref::<crate::instance_v2::InstanceBox>().unwrap();
let vkey = self.build_vtable_key(&inst.class_name, mid, args.len());
if let Some(func_name) = self.boxcall_vtable_funcname.get(&vkey).cloned() {
let mut vm_args = Vec::with_capacity(1 + args.len());
vm_args.push(recv.clone());
for a in args { vm_args.push(self.get_value(*a)?); }
let res = self.call_function_by_name(&func_name, vm_args)?;
if let Some(dst_id) = dst { self.set_value(dst_id, res); }
return Ok(ControlFlow::Continue);
}
}
}
}
// Poly-PIC direct call to lowered function if present
if let VMValue::BoxRef(arc_box) = &recv {
if arc_box.as_any().downcast_ref::<crate::instance_v2::InstanceBox>().is_some() {
if let Some(func_name) = self.try_poly_pic(&pic_key, &recv) {
if crate::config::env::vm_pic_trace() { eprintln!("[PIC] poly hit {}", pic_key); }
self.boxcall_hits_poly_pic = self.boxcall_hits_poly_pic.saturating_add(1);
let mut vm_args = Vec::with_capacity(1 + args.len());
vm_args.push(recv.clone());
for a in args { vm_args.push(self.get_value(*a)?); }
let res = self.call_function_by_name(&func_name, vm_args)?;
if let Some(dst_id) = dst { self.set_value(dst_id, res); }
return Ok(ControlFlow::Continue);
}
if let Some(func_name) = self.boxcall_pic_funcname.get(&pic_key).cloned() {
if crate::config::env::vm_pic_trace() { eprintln!("[PIC] mono hit {}", pic_key); }
self.boxcall_hits_mono_pic = self.boxcall_hits_mono_pic.saturating_add(1);
let mut vm_args = Vec::with_capacity(1 + args.len());
vm_args.push(recv.clone());
for a in args { vm_args.push(self.get_value(*a)?); }
let res = self.call_function_by_name(&func_name, vm_args)?;
if let Some(dst_id) = dst { self.set_value(dst_id, res); }
return Ok(ControlFlow::Continue);
}
}
}
// Fast universal slots (0..3)
if let Some(mid) = method_id {
if let Some(fast_res) = self.try_fast_universal(mid, &recv, args)? { if let Some(dst_id) = dst { self.set_value(dst_id, fast_res); } return Ok(ControlFlow::Continue); }
}
// Generic path: convert args to NyashBox and call
let nyash_args: Vec<Box<dyn NyashBox>> = args.iter().map(|arg| { let val = self.get_value(*arg)?; Ok(val.to_nyash_box()) }).collect::<Result<Vec<_>, VMError>>()?;
// PluginBoxV2 fast-path via direct invoke_fn when method_id present
if let (Some(mid), VMValue::BoxRef(arc_box)) = (method_id, &recv) {
if let Some(p) = arc_box.as_any().downcast_ref::<crate::runtime::plugin_loader_v2::PluginBoxV2>() {
self.enter_root_region();
let mut tlv = crate::runtime::plugin_ffi_common::encode_tlv_header(nyash_args.len() as u16);
let mut enc_failed = false;
for a in &nyash_args {
if let Some(buf) = a.as_any().downcast_ref::<crate::boxes::buffer::BufferBox>() { let snapshot = buf.to_vec(); crate::runtime::plugin_ffi_common::encode::bytes(&mut tlv, &snapshot); continue; }
if let Some(s) = a.as_any().downcast_ref::<crate::box_trait::StringBox>() { crate::runtime::plugin_ffi_common::encode::string(&mut tlv, &s.value); }
else if let Some(i) = a.as_any().downcast_ref::<crate::box_trait::IntegerBox>() { if i.value >= i32::MIN as i64 && i.value <= i32::MAX as i64 { crate::runtime::plugin_ffi_common::encode::i32(&mut tlv, i.value as i32); } else { crate::runtime::plugin_ffi_common::encode::i64(&mut tlv, i.value as i64); } }
else if let Some(b) = a.as_any().downcast_ref::<crate::box_trait::BoolBox>() { crate::runtime::plugin_ffi_common::encode::bool(&mut tlv, b.value); }
else if let Some(f) = a.as_any().downcast_ref::<crate::boxes::math_box::FloatBox>() { crate::runtime::plugin_ffi_common::encode::f64(&mut tlv, f.value); }
else if let Some(arr) = a.as_any().downcast_ref::<crate::boxes::array::ArrayBox>() {
let items = arr.items.read().unwrap();
let mut tmp = Vec::with_capacity(items.len());
let mut ok = true;
for item in items.iter() {
if let Some(intb) = item.as_any().downcast_ref::<crate::box_trait::IntegerBox>() { if intb.value >= 0 && intb.value <= 255 { tmp.push(intb.value as u8); } else { ok = false; break; } } else { ok = false; break; }
}
if ok { crate::runtime::plugin_ffi_common::encode::bytes(&mut tlv, &tmp); } else { enc_failed = true; break; }
} else if let Some(h) = a.as_any().downcast_ref::<crate::runtime::plugin_loader_v2::PluginBoxV2>() { crate::runtime::plugin_ffi_common::encode::plugin_handle(&mut tlv, h.inner.type_id, h.inner.instance_id); }
else { enc_failed = true; break; }
}
if !enc_failed {
let mut out = vec![0u8; 4096];
let mut out_len: usize = out.len();
let code = unsafe { (p.inner.invoke_fn)(p.inner.type_id, mid as u32, p.inner.instance_id, tlv.as_ptr(), tlv.len(), out.as_mut_ptr(), &mut out_len) };
if code == 0 {
// Record TypeMeta thunk for plugin invoke so next time VT path can hit
let tm = crate::runtime::type_meta::get_or_create_type_meta(&p.box_type);
tm.set_thunk_plugin_invoke(mid as usize, mid as u16);
let vm_out = if let Some((tag, _sz, payload)) = crate::runtime::plugin_ffi_common::decode::tlv_first(&out[..out_len]) {
match tag {
1 => crate::runtime::plugin_ffi_common::decode::bool(payload).map(VMValue::Bool).unwrap_or(VMValue::Void),
2 => crate::runtime::plugin_ffi_common::decode::i32(payload).map(|v| VMValue::Integer(v as i64)).unwrap_or(VMValue::Void),
5 => crate::runtime::plugin_ffi_common::decode::f64(payload).map(VMValue::Float).unwrap_or(VMValue::Void),
6 => VMValue::String(crate::runtime::plugin_ffi_common::decode::string(payload)),
_ => VMValue::Void,
}
} else { VMValue::Void };
if let Some(dst_id) = dst { self.set_value(dst_id, vm_out); }
self.leave_root_region();
return Ok(ControlFlow::Continue);
}
self.leave_root_region();
}
}
}
if debug_boxcall { self.debug_log_boxcall(&recv, method, &nyash_args, "START", None); }
// Call the method based on receiver type
let result = match &recv {
VMValue::BoxRef(arc_box) => {
if let Some(inst) = arc_box.as_any().downcast_ref::<crate::instance_v2::InstanceBox>() {
let func_name = format!("{}.{}{}", inst.class_name, method, format!("/{}", args.len()));
if let Some(mid) = method_id {
let tm = crate::runtime::type_meta::get_or_create_type_meta(&inst.class_name);
tm.set_thunk_mir_target(mid as usize, func_name.clone());
let vkey = self.build_vtable_key(&inst.class_name, mid, args.len());
self.boxcall_vtable_funcname.entry(vkey).or_insert(func_name.clone());
}
self.record_poly_pic(&pic_key, &recv, &func_name);
let threshold = crate::config::env::vm_pic_threshold();
if self.pic_hits(&pic_key) >= threshold { self.boxcall_pic_funcname.insert(pic_key.clone(), func_name.clone()); }
if debug_boxcall { eprintln!("[BoxCall] InstanceBox -> call {}", func_name); }
let mut vm_args = Vec::with_capacity(1 + args.len());
vm_args.push(recv.clone());
for a in args { vm_args.push(self.get_value(*a)?); }
let res = self.call_function_by_name(&func_name, vm_args)?;
return { if let Some(dst_id) = dst { self.set_value(dst_id, res); } Ok(ControlFlow::Continue) };
}
if debug_boxcall { eprintln!("[BoxCall] Taking BoxRef path for method '{}'", method); }
if let Some(mid) = method_id {
let label = arc_box.type_name().to_string();
let tm = crate::runtime::type_meta::get_or_create_type_meta(&label);
tm.set_thunk_builtin(mid as usize, method.to_string());
}
if crate::backend::gc_helpers::is_mutating_builtin_call(&recv, method) { crate::backend::gc_helpers::gc_write_barrier_site(&self.runtime, "BoxCall"); }
else if method == "setField" { crate::backend::gc_helpers::gc_write_barrier_site(&self.runtime, "BoxCall.setField"); }
let cloned_box = arc_box.share_box();
self.call_box_method(cloned_box, method, nyash_args)?
}
_ => {
if debug_boxcall { eprintln!("[BoxCall] Converting primitive to box for method '{}'", method); }
let box_value = recv.to_nyash_box();
self.call_box_method(box_value, method, nyash_args)?
}
};
let result_val = VMValue::from_nyash_box(result);
if debug_boxcall { self.debug_log_boxcall(&recv, method, &[], "END", Some(&result_val)); }
if let Some(dst_id) = dst { self.set_value(dst_id, result_val); }
Ok(ControlFlow::Continue)
}
/// Phase 12 Tier-0: vtable-first stub for selected types
pub(super) fn try_boxcall_vtable_stub(&mut self, _dst: Option<ValueId>, _recv: &VMValue, _method: &str, _method_id: Option<u16>, _args: &[ValueId]) -> Option<Result<ControlFlow, VMError>> {
if crate::config::env::vm_vt_trace() {
match _recv { VMValue::BoxRef(b) => eprintln!("[VT] probe recv_ty={} method={} argc={}", b.type_name(), _method, _args.len()), other => eprintln!("[VT] probe recv_prim={:?} method={} argc={}", other, _method, _args.len()), }
}
if let VMValue::BoxRef(b) = _recv {
let ty_name = b.type_name();
let ty_name_for_reg: std::borrow::Cow<'_, str> = if let Some(p) = b.as_any().downcast_ref::<crate::runtime::plugin_loader_v2::PluginBoxV2>() { std::borrow::Cow::Owned(p.box_type.clone()) } else { std::borrow::Cow::Borrowed(ty_name) };
if let Some(_tb) = crate::runtime::type_registry::resolve_typebox_by_name(&ty_name_for_reg) {
let slot = crate::runtime::type_registry::resolve_slot_by_name(&ty_name_for_reg, _method, _args.len());
if let Some(p) = b.as_any().downcast_ref::<crate::runtime::plugin_loader_v2::PluginBoxV2>() {
if crate::config::env::vm_vt_trace() { eprintln!("[VT] plugin recv ty={} method={} arity={}", ty_name, _method, _args.len()); }
let mut nyash_args: Vec<Box<dyn NyashBox>> = Vec::with_capacity(_args.len());
for aid in _args.iter() { if let Ok(v) = self.get_value(*aid) { nyash_args.push(v.to_nyash_box()); } else { nyash_args.push(Box::new(crate::box_trait::VoidBox::new())); } }
match ty_name {
"MapBox" => {
match slot {
Some(200) | Some(201) => {
let host = crate::runtime::get_global_plugin_host();
let ro = host.read().unwrap();
if let Ok(val_opt) = ro.invoke_instance_method("MapBox", _method, p.inner.instance_id, &[]) {
if let Some(out) = val_opt { if let Some(dst_id) = _dst { self.set_value(dst_id, VMValue::from_nyash_box(out)); } }
self.boxcall_hits_vtable = self.boxcall_hits_vtable.saturating_add(1);
return Some(Ok(ControlFlow::Continue));
}
}
Some(202) | Some(203) | Some(204) => {
if matches!(slot, Some(204)) { crate::backend::gc_helpers::gc_write_barrier_site(&self.runtime, "VTable.Plugin.Map.set"); }
let host = crate::runtime::get_global_plugin_host();
let ro = host.read().unwrap();
let mut method_eff = _method;
if (matches!(slot, Some(202)) && _args.len() >= 1) || (matches!(slot, Some(203)) && _args.len() >= 1) {
if let Ok(a0v) = self.get_value(_args[0]) { if matches!(a0v, VMValue::String(_)) { method_eff = if matches!(slot, Some(203)) { "getS" } else { "hasS" }; } }
}
if let Ok(val_opt) = ro.invoke_instance_method("MapBox", method_eff, p.inner.instance_id, &nyash_args) {
if let Some(out) = val_opt { if let Some(dst_id) = _dst { self.set_value(dst_id, VMValue::from_nyash_box(out)); } }
else if _dst.is_some() { if let Some(dst_id) = _dst { self.set_value(dst_id, VMValue::Void); } }
self.boxcall_hits_vtable = self.boxcall_hits_vtable.saturating_add(1);
return Some(Ok(ControlFlow::Continue));
}
}
_ => {}
}
}
"ArrayBox" => {
match slot {
Some(100) | Some(101) | Some(102) => {
if matches!(slot, Some(101)) { crate::backend::gc_helpers::gc_write_barrier_site(&self.runtime, "VTable.Plugin.Array.set"); }
let host = crate::runtime::get_global_plugin_host();
let ro = host.read().unwrap();
if let Ok(val_opt) = ro.invoke_instance_method("ArrayBox", _method, p.inner.instance_id, &nyash_args) {
if let Some(out) = val_opt { if let Some(dst_id) = _dst { self.set_value(dst_id, VMValue::from_nyash_box(out)); } }
self.boxcall_hits_vtable = self.boxcall_hits_vtable.saturating_add(1);
return Some(Ok(ControlFlow::Continue));
}
}
_ => {}
}
}
_ => {}
}
}
// Builtin boxes
if let Some(map) = b.as_any().downcast_ref::<crate::boxes::map_box::MapBox>() {
if matches!(slot, Some(200)) || matches!(slot, Some(201)) {
self.boxcall_hits_vtable = self.boxcall_hits_vtable.saturating_add(1);
if crate::config::env::vm_vt_trace() { eprintln!("[VT] MapBox.size/len"); }
let out = map.size();
if let Some(dst_id) = _dst { self.set_value(dst_id, VMValue::from_nyash_box(out)); }
return Some(Ok(ControlFlow::Continue));
}
if matches!(slot, Some(202)) {
if let Ok(arg_v) = self.get_value(_args[0]) {
let key_box: Box<dyn NyashBox> = match arg_v {
VMValue::Integer(i) => Box::new(crate::box_trait::IntegerBox::new(i)),
VMValue::String(ref s) => Box::new(crate::box_trait::StringBox::new(s)),
VMValue::Bool(b) => Box::new(crate::box_trait::BoolBox::new(b)),
VMValue::Float(f) => Box::new(crate::boxes::math_box::FloatBox::new(f)),
VMValue::BoxRef(ref bx) => bx.share_box(),
VMValue::Future(ref fut) => Box::new(fut.clone()),
VMValue::Void => Box::new(crate::box_trait::VoidBox::new()),
};
self.boxcall_hits_vtable = self.boxcall_hits_vtable.saturating_add(1);
if crate::config::env::vm_vt_trace() { eprintln!("[VT] MapBox.has"); }
let out = map.has(key_box);
if let Some(dst_id) = _dst { self.set_value(dst_id, VMValue::from_nyash_box(out)); }
return Some(Ok(ControlFlow::Continue));
}
}
if matches!(slot, Some(203)) {
if let Ok(arg_v) = self.get_value(_args[0]) {
let key_box: Box<dyn NyashBox> = match arg_v {
VMValue::Integer(i) => Box::new(crate::box_trait::IntegerBox::new(i)),
VMValue::String(ref s) => Box::new(crate::box_trait::StringBox::new(s)),
VMValue::Bool(b) => Box::new(crate::box_trait::BoolBox::new(b)),
VMValue::Float(f) => Box::new(crate::boxes::math_box::FloatBox::new(f)),
VMValue::BoxRef(ref bx) => bx.share_box(),
VMValue::Future(ref fut) => Box::new(fut.clone()),
VMValue::Void => Box::new(crate::box_trait::VoidBox::new()),
};
self.boxcall_hits_vtable = self.boxcall_hits_vtable.saturating_add(1);
if crate::config::env::vm_vt_trace() { eprintln!("[VT] MapBox.get"); }
let out = map.get(key_box);
if let Some(dst_id) = _dst { self.set_value(dst_id, VMValue::from_nyash_box(out)); }
return Some(Ok(ControlFlow::Continue));
}
}
if matches!(slot, Some(204)) {
if let (Ok(a0), Ok(a1)) = (self.get_value(_args[0]), self.get_value(_args[1])) {
if let VMValue::String(ref s) = a0 { let vb: Box<dyn NyashBox> = match a1 { VMValue::Integer(i) => Box::new(crate::box_trait::IntegerBox::new(i)), VMValue::String(ref s) => Box::new(crate::box_trait::StringBox::new(s)), VMValue::Bool(b) => Box::new(crate::box_trait::BoolBox::new(b)), VMValue::Float(f) => Box::new(crate::boxes::math_box::FloatBox::new(f)), VMValue::BoxRef(ref bx) => bx.share_box(), VMValue::Future(ref fut) => Box::new(fut.clone()), VMValue::Void => Box::new(crate::box_trait::VoidBox::new()), }; let out = map.set(Box::new(crate::box_trait::StringBox::new(s)), vb); if let Some(dst_id) = _dst { self.set_value(dst_id, VMValue::from_nyash_box(out)); } return Some(Ok(ControlFlow::Continue)); }
let key_box: Box<dyn NyashBox> = match a0 {
VMValue::Integer(i) => Box::new(crate::box_trait::IntegerBox::new(i)),
VMValue::String(ref s) => Box::new(crate::box_trait::StringBox::new(s)),
VMValue::Bool(b) => Box::new(crate::box_trait::BoolBox::new(b)),
VMValue::Float(f) => Box::new(crate::boxes::math_box::FloatBox::new(f)),
VMValue::BoxRef(ref bx) => bx.share_box(),
VMValue::Future(ref fut) => Box::new(fut.clone()),
VMValue::Void => Box::new(crate::box_trait::VoidBox::new()),
};
let val_box: Box<dyn NyashBox> = match a1 {
VMValue::Integer(i) => Box::new(crate::box_trait::IntegerBox::new(i)),
VMValue::String(ref s) => Box::new(crate::box_trait::StringBox::new(s)),
VMValue::Bool(b) => Box::new(crate::box_trait::BoolBox::new(b)),
VMValue::Float(f) => Box::new(crate::boxes::math_box::FloatBox::new(f)),
VMValue::BoxRef(ref bx) => bx.share_box(),
VMValue::Future(ref fut) => Box::new(fut.clone()),
VMValue::Void => Box::new(crate::box_trait::VoidBox::new()),
};
// Barrier: mutation
crate::backend::gc_helpers::gc_write_barrier_site(&self.runtime, "VTable.Map.set");
self.boxcall_hits_vtable = self.boxcall_hits_vtable.saturating_add(1);
if crate::config::env::vm_vt_trace() { eprintln!("[VT] MapBox.set"); }
let out = map.set(key_box, val_box);
if let Some(dst_id) = _dst { self.set_value(dst_id, VMValue::from_nyash_box(out)); }
return Some(Ok(ControlFlow::Continue));
}
}
}
// StringBox: len
if let Some(sb) = b.as_any().downcast_ref::<crate::box_trait::StringBox>() {
if matches!(slot, Some(300)) {
self.boxcall_hits_vtable = self.boxcall_hits_vtable.saturating_add(1);
if crate::config::env::vm_vt_trace() { eprintln!("[VT] StringBox.len"); }
let out = crate::box_trait::IntegerBox::new(sb.value.len() as i64);
if let Some(dst_id) = _dst { self.set_value(dst_id, VMValue::from_nyash_box(Box::new(out))); }
return Some(Ok(ControlFlow::Continue));
}
}
if crate::config::env::abi_strict() {
let known = crate::runtime::type_registry::known_methods_for(ty_name).unwrap_or_default().join(", ");
let msg = format!("ABI_STRICT: undefined vtable method {}.{}(arity={}) — known: {}", ty_name, _method, _args.len(), known);
return Some(Err(VMError::TypeError(msg)));
}
}
}
None
}
}
impl VM {
/// Try fast universal-thunk dispatch using reserved method slots 0..3.
fn try_fast_universal(&mut self, method_id: u16, recv: &VMValue, args: &[ValueId]) -> Result<Option<VMValue>, VMError> {
match method_id {
0 => { let s = recv.to_string(); return Ok(Some(VMValue::String(s))); }
1 => {
let t = match recv {
VMValue::Integer(_) => "Integer".to_string(),
VMValue::Float(_) => "Float".to_string(),
VMValue::Bool(_) => "Bool".to_string(),
VMValue::String(_) => "String".to_string(),
VMValue::Future(_) => "Future".to_string(),
VMValue::Void => "Void".to_string(),
VMValue::BoxRef(b) => b.type_name().to_string(),
};
return Ok(Some(VMValue::String(t)));
}
2 => {
let other = if let Some(arg0) = args.get(0) { self.get_value(*arg0)? } else { VMValue::Void };
let res = match (recv, &other) {
(VMValue::Integer(a), VMValue::Integer(b)) => a == b,
(VMValue::Bool(a), VMValue::Bool(b)) => a == b,
(VMValue::String(a), VMValue::String(b)) => a == b,
(VMValue::Void, VMValue::Void) => true,
_ => recv.to_string() == other.to_string(),
};
return Ok(Some(VMValue::Bool(res)));
}
3 => {
let v = match recv {
VMValue::Integer(i) => VMValue::Integer(*i),
VMValue::Float(f) => VMValue::Float(*f),
VMValue::Bool(b) => VMValue::Bool(*b),
VMValue::String(s) => VMValue::String(s.clone()),
VMValue::Future(f) => VMValue::Future(f.clone()),
VMValue::Void => VMValue::Void,
VMValue::BoxRef(b) => VMValue::from_nyash_box(b.share_box()),
};
return Ok(Some(v));
}
_ => {}
}
Ok(None)
}
}

View File

@ -0,0 +1,41 @@
use crate::box_trait::NyashBox;
use crate::mir::ValueId;
use crate::backend::vm::ControlFlow;
use crate::backend::{VM, VMError, VMValue};
impl VM {
/// Execute Call instruction (supports function name or FunctionBox value)
pub(crate) fn execute_call(&mut self, dst: Option<ValueId>, func: ValueId, args: &[ValueId]) -> Result<ControlFlow, VMError> {
// Evaluate function value
let fval = self.get_value(func)?;
match fval {
VMValue::String(func_name) => {
// Legacy: call function by name
let arg_values: Vec<VMValue> = args.iter().map(|arg| self.get_value(*arg)).collect::<Result<Vec<_>, _>>()?;
let result = self.call_function_by_name(&func_name, arg_values)?;
if let Some(dst_id) = dst { self.set_value(dst_id, result); }
Ok(ControlFlow::Continue)
}
VMValue::BoxRef(arc_box) => {
// FunctionBox call path
if let Some(fun) = arc_box.as_any().downcast_ref::<crate::boxes::function_box::FunctionBox>() {
// Convert args to NyashBox for interpreter helper
let nyash_args: Vec<Box<dyn NyashBox>> = args.iter()
.map(|a| self.get_value(*a).map(|v| v.to_nyash_box()))
.collect::<Result<Vec<_>, VMError>>()?;
// Execute via interpreter helper
match crate::interpreter::run_function_box(fun, nyash_args) {
Ok(out) => {
if let Some(dst_id) = dst { self.set_value(dst_id, VMValue::from_nyash_box(out)); }
Ok(ControlFlow::Continue)
}
Err(e) => Err(VMError::InvalidInstruction(format!("FunctionBox call failed: {:?}", e)))
}
} else {
Err(VMError::TypeError(format!("Call target not callable: {}", arc_box.type_name())))
}
}
other => Err(VMError::TypeError(format!("Call target must be function name or FunctionBox, got {:?}", other))),
}
}
}

View File

@ -0,0 +1,365 @@
use crate::mir::{ConstValue, BinaryOp, CompareOp, UnaryOp, ValueId, BasicBlockId, TypeOpKind, MirType};
use crate::box_trait::{NyashBox, BoolBox, VoidBox};
use crate::boxes::ArrayBox;
use std::sync::Arc;
use crate::backend::vm::ControlFlow;
use crate::backend::{VM, VMError, VMValue};
impl VM {
// ---- Helpers (PIC/VTable bookkeeping) ----
pub(super) fn build_pic_key(&self, recv: &VMValue, method: &str, method_id: Option<u16>) -> String {
let label = self.cache_label_for_recv(recv);
let ver = self.cache_version_for_label(&label);
if let Some(mid) = method_id { format!("v{}:{}#{}", ver, label, mid) } else { format!("v{}:{}#{}", ver, label, method) }
}
pub(super) fn pic_record_hit(&mut self, key: &str) {
use std::collections::hash_map::Entry;
match self.boxcall_pic_hits.entry(key.to_string()) {
Entry::Occupied(mut e) => {
let v = e.get_mut();
*v = v.saturating_add(1);
if std::env::var("NYASH_VM_PIC_DEBUG").ok().as_deref() == Some("1") {
if *v == 8 || *v == 32 { eprintln!("[PIC] Hot BoxCall site '{}' hits={} (skeleton)", key, v); }
}
}
Entry::Vacant(v) => { v.insert(1); }
}
}
pub(super) fn pic_hits(&self, key: &str) -> u32 { *self.boxcall_pic_hits.get(key).unwrap_or(&0) }
pub(super) fn build_vtable_key(&self, class_name: &str, method_id: u16, arity: usize) -> String {
let label = format!("BoxRef:{}", class_name);
let ver = self.cache_version_for_label(&label);
format!("VT@v{}:{}#{}{}", ver, class_name, method_id, format!("/{}", arity))
}
pub(super) fn try_poly_pic(&mut self, pic_site_key: &str, recv: &VMValue) -> Option<String> {
let label = self.cache_label_for_recv(recv);
let ver = self.cache_version_for_label(&label);
if let Some(entries) = self.boxcall_poly_pic.get_mut(pic_site_key) {
if let Some(idx) = entries.iter().position(|(l, v, _)| *l == label && *v == ver) {
let entry = entries.remove(idx);
entries.push(entry.clone());
return Some(entry.2);
}
}
None
}
pub(super) fn record_poly_pic(&mut self, pic_site_key: &str, recv: &VMValue, func_name: &str) {
let label = self.cache_label_for_recv(recv);
let ver = self.cache_version_for_label(&label);
use std::collections::hash_map::Entry;
match self.boxcall_poly_pic.entry(pic_site_key.to_string()) {
Entry::Occupied(mut e) => {
let v = e.get_mut();
if let Some(idx) = v.iter().position(|(l, vv, _)| *l == label && *vv == ver) { v.remove(idx); }
if v.len() >= 4 { v.remove(0); }
v.push((label.clone(), ver, func_name.to_string()));
}
Entry::Vacant(v) => { v.insert(vec![(label.clone(), ver, func_name.to_string())]); }
}
if std::env::var("NYASH_VM_PIC_STATS").ok().as_deref() == Some("1") {
if let Some(v) = self.boxcall_poly_pic.get(pic_site_key) {
eprintln!("[PIC] site={} size={} last=({}, v{}) -> {}", pic_site_key, v.len(), label, ver, func_name);
}
}
}
pub(super) fn cache_label_for_recv(&self, recv: &VMValue) -> String {
match recv {
VMValue::Integer(_) => "Int".to_string(),
VMValue::Float(_) => "Float".to_string(),
VMValue::Bool(_) => "Bool".to_string(),
VMValue::String(_) => "String".to_string(),
VMValue::Future(_) => "Future".to_string(),
VMValue::Void => "Void".to_string(),
VMValue::BoxRef(b) => format!("BoxRef:{}", b.type_name()),
}
}
pub(super) fn cache_version_for_label(&self, label: &str) -> u32 { crate::runtime::cache_versions::get_version(label) }
#[allow(dead_code)]
pub fn bump_cache_version(&mut self, label: &str) { crate::runtime::cache_versions::bump_version(label) }
// ---- Basics ----
pub(crate) fn execute_const(&mut self, dst: ValueId, value: &ConstValue) -> Result<ControlFlow, VMError> {
let vm_value = VMValue::from(value);
self.set_value(dst, vm_value);
Ok(ControlFlow::Continue)
}
pub(crate) fn execute_binop(&mut self, dst: ValueId, op: &BinaryOp, lhs: ValueId, rhs: ValueId) -> Result<ControlFlow, VMError> {
match *op {
BinaryOp::And | BinaryOp::Or => {
if std::env::var("NYASH_VM_DEBUG_ANDOR").ok().as_deref() == Some("1") { eprintln!("[VM] And/Or short-circuit path"); }
let left = self.get_value(lhs)?;
let right = self.get_value(rhs)?;
let lb = left.as_bool()?;
let rb = right.as_bool()?;
let out = match *op { BinaryOp::And => lb && rb, BinaryOp::Or => lb || rb, _ => unreachable!() };
self.set_value(dst, VMValue::Bool(out));
Ok(ControlFlow::Continue)
}
_ => {
let left = self.get_value(lhs)?;
let right = self.get_value(rhs)?;
let result = self.execute_binary_op(op, &left, &right)?;
self.set_value(dst, result);
Ok(ControlFlow::Continue)
}
}
}
pub(crate) fn execute_unaryop(&mut self, dst: ValueId, op: &UnaryOp, operand: ValueId) -> Result<ControlFlow, VMError> {
let operand_val = self.get_value(operand)?;
let result = self.execute_unary_op(op, &operand_val)?;
self.set_value(dst, result);
Ok(ControlFlow::Continue)
}
pub(crate) fn execute_compare(&mut self, dst: ValueId, op: &CompareOp, lhs: ValueId, rhs: ValueId) -> Result<ControlFlow, VMError> {
let debug_cmp = std::env::var("NYASH_VM_DEBUG").ok().as_deref() == Some("1") || std::env::var("NYASH_VM_DEBUG_CMP").ok().as_deref() == Some("1");
if debug_cmp { eprintln!("[VM] execute_compare enter op={:?} lhs={:?} rhs={:?}", op, lhs, rhs); }
let mut left = self.get_value(lhs)?;
let mut right = self.get_value(rhs)?;
if debug_cmp { eprintln!("[VM] execute_compare values: left={:?} right={:?}", left, right); }
left = match left {
VMValue::BoxRef(b) => {
if let Some(ib) = b.as_any().downcast_ref::<crate::box_trait::IntegerBox>() { VMValue::Integer(ib.value) }
else { match b.to_string_box().value.trim().parse::<i64>() { Ok(n) => VMValue::Integer(n), Err(_) => VMValue::BoxRef(b) } }
}
other => other,
};
right = match right {
VMValue::BoxRef(b) => {
if let Some(ib) = b.as_any().downcast_ref::<crate::box_trait::IntegerBox>() { VMValue::Integer(ib.value) }
else { match b.to_string_box().value.trim().parse::<i64>() { Ok(n) => VMValue::Integer(n), Err(_) => VMValue::BoxRef(b) } }
}
other => other,
};
let result = self.execute_compare_op(op, &left, &right)?;
self.set_value(dst, VMValue::Bool(result));
Ok(ControlFlow::Continue)
}
pub(crate) fn execute_print(&self, value: ValueId) -> Result<ControlFlow, VMError> {
let val = self.get_value(value)?;
println!("{}", val.to_string());
Ok(ControlFlow::Continue)
}
pub(crate) fn execute_jump(&self, target: BasicBlockId) -> Result<ControlFlow, VMError> { Ok(ControlFlow::Jump(target)) }
pub(crate) fn execute_branch(&self, condition: ValueId, then_bb: BasicBlockId, else_bb: BasicBlockId) -> Result<ControlFlow, VMError> {
let cond_val = self.get_value(condition)?;
let should_branch = match &cond_val {
VMValue::Bool(b) => *b,
VMValue::Void => false,
VMValue::Integer(i) => *i != 0,
VMValue::BoxRef(b) => {
if let Some(bool_box) = b.as_any().downcast_ref::<BoolBox>() { bool_box.value }
else if b.as_any().downcast_ref::<VoidBox>().is_some() { false }
else { return Err(VMError::TypeError(format!("Branch condition must be bool, void, or integer, got BoxRef({})", b.type_name()))); }
}
_ => return Err(VMError::TypeError(format!("Branch condition must be bool, void, or integer, got {:?}", cond_val))),
};
Ok(ControlFlow::Jump(if should_branch { then_bb } else { else_bb }))
}
pub(crate) fn execute_return(&self, value: Option<ValueId>) -> Result<ControlFlow, VMError> {
if let Some(val_id) = value { let return_val = self.get_value(val_id)?; Ok(ControlFlow::Return(return_val)) } else { Ok(ControlFlow::Return(VMValue::Void)) }
}
pub(crate) fn execute_typeop(&mut self, dst: ValueId, op: &TypeOpKind, value: ValueId, ty: &MirType) -> Result<ControlFlow, VMError> {
let val = self.get_value(value)?;
match op {
TypeOpKind::Check => {
let is_type = match (&val, ty) {
(VMValue::Integer(_), MirType::Integer) => true,
(VMValue::Float(_), MirType::Float) => true,
(VMValue::Bool(_), MirType::Bool) => true,
(VMValue::String(_), MirType::String) => true,
(VMValue::Void, MirType::Void) => true,
(VMValue::BoxRef(arc_box), MirType::Box(box_name)) => arc_box.type_name() == box_name,
_ => false,
};
self.set_value(dst, VMValue::Bool(is_type));
Ok(ControlFlow::Continue)
}
TypeOpKind::Cast => {
let result = match (&val, ty) {
(VMValue::Integer(i), MirType::Float) => VMValue::Float(*i as f64),
(VMValue::Float(f), MirType::Integer) => VMValue::Integer(*f as i64),
(VMValue::Integer(_), MirType::Integer) | (VMValue::Float(_), MirType::Float) | (VMValue::Bool(_), MirType::Bool) | (VMValue::String(_), MirType::String) => val.clone(),
(VMValue::BoxRef(arc_box), MirType::Box(box_name)) if arc_box.type_name() == box_name => val.clone(),
_ => { return Err(VMError::TypeError(format!("Cannot cast {:?} to {:?}", val, ty))); }
};
self.set_value(dst, result);
Ok(ControlFlow::Continue)
}
}
}
pub(crate) fn execute_phi(&mut self, dst: ValueId, inputs: &[(BasicBlockId, ValueId)]) -> Result<ControlFlow, VMError> {
let selected = self.loop_execute_phi(dst, inputs)?;
self.set_value(dst, selected);
Ok(ControlFlow::Continue)
}
pub(crate) fn execute_load(&mut self, dst: ValueId, ptr: ValueId) -> Result<ControlFlow, VMError> {
let loaded_value = self.get_value(ptr)?;
self.set_value(dst, loaded_value);
Ok(ControlFlow::Continue)
}
pub(crate) fn execute_store(&mut self, value: ValueId, ptr: ValueId) -> Result<ControlFlow, VMError> {
let val = self.get_value(value)?;
self.set_value(ptr, val);
Ok(ControlFlow::Continue)
}
pub(crate) fn execute_copy(&mut self, dst: ValueId, src: ValueId) -> Result<ControlFlow, VMError> {
let value = self.get_value(src)?;
let cloned = match &value {
VMValue::BoxRef(arc_box) => { let cloned_box = arc_box.clone_or_share(); VMValue::BoxRef(Arc::from(cloned_box)) }
other => other.clone(),
};
self.set_value(dst, cloned);
Ok(ControlFlow::Continue)
}
// ---- Arrays ----
pub(crate) fn execute_array_get(&mut self, dst: ValueId, array: ValueId, index: ValueId) -> Result<ControlFlow, VMError> {
let array_val = self.get_value(array)?;
let index_val = self.get_value(index)?;
if let VMValue::BoxRef(array_box) = &array_val {
if let Some(array) = array_box.as_any().downcast_ref::<ArrayBox>() {
let index_box = index_val.to_nyash_box();
let result = array.get(index_box);
self.set_value(dst, VMValue::BoxRef(Arc::from(result)));
Ok(ControlFlow::Continue)
} else { Err(VMError::TypeError("ArrayGet requires an ArrayBox".to_string())) }
} else { Err(VMError::TypeError("ArrayGet requires array and integer index".to_string())) }
}
pub(crate) fn execute_array_set(&mut self, array: ValueId, index: ValueId, value: ValueId) -> Result<ControlFlow, VMError> {
let array_val = self.get_value(array)?;
let index_val = self.get_value(index)?;
let value_val = self.get_value(value)?;
if let VMValue::BoxRef(array_box) = &array_val {
if let Some(array) = array_box.as_any().downcast_ref::<ArrayBox>() {
crate::backend::gc_helpers::gc_write_barrier_site(&self.runtime, "ArraySet");
let index_box = index_val.to_nyash_box();
let box_value = value_val.to_nyash_box();
array.set(index_box, box_value);
Ok(ControlFlow::Continue)
} else { Err(VMError::TypeError("ArraySet requires an ArrayBox".to_string())) }
} else { Err(VMError::TypeError("ArraySet requires array and integer index".to_string())) }
}
// ---- Refs/Weak/Barriers ----
pub(crate) fn execute_ref_new(&mut self, dst: ValueId, box_val: ValueId) -> Result<ControlFlow, VMError> {
let box_value = self.get_value(box_val)?;
self.set_value(dst, box_value);
Ok(ControlFlow::Continue)
}
pub(crate) fn execute_ref_get(&mut self, dst: ValueId, reference: ValueId, field: &str) -> Result<ControlFlow, VMError> {
let debug_ref = std::env::var("NYASH_VM_DEBUG_REF").ok().as_deref() == Some("1");
if debug_ref { eprintln!("[VM] RefGet ref={:?} field={}", reference, field); }
let is_internal = self.object_internal.contains(&reference);
if !is_internal {
if let Some(class_name) = self.object_class.get(&reference) {
if let Ok(decls) = self.runtime.box_declarations.read() {
if let Some(decl) = decls.get(class_name) {
let has_vis = !decl.public_fields.is_empty() || !decl.private_fields.is_empty();
if has_vis && !decl.public_fields.iter().any(|f| f == field) {
return Err(VMError::TypeError(format!("Field '{}' is private in {}", field, class_name)));
}
}
}
}
}
let mut field_value = if let Some(fields) = self.object_fields.get(&reference) {
if let Some(value) = fields.get(field) {
if debug_ref { eprintln!("[VM] RefGet hit: {} -> {:?}", field, value); }
value.clone()
} else {
if debug_ref { eprintln!("[VM] RefGet miss: {} -> default 0", field); }
VMValue::Integer(0)
}
} else {
if debug_ref { eprintln!("[VM] RefGet no fields: -> default 0"); }
VMValue::Integer(0)
};
if matches!(field_value, VMValue::Integer(0)) && field == "console" {
if debug_ref { eprintln!("[VM] RefGet special binding: console -> Plugin ConsoleBox"); }
let host = crate::runtime::get_global_plugin_host();
let host = host.read().unwrap();
if let Ok(pbox) = host.create_box("ConsoleBox", &[]) {
field_value = VMValue::from_nyash_box(pbox);
if !self.object_fields.contains_key(&reference) { self.object_fields.insert(reference, std::collections::HashMap::new()); }
if let Some(fields) = self.object_fields.get_mut(&reference) { fields.insert(field.to_string(), field_value.clone()); }
}
}
self.set_value(dst, field_value);
Ok(ControlFlow::Continue)
}
pub(crate) fn execute_ref_set(&mut self, reference: ValueId, field: &str, value: ValueId) -> Result<ControlFlow, VMError> {
let debug_ref = std::env::var("NYASH_VM_DEBUG_REF").ok().as_deref() == Some("1");
let new_value = self.get_value(value)?;
if debug_ref { eprintln!("[VM] RefSet ref={:?} field={} value={:?}", reference, field, new_value); }
let is_internal = self.object_internal.contains(&reference);
if !is_internal {
if let Some(class_name) = self.object_class.get(&reference) {
if let Ok(decls) = self.runtime.box_declarations.read() {
if let Some(decl) = decls.get(class_name) {
let has_vis = !decl.public_fields.is_empty() || !decl.private_fields.is_empty();
if has_vis && !decl.public_fields.iter().any(|f| f == field) {
return Err(VMError::TypeError(format!("Field '{}' is private in {}", field, class_name)));
}
}
}
}
}
if !self.object_fields.contains_key(&reference) { self.object_fields.insert(reference, std::collections::HashMap::new()); }
crate::backend::gc_helpers::gc_write_barrier_site(&self.runtime, "RefSet");
if let Some(fields) = self.object_fields.get_mut(&reference) { fields.insert(field.to_string(), new_value); if debug_ref { eprintln!("[VM] RefSet stored: {}", field); } }
Ok(ControlFlow::Continue)
}
pub(crate) fn execute_weak_new(&mut self, dst: ValueId, box_val: ValueId) -> Result<ControlFlow, VMError> {
let box_value = self.get_value(box_val)?;
self.set_value(dst, box_value);
Ok(ControlFlow::Continue)
}
pub(crate) fn execute_weak_load(&mut self, dst: ValueId, weak_ref: ValueId) -> Result<ControlFlow, VMError> {
let weak_value = self.get_value(weak_ref)?;
self.set_value(dst, weak_value);
Ok(ControlFlow::Continue)
}
pub(crate) fn execute_barrier_read(&mut self, dst: ValueId, value: ValueId) -> Result<ControlFlow, VMError> {
let val = self.get_value(value)?;
self.set_value(dst, val);
Ok(ControlFlow::Continue)
}
pub(crate) fn execute_barrier_write(&mut self, _value: ValueId) -> Result<ControlFlow, VMError> { Ok(ControlFlow::Continue) }
pub(crate) fn execute_throw(&mut self, exception: ValueId) -> Result<ControlFlow, VMError> {
let exc_value = self.get_value(exception)?;
Err(VMError::InvalidInstruction(format!("Exception thrown: {:?}", exc_value)))
}
pub(crate) fn execute_catch(&mut self, exception_value: ValueId) -> Result<ControlFlow, VMError> {
self.set_value(exception_value, VMValue::Void);
Ok(ControlFlow::Continue)
}
// ---- Futures ----
pub(crate) fn execute_await(&mut self, dst: ValueId, future: ValueId) -> Result<ControlFlow, VMError> {
let future_val = self.get_value(future)?;
if let VMValue::Future(ref future_box) = future_val {
let max_ms: u64 = crate::config::env::await_max_ms();
let start = std::time::Instant::now();
let mut spins = 0usize;
while !future_box.ready() {
self.runtime.gc.safepoint();
if let Some(s) = &self.runtime.scheduler { s.poll(); }
std::thread::yield_now();
spins += 1;
if spins % 1024 == 0 { std::thread::sleep(std::time::Duration::from_millis(1)); }
if start.elapsed() >= std::time::Duration::from_millis(max_ms) {
let err = Box::new(crate::box_trait::StringBox::new("Timeout"));
let rb = crate::boxes::result::NyashResultBox::new_err(err);
let vm_value = VMValue::from_nyash_box(Box::new(rb));
self.set_value(dst, vm_value);
return Ok(ControlFlow::Continue);
}
}
let result = future_box.get();
let ok = crate::boxes::result::NyashResultBox::new_ok(result);
let vm_value = VMValue::from_nyash_box(Box::new(ok));
self.set_value(dst, vm_value);
Ok(ControlFlow::Continue)
} else { Err(VMError::TypeError(format!("Expected Future, got {:?}", future_val))) }
}
}

View File

@ -0,0 +1,111 @@
use crate::box_trait::NyashBox;
use crate::mir::ValueId;
use crate::backend::vm::ControlFlow;
use crate::backend::{VM, VMError, VMValue};
impl VM {
/// Execute ExternCall instruction
pub(crate) fn execute_extern_call(&mut self, dst: Option<ValueId>, iface_name: &str, method_name: &str, args: &[ValueId]) -> Result<ControlFlow, VMError> {
// Optional routing to name→slot handlers for stability and diagnostics
if crate::config::env::extern_route_slots() {
if let Some(slot) = crate::runtime::extern_registry::resolve_slot(iface_name, method_name) {
// Decode args to VMValue as needed by handlers below
let vm_args: Vec<VMValue> = args.iter().filter_map(|a| self.get_value(*a).ok()).collect();
match (iface_name, method_name, slot) {
("env.console", m @ ("log" | "warn" | "error" | "println"), 10) => {
if let Some(a0) = vm_args.get(0) {
match m { "warn" => eprintln!("[warn] {}", a0.to_string()), "error" => eprintln!("[error] {}", a0.to_string()), _ => println!("{}", a0.to_string()), }
}
if let Some(d) = dst { self.set_value(d, VMValue::Void); }
return Ok(ControlFlow::Continue);
}
("env.debug", "trace", 11) => {
if let Some(a0) = vm_args.get(0) { eprintln!("[trace] {}", a0.to_string()); }
if let Some(d) = dst { self.set_value(d, VMValue::Void); }
return Ok(ControlFlow::Continue);
}
("env.runtime", "checkpoint", 12) => {
if crate::config::env::runtime_checkpoint_trace() {
let (func, bb, pc) = self.gc_site_info();
eprintln!("[rt] checkpoint @{} bb={} pc={}", func, bb, pc);
}
self.runtime.gc.safepoint();
if let Some(s) = &self.runtime.scheduler { s.poll(); }
if let Some(d) = dst { self.set_value(d, VMValue::Void); }
return Ok(ControlFlow::Continue);
}
("env.future", "new", 20) | ("env.future", "birth", 20) => {
// Create a new Future and optionally set initial value from arg0
let fut = crate::boxes::future::FutureBox::new();
if let Some(a0) = vm_args.get(0) { fut.set_result(a0.to_nyash_box()); }
if let Some(d) = dst { self.set_value(d, VMValue::Future(fut)); }
return Ok(ControlFlow::Continue);
}
("env.future", "set", 21) => {
// set(future, value)
if vm_args.len() >= 2 { if let VMValue::Future(f) = &vm_args[0] { f.set_result(vm_args[1].to_nyash_box()); } }
if let Some(d) = dst { self.set_value(d, VMValue::Void); }
return Ok(ControlFlow::Continue);
}
("env.future", "await", 22) => {
if let Some(VMValue::Future(fb)) = vm_args.get(0) {
// Simple blocking await
let start = std::time::Instant::now();
let max_ms = crate::config::env::await_max_ms();
while !fb.ready() {
std::thread::yield_now();
if start.elapsed() >= std::time::Duration::from_millis(max_ms) { break; }
}
let result = if fb.ready() { fb.get() } else { Box::new(crate::box_trait::StringBox::new("Timeout")) };
let ok = crate::boxes::result::NyashResultBox::new_ok(result);
if let Some(d) = dst { self.set_value(d, VMValue::from_nyash_box(Box::new(ok))); }
} else if let Some(d) = dst { self.set_value(d, VMValue::Void); }
return Ok(ControlFlow::Continue);
}
("env.task", "cancelCurrent", 30) => { if let Some(d) = dst { self.set_value(d, VMValue::Void); } return Ok(ControlFlow::Continue); }
("env.task", "currentToken", 31) => { if let Some(d) = dst { self.set_value(d, VMValue::Integer(0)); } return Ok(ControlFlow::Continue); }
("env.task", "yieldNow", 32) => { std::thread::yield_now(); if let Some(d) = dst { self.set_value(d, VMValue::Void); } return Ok(ControlFlow::Continue); }
("env.task", "sleepMs", 33) => {
let ms = vm_args.get(0).map(|v| match v { VMValue::Integer(i) => *i, _ => 0 }).unwrap_or(0);
if ms > 0 { std::thread::sleep(std::time::Duration::from_millis(ms as u64)); }
if let Some(d) = dst { self.set_value(d, VMValue::Void); }
return Ok(ControlFlow::Continue);
}
_ => { /* fallthrough to host */ }
}
}
}
// Evaluate arguments as NyashBox for loader
let mut nyash_args: Vec<Box<dyn NyashBox>> = Vec::new();
for arg_id in args { let arg_value = self.get_value(*arg_id)?; nyash_args.push(arg_value.to_nyash_box()); }
if crate::config::env::extern_trace() {
if let Some(slot) = crate::runtime::extern_registry::resolve_slot(iface_name, method_name) {
eprintln!("[EXT] call {}.{} slot={} argc={}", iface_name, method_name, slot, nyash_args.len());
} else { eprintln!("[EXT] call {}.{} argc={}", iface_name, method_name, nyash_args.len()); }
}
let host = crate::runtime::get_global_plugin_host();
let host = host.read().map_err(|_| VMError::InvalidInstruction("Plugin host lock poisoned".into()))?;
match host.extern_call(iface_name, method_name, &nyash_args) {
Ok(Some(result_box)) => { if let Some(dst_id) = dst { self.set_value(dst_id, VMValue::from_nyash_box(result_box)); } }
Ok(None) => { if let Some(dst_id) = dst { self.set_value(dst_id, VMValue::Void); } }
Err(_) => {
let strict = crate::config::env::extern_strict() || crate::config::env::abi_strict();
let mut msg = String::new();
if strict { msg.push_str("ExternCall STRICT: unregistered or unsupported call "); } else { msg.push_str("ExternCall failed: "); }
msg.push_str(&format!("{}.{}", iface_name, method_name));
if let Err(detail) = crate::runtime::extern_registry::check_arity(iface_name, method_name, nyash_args.len()) { msg.push_str(&format!(" ({})", detail)); }
if let Some(spec) = crate::runtime::extern_registry::resolve(iface_name, method_name) {
msg.push_str(&format!(" (expected arity {}..{})", spec.min_arity, spec.max_arity));
} else {
let known = crate::runtime::extern_registry::known_for_iface(iface_name);
if !known.is_empty() { msg.push_str(&format!("; known methods: {}", known.join(", "))); }
else { let ifaces = crate::runtime::extern_registry::all_ifaces(); msg.push_str(&format!("; known interfaces: {}", ifaces.join(", "))); }
}
return Err(VMError::InvalidInstruction(msg));
}
}
Ok(ControlFlow::Continue)
}
}

View File

@ -0,0 +1,34 @@
use crate::mir::ValueId;
use std::sync::Arc;
use crate::backend::vm::ControlFlow;
use crate::backend::{VM, VMError, VMValue};
impl VM {
/// Execute FunctionNew instruction (construct a FunctionBox value)
pub(crate) fn execute_function_new(
&mut self,
dst: ValueId,
params: &[String],
body: &[crate::ast::ASTNode],
captures: &[(String, ValueId)],
me: &Option<ValueId>,
) -> Result<ControlFlow, VMError> {
// Build ClosureEnv
let mut env = crate::boxes::function_box::ClosureEnv::new();
// Add captures by value
for (name, vid) in captures.iter() {
let v = self.get_value(*vid)?;
env.captures.insert(name.clone(), v.to_nyash_box());
}
// Capture 'me' weakly if provided and is a BoxRef
if let Some(m) = me {
match self.get_value(*m)? {
VMValue::BoxRef(b) => { env.me_value = Some(Arc::downgrade(&b)); }
_ => {}
}
}
let fun = crate::boxes::function_box::FunctionBox::with_env(params.to_vec(), body.to_vec(), env);
self.set_value(dst, VMValue::BoxRef(Arc::new(fun)));
Ok(ControlFlow::Continue)
}
}

View File

@ -0,0 +1,15 @@
/*!
* VM Instruction Handlers (split modules)
*
* This module was split to keep files under ~1000 lines while preserving
* behavior and public APIs. Methods remain as `impl VM` across submodules.
*/
pub mod core; // const/binop/unary/compare/print/ctrl/type/phi/mem/array/refs/weak/barriers/exn/await
pub mod call; // execute_call (Function name or FunctionBox)
pub mod newbox; // execute_newbox
pub mod function_new; // execute_function_new
pub mod extern_call; // execute_extern_call
pub mod boxcall; // execute_boxcall + vtable stub
pub mod plugin_invoke; // execute_plugin_invoke + helpers

View File

@ -0,0 +1,47 @@
use crate::box_trait::NyashBox;
use crate::mir::ValueId;
use std::sync::Arc;
use crate::backend::vm::ControlFlow;
use crate::backend::{VM, VMError, VMValue};
impl VM {
/// Execute NewBox instruction
pub(crate) fn execute_newbox(&mut self, dst: ValueId, box_type: &str, args: &[ValueId]) -> Result<ControlFlow, VMError> {
// Convert args to NyashBox values
let arg_values: Vec<Box<dyn NyashBox>> = args.iter()
.map(|arg| {
let val = self.get_value(*arg)?;
Ok(val.to_nyash_box())
})
.collect::<Result<Vec<_>, VMError>>()?;
// Create new box using runtime's registry
let new_box = {
let registry = self.runtime.box_registry.lock()
.map_err(|_| VMError::InvalidInstruction("Failed to lock box registry".to_string()))?;
registry.create_box(box_type, &arg_values)
.map_err(|e| VMError::InvalidInstruction(format!("Failed to create {}: {}", box_type, e)))?
};
// 80/20: Basic boxes are stored as primitives in VMValue for simpler ops
if box_type == "IntegerBox" {
if let Some(ib) = new_box.as_any().downcast_ref::<crate::box_trait::IntegerBox>() {
self.set_value(dst, VMValue::Integer(ib.value));
return Ok(ControlFlow::Continue);
}
} else if box_type == "BoolBox" {
if let Some(bb) = new_box.as_any().downcast_ref::<crate::box_trait::BoolBox>() {
self.set_value(dst, VMValue::Bool(bb.value));
return Ok(ControlFlow::Continue);
}
} else if box_type == "StringBox" {
if let Some(sb) = new_box.as_any().downcast_ref::<crate::box_trait::StringBox>() {
self.set_value(dst, VMValue::String(sb.value.clone()));
return Ok(ControlFlow::Continue);
}
}
self.set_value(dst, VMValue::BoxRef(Arc::from(new_box)));
Ok(ControlFlow::Continue)
}
}

View File

@ -0,0 +1,154 @@
use crate::mir::ValueId;
use std::sync::Arc;
use crate::backend::vm::ControlFlow;
use crate::backend::{VM, VMError, VMValue};
impl VM {
/// Execute a forced plugin invocation (no builtin fallback)
pub(crate) fn execute_plugin_invoke(&mut self, dst: Option<ValueId>, box_val: ValueId, method: &str, args: &[ValueId]) -> Result<ControlFlow, VMError> {
// Helper: extract UTF-8 string from internal StringBox, Result.Ok(String-like), or plugin StringBox via toUtf8
fn extract_string_from_box(bx: &dyn crate::box_trait::NyashBox) -> Option<String> {
if let Some(sb) = bx.as_any().downcast_ref::<crate::box_trait::StringBox>() { return Some(sb.value.clone()); }
if let Some(res) = bx.as_any().downcast_ref::<crate::boxes::result::NyashResultBox>() {
if let crate::boxes::result::NyashResultBox::Ok(inner) = res { return extract_string_from_box(inner.as_ref()); }
}
if let Some(p) = bx.as_any().downcast_ref::<crate::runtime::plugin_loader_v2::PluginBoxV2>() {
if p.box_type == "StringBox" {
let host = crate::runtime::get_global_plugin_host();
let tmp: Option<String> = if let Ok(ro) = host.read() {
if let Ok(val_opt) = ro.invoke_instance_method("StringBox", "toUtf8", p.inner.instance_id, &[]) {
if let Some(vb) = val_opt { if let Some(sb2) = vb.as_any().downcast_ref::<crate::box_trait::StringBox>() { Some(sb2.value.clone()) } else { None } } else { None }
} else { None }
} else { None };
if tmp.is_some() { return tmp; }
}
}
None
}
let recv = self.get_value(box_val)?;
if method == "birth" && !matches!(recv, VMValue::BoxRef(ref b) if b.as_any().downcast_ref::<crate::runtime::plugin_loader_v2::PluginBoxV2>().is_some()) {
eprintln!("[VM PluginInvoke] static birth fallback recv={:?}", recv);
let mut created: Option<VMValue> = None;
match &recv {
VMValue::String(s) => {
let host = crate::runtime::get_global_plugin_host();
let host = host.read().unwrap();
let sb: Box<dyn crate::box_trait::NyashBox> = Box::new(crate::box_trait::StringBox::new(s.clone()));
if let Ok(b) = host.create_box("StringBox", &[sb]) { created = Some(VMValue::from_nyash_box(b)); }
}
VMValue::Integer(_n) => {
let host = crate::runtime::get_global_plugin_host();
let host = host.read().unwrap();
if let Ok(b) = host.create_box("IntegerBox", &[]) { created = Some(VMValue::from_nyash_box(b)); }
}
_ => {}
}
if let Some(val) = created { if let Some(dst_id) = dst { self.set_value(dst_id, val); } return Ok(ControlFlow::Continue); }
}
if let VMValue::BoxRef(pbox) = &recv {
if let Some(p) = pbox.as_any().downcast_ref::<crate::runtime::plugin_loader_v2::PluginBoxV2>() {
let host = crate::runtime::get_global_plugin_host();
let host = host.read().unwrap();
let mh = host.resolve_method(&p.box_type, method).map_err(|_| VMError::InvalidInstruction(format!("Plugin method not found: {}.{}", p.box_type, method)))?;
let mut tlv = crate::runtime::plugin_ffi_common::encode_tlv_header(args.len() as u16);
for (idx, a) in args.iter().enumerate() {
let v = self.get_value(*a)?;
match v {
VMValue::Integer(n) => { if std::env::var("NYASH_DEBUG_PLUGIN").ok().as_deref() == Some("1") { eprintln!("[VM→Plugin][vm] arg[{}] encode I64 {}", idx, n); } crate::runtime::plugin_ffi_common::encode::i64(&mut tlv, n) }
VMValue::Float(x) => { if std::env::var("NYASH_DEBUG_PLUGIN").ok().as_deref() == Some("1") { eprintln!("[VM→Plugin][vm] arg[{}] encode F64 {}", idx, x); } crate::runtime::plugin_ffi_common::encode::f64(&mut tlv, x) }
VMValue::Bool(b) => crate::runtime::plugin_ffi_common::encode::bool(&mut tlv, b),
VMValue::String(ref s) => crate::runtime::plugin_ffi_common::encode::string(&mut tlv, s),
VMValue::BoxRef(ref b) => {
if let Some(h) = b.as_any().downcast_ref::<crate::runtime::plugin_loader_v2::PluginBoxV2>() {
if h.box_type == "StringBox" {
let host = crate::runtime::get_global_plugin_host();
let host = host.read().unwrap();
if let Ok(val_opt) = host.invoke_instance_method("StringBox", "toUtf8", h.inner.instance_id, &[]) {
if let Some(sb) = val_opt.and_then(|bx| bx.as_any().downcast_ref::<crate::box_trait::StringBox>().map(|s| s.value.clone())) { crate::runtime::plugin_ffi_common::encode::string(&mut tlv, &sb); continue; }
}
} else if h.box_type == "IntegerBox" {
let host = crate::runtime::get_global_plugin_host();
let host = host.read().unwrap();
if let Ok(val_opt) = host.invoke_instance_method("IntegerBox", "get", h.inner.instance_id, &[]) {
if let Some(ib) = val_opt.and_then(|bx| bx.as_any().downcast_ref::<crate::box_trait::IntegerBox>().map(|i| i.value)) { crate::runtime::plugin_ffi_common::encode::i64(&mut tlv, ib); continue; }
}
}
crate::runtime::plugin_ffi_common::encode::plugin_handle(&mut tlv, h.inner.type_id, h.inner.instance_id);
} else {
let h = crate::runtime::host_handles::to_handle_arc(b.clone());
crate::runtime::plugin_ffi_common::encode::host_handle(&mut tlv, h);
}
}
VMValue::Future(_) | VMValue::Void => {}
}
}
let mut out = vec![0u8; 32768];
let mut out_len: usize = out.len();
unsafe { (p.inner.invoke_fn)(p.inner.type_id, mh.method_id as u32, p.inner.instance_id, tlv.as_ptr(), tlv.len(), out.as_mut_ptr(), &mut out_len) };
let vm_out_raw: VMValue = if let Some((tag, _sz, payload)) = crate::runtime::plugin_ffi_common::decode::tlv_first(&out[..out_len]) {
match tag {
1 => crate::runtime::plugin_ffi_common::decode::bool(payload).map(VMValue::Bool).unwrap_or(VMValue::Void),
2 => crate::runtime::plugin_ffi_common::decode::i32(payload).map(|v| VMValue::Integer(v as i64)).unwrap_or(VMValue::Void),
5 => crate::runtime::plugin_ffi_common::decode::f64(payload).map(VMValue::Float).unwrap_or(VMValue::Void),
6 | 7 => VMValue::String(crate::runtime::plugin_ffi_common::decode::string(payload)),
8 => {
if let Some(u) = crate::runtime::plugin_ffi_common::decode::u64(payload) {
if let Some(arc) = crate::runtime::host_handles::get(u) { VMValue::BoxRef(arc) } else { VMValue::Void }
} else { VMValue::Void }
}
_ => VMValue::Void,
}
} else { VMValue::Void };
// Wrap into Result.Ok when method is declared returns_result
let vm_out = {
let host = crate::runtime::get_global_plugin_host();
let host = host.read().unwrap();
let rr = host.method_returns_result(&p.box_type, method);
if rr {
let boxed: Box<dyn crate::box_trait::NyashBox> = match vm_out_raw {
VMValue::Integer(i) => Box::new(crate::box_trait::IntegerBox::new(i)),
VMValue::Float(f) => Box::new(crate::boxes::math_box::FloatBox::new(f)),
VMValue::Bool(b) => Box::new(crate::box_trait::BoolBox::new(b)),
VMValue::String(s) => Box::new(crate::box_trait::StringBox::new(s)),
VMValue::BoxRef(b) => b.share_box(),
VMValue::Void => Box::new(crate::box_trait::VoidBox::new()),
_ => Box::new(crate::box_trait::StringBox::new(vm_out_raw.to_string()))
};
let res = crate::boxes::result::NyashResultBox::new_ok(boxed);
VMValue::BoxRef(std::sync::Arc::from(Box::new(res) as Box<dyn crate::box_trait::NyashBox>))
} else { vm_out_raw }
};
if let Some(dst_id) = dst { self.set_value(dst_id, vm_out); }
return Ok(ControlFlow::Continue);
}
}
// Fallback: support common string-like methods without requiring PluginBox receiver
if let VMValue::BoxRef(ref bx) = recv {
if let Some(s) = extract_string_from_box(bx.as_ref()) {
match method {
"length" => { if let Some(dst_id) = dst { self.set_value(dst_id, VMValue::Integer(s.len() as i64)); } return Ok(ControlFlow::Continue); }
"is_empty" | "isEmpty" => { if let Some(dst_id) = dst { self.set_value(dst_id, VMValue::Bool(s.is_empty())); } return Ok(ControlFlow::Continue); }
"charCodeAt" => {
let idx_v = if let Some(a0) = args.get(0) { self.get_value(*a0)? } else { VMValue::Integer(0) };
let idx = match idx_v { VMValue::Integer(i) => i.max(0) as usize, _ => 0 };
let code = s.chars().nth(idx).map(|c| c as u32 as i64).unwrap_or(0);
if let Some(dst_id) = dst { self.set_value(dst_id, VMValue::Integer(code)); }
return Ok(ControlFlow::Continue);
}
"concat" => {
let rhs_v = if let Some(a0) = args.get(0) { self.get_value(*a0)? } else { VMValue::String(String::new()) };
let rhs_s = match rhs_v { VMValue::String(ss) => ss, VMValue::BoxRef(br) => extract_string_from_box(br.as_ref()).unwrap_or_else(|| br.to_string_box().value), _ => rhs_v.to_string(), };
let mut new_s = s.clone();
new_s.push_str(&rhs_s);
let out = Box::new(crate::box_trait::StringBox::new(new_s));
if let Some(dst_id) = dst { self.set_value(dst_id, VMValue::BoxRef(std::sync::Arc::from(out as Box<dyn crate::box_trait::NyashBox>))); }
return Ok(ControlFlow::Continue);
}
_ => {}
}
}
}
Err(VMError::InvalidInstruction(format!("PluginInvoke requires PluginBox receiver; method={} got {:?}", method, recv)))
}
}

193
src/backend/vm_state.rs Normal file
View File

@ -0,0 +1,193 @@
/*!
* VM State & Basics
*
* Contains constructor helpers, basic value storage, instruction accounting,
* phi selection delegation, and small utilities that support the exec loop.
*/
use super::vm::{VM, VMError, VMValue};
use super::vm_phi::LoopExecutor;
use super::frame::ExecutionFrame;
use crate::mir::{BasicBlockId, ValueId};
use crate::runtime::NyashRuntime;
use crate::scope_tracker::ScopeTracker;
use std::collections::HashMap;
use std::time::Instant;
impl VM {
fn jit_threshold_from_env() -> u32 {
std::env::var("NYASH_JIT_THRESHOLD")
.ok()
.and_then(|s| s.parse::<u32>().ok())
.filter(|&v| v > 0)
.unwrap_or(64)
}
/// Helper: execute phi via LoopExecutor with previous_block-based selection
pub(super) fn loop_execute_phi(
&mut self,
dst: ValueId,
inputs: &[(BasicBlockId, ValueId)],
) -> Result<VMValue, VMError> {
if inputs.is_empty() {
return Err(VMError::InvalidInstruction("Phi node has no inputs".to_string()));
}
let debug_phi = std::env::var("NYASH_VM_DEBUG").ok().as_deref() == Some("1")
|| std::env::var("NYASH_VM_DEBUG_PHI").ok().as_deref() == Some("1");
if debug_phi {
eprintln!(
"[VM] phi-select (delegated) prev={:?} inputs={:?}",
self.previous_block, inputs
);
}
let values_ref = &self.values;
let res = self.loop_executor.execute_phi(dst, inputs, |val_id| {
let index = val_id.to_usize();
if index < values_ref.len() {
if let Some(ref value) = values_ref[index] {
Ok(value.clone())
} else {
Err(VMError::InvalidValue(format!("Value {} not set", val_id)))
}
} else {
Err(VMError::InvalidValue(format!("Value {} out of bounds", val_id)))
}
});
if debug_phi {
match &res {
Ok(v) => eprintln!("[VM] phi-result -> {:?}", v),
Err(e) => eprintln!("[VM] phi-error -> {:?}", e),
}
}
res
}
/// Create a new VM instance
pub fn new() -> Self {
Self {
values: Vec::new(),
current_function: None,
frame: ExecutionFrame::new(),
previous_block: None,
object_fields: HashMap::new(),
object_class: HashMap::new(),
object_internal: std::collections::HashSet::new(),
loop_executor: LoopExecutor::new(),
runtime: NyashRuntime::new(),
scope_tracker: ScopeTracker::new(),
module: None,
instr_counter: std::collections::HashMap::new(),
exec_start: None,
boxcall_hits_vtable: 0,
boxcall_hits_poly_pic: 0,
boxcall_hits_mono_pic: 0,
boxcall_hits_generic: 0,
boxcall_pic_hits: std::collections::HashMap::new(),
boxcall_pic_funcname: std::collections::HashMap::new(),
boxcall_poly_pic: std::collections::HashMap::new(),
boxcall_vtable_funcname: std::collections::HashMap::new(),
type_versions: std::collections::HashMap::new(),
jit_manager: Some(crate::jit::manager::JitManager::new(Self::jit_threshold_from_env())),
}
}
/// Create a VM with an external runtime (dependency injection)
pub fn with_runtime(runtime: NyashRuntime) -> Self {
Self {
values: Vec::new(),
current_function: None,
frame: ExecutionFrame::new(),
previous_block: None,
object_fields: HashMap::new(),
object_class: HashMap::new(),
object_internal: std::collections::HashSet::new(),
loop_executor: LoopExecutor::new(),
runtime,
scope_tracker: ScopeTracker::new(),
module: None,
instr_counter: std::collections::HashMap::new(),
exec_start: None,
boxcall_hits_vtable: 0,
boxcall_hits_poly_pic: 0,
boxcall_hits_mono_pic: 0,
boxcall_hits_generic: 0,
boxcall_pic_hits: std::collections::HashMap::new(),
boxcall_pic_funcname: std::collections::HashMap::new(),
boxcall_poly_pic: std::collections::HashMap::new(),
boxcall_vtable_funcname: std::collections::HashMap::new(),
type_versions: std::collections::HashMap::new(),
jit_manager: Some(crate::jit::manager::JitManager::new(Self::jit_threshold_from_env())),
}
}
/// Get a value from storage
pub(super) fn get_value(&self, value_id: ValueId) -> Result<VMValue, VMError> {
let index = value_id.to_usize();
if index < self.values.len() {
if let Some(ref value) = self.values[index] {
Ok(value.clone())
} else {
Err(VMError::InvalidValue(format!("Value {} not set", value_id)))
}
} else {
Err(VMError::InvalidValue(format!("Value {} out of bounds", value_id)))
}
}
/// Set a value in the VM storage
pub(super) fn set_value(&mut self, value_id: ValueId, value: VMValue) {
let index = value_id.to_usize();
if index >= self.values.len() {
self.values.resize(index + 1, None);
}
self.values[index] = Some(value);
}
/// Record an instruction execution for statistics
pub(super) fn record_instruction(&mut self, instruction: &crate::mir::MirInstruction) {
let key: &'static str = match instruction {
crate::mir::MirInstruction::Const { .. } => "Const",
crate::mir::MirInstruction::BinOp { .. } => "BinOp",
crate::mir::MirInstruction::UnaryOp { .. } => "UnaryOp",
crate::mir::MirInstruction::Compare { .. } => "Compare",
crate::mir::MirInstruction::Load { .. } => "Load",
crate::mir::MirInstruction::Store { .. } => "Store",
crate::mir::MirInstruction::Call { .. } => "Call",
crate::mir::MirInstruction::FunctionNew { .. } => "FunctionNew",
crate::mir::MirInstruction::BoxCall { .. } => "BoxCall",
crate::mir::MirInstruction::Branch { .. } => "Branch",
crate::mir::MirInstruction::Jump { .. } => "Jump",
crate::mir::MirInstruction::Return { .. } => "Return",
crate::mir::MirInstruction::Phi { .. } => "Phi",
crate::mir::MirInstruction::NewBox { .. } => "NewBox",
crate::mir::MirInstruction::TypeCheck { .. } => "TypeCheck",
crate::mir::MirInstruction::Cast { .. } => "Cast",
crate::mir::MirInstruction::TypeOp { .. } => "TypeOp",
crate::mir::MirInstruction::ArrayGet { .. } => "ArrayGet",
crate::mir::MirInstruction::ArraySet { .. } => "ArraySet",
crate::mir::MirInstruction::Copy { .. } => "Copy",
crate::mir::MirInstruction::Debug { .. } => "Debug",
crate::mir::MirInstruction::Print { .. } => "Print",
crate::mir::MirInstruction::Nop => "Nop",
crate::mir::MirInstruction::Throw { .. } => "Throw",
crate::mir::MirInstruction::Catch { .. } => "Catch",
crate::mir::MirInstruction::Safepoint => "Safepoint",
crate::mir::MirInstruction::RefNew { .. } => "RefNew",
crate::mir::MirInstruction::RefGet { .. } => "RefGet",
crate::mir::MirInstruction::RefSet { .. } => "RefSet",
crate::mir::MirInstruction::WeakNew { .. } => "WeakNew",
crate::mir::MirInstruction::WeakLoad { .. } => "WeakLoad",
crate::mir::MirInstruction::BarrierRead { .. } => "BarrierRead",
crate::mir::MirInstruction::BarrierWrite { .. } => "BarrierWrite",
crate::mir::MirInstruction::WeakRef { .. } => "WeakRef",
crate::mir::MirInstruction::Barrier { .. } => "Barrier",
crate::mir::MirInstruction::FutureNew { .. } => "FutureNew",
crate::mir::MirInstruction::FutureSet { .. } => "FutureSet",
crate::mir::MirInstruction::Await { .. } => "Await",
crate::mir::MirInstruction::ExternCall { .. } => "ExternCall",
crate::mir::MirInstruction::PluginInvoke { .. } => "PluginInvoke",
};
*self.instr_counter.entry(key).or_insert(0) += 1;
}
}