Files
hakorune/src/backend/mir_interpreter/handlers/extern_provider.rs

315 lines
18 KiB
Rust
Raw Normal View History

use super::*;
use super::super::utils::*;
use serde_json::Value as JsonValue;
impl MirInterpreter {
Phase 22.1 WIP: SSOT resolver + TLV infrastructure + Hako MIR builder setup Setup infrastructure for Phase 22.1 (TLV C shim & Resolver SSOT): Core changes: - Add nyash_tlv, nyash_c_core, nyash_kernel_min_c crates (opt-in) - Implement SSOT resolver bridge (src/using/ssot_bridge.rs) - Add HAKO_USING_SSOT=1 / HAKO_USING_SSOT_HAKO=1 env support - Add HAKO_TLV_SHIM=1 infrastructure (requires --features tlv-shim) MIR builder improvements: - Fix using/alias consistency in Hako MIR builder - Add hako.mir.builder.internal.{prog_scan,pattern_util} to nyash.toml - Normalize LLVM extern calls: nyash.console.* → nyash_console_* Smoke tests: - Add phase2211 tests (using_ssot_hako_parity_canary_vm.sh) - Add phase2220, phase2230, phase2231 test structure - Add phase2100 S3 backend selector tests - Improve test_runner.sh with quiet/timeout controls Documentation: - Add docs/ENV_VARS.md (Phase 22.1 env vars reference) - Add docs/development/runtime/C_CORE_ABI.md - Update de-rust-roadmap.md with Phase 22.x details Tools: - Add tools/hakorune_emit_mir.sh (Hako-first MIR emission wrapper) - Add tools/tlv_roundtrip_smoke.sh placeholder - Improve ny_mir_builder.sh with better backend selection Known issues (to be fixed): - Parser infinite loop in static method parameter parsing - Stage-B output contamination with "RC: 0" (needs NYASH_JSON_ONLY=1) - phase2211/using_ssot_hako_parity_canary_vm.sh fork bomb (needs recursion guard) Next steps: Fix parser infinite loop + Stage-B quiet mode for green tests
2025-11-09 15:11:18 +09:00
#[inline]
fn should_trace_call_extern(target: &str, method: &str) -> bool {
if let Ok(flt) = std::env::var("HAKO_CALL_TRACE_FILTER") {
let key = format!("{}.{}", target, method);
for pat in flt.split(',') {
let p = pat.trim();
if p.is_empty() { continue; }
if p == method || p == key { return true; }
}
return false;
}
true
}
fn patch_mir_json_version(s: &str) -> String {
match serde_json::from_str::<JsonValue>(s) {
Ok(mut v) => {
if let JsonValue::Object(ref mut m) = v {
if !m.contains_key("version") {
m.insert("version".to_string(), JsonValue::from(0));
if let Ok(out) = serde_json::to_string(&v) { return out; }
}
}
s.to_string()
}
Err(_) => s.to_string(),
}
}
/// Central extern dispatcher used by both execute_extern_function (calls.rs)
/// and handle_extern_call (externals.rs). Returns a VMValue; callers are
/// responsible for writing it to registers when needed.
pub(super) fn extern_provider_dispatch(
&mut self,
extern_name: &str,
args: &[ValueId],
) -> Option<Result<VMValue, VMError>> {
Phase 22.1 WIP: SSOT resolver + TLV infrastructure + Hako MIR builder setup Setup infrastructure for Phase 22.1 (TLV C shim & Resolver SSOT): Core changes: - Add nyash_tlv, nyash_c_core, nyash_kernel_min_c crates (opt-in) - Implement SSOT resolver bridge (src/using/ssot_bridge.rs) - Add HAKO_USING_SSOT=1 / HAKO_USING_SSOT_HAKO=1 env support - Add HAKO_TLV_SHIM=1 infrastructure (requires --features tlv-shim) MIR builder improvements: - Fix using/alias consistency in Hako MIR builder - Add hako.mir.builder.internal.{prog_scan,pattern_util} to nyash.toml - Normalize LLVM extern calls: nyash.console.* → nyash_console_* Smoke tests: - Add phase2211 tests (using_ssot_hako_parity_canary_vm.sh) - Add phase2220, phase2230, phase2231 test structure - Add phase2100 S3 backend selector tests - Improve test_runner.sh with quiet/timeout controls Documentation: - Add docs/ENV_VARS.md (Phase 22.1 env vars reference) - Add docs/development/runtime/C_CORE_ABI.md - Update de-rust-roadmap.md with Phase 22.x details Tools: - Add tools/hakorune_emit_mir.sh (Hako-first MIR emission wrapper) - Add tools/tlv_roundtrip_smoke.sh placeholder - Improve ny_mir_builder.sh with better backend selection Known issues (to be fixed): - Parser infinite loop in static method parameter parsing - Stage-B output contamination with "RC: 0" (needs NYASH_JSON_ONLY=1) - phase2211/using_ssot_hako_parity_canary_vm.sh fork bomb (needs recursion guard) Next steps: Fix parser infinite loop + Stage-B quiet mode for green tests
2025-11-09 15:11:18 +09:00
// Unified call trace (optional)
if std::env::var("HAKO_CALL_TRACE").ok().as_deref() == Some("1") {
// Split iface.method for filtering
if let Some((iface, method)) = extern_name.rsplit_once('.') {
if Self::should_trace_call_extern(iface, method) {
eprintln!("[call:{}.{}]", iface, method);
}
} else {
// Fallback: no dot in extern name (e.g., 'print')
if Self::should_trace_call_extern("", extern_name) {
eprintln!("[call:{}]", extern_name);
}
}
}
match extern_name {
// Console family (minimal)
"nyash.console.log" | "env.console.log" | "print" | "nyash.builtin.print" => {
let s = if let Some(a0) = args.get(0) { self.reg_load(*a0).ok() } else { None };
if let Some(v) = s { println!("{}", v.to_string()); } else { println!(""); }
Some(Ok(VMValue::Void))
}
"env.console.warn" | "nyash.console.warn" => {
let s = if let Some(a0) = args.get(0) { self.reg_load(*a0).ok() } else { None };
if let Some(v) = s { eprintln!("[warn] {}", v.to_string()); } else { eprintln!("[warn]"); }
Some(Ok(VMValue::Void))
}
"env.console.error" | "nyash.console.error" => {
let s = if let Some(a0) = args.get(0) { self.reg_load(*a0).ok() } else { None };
if let Some(v) = s { eprintln!("[error] {}", v.to_string()); } else { eprintln!("[error]"); }
Some(Ok(VMValue::Void))
}
// Extern providers (env.mirbuilder / env.codegen)
"env.mirbuilder.emit" => {
// Guarded stub path for verify/Hakorune-primary bring-up
if std::env::var("HAKO_V1_EXTERN_PROVIDER").ok().as_deref() == Some("1") {
return Some(Ok(VMValue::String(String::new())));
}
refactor: unify error message generation (Phase 3) Add ErrorBuilder utility and migrate 35 error generation sites Phase 3: Error Message Generation Unification ============================================ Infrastructure: - Add src/backend/mir_interpreter/utils/error_helpers.rs (255 lines) - Implement ErrorBuilder with 7 standardized error patterns - Add MirInterpreter convenience methods (err_invalid, err_type_mismatch, etc.) Migration Results: - Total patterns migrated: 35 instances (80 → 45, 44% reduction) - calls.rs: 37 → 13 patterns (65% reduction) - extern_provider.rs: 20 → 9 patterns (55% reduction) - Lines saved: 33 lines (1.0% of handlers) Error Patterns Unified: 1. Invalid instruction errors → ErrorBuilder::invalid_instruction() 2. Type mismatch errors → ErrorBuilder::type_mismatch() 3. Argument count errors → ErrorBuilder::arg_count_mismatch() 4. Method not found → ErrorBuilder::method_not_found() 5. Unsupported operations → ErrorBuilder::unsupported_operation() 6. Context errors → ErrorBuilder::with_context() 7. Bounds errors → ErrorBuilder::out_of_bounds() Benefits: - Consistent error message formatting across all handlers - Single point of change for error improvements - Better IDE autocomplete support - Easier future i18n integration - Reduced code duplication Cumulative Impact (Phase 1+2+3): - Total lines saved: 150-187 lines (4.5-5.7% of handlers) - Total patterns unified: 124 instances * Phase 1: 37 destination patterns * Phase 2: 52 argument validation patterns * Phase 3: 35 error generation patterns Remaining Work: - 45 error patterns still to migrate (estimated 50-80 lines) - Complex cases requiring manual review Testing: - Build: ✅ 0 errors, 0 new warnings - Smoke tests: ⚠️ 8/9 passed (1 timeout unrelated) - Core functionality: ✅ Verified Related: Phase 21.0 MIR Interpreter refactoring Risk: Low (error messages only, behavior preserved) Impact: High (maintainability, consistency, i18n-ready) Co-authored-by: Claude Code <claude@anthropic.com>
2025-11-06 23:18:10 +09:00
if args.is_empty() { return Some(Err(ErrorBuilder::arg_count_mismatch("env.mirbuilder.emit", 1, args.len()))); }
let program_json = match self.reg_load(args[0]) { Ok(v) => v.to_string(), Err(e) => return Some(Err(e)) };
let res = match crate::host_providers::mir_builder::program_json_to_mir_json(&program_json) {
Ok(s) => Ok(VMValue::String(Self::patch_mir_json_version(&s))),
refactor: unify error message generation (Phase 3) Add ErrorBuilder utility and migrate 35 error generation sites Phase 3: Error Message Generation Unification ============================================ Infrastructure: - Add src/backend/mir_interpreter/utils/error_helpers.rs (255 lines) - Implement ErrorBuilder with 7 standardized error patterns - Add MirInterpreter convenience methods (err_invalid, err_type_mismatch, etc.) Migration Results: - Total patterns migrated: 35 instances (80 → 45, 44% reduction) - calls.rs: 37 → 13 patterns (65% reduction) - extern_provider.rs: 20 → 9 patterns (55% reduction) - Lines saved: 33 lines (1.0% of handlers) Error Patterns Unified: 1. Invalid instruction errors → ErrorBuilder::invalid_instruction() 2. Type mismatch errors → ErrorBuilder::type_mismatch() 3. Argument count errors → ErrorBuilder::arg_count_mismatch() 4. Method not found → ErrorBuilder::method_not_found() 5. Unsupported operations → ErrorBuilder::unsupported_operation() 6. Context errors → ErrorBuilder::with_context() 7. Bounds errors → ErrorBuilder::out_of_bounds() Benefits: - Consistent error message formatting across all handlers - Single point of change for error improvements - Better IDE autocomplete support - Easier future i18n integration - Reduced code duplication Cumulative Impact (Phase 1+2+3): - Total lines saved: 150-187 lines (4.5-5.7% of handlers) - Total patterns unified: 124 instances * Phase 1: 37 destination patterns * Phase 2: 52 argument validation patterns * Phase 3: 35 error generation patterns Remaining Work: - 45 error patterns still to migrate (estimated 50-80 lines) - Complex cases requiring manual review Testing: - Build: ✅ 0 errors, 0 new warnings - Smoke tests: ⚠️ 8/9 passed (1 timeout unrelated) - Core functionality: ✅ Verified Related: Phase 21.0 MIR Interpreter refactoring Risk: Low (error messages only, behavior preserved) Impact: High (maintainability, consistency, i18n-ready) Co-authored-by: Claude Code <claude@anthropic.com>
2025-11-06 23:18:10 +09:00
Err(e) => Err(ErrorBuilder::with_context("env.mirbuilder.emit", &e.to_string())),
};
Some(res)
}
"env.codegen.emit_object" => {
// Guarded stub path for verify/Hakorune-primary bring-up
if std::env::var("HAKO_V1_EXTERN_PROVIDER").ok().as_deref() == Some("1") {
return Some(Ok(VMValue::String(String::new())));
}
refactor: unify error message generation (Phase 3) Add ErrorBuilder utility and migrate 35 error generation sites Phase 3: Error Message Generation Unification ============================================ Infrastructure: - Add src/backend/mir_interpreter/utils/error_helpers.rs (255 lines) - Implement ErrorBuilder with 7 standardized error patterns - Add MirInterpreter convenience methods (err_invalid, err_type_mismatch, etc.) Migration Results: - Total patterns migrated: 35 instances (80 → 45, 44% reduction) - calls.rs: 37 → 13 patterns (65% reduction) - extern_provider.rs: 20 → 9 patterns (55% reduction) - Lines saved: 33 lines (1.0% of handlers) Error Patterns Unified: 1. Invalid instruction errors → ErrorBuilder::invalid_instruction() 2. Type mismatch errors → ErrorBuilder::type_mismatch() 3. Argument count errors → ErrorBuilder::arg_count_mismatch() 4. Method not found → ErrorBuilder::method_not_found() 5. Unsupported operations → ErrorBuilder::unsupported_operation() 6. Context errors → ErrorBuilder::with_context() 7. Bounds errors → ErrorBuilder::out_of_bounds() Benefits: - Consistent error message formatting across all handlers - Single point of change for error improvements - Better IDE autocomplete support - Easier future i18n integration - Reduced code duplication Cumulative Impact (Phase 1+2+3): - Total lines saved: 150-187 lines (4.5-5.7% of handlers) - Total patterns unified: 124 instances * Phase 1: 37 destination patterns * Phase 2: 52 argument validation patterns * Phase 3: 35 error generation patterns Remaining Work: - 45 error patterns still to migrate (estimated 50-80 lines) - Complex cases requiring manual review Testing: - Build: ✅ 0 errors, 0 new warnings - Smoke tests: ⚠️ 8/9 passed (1 timeout unrelated) - Core functionality: ✅ Verified Related: Phase 21.0 MIR Interpreter refactoring Risk: Low (error messages only, behavior preserved) Impact: High (maintainability, consistency, i18n-ready) Co-authored-by: Claude Code <claude@anthropic.com>
2025-11-06 23:18:10 +09:00
if args.is_empty() { return Some(Err(ErrorBuilder::arg_count_mismatch("env.codegen.emit_object", 1, args.len()))); }
let mir_json_raw = match self.reg_load(args[0]) { Ok(v) => v.to_string(), Err(e) => return Some(Err(e)) };
// Normalize to v1 shape if missing/legacy (prevents harness NoneType errors)
let mir_json = Self::patch_mir_json_version(&mir_json_raw);
let opts = crate::host_providers::llvm_codegen::Opts {
out: None,
nyrt: std::env::var("NYASH_EMIT_EXE_NYRT").ok().map(std::path::PathBuf::from),
opt_level: std::env::var("HAKO_LLVM_OPT_LEVEL").ok().or(Some("0".to_string())),
timeout_ms: None,
};
let res = match crate::host_providers::llvm_codegen::mir_json_to_object(&mir_json, opts) {
Ok(p) => Ok(VMValue::String(p.to_string_lossy().into_owned())),
refactor: unify error message generation (Phase 3) Add ErrorBuilder utility and migrate 35 error generation sites Phase 3: Error Message Generation Unification ============================================ Infrastructure: - Add src/backend/mir_interpreter/utils/error_helpers.rs (255 lines) - Implement ErrorBuilder with 7 standardized error patterns - Add MirInterpreter convenience methods (err_invalid, err_type_mismatch, etc.) Migration Results: - Total patterns migrated: 35 instances (80 → 45, 44% reduction) - calls.rs: 37 → 13 patterns (65% reduction) - extern_provider.rs: 20 → 9 patterns (55% reduction) - Lines saved: 33 lines (1.0% of handlers) Error Patterns Unified: 1. Invalid instruction errors → ErrorBuilder::invalid_instruction() 2. Type mismatch errors → ErrorBuilder::type_mismatch() 3. Argument count errors → ErrorBuilder::arg_count_mismatch() 4. Method not found → ErrorBuilder::method_not_found() 5. Unsupported operations → ErrorBuilder::unsupported_operation() 6. Context errors → ErrorBuilder::with_context() 7. Bounds errors → ErrorBuilder::out_of_bounds() Benefits: - Consistent error message formatting across all handlers - Single point of change for error improvements - Better IDE autocomplete support - Easier future i18n integration - Reduced code duplication Cumulative Impact (Phase 1+2+3): - Total lines saved: 150-187 lines (4.5-5.7% of handlers) - Total patterns unified: 124 instances * Phase 1: 37 destination patterns * Phase 2: 52 argument validation patterns * Phase 3: 35 error generation patterns Remaining Work: - 45 error patterns still to migrate (estimated 50-80 lines) - Complex cases requiring manual review Testing: - Build: ✅ 0 errors, 0 new warnings - Smoke tests: ⚠️ 8/9 passed (1 timeout unrelated) - Core functionality: ✅ Verified Related: Phase 21.0 MIR Interpreter refactoring Risk: Low (error messages only, behavior preserved) Impact: High (maintainability, consistency, i18n-ready) Co-authored-by: Claude Code <claude@anthropic.com>
2025-11-06 23:18:10 +09:00
Err(e) => Err(ErrorBuilder::with_context("env.codegen.emit_object", &e.to_string())),
};
Some(res)
}
"env.codegen.link_object" => {
// Only supported on C-API route; expect 1 or 2 args: obj_path [, exe_out]
let obj_path = match args.get(0) {
Some(v) => match self.reg_load(*v) { Ok(v) => v.to_string(), Err(e) => return Some(Err(e)) },
None => return Some(Err(self.err_invalid("env.codegen.link_object expects 1+ args"))),
};
let exe_out = match args.get(1) {
Some(v) => Some(match self.reg_load(*v) { Ok(v) => v.to_string(), Err(e) => return Some(Err(e)) }),
None => None,
};
let extra = std::env::var("HAKO_AOT_LDFLAGS").ok();
// Require C-API toggles
if std::env::var("NYASH_LLVM_USE_CAPI").ok().as_deref() != Some("1") ||
std::env::var("HAKO_V1_EXTERN_PROVIDER_C_ABI").ok().as_deref() != Some("1") {
refactor: unify error message generation (Phase 3) Add ErrorBuilder utility and migrate 35 error generation sites Phase 3: Error Message Generation Unification ============================================ Infrastructure: - Add src/backend/mir_interpreter/utils/error_helpers.rs (255 lines) - Implement ErrorBuilder with 7 standardized error patterns - Add MirInterpreter convenience methods (err_invalid, err_type_mismatch, etc.) Migration Results: - Total patterns migrated: 35 instances (80 → 45, 44% reduction) - calls.rs: 37 → 13 patterns (65% reduction) - extern_provider.rs: 20 → 9 patterns (55% reduction) - Lines saved: 33 lines (1.0% of handlers) Error Patterns Unified: 1. Invalid instruction errors → ErrorBuilder::invalid_instruction() 2. Type mismatch errors → ErrorBuilder::type_mismatch() 3. Argument count errors → ErrorBuilder::arg_count_mismatch() 4. Method not found → ErrorBuilder::method_not_found() 5. Unsupported operations → ErrorBuilder::unsupported_operation() 6. Context errors → ErrorBuilder::with_context() 7. Bounds errors → ErrorBuilder::out_of_bounds() Benefits: - Consistent error message formatting across all handlers - Single point of change for error improvements - Better IDE autocomplete support - Easier future i18n integration - Reduced code duplication Cumulative Impact (Phase 1+2+3): - Total lines saved: 150-187 lines (4.5-5.7% of handlers) - Total patterns unified: 124 instances * Phase 1: 37 destination patterns * Phase 2: 52 argument validation patterns * Phase 3: 35 error generation patterns Remaining Work: - 45 error patterns still to migrate (estimated 50-80 lines) - Complex cases requiring manual review Testing: - Build: ✅ 0 errors, 0 new warnings - Smoke tests: ⚠️ 8/9 passed (1 timeout unrelated) - Core functionality: ✅ Verified Related: Phase 21.0 MIR Interpreter refactoring Risk: Low (error messages only, behavior preserved) Impact: High (maintainability, consistency, i18n-ready) Co-authored-by: Claude Code <claude@anthropic.com>
2025-11-06 23:18:10 +09:00
return Some(Err(ErrorBuilder::invalid_instruction("env.codegen.link_object: C-API route disabled")));
}
let obj = std::path::PathBuf::from(obj_path);
let exe = exe_out.map(std::path::PathBuf::from).unwrap_or_else(|| std::env::temp_dir().join("hako_link_out.exe"));
match crate::host_providers::llvm_codegen::link_object_capi(&obj, &exe, extra.as_deref()) {
Ok(()) => Some(Ok(VMValue::String(exe.to_string_lossy().into_owned()))),
refactor: unify error message generation (Phase 3) Add ErrorBuilder utility and migrate 35 error generation sites Phase 3: Error Message Generation Unification ============================================ Infrastructure: - Add src/backend/mir_interpreter/utils/error_helpers.rs (255 lines) - Implement ErrorBuilder with 7 standardized error patterns - Add MirInterpreter convenience methods (err_invalid, err_type_mismatch, etc.) Migration Results: - Total patterns migrated: 35 instances (80 → 45, 44% reduction) - calls.rs: 37 → 13 patterns (65% reduction) - extern_provider.rs: 20 → 9 patterns (55% reduction) - Lines saved: 33 lines (1.0% of handlers) Error Patterns Unified: 1. Invalid instruction errors → ErrorBuilder::invalid_instruction() 2. Type mismatch errors → ErrorBuilder::type_mismatch() 3. Argument count errors → ErrorBuilder::arg_count_mismatch() 4. Method not found → ErrorBuilder::method_not_found() 5. Unsupported operations → ErrorBuilder::unsupported_operation() 6. Context errors → ErrorBuilder::with_context() 7. Bounds errors → ErrorBuilder::out_of_bounds() Benefits: - Consistent error message formatting across all handlers - Single point of change for error improvements - Better IDE autocomplete support - Easier future i18n integration - Reduced code duplication Cumulative Impact (Phase 1+2+3): - Total lines saved: 150-187 lines (4.5-5.7% of handlers) - Total patterns unified: 124 instances * Phase 1: 37 destination patterns * Phase 2: 52 argument validation patterns * Phase 3: 35 error generation patterns Remaining Work: - 45 error patterns still to migrate (estimated 50-80 lines) - Complex cases requiring manual review Testing: - Build: ✅ 0 errors, 0 new warnings - Smoke tests: ⚠️ 8/9 passed (1 timeout unrelated) - Core functionality: ✅ Verified Related: Phase 21.0 MIR Interpreter refactoring Risk: Low (error messages only, behavior preserved) Impact: High (maintainability, consistency, i18n-ready) Co-authored-by: Claude Code <claude@anthropic.com>
2025-11-06 23:18:10 +09:00
Err(e) => Some(Err(ErrorBuilder::with_context("env.codegen.link_object", &e.to_string()))),
}
}
// Environment
"env.get" => {
refactor: unify error message generation (Phase 3) Add ErrorBuilder utility and migrate 35 error generation sites Phase 3: Error Message Generation Unification ============================================ Infrastructure: - Add src/backend/mir_interpreter/utils/error_helpers.rs (255 lines) - Implement ErrorBuilder with 7 standardized error patterns - Add MirInterpreter convenience methods (err_invalid, err_type_mismatch, etc.) Migration Results: - Total patterns migrated: 35 instances (80 → 45, 44% reduction) - calls.rs: 37 → 13 patterns (65% reduction) - extern_provider.rs: 20 → 9 patterns (55% reduction) - Lines saved: 33 lines (1.0% of handlers) Error Patterns Unified: 1. Invalid instruction errors → ErrorBuilder::invalid_instruction() 2. Type mismatch errors → ErrorBuilder::type_mismatch() 3. Argument count errors → ErrorBuilder::arg_count_mismatch() 4. Method not found → ErrorBuilder::method_not_found() 5. Unsupported operations → ErrorBuilder::unsupported_operation() 6. Context errors → ErrorBuilder::with_context() 7. Bounds errors → ErrorBuilder::out_of_bounds() Benefits: - Consistent error message formatting across all handlers - Single point of change for error improvements - Better IDE autocomplete support - Easier future i18n integration - Reduced code duplication Cumulative Impact (Phase 1+2+3): - Total lines saved: 150-187 lines (4.5-5.7% of handlers) - Total patterns unified: 124 instances * Phase 1: 37 destination patterns * Phase 2: 52 argument validation patterns * Phase 3: 35 error generation patterns Remaining Work: - 45 error patterns still to migrate (estimated 50-80 lines) - Complex cases requiring manual review Testing: - Build: ✅ 0 errors, 0 new warnings - Smoke tests: ⚠️ 8/9 passed (1 timeout unrelated) - Core functionality: ✅ Verified Related: Phase 21.0 MIR Interpreter refactoring Risk: Low (error messages only, behavior preserved) Impact: High (maintainability, consistency, i18n-ready) Co-authored-by: Claude Code <claude@anthropic.com>
2025-11-06 23:18:10 +09:00
if args.is_empty() { return Some(Err(ErrorBuilder::arg_count_mismatch("env.get", 1, args.len()))); }
let key = match self.reg_load(args[0]) { Ok(v) => v.to_string(), Err(e) => return Some(Err(e)) };
let val = std::env::var(&key).ok();
Some(Ok(match val { Some(s) => VMValue::String(s), None => VMValue::Void }))
}
// Legacy global-call form: hostbridge.extern_invoke(name, method, args?)
"hostbridge.extern_invoke" => {
if std::env::var("HAKO_CABI_TRACE").ok().as_deref() == Some("1") {
eprintln!("[hb:entry:provider] hostbridge.extern_invoke");
}
if args.len() < 2 {
return Some(Err(self.err_invalid("extern_invoke expects at least 2 args")));
}
let name = match self.reg_load(args[0]) { Ok(v) => v.to_string(), Err(e) => return Some(Err(e)) };
let method = match self.reg_load(args[1]) { Ok(v) => v.to_string(), Err(e) => return Some(Err(e)) };
// Extract first payload arg (optional)
let mut first_arg_str: Option<String> = None;
if let Some(a2) = args.get(2) {
let v = match self.reg_load(*a2) { Ok(v) => v, Err(e) => return Some(Err(e)) };
match v {
VMValue::BoxRef(b) => {
if let Some(ab) = b.as_any().downcast_ref::<crate::boxes::array::ArrayBox>() {
let idx: Box<dyn crate::box_trait::NyashBox> =
Box::new(crate::box_trait::IntegerBox::new(0));
let elem = ab.get(idx);
first_arg_str = Some(elem.to_string_box().value);
} else {
first_arg_str = Some(b.to_string_box().value);
}
}
_ => first_arg_str = Some(v.to_string()),
}
}
// Dispatch to known providers
if std::env::var("HAKO_CABI_TRACE").ok().as_deref() == Some("1") {
eprintln!("[hb:dispatch:provider] {} {}", name, method);
}
let out = match (name.as_str(), method.as_str()) {
("env.codegen", "link_object") if std::env::var("HAKO_CABI_TRACE").ok().as_deref() == Some("1") => {
// Trace payload shape before actual handling
if let Some(a2) = args.get(2) {
let v = match self.reg_load(*a2) { Ok(v) => v, Err(_) => VMValue::Void };
match &v {
VMValue::BoxRef(b) => {
if b.as_any().downcast_ref::<crate::boxes::array::ArrayBox>().is_some() {
eprintln!("[hb:provider:args] link_object third=ArrayBox");
} else {
eprintln!("[hb:provider:args] link_object third=BoxRef({})", b.type_name());
}
}
other => {
eprintln!("[hb:provider:args] link_object third={:?}", other);
}
}
} else {
eprintln!("[hb:provider:args] link_object third=<none>");
}
// fallthrough to real handler below by duplicating arm
// Args in third param (ArrayBox): [obj_path, exe_out?]
let (objs, exe_out) = if let Some(a2) = args.get(2) {
let v = match self.reg_load(*a2) {
Ok(v) => v,
Err(e) => return Some(Err(e)),
};
match v {
VMValue::BoxRef(b) => {
if let Some(ab) = b.as_any().downcast_ref::<crate::boxes::array::ArrayBox>() {
let idx0: Box<dyn crate::box_trait::NyashBox> = Box::new(crate::box_trait::IntegerBox::new(0));
let elem0 = ab.get(idx0).to_string_box().value;
let mut exe: Option<String> = None;
let idx1: Box<dyn crate::box_trait::NyashBox> = Box::new(crate::box_trait::IntegerBox::new(1));
let e1 = ab.get(idx1).to_string_box().value;
if !e1.is_empty() { exe = Some(e1); }
(elem0, exe)
} else {
(b.to_string_box().value, None)
}
}
_ => (v.to_string(), None),
}
} else {
return Some(Err(self.err_invalid("extern_invoke env.codegen.link_object expects args array")));
};
if std::env::var("NYASH_LLVM_USE_CAPI").ok().as_deref() != Some("1") ||
std::env::var("HAKO_V1_EXTERN_PROVIDER_C_ABI").ok().as_deref() != Some("1") {
refactor: unify error message generation (Phase 3) Add ErrorBuilder utility and migrate 35 error generation sites Phase 3: Error Message Generation Unification ============================================ Infrastructure: - Add src/backend/mir_interpreter/utils/error_helpers.rs (255 lines) - Implement ErrorBuilder with 7 standardized error patterns - Add MirInterpreter convenience methods (err_invalid, err_type_mismatch, etc.) Migration Results: - Total patterns migrated: 35 instances (80 → 45, 44% reduction) - calls.rs: 37 → 13 patterns (65% reduction) - extern_provider.rs: 20 → 9 patterns (55% reduction) - Lines saved: 33 lines (1.0% of handlers) Error Patterns Unified: 1. Invalid instruction errors → ErrorBuilder::invalid_instruction() 2. Type mismatch errors → ErrorBuilder::type_mismatch() 3. Argument count errors → ErrorBuilder::arg_count_mismatch() 4. Method not found → ErrorBuilder::method_not_found() 5. Unsupported operations → ErrorBuilder::unsupported_operation() 6. Context errors → ErrorBuilder::with_context() 7. Bounds errors → ErrorBuilder::out_of_bounds() Benefits: - Consistent error message formatting across all handlers - Single point of change for error improvements - Better IDE autocomplete support - Easier future i18n integration - Reduced code duplication Cumulative Impact (Phase 1+2+3): - Total lines saved: 150-187 lines (4.5-5.7% of handlers) - Total patterns unified: 124 instances * Phase 1: 37 destination patterns * Phase 2: 52 argument validation patterns * Phase 3: 35 error generation patterns Remaining Work: - 45 error patterns still to migrate (estimated 50-80 lines) - Complex cases requiring manual review Testing: - Build: ✅ 0 errors, 0 new warnings - Smoke tests: ⚠️ 8/9 passed (1 timeout unrelated) - Core functionality: ✅ Verified Related: Phase 21.0 MIR Interpreter refactoring Risk: Low (error messages only, behavior preserved) Impact: High (maintainability, consistency, i18n-ready) Co-authored-by: Claude Code <claude@anthropic.com>
2025-11-06 23:18:10 +09:00
return Some(Err(ErrorBuilder::invalid_instruction("env.codegen.link_object: C-API route disabled")));
}
let extra = std::env::var("HAKO_AOT_LDFLAGS").ok();
let obj = std::path::PathBuf::from(objs);
let exe = exe_out.map(std::path::PathBuf::from).unwrap_or_else(|| std::env::temp_dir().join("hako_link_out.exe"));
match crate::host_providers::llvm_codegen::link_object_capi(&obj, &exe, extra.as_deref()) {
Ok(()) => Ok(VMValue::String(exe.to_string_lossy().into_owned())),
refactor: unify error message generation (Phase 3) Add ErrorBuilder utility and migrate 35 error generation sites Phase 3: Error Message Generation Unification ============================================ Infrastructure: - Add src/backend/mir_interpreter/utils/error_helpers.rs (255 lines) - Implement ErrorBuilder with 7 standardized error patterns - Add MirInterpreter convenience methods (err_invalid, err_type_mismatch, etc.) Migration Results: - Total patterns migrated: 35 instances (80 → 45, 44% reduction) - calls.rs: 37 → 13 patterns (65% reduction) - extern_provider.rs: 20 → 9 patterns (55% reduction) - Lines saved: 33 lines (1.0% of handlers) Error Patterns Unified: 1. Invalid instruction errors → ErrorBuilder::invalid_instruction() 2. Type mismatch errors → ErrorBuilder::type_mismatch() 3. Argument count errors → ErrorBuilder::arg_count_mismatch() 4. Method not found → ErrorBuilder::method_not_found() 5. Unsupported operations → ErrorBuilder::unsupported_operation() 6. Context errors → ErrorBuilder::with_context() 7. Bounds errors → ErrorBuilder::out_of_bounds() Benefits: - Consistent error message formatting across all handlers - Single point of change for error improvements - Better IDE autocomplete support - Easier future i18n integration - Reduced code duplication Cumulative Impact (Phase 1+2+3): - Total lines saved: 150-187 lines (4.5-5.7% of handlers) - Total patterns unified: 124 instances * Phase 1: 37 destination patterns * Phase 2: 52 argument validation patterns * Phase 3: 35 error generation patterns Remaining Work: - 45 error patterns still to migrate (estimated 50-80 lines) - Complex cases requiring manual review Testing: - Build: ✅ 0 errors, 0 new warnings - Smoke tests: ⚠️ 8/9 passed (1 timeout unrelated) - Core functionality: ✅ Verified Related: Phase 21.0 MIR Interpreter refactoring Risk: Low (error messages only, behavior preserved) Impact: High (maintainability, consistency, i18n-ready) Co-authored-by: Claude Code <claude@anthropic.com>
2025-11-06 23:18:10 +09:00
Err(e) => Err(ErrorBuilder::with_context("env.codegen.link_object", &e.to_string()))
}
}
("env.mirbuilder", "emit") => {
if let Some(s) = first_arg_str {
match crate::host_providers::mir_builder::program_json_to_mir_json(&s) {
Ok(out) => Ok(VMValue::String(Self::patch_mir_json_version(&out))),
Err(e) => Err(self.err_with_context("env.mirbuilder.emit", &e.to_string())),
}
} else {
Err(self.err_invalid("extern_invoke env.mirbuilder.emit expects 1 arg"))
}
}
("env.codegen", "emit_object") => {
if let Some(s) = first_arg_str {
let opts = crate::host_providers::llvm_codegen::Opts {
out: None,
nyrt: std::env::var("NYASH_EMIT_EXE_NYRT").ok().map(std::path::PathBuf::from),
opt_level: std::env::var("HAKO_LLVM_OPT_LEVEL").ok(),
timeout_ms: None,
};
match crate::host_providers::llvm_codegen::mir_json_to_object(&s, opts) {
Ok(p) => Ok(VMValue::String(p.to_string_lossy().into_owned())),
Err(e) => Err(self.err_with_context("env.codegen.emit_object", &e.to_string())),
}
} else {
Err(self.err_invalid("extern_invoke env.codegen.emit_object expects 1 arg"))
}
}
("env.codegen", "link_object") => {
// Unify both shapes:
// 1) third arg is ArrayBox [obj, exe?]
// 2) first_arg_str has obj and third arg has optional exe
let mut obj_s: Option<String> = None;
let mut exe_s: Option<String> = None;
if let Some(a2) = args.get(2) {
let v = match self.reg_load(*a2) {
Ok(v) => v,
Err(e) => return Some(Err(e)),
};
match v {
VMValue::BoxRef(b) => {
if let Some(ab) = b.as_any().downcast_ref::<crate::boxes::array::ArrayBox>() {
let idx0: Box<dyn crate::box_trait::NyashBox> = Box::new(crate::box_trait::IntegerBox::new(0));
obj_s = Some(ab.get(idx0).to_string_box().value);
let idx1: Box<dyn crate::box_trait::NyashBox> = Box::new(crate::box_trait::IntegerBox::new(1));
let s1 = ab.get(idx1).to_string_box().value;
if !s1.is_empty() { exe_s = Some(s1); }
} else {
obj_s = Some(b.to_string_box().value);
}
}
_ => obj_s = Some(v.to_string()),
}
}
if obj_s.is_none() {
obj_s = first_arg_str;
}
let objs = match obj_s {
Some(s) => s,
None => return Some(Err(self.err_invalid("extern_invoke env.codegen.link_object expects args"))),
};
if std::env::var("NYASH_LLVM_USE_CAPI").ok().as_deref() != Some("1") ||
std::env::var("HAKO_V1_EXTERN_PROVIDER_C_ABI").ok().as_deref() != Some("1") {
refactor: unify error message generation (Phase 3) Add ErrorBuilder utility and migrate 35 error generation sites Phase 3: Error Message Generation Unification ============================================ Infrastructure: - Add src/backend/mir_interpreter/utils/error_helpers.rs (255 lines) - Implement ErrorBuilder with 7 standardized error patterns - Add MirInterpreter convenience methods (err_invalid, err_type_mismatch, etc.) Migration Results: - Total patterns migrated: 35 instances (80 → 45, 44% reduction) - calls.rs: 37 → 13 patterns (65% reduction) - extern_provider.rs: 20 → 9 patterns (55% reduction) - Lines saved: 33 lines (1.0% of handlers) Error Patterns Unified: 1. Invalid instruction errors → ErrorBuilder::invalid_instruction() 2. Type mismatch errors → ErrorBuilder::type_mismatch() 3. Argument count errors → ErrorBuilder::arg_count_mismatch() 4. Method not found → ErrorBuilder::method_not_found() 5. Unsupported operations → ErrorBuilder::unsupported_operation() 6. Context errors → ErrorBuilder::with_context() 7. Bounds errors → ErrorBuilder::out_of_bounds() Benefits: - Consistent error message formatting across all handlers - Single point of change for error improvements - Better IDE autocomplete support - Easier future i18n integration - Reduced code duplication Cumulative Impact (Phase 1+2+3): - Total lines saved: 150-187 lines (4.5-5.7% of handlers) - Total patterns unified: 124 instances * Phase 1: 37 destination patterns * Phase 2: 52 argument validation patterns * Phase 3: 35 error generation patterns Remaining Work: - 45 error patterns still to migrate (estimated 50-80 lines) - Complex cases requiring manual review Testing: - Build: ✅ 0 errors, 0 new warnings - Smoke tests: ⚠️ 8/9 passed (1 timeout unrelated) - Core functionality: ✅ Verified Related: Phase 21.0 MIR Interpreter refactoring Risk: Low (error messages only, behavior preserved) Impact: High (maintainability, consistency, i18n-ready) Co-authored-by: Claude Code <claude@anthropic.com>
2025-11-06 23:18:10 +09:00
return Some(Err(ErrorBuilder::invalid_instruction("env.codegen.link_object: C-API route disabled")));
}
let extra = std::env::var("HAKO_AOT_LDFLAGS").ok();
let obj = std::path::PathBuf::from(objs);
let exe = exe_s.map(std::path::PathBuf::from).unwrap_or_else(|| std::env::temp_dir().join("hako_link_out.exe"));
match crate::host_providers::llvm_codegen::link_object_capi(&obj, &exe, extra.as_deref()) {
Ok(()) => Ok(VMValue::String(exe.to_string_lossy().into_owned())),
refactor: unify error message generation (Phase 3) Add ErrorBuilder utility and migrate 35 error generation sites Phase 3: Error Message Generation Unification ============================================ Infrastructure: - Add src/backend/mir_interpreter/utils/error_helpers.rs (255 lines) - Implement ErrorBuilder with 7 standardized error patterns - Add MirInterpreter convenience methods (err_invalid, err_type_mismatch, etc.) Migration Results: - Total patterns migrated: 35 instances (80 → 45, 44% reduction) - calls.rs: 37 → 13 patterns (65% reduction) - extern_provider.rs: 20 → 9 patterns (55% reduction) - Lines saved: 33 lines (1.0% of handlers) Error Patterns Unified: 1. Invalid instruction errors → ErrorBuilder::invalid_instruction() 2. Type mismatch errors → ErrorBuilder::type_mismatch() 3. Argument count errors → ErrorBuilder::arg_count_mismatch() 4. Method not found → ErrorBuilder::method_not_found() 5. Unsupported operations → ErrorBuilder::unsupported_operation() 6. Context errors → ErrorBuilder::with_context() 7. Bounds errors → ErrorBuilder::out_of_bounds() Benefits: - Consistent error message formatting across all handlers - Single point of change for error improvements - Better IDE autocomplete support - Easier future i18n integration - Reduced code duplication Cumulative Impact (Phase 1+2+3): - Total lines saved: 150-187 lines (4.5-5.7% of handlers) - Total patterns unified: 124 instances * Phase 1: 37 destination patterns * Phase 2: 52 argument validation patterns * Phase 3: 35 error generation patterns Remaining Work: - 45 error patterns still to migrate (estimated 50-80 lines) - Complex cases requiring manual review Testing: - Build: ✅ 0 errors, 0 new warnings - Smoke tests: ⚠️ 8/9 passed (1 timeout unrelated) - Core functionality: ✅ Verified Related: Phase 21.0 MIR Interpreter refactoring Risk: Low (error messages only, behavior preserved) Impact: High (maintainability, consistency, i18n-ready) Co-authored-by: Claude Code <claude@anthropic.com>
2025-11-06 23:18:10 +09:00
Err(e) => Err(ErrorBuilder::with_context("env.codegen.link_object", &e.to_string()))
}
}
_ => {
if std::env::var("HAKO_CABI_TRACE").ok().as_deref() == Some("1") {
eprintln!("[hb:unsupported:provider] {}.{}", name, method);
}
Err(self.err_invalid(format!(
"hostbridge.extern_invoke unsupported for {}.{} [provider]",
name, method
)))
},
};
Some(out)
}
_ => None,
}
}
}