1#![allow(
9 clippy::missing_const_for_thread_local,
10 clippy::never_loop,
11 clippy::not_unsafe_ptr_arg_deref,
12 clippy::redundant_closure,
13 clippy::result_large_err
14)]
15
16use cranelift::prelude::*;
17use cranelift_jit::{JITBuilder, JITModule};
18use cranelift_module::{default_libcall_names, FuncId, Linkage, Module};
19use futures::task::noop_waker;
20use log::{debug, error, info, warn};
21use runmat_builtins::Value;
22use runmat_runtime::{build_runtime_error, RuntimeError};
23use runmat_vm::{ArgSpec, Bytecode, FunctionRegistry, Instr, InterpreterOutcome};
24use std::cell::Cell;
25use std::env;
26use std::future::Future;
27use std::hash::{Hash, Hasher};
28use std::pin::Pin;
29use std::task::Context;
30
31use target_lexicon::Triple;
32use thiserror::Error;
33use tracing::info_span;
34
35pub mod cache;
36pub mod compiler;
37pub mod jit_memory;
38pub mod profiler;
39pub mod value_abi;
40
41pub use cache::*;
42pub use compiler::*;
43pub use jit_memory::*;
44pub use profiler::HotspotProfiler;
45pub use value_abi::{TurbineAbiRootScope, TurbineArgSpec, TurbineValue, TurbineValueTag};
46
47const JIT_FALLBACK_STACK_BYTES: usize = 16 * 1024 * 1024;
48const JIT_FALLBACK_STACK_ENV: &str = "RUNMAT_TURBINE_STACK_MB";
49
50fn run_immediate<F: Future>(mut future: Pin<Box<F>>) -> Result<F::Output> {
51 let stack_bytes = env::var(JIT_FALLBACK_STACK_ENV)
52 .ok()
53 .and_then(|value| value.parse::<usize>().ok())
54 .filter(|mb| *mb > 0)
55 .map(|mb| mb.saturating_mul(1024 * 1024))
56 .unwrap_or(JIT_FALLBACK_STACK_BYTES);
57 stacker::grow(stack_bytes, || {
58 let waker = noop_waker();
59 let mut context = Context::from_waker(&waker);
60 loop {
61 match future.as_mut().poll(&mut context) {
62 std::task::Poll::Ready(output) => return Ok(output),
63 std::task::Poll::Pending => {
64 return Err(execution_error(
65 "async interpreter yielded unexpectedly in sync JIT path",
66 ))
67 }
68 }
69 }
70 })
71}
72
73struct RuntimeContext {
74 function_registry: FunctionRegistry,
75}
76
77impl RuntimeContext {
78 fn new(function_registry: FunctionRegistry) -> Self {
79 Self { function_registry }
80 }
81}
82
83thread_local! {
84 static RUNTIME_CONTEXT: Cell<*const RuntimeContext> = Cell::new(std::ptr::null());
85}
86
87struct RuntimeContextGuard {
88 previous: *const RuntimeContext,
89 _context: Box<RuntimeContext>,
90}
91
92impl Drop for RuntimeContextGuard {
93 fn drop(&mut self) {
94 RUNTIME_CONTEXT.with(|cell| cell.set(self.previous));
95 }
96}
97
98fn enter_runtime_context(context: RuntimeContext) -> RuntimeContextGuard {
99 let context = Box::new(context);
100 let ptr = context.as_ref() as *const RuntimeContext;
101 let previous = RUNTIME_CONTEXT.with(|cell| cell.replace(ptr));
102 RuntimeContextGuard {
103 previous,
104 _context: context,
105 }
106}
107
108fn with_runtime_context<R>(f: impl FnOnce(&RuntimeContext) -> R) -> Option<R> {
109 RUNTIME_CONTEXT.with(|cell| {
110 let ptr = cell.get();
111 (!ptr.is_null()).then(|| f(unsafe { &*ptr }))
112 })
113}
114
115fn runtime_function_registry() -> Option<FunctionRegistry> {
116 with_runtime_context(|context| context.function_registry.clone())
117}
118
119fn declare_host_semantic_call_in_module(module: &mut JITModule) -> FuncId {
120 let mut sig = module.make_signature();
121 let pointer_type = module.isa().pointer_type();
122 sig.params.push(AbiParam::new(types::I64)); sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.returns.push(AbiParam::new(types::I32)); module
129 .declare_function("runmat_call_semantic_function", Linkage::Import, &sig)
130 .expect("Failed to declare runmat_call_semantic_function")
131}
132
133fn declare_host_semantic_call_outputs_in_module(module: &mut JITModule) -> FuncId {
134 let mut sig = module.make_signature();
135 let pointer_type = module.isa().pointer_type();
136 sig.params.push(AbiParam::new(types::I64)); sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.returns.push(AbiParam::new(types::I32)); module
144 .declare_function(
145 "runmat_call_semantic_function_outputs",
146 Linkage::Import,
147 &sig,
148 )
149 .expect("Failed to declare runmat_call_semantic_function_outputs")
150}
151
152fn declare_host_semantic_value_call_in_module(module: &mut JITModule) -> FuncId {
153 let mut sig = module.make_signature();
154 let pointer_type = module.isa().pointer_type();
155 sig.params.push(AbiParam::new(types::I64)); sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.returns.push(AbiParam::new(types::I32)); module
162 .declare_function("runmat_call_semantic_function_value", Linkage::Import, &sig)
163 .expect("Failed to declare runmat_call_semantic_function_value")
164}
165
166fn declare_host_semantic_value_outputs_in_module(module: &mut JITModule) -> FuncId {
167 let mut sig = module.make_signature();
168 let pointer_type = module.isa().pointer_type();
169 sig.params.push(AbiParam::new(types::I64)); sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.returns.push(AbiParam::new(types::I32)); module
177 .declare_function(
178 "runmat_call_semantic_function_values",
179 Linkage::Import,
180 &sig,
181 )
182 .expect("Failed to declare runmat_call_semantic_function_values")
183}
184
185fn declare_host_semantic_expanded_value_call_in_module(module: &mut JITModule) -> FuncId {
186 let mut sig = module.make_signature();
187 let pointer_type = module.isa().pointer_type();
188 sig.params.push(AbiParam::new(types::I64)); sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.returns.push(AbiParam::new(types::I32)); module
197 .declare_function(
198 "runmat_call_semantic_function_expanded_value",
199 Linkage::Import,
200 &sig,
201 )
202 .expect("Failed to declare runmat_call_semantic_function_expanded_value")
203}
204
205fn declare_host_semantic_expanded_value_outputs_in_module(module: &mut JITModule) -> FuncId {
206 let mut sig = module.make_signature();
207 let pointer_type = module.isa().pointer_type();
208 sig.params.push(AbiParam::new(types::I64)); sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.returns.push(AbiParam::new(types::I32)); module
218 .declare_function(
219 "runmat_call_semantic_function_expanded_values",
220 Linkage::Import,
221 &sig,
222 )
223 .expect("Failed to declare runmat_call_semantic_function_expanded_values")
224}
225
226fn declare_host_feval_expanded_value_outputs_in_module(module: &mut JITModule) -> FuncId {
227 let mut sig = module.make_signature();
228 let pointer_type = module.isa().pointer_type();
229 sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.returns.push(AbiParam::new(types::I32)); module
238 .declare_function("runmat_call_feval_expanded_values", Linkage::Import, &sig)
239 .expect("Failed to declare runmat_call_feval_expanded_values")
240}
241
242fn declare_host_builtin_expanded_value_outputs_in_module(module: &mut JITModule) -> FuncId {
243 let mut sig = module.make_signature();
244 let pointer_type = module.isa().pointer_type();
245 sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.returns.push(AbiParam::new(types::I32)); module
256 .declare_function("runmat_call_builtin_expanded_values", Linkage::Import, &sig)
257 .expect("Failed to declare runmat_call_builtin_expanded_values")
258}
259
260fn declare_host_method_member_expanded_value_outputs_in_module(module: &mut JITModule) -> FuncId {
261 let mut sig = module.make_signature();
262 let pointer_type = module.isa().pointer_type();
263 sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(types::I32)); sig.params.push(AbiParam::new(pointer_type)); sig.returns.push(AbiParam::new(types::I32)); module
275 .declare_function(
276 "runmat_call_method_member_expanded_values",
277 Linkage::Import,
278 &sig,
279 )
280 .expect("Failed to declare runmat_call_method_member_expanded_values")
281}
282
283pub struct TurbineEngine {
285 module: JITModule,
286 ctx: codegen::Context,
287 cache: FunctionCache,
288 profiler: HotspotProfiler,
289 target_isa: codegen::isa::OwnedTargetIsa,
290 compiler: BytecodeCompiler,
291 runmat_call_semantic_function_id: FuncId,
292 runmat_call_semantic_function_outputs_id: FuncId,
293 runmat_call_semantic_function_values_id: FuncId,
294 runmat_call_semantic_function_expanded_values_id: FuncId,
295 runmat_call_feval_expanded_values_id: FuncId,
296 runmat_call_builtin_expanded_values_id: FuncId,
297 runmat_call_method_member_expanded_values_id: FuncId,
298}
299
300#[derive(Clone)]
302pub struct CompiledFunction {
303 pub ptr: *const u8,
304 pub signature: Signature,
305 pub hotness: u32,
306}
307
308#[derive(Error, Debug)]
310pub enum TurbineError {
311 #[error("Cranelift compilation failed: {0}")]
312 CompilationError(#[from] cranelift_codegen::CodegenError),
313
314 #[error("Module error: {0}")]
315 ModuleError(String),
316
317 #[error("Unsupported bytecode instruction: {0:?}")]
318 UnsupportedInstruction(Instr),
319
320 #[error("Function not found: {0}")]
321 FunctionNotFound(u64),
322
323 #[error("Target ISA not supported: {0}")]
324 UnsupportedTarget(String),
325
326 #[error("JIT not available on this platform: {0}")]
327 JitUnavailable(String),
328
329 #[error("Execution error: {0}")]
330 ExecutionError(RuntimeError),
331
332 #[error("Invalid function pointer")]
333 InvalidFunctionPointer,
334}
335
336pub type Result<T> = std::result::Result<T, TurbineError>;
337
338pub(crate) fn execution_error(message: impl Into<String>) -> TurbineError {
339 TurbineError::ExecutionError(build_runtime_error(message).build())
340}
341
342impl TurbineEngine {
343 pub fn new() -> Result<Self> {
345 Self::with_config(CompilerConfig::default())
346 }
347
348 pub fn with_config(config: CompilerConfig) -> Result<Self> {
350 info!("Initializing Turbine JIT engine");
351
352 if !Self::is_jit_supported() {
354 warn!("JIT compilation not supported on this platform");
355 return Err(TurbineError::JitUnavailable(format!(
356 "Architecture {} not supported",
357 Triple::host().architecture
358 )));
359 }
360
361 let target_triple = Triple::host();
363
364 info!("Target triple: {target_triple}");
365
366 let mut flags_builder = cranelift_codegen::settings::builder();
368
369 match config.optimization_level {
371 OptimizationLevel::None => {
372 flags_builder.set("opt_level", "none").unwrap();
373 flags_builder.set("enable_verifier", "true").unwrap();
374 }
375 OptimizationLevel::Fast => {
376 flags_builder.set("opt_level", "speed").unwrap();
377 flags_builder.set("enable_verifier", "false").unwrap(); }
379 OptimizationLevel::Aggressive => {
380 flags_builder.set("opt_level", "speed_and_size").unwrap();
381 flags_builder.set("enable_verifier", "false").unwrap();
382 }
383 }
384
385 flags_builder
387 .set("use_colocated_libcalls", "false")
388 .unwrap();
389 flags_builder.set("is_pic", "false").unwrap();
390
391 if config.enable_profiling {
393 debug!("Profiling enabled for JIT compilation");
394 }
395
396 let flags = cranelift_codegen::settings::Flags::new(flags_builder);
397
398 let isa_builder = cranelift_native::builder()
400 .map_err(|e| TurbineError::UnsupportedTarget(e.to_string()))?;
401
402 let target_isa = isa_builder
404 .finish(flags)
405 .map_err(|e| TurbineError::UnsupportedTarget(e.to_string()))?;
406
407 let mut builder = JITBuilder::with_isa(target_isa.clone(), default_libcall_names());
409
410 builder.symbol(
412 "runmat_call_semantic_function",
413 runmat_call_semantic_function as *const u8,
414 );
415 builder.symbol(
416 "runmat_call_semantic_function_outputs",
417 runmat_call_semantic_function_outputs as *const u8,
418 );
419 builder.symbol(
420 "runmat_call_semantic_function_value",
421 runmat_call_semantic_function_value as *const u8,
422 );
423 builder.symbol(
424 "runmat_call_semantic_function_values",
425 runmat_call_semantic_function_values as *const u8,
426 );
427 builder.symbol(
428 "runmat_call_semantic_function_expanded_value",
429 runmat_call_semantic_function_expanded_value as *const u8,
430 );
431 builder.symbol(
432 "runmat_call_semantic_function_expanded_values",
433 runmat_call_semantic_function_expanded_values as *const u8,
434 );
435 builder.symbol(
436 "runmat_call_feval_expanded_values",
437 runmat_call_feval_expanded_values as *const u8,
438 );
439 builder.symbol(
440 "runmat_call_builtin_expanded_values",
441 runmat_call_builtin_expanded_values as *const u8,
442 );
443 builder.symbol(
444 "runmat_call_method_member_expanded_values",
445 runmat_call_method_member_expanded_values as *const u8,
446 );
447
448 let mut module = JITModule::new(builder);
450
451 let runmat_call_semantic_function_id = declare_host_semantic_call_in_module(&mut module);
453 let runmat_call_semantic_function_outputs_id =
454 declare_host_semantic_call_outputs_in_module(&mut module);
455 let _runmat_call_semantic_function_value_id =
456 declare_host_semantic_value_call_in_module(&mut module);
457 let runmat_call_semantic_function_values_id =
458 declare_host_semantic_value_outputs_in_module(&mut module);
459 let _runmat_call_semantic_function_expanded_value_id =
460 declare_host_semantic_expanded_value_call_in_module(&mut module);
461 let runmat_call_semantic_function_expanded_values_id =
462 declare_host_semantic_expanded_value_outputs_in_module(&mut module);
463 let runmat_call_feval_expanded_values_id =
464 declare_host_feval_expanded_value_outputs_in_module(&mut module);
465 let runmat_call_builtin_expanded_values_id =
466 declare_host_builtin_expanded_value_outputs_in_module(&mut module);
467 let runmat_call_method_member_expanded_values_id =
468 declare_host_method_member_expanded_value_outputs_in_module(&mut module);
469
470 let ctx = module.make_context();
471
472 let engine = Self {
473 module,
474 ctx,
475 cache: FunctionCache::with_capacity(1000),
476 profiler: HotspotProfiler::new(),
477 target_isa,
478 compiler: BytecodeCompiler::new(),
479 runmat_call_semantic_function_id,
480 runmat_call_semantic_function_outputs_id,
481 runmat_call_semantic_function_values_id,
482 runmat_call_semantic_function_expanded_values_id,
483 runmat_call_feval_expanded_values_id,
484 runmat_call_builtin_expanded_values_id,
485 runmat_call_method_member_expanded_values_id,
486 };
487
488 info!("Turbine JIT engine initialized successfully for {target_triple}");
489 Ok(engine)
490 }
491
492 pub fn is_jit_supported() -> bool {
494 let triple = Triple::host();
495 matches!(
497 triple.architecture,
498 target_lexicon::Architecture::X86_64 | target_lexicon::Architecture::Aarch64(_)
499 )
500 }
501
502 pub fn target_info(&self) -> String {
504 format!("Target ISA: {}", self.target_isa.triple())
505 }
506
507 pub fn should_compile(&mut self, bytecode_hash: u64) -> bool {
509 self.profiler.record_execution(bytecode_hash);
510
511 if self.cache.contains(bytecode_hash) {
513 return false;
514 }
515
516 self.profiler.is_hot(bytecode_hash)
517 }
518
519 pub fn compile_bytecode(&mut self, bytecode: &Bytecode) -> Result<u64> {
521 let hash = self.calculate_bytecode_hash(bytecode);
522
523 if self.cache.contains(hash) {
524 debug!("Function already compiled: {hash}");
525 return Ok(hash);
526 }
527
528 info!("Compiling hot bytecode to native code: {hash}");
529
530 let mut sig = self.module.make_signature();
532 sig.params.push(AbiParam::new(types::I64)); sig.params.push(AbiParam::new(types::I64)); sig.returns.push(AbiParam::new(types::I32)); let func_name = format!("jit_func_{hash}");
538 let func_id = self
539 .module
540 .declare_function(&func_name, Linkage::Local, &sig)
541 .map_err(|e| TurbineError::ModuleError(e.to_string()))?;
542
543 let mut func = codegen::ir::Function::with_name_signature(
545 codegen::ir::UserFuncName::user(0, func_id.as_u32()),
546 sig.clone(),
547 );
548
549 self.compiler
550 .compile_instructions(CompileInstructionParams {
551 instructions: &bytecode.instructions,
552 func: &mut func,
553 var_count: bytecode.var_count,
554 function_registry: &bytecode.function_registry(),
555 module: &mut self.module,
556 runtime_call_ids: RuntimeCallIds {
557 runmat_call_semantic_function_id: self.runmat_call_semantic_function_id,
558 runmat_call_semantic_function_outputs_id: self
559 .runmat_call_semantic_function_outputs_id,
560 runmat_call_semantic_function_values_id: self
561 .runmat_call_semantic_function_values_id,
562 runmat_call_semantic_function_expanded_values_id: self
563 .runmat_call_semantic_function_expanded_values_id,
564 runmat_call_feval_expanded_values_id: self.runmat_call_feval_expanded_values_id,
565 runmat_call_builtin_expanded_values_id: self
566 .runmat_call_builtin_expanded_values_id,
567 runmat_call_method_member_expanded_values_id: self
568 .runmat_call_method_member_expanded_values_id,
569 },
570 })?;
571
572 self.ctx.func = func;
574 self.module
575 .define_function(func_id, &mut self.ctx)
576 .map_err(|e| TurbineError::ModuleError(e.to_string()))?;
577
578 self.module
579 .finalize_definitions()
580 .map_err(|e| TurbineError::ModuleError(e.to_string()))?;
581
582 let ptr = self.module.get_finalized_function(func_id);
584
585 let compiled_func = CompiledFunction {
586 ptr,
587 signature: sig,
588 hotness: self.profiler.get_hotness(hash),
589 };
590
591 self.cache.insert(hash, compiled_func);
592
593 info!("Successfully compiled function {hash}");
594 Ok(hash)
595 }
596
597 pub fn execute_compiled(&mut self, hash: u64, vars: &mut [Value]) -> Result<i32> {
599 self.execute_compiled_with_registry(hash, vars, &FunctionRegistry::default())
600 }
601
602 pub fn execute_compiled_with_registry(
604 &mut self,
605 hash: u64,
606 vars: &mut [Value],
607 function_registry: &FunctionRegistry,
608 ) -> Result<i32> {
609 self.execute_compiled_with_function_products(hash, vars, function_registry)
610 }
611
612 fn execute_compiled_with_function_products(
613 &mut self,
614 hash: u64,
615 vars: &mut [Value],
616 function_registry: &FunctionRegistry,
617 ) -> Result<i32> {
618 let func = self
619 .cache
620 .get(hash)
621 .ok_or(TurbineError::FunctionNotFound(hash))?;
622
623 debug!("Executing compiled function {hash}");
624
625 let _abi_root_scope = TurbineAbiRootScope::enter();
626 let mut turbine_vars: Vec<TurbineValue> = vars
627 .iter()
628 .cloned()
629 .map(TurbineValue::from_runtime_value)
630 .collect::<Result<Vec<_>>>()?;
631
632 if func.ptr.is_null() {
633 return Err(TurbineError::InvalidFunctionPointer);
634 }
635
636 let _runtime_context =
638 enter_runtime_context(RuntimeContext::new(function_registry.clone()));
639 let result = unsafe {
640 let jit_fn: extern "C" fn(*mut TurbineValue, usize) -> i32 =
642 std::mem::transmute(func.ptr);
643
644 jit_fn(turbine_vars.as_mut_ptr(), turbine_vars.len())
645 };
646
647 for (i, turbine_value) in turbine_vars.iter().copied().enumerate() {
648 if i < vars.len() {
649 vars[i] = turbine_value.to_runtime_value()?;
650 }
651 }
652
653 if result != 0 {
654 return Err(execution_error(format!(
655 "JIT execution failed with status code {result}"
656 )));
657 }
658
659 debug!("JIT function execution completed with result: {result}");
660 Ok(result)
661 }
662
663 pub fn execute_or_compile(
666 &mut self,
667 bytecode: &Bytecode,
668 vars: &mut Vec<Value>,
669 ) -> Result<(i32, bool)> {
670 let hash = self.calculate_bytecode_hash(bytecode);
671 let _span = info_span!(
672 "turbine.execute_or_compile",
673 hash = hash,
674 instrs = bytecode.instructions.len()
675 )
676 .entered();
677 let function_registry = bytecode.function_registry();
678
679 if self.cache.contains(hash) {
681 match self.execute_compiled_with_function_products(
682 hash,
683 vars.as_mut_slice(),
684 &function_registry,
685 ) {
686 Ok(result) => return Ok((result, true)),
687 Err(err) => {
688 warn!(
689 "JIT execution failed for cached function, falling back to interpreter: {err}"
690 );
691 }
692 }
693 }
694
695 if self.should_compile(hash) {
697 match self.compile_bytecode(bytecode) {
698 Ok(_) => {
699 info!("Bytecode compiled successfully, executing JIT version");
700 match self.execute_compiled_with_function_products(
701 hash,
702 vars.as_mut_slice(),
703 &function_registry,
704 ) {
705 Ok(result) => return Ok((result, true)),
706 Err(err) => {
707 warn!(
708 "JIT execution failed after compilation, falling back to interpreter: {err}"
709 );
710 }
711 }
712 }
713 Err(e) => {
714 warn!("JIT compilation failed, falling back to interpreter: {e}");
715 }
717 }
718 }
719
720 self.profiler.record_execution(hash);
722
723 debug!("Executing bytecode in VM interpreter mode (supports user functions)");
725
726 match run_immediate(Box::pin(runmat_vm::interpret_with_vars(
728 bytecode,
729 vars,
730 Some("<main>"),
731 )))? {
732 Ok(InterpreterOutcome::Completed(_)) => Ok((0, false)),
733
734 Err(e) => Err(TurbineError::ExecutionError(e)),
735 }
736 }
737
738 pub fn stats(&self) -> TurbineStats {
740 let cache_stats = self.cache.stats();
741 let profiler_stats = self.profiler.stats();
742
743 let stats_snapshot = TurbineStats {
744 compiled_functions: cache_stats.size,
745 total_compilations: profiler_stats.total_executions,
746 hottest_functions: self.profiler.get_hottest_functions(5),
747 cache_hit_rate: cache_stats.hit_rate,
748 hot_functions: profiler_stats.hot_functions,
749 cache_size: cache_stats.size,
750 cache_capacity: cache_stats.capacity,
751 };
752 unsafe {
754 let this = self as *const Self as *mut Self;
756 (*this).cache.clear();
757 (*this).profiler.reset();
758 }
759
760 stats_snapshot
761 }
762
763 pub fn reset(&mut self) {
765 self.cache.clear();
766 self.profiler.reset();
767 info!("Turbine engine reset - all compiled functions and profiling data cleared");
768 }
769
770 fn hash_named_function_call<H: Hasher>(
771 hasher: &mut H,
772 discriminator: &str,
773 identity: &runmat_hir::CallableIdentity,
774 fallback_policy: runmat_hir::CallableFallbackPolicy,
775 argc: usize,
776 out_count: Option<usize>,
777 ) {
778 discriminator.hash(hasher);
779 identity.hash(hasher);
780 fallback_policy.hash(hasher);
781 argc.hash(hasher);
782 if let Some(out_count) = out_count {
783 out_count.hash(hasher);
784 }
785 }
786
787 fn hash_arg_specs<H: Hasher>(hasher: &mut H, specs: &[ArgSpec]) {
788 specs.len().hash(hasher);
789 for spec in specs {
790 spec.is_expand.hash(hasher);
791 spec.num_indices.hash(hasher);
792 spec.expand_all.hash(hasher);
793 }
794 }
795
796 pub fn calculate_bytecode_hash(&self, bytecode: &Bytecode) -> u64 {
798 use std::collections::hash_map::DefaultHasher;
799
800 let mut hasher = DefaultHasher::new();
801
802 bytecode.var_count.hash(&mut hasher);
804 if let Some(layout) = &bytecode.layout {
805 let mut functions: Vec<_> = layout.functions.iter().collect();
806 functions.sort_by_key(|(id, _)| id.0);
807 for (id, function) in functions {
808 "layout_function".hash(&mut hasher);
809 id.0.hash(&mut hasher);
810 function.local_count.hash(&mut hasher);
811 function.display_name.hash(&mut hasher);
812
813 let mut binding_slots: Vec<_> = function.binding_slots.iter().collect();
814 binding_slots.sort_by_key(|(binding, _)| binding.0);
815 for (binding, slot) in binding_slots {
816 binding.0.hash(&mut hasher);
817 slot.0.hash(&mut hasher);
818 }
819
820 let mut mir_local_slots: Vec<_> = function.mir_local_slots.iter().collect();
821 mir_local_slots.sort_by_key(|(local, _)| local.0);
822 for (local, slot) in mir_local_slots {
823 local.0.hash(&mut hasher);
824 slot.0.hash(&mut hasher);
825 }
826 }
827
828 let mut entrypoints: Vec<_> = layout.entrypoints.iter().collect();
829 entrypoints.sort_by_key(|(id, _)| id.0);
830 for (id, entrypoint) in entrypoints {
831 "layout_entrypoint".hash(&mut hasher);
832 id.0.hash(&mut hasher);
833 entrypoint.target.0.hash(&mut hasher);
834 for export in &entrypoint.exports {
835 export.binding.0.hash(&mut hasher);
836 export.name.hash(&mut hasher);
837 export.slot.0.hash(&mut hasher);
838 }
839 }
840 }
841 for instr in &bytecode.instructions {
842 match instr {
844 Instr::LoadConst(val) => {
845 "LoadConst".hash(&mut hasher);
846 val.to_bits().hash(&mut hasher);
847 }
848 Instr::LoadComplex(re, im) => {
849 "LoadComplex".hash(&mut hasher);
850 re.to_bits().hash(&mut hasher);
851 im.to_bits().hash(&mut hasher);
852 }
853 Instr::LoadString(s) => {
854 "LoadString".hash(&mut hasher);
855 s.hash(&mut hasher);
856 }
857 Instr::LoadBool(b) => {
858 "LoadBool".hash(&mut hasher);
859 b.hash(&mut hasher);
860 }
861 Instr::LoadVar(idx) => {
862 "LoadVar".hash(&mut hasher);
863 idx.hash(&mut hasher);
864 }
865 Instr::StoreVar(idx) => {
866 "StoreVar".hash(&mut hasher);
867 idx.hash(&mut hasher);
868 }
869 Instr::Add => "Add".hash(&mut hasher),
870 Instr::Sub => "Sub".hash(&mut hasher),
871 Instr::Mul => "Mul".hash(&mut hasher),
872 Instr::RightDiv => "RightDiv".hash(&mut hasher),
873 Instr::LeftDiv => "LeftDiv".hash(&mut hasher),
874 Instr::Pow => "Pow".hash(&mut hasher),
875 Instr::Neg => "Neg".hash(&mut hasher),
876 Instr::Transpose => "Transpose".hash(&mut hasher),
877 Instr::ConjugateTranspose => "ConjugateTranspose".hash(&mut hasher),
878 Instr::ElemMul => "ElemMul".hash(&mut hasher),
879 Instr::ElemDiv => "ElemDiv".hash(&mut hasher),
880 Instr::ElemPow => "ElemPow".hash(&mut hasher),
881 Instr::ElemLeftDiv => "ElemLeftDiv".hash(&mut hasher),
882 Instr::LessEqual => "LessEqual".hash(&mut hasher),
883 Instr::Less => "Less".hash(&mut hasher),
884 Instr::Greater => "Greater".hash(&mut hasher),
885 Instr::GreaterEqual => "GreaterEqual".hash(&mut hasher),
886 Instr::Equal => "Equal".hash(&mut hasher),
887 Instr::NotEqual => "NotEqual".hash(&mut hasher),
888 Instr::LogicalNot => "LogicalNot".hash(&mut hasher),
889 Instr::LogicalAnd => "LogicalAnd".hash(&mut hasher),
890 Instr::LogicalOr => "LogicalOr".hash(&mut hasher),
891 Instr::JumpIfFalse(target) => {
892 "JumpIfFalse".hash(&mut hasher);
893 target.hash(&mut hasher);
894 }
895 Instr::Jump(target) => {
896 "Jump".hash(&mut hasher);
897 target.hash(&mut hasher);
898 }
899 Instr::Pop => "Pop".hash(&mut hasher),
900 Instr::CreateMatrix(rows, cols) => {
901 "CreateMatrix".hash(&mut hasher);
902 rows.hash(&mut hasher);
903 cols.hash(&mut hasher);
904 }
905 Instr::CreateMatrixDynamic(num_rows) => {
906 "CreateMatrixDynamic".hash(&mut hasher);
907 num_rows.hash(&mut hasher);
908 }
909 Instr::CreateRange(has_step) => {
910 "CreateRange".hash(&mut hasher);
911 has_step.hash(&mut hasher);
912 }
913 Instr::Index(num_indices) => {
914 "Index".hash(&mut hasher);
915 num_indices.hash(&mut hasher);
916 }
917 Instr::Return => "Return".hash(&mut hasher),
918 Instr::CallFunctionMulti {
919 identity,
920 fallback_policy,
921 arg_count,
922 out_count,
923 } => {
924 Self::hash_named_function_call(
925 &mut hasher,
926 "CallFunctionMulti",
927 identity,
928 *fallback_policy,
929 *arg_count,
930 Some(*out_count),
931 );
932 }
933 Instr::CallSemanticFunctionMulti(function, argc, out_count) => {
934 "CallSemanticFunctionMulti".hash(&mut hasher);
935 function.0.hash(&mut hasher);
936 argc.hash(&mut hasher);
937 out_count.hash(&mut hasher);
938 }
939 Instr::CallSemanticFunctionExpandMultiOutput(function, specs, out_count) => {
940 "CallSemanticFunctionExpandMultiOutput".hash(&mut hasher);
941 function.0.hash(&mut hasher);
942 Self::hash_arg_specs(&mut hasher, specs);
943 out_count.hash(&mut hasher);
944 }
945 Instr::Unpack(count) => {
946 "Unpack".hash(&mut hasher);
947 count.hash(&mut hasher);
948 }
949 Instr::LoadLocal(offset) => {
950 "LoadLocal".hash(&mut hasher);
951 offset.hash(&mut hasher);
952 }
953 Instr::StoreLocal(offset) => {
954 "StoreLocal".hash(&mut hasher);
955 offset.hash(&mut hasher);
956 }
957 Instr::EnterScope(count) => {
958 "EnterScope".hash(&mut hasher);
959 count.hash(&mut hasher);
960 }
961 Instr::ExitScope(count) => {
962 "ExitScope".hash(&mut hasher);
963 count.hash(&mut hasher);
964 }
965 Instr::ReturnValue => "ReturnValue".hash(&mut hasher),
966 Instr::IndexSlice(d, n, c, e) => {
967 "IndexSlice".hash(&mut hasher);
968 d.hash(&mut hasher);
969 n.hash(&mut hasher);
970 c.hash(&mut hasher);
971 e.hash(&mut hasher);
972 }
973 Instr::CreateCell2D(r, c) => {
974 "CreateCell2D".hash(&mut hasher);
975 r.hash(&mut hasher);
976 c.hash(&mut hasher);
977 }
978 Instr::IndexCell { num_indices: k, .. } => {
979 "IndexCell".hash(&mut hasher);
980 k.hash(&mut hasher);
981 }
982 Instr::LoadStaticProperty(class, prop) => {
983 "LoadStaticProperty".hash(&mut hasher);
984 class.hash(&mut hasher);
985 prop.hash(&mut hasher);
986 }
987 Instr::LoadWorkspaceFirstStaticProperty {
988 name,
989 class_name,
990 property,
991 } => {
992 "LoadWorkspaceFirstStaticProperty".hash(&mut hasher);
993 name.hash(&mut hasher);
994 class_name.hash(&mut hasher);
995 property.hash(&mut hasher);
996 }
997 Instr::EnterTry(catch_pc, catch_var) => {
998 "EnterTry".hash(&mut hasher);
999 catch_pc.hash(&mut hasher);
1000 catch_var.hash(&mut hasher);
1001 }
1002 Instr::PopTry => {
1003 "PopTry".hash(&mut hasher);
1004 }
1005 _ => {
1006 "Other".hash(&mut hasher);
1007 }
1008 }
1009 }
1010
1011 hasher.finish()
1012 }
1013}
1014
1015impl Default for TurbineEngine {
1016 fn default() -> Self {
1017 Self::new().expect("Failed to create Turbine engine")
1018 }
1019}
1020
1021#[derive(Debug, Clone)]
1023pub struct TurbineStats {
1024 pub compiled_functions: usize,
1025 pub total_compilations: u64,
1026 pub hottest_functions: Vec<(u64, u32)>,
1027 pub cache_hit_rate: f64,
1028 pub hot_functions: usize,
1029 pub cache_size: usize,
1030 pub cache_capacity: usize,
1031}
1032
1033unsafe impl Send for CompiledFunction {}
1035unsafe impl Sync for CompiledFunction {}
1036
1037#[no_mangle]
1040pub extern "C" fn runmat_call_semantic_function(
1041 function_id: i64,
1042 args_ptr: *const f64,
1043 args_len: i32,
1044 result_ptr: *mut f64,
1045) -> i32 {
1046 if result_ptr.is_null() {
1047 error!("Null result pointer passed to runmat_call_semantic_function");
1048 return 1;
1049 }
1050
1051 let args_slice = if args_len > 0 {
1052 if args_ptr.is_null() {
1053 error!("Null args pointer passed to runmat_call_semantic_function");
1054 return 1;
1055 }
1056 unsafe { std::slice::from_raw_parts(args_ptr, args_len as usize) }
1057 } else {
1058 &[]
1059 };
1060
1061 let function_registry = match runtime_function_registry() {
1062 Some(function_registry) => function_registry,
1063 None => {
1064 error!("No runtime context available for semantic function call");
1065 return 1;
1066 }
1067 };
1068
1069 let function_id = match usize::try_from(function_id) {
1070 Ok(function_id) => function_id,
1071 Err(_) => {
1072 error!("Invalid semantic function id: {function_id}");
1073 return 1;
1074 }
1075 };
1076 let args: Vec<Value> = args_slice.iter().map(|value| Value::Num(*value)).collect();
1077 let output = run_immediate(Box::pin(runmat_vm::invoke_semantic_function_value(
1078 function_id,
1079 &args,
1080 1,
1081 &function_registry,
1082 )))
1083 .and_then(|result| result.map_err(TurbineError::ExecutionError));
1084
1085 let output = match output {
1086 Ok(result) => result,
1087 Err(err) => {
1088 error!("Semantic function execution failed: {err}");
1089 return 1;
1090 }
1091 };
1092
1093 let output_value = match output {
1094 Value::Num(val) => val,
1095 Value::Int(val) => val.to_f64(),
1096 Value::Bool(val) => {
1097 if val {
1098 1.0
1099 } else {
1100 0.0
1101 }
1102 }
1103 _ => {
1104 error!("Semantic function returned unsupported value: {output:?}");
1105 return 1;
1106 }
1107 };
1108
1109 unsafe {
1110 *result_ptr = output_value;
1111 }
1112
1113 0
1114}
1115
1116#[no_mangle]
1117pub extern "C" fn runmat_call_semantic_function_outputs(
1118 function_id: i64,
1119 args_ptr: *const f64,
1120 args_len: i32,
1121 out_count: i32,
1122 results_ptr: *mut f64,
1123) -> i32 {
1124 if results_ptr.is_null() {
1125 error!("Null results pointer passed to runmat_call_semantic_function_outputs");
1126 return 1;
1127 }
1128 if out_count < 0 {
1129 error!("Invalid output count passed to runmat_call_semantic_function_outputs");
1130 return 1;
1131 }
1132
1133 let args_slice = if args_len > 0 {
1134 if args_ptr.is_null() {
1135 error!("Null args pointer passed to runmat_call_semantic_function_outputs");
1136 return 1;
1137 }
1138 unsafe { std::slice::from_raw_parts(args_ptr, args_len as usize) }
1139 } else {
1140 &[]
1141 };
1142
1143 let function_registry = match runtime_function_registry() {
1144 Some(function_registry) => function_registry,
1145 None => {
1146 error!("No runtime context available for semantic function outputs call");
1147 return 1;
1148 }
1149 };
1150
1151 let function_id = match usize::try_from(function_id) {
1152 Ok(function_id) => function_id,
1153 Err(_) => {
1154 error!("Invalid semantic function id: {function_id}");
1155 return 1;
1156 }
1157 };
1158 let args: Vec<Value> = args_slice.iter().map(|value| Value::Num(*value)).collect();
1159 let out_count = out_count as usize;
1160 let output = run_immediate(Box::pin(runmat_vm::invoke_semantic_function_value(
1161 function_id,
1162 &args,
1163 out_count,
1164 &function_registry,
1165 )))
1166 .and_then(|result| result.map_err(TurbineError::ExecutionError));
1167
1168 let outputs = match output {
1169 Ok(Value::OutputList(values)) => values,
1170 Ok(value) => vec![value],
1171 Err(err) => {
1172 error!("Semantic function outputs execution failed: {err}");
1173 return 1;
1174 }
1175 };
1176
1177 for i in 0..out_count {
1178 let output_value = match outputs.get(i).cloned().unwrap_or(Value::Num(0.0)) {
1179 Value::Num(val) => val,
1180 Value::Int(val) => val.to_f64(),
1181 Value::Bool(val) => {
1182 if val {
1183 1.0
1184 } else {
1185 0.0
1186 }
1187 }
1188 other => {
1189 error!("Semantic function returned unsupported output value: {other:?}");
1190 return 1;
1191 }
1192 };
1193
1194 unsafe {
1195 *results_ptr.add(i) = output_value;
1196 }
1197 }
1198
1199 0
1200}
1201
1202fn read_turbine_value_args(args_ptr: *const TurbineValue, args_len: i32) -> Result<Vec<Value>> {
1203 if args_len < 0 {
1204 return Err(execution_error("negative TurbineValue argument count"));
1205 }
1206 if args_len == 0 {
1207 return Ok(Vec::new());
1208 }
1209 if args_ptr.is_null() {
1210 return Err(execution_error("null TurbineValue args pointer"));
1211 }
1212
1213 unsafe { std::slice::from_raw_parts(args_ptr, args_len as usize) }
1214 .iter()
1215 .map(|value| value.to_runtime_value())
1216 .collect()
1217}
1218
1219fn read_turbine_arg_specs(
1220 specs_ptr: *const TurbineArgSpec,
1221 specs_len: i32,
1222) -> Result<Vec<ArgSpec>> {
1223 if specs_len < 0 {
1224 return Err(execution_error("negative TurbineArgSpec count"));
1225 }
1226 if specs_len == 0 {
1227 return Ok(Vec::new());
1228 }
1229 if specs_ptr.is_null() {
1230 return Err(execution_error("null TurbineArgSpec pointer"));
1231 }
1232
1233 unsafe { std::slice::from_raw_parts(specs_ptr, specs_len as usize) }
1234 .iter()
1235 .map(|spec| {
1236 Ok(ArgSpec {
1237 is_expand: spec.is_expand != 0,
1238 num_indices: spec.num_indices as usize,
1239 expand_all: spec.expand_all != 0,
1240 })
1241 })
1242 .collect()
1243}
1244
1245fn row_major_pos_from_linear(cell: &runmat_builtins::CellArray, idx: usize) -> Result<usize> {
1246 if idx == 0 || idx > cell.data.len() {
1247 return Err(execution_error("Cell index out of bounds"));
1248 }
1249 if cell.rows <= 1 || cell.cols <= 1 {
1250 return Ok(idx - 1);
1251 }
1252 let zero = idx - 1;
1253 let row = zero % cell.rows;
1254 let col = zero / cell.rows;
1255 Ok(row * cell.cols + col)
1256}
1257
1258fn turbine_index_cell_value(cell: &runmat_builtins::CellArray, indices: &[usize]) -> Result<Value> {
1259 match indices.len() {
1260 1 => Ok(cell.data[row_major_pos_from_linear(cell, indices[0])?].clone()),
1261 2 => {
1262 let row = indices[0];
1263 let col = indices[1];
1264 if row == 0 || row > cell.rows || col == 0 || col > cell.cols {
1265 return Err(execution_error("Cell subscript out of bounds"));
1266 }
1267 Ok(cell.data[(row - 1) * cell.cols + (col - 1)].clone())
1268 }
1269 _ => Err(execution_error("Unsupported number of cell indices")),
1270 }
1271}
1272
1273fn turbine_expand_cell_indices(
1274 cell: &runmat_builtins::CellArray,
1275 indices: &[Value],
1276) -> Result<Vec<Value>> {
1277 match indices.len() {
1278 1 => match &indices[0] {
1279 Value::Num(n) if *n == 0.0 && n.is_sign_negative() => {
1280 Ok(vec![turbine_index_cell_value(cell, &[cell.data.len()])?])
1281 }
1282 Value::Num(n) if *n < 0.0 => {
1283 let idx = cell.data.len() as isize + *n as isize;
1284 if idx < 1 || idx as usize > cell.data.len() {
1285 return Err(execution_error("Cell index out of bounds"));
1286 }
1287 Ok(vec![turbine_index_cell_value(cell, &[idx as usize])?])
1288 }
1289 Value::Num(n) => Ok(vec![turbine_index_cell_value(cell, &[*n as usize])?]),
1290 Value::Int(i) => Ok(vec![turbine_index_cell_value(
1291 cell,
1292 &[i.to_i64() as usize],
1293 )?]),
1294 Value::Tensor(t) => t
1295 .data
1296 .iter()
1297 .map(|&value| turbine_index_cell_value(cell, &[value as usize]))
1298 .collect(),
1299 _ => Err(execution_error("Unsupported cell index type")),
1300 },
1301 2 => {
1302 let row = value_to_usize_index(&indices[0])?;
1303 let col = value_to_usize_index(&indices[1])?;
1304 Ok(vec![turbine_index_cell_value(cell, &[row, col])?])
1305 }
1306 _ => Err(execution_error("Unsupported cell index type")),
1307 }
1308}
1309
1310fn value_to_usize_index(value: &Value) -> Result<usize> {
1311 match value {
1312 Value::Num(value) => Ok(*value as usize),
1313 Value::Int(value) => Ok(value.to_i64() as usize),
1314 other => Err(execution_error(format!(
1315 "Unsupported cell index value: {other:?}"
1316 ))),
1317 }
1318}
1319
1320fn expand_turbine_args(args: Vec<Value>, specs: &[ArgSpec]) -> Result<Vec<Value>> {
1321 let expected_args = specs.iter().fold(0usize, |count, spec| {
1322 count + 1 + if spec.is_expand { spec.num_indices } else { 0 }
1323 });
1324 if expected_args != args.len() {
1325 return Err(execution_error(format!(
1326 "expanded Turbine argument count mismatch: expected {expected_args}, got {}",
1327 args.len()
1328 )));
1329 }
1330
1331 let mut cursor = 0;
1332 let mut expanded = Vec::new();
1333 for spec in specs {
1334 let value = args[cursor].clone();
1335 cursor += 1;
1336 if !spec.is_expand {
1337 expanded.push(value);
1338 continue;
1339 }
1340
1341 let indices = args[cursor..cursor + spec.num_indices].to_vec();
1342 cursor += spec.num_indices;
1343 let values = if spec.expand_all {
1344 match value {
1345 Value::OutputList(values) => values,
1346 Value::Cell(cell) => (1..=cell.data.len())
1347 .map(|idx| turbine_index_cell_value(&cell, &[idx]))
1348 .collect::<Result<Vec<_>>>()?,
1349 other => {
1350 return Err(execution_error(format!(
1351 "expanded Turbine call requires cell or output list for expand_all, got {other:?}"
1352 )))
1353 }
1354 }
1355 } else {
1356 match value {
1357 Value::Cell(cell) => turbine_expand_cell_indices(&cell, &indices)?,
1358 other => {
1359 return Err(execution_error(format!(
1360 "expanded Turbine call requires cell for indexed expansion, got {other:?}"
1361 )))
1362 }
1363 }
1364 };
1365 expanded.extend(values);
1366 }
1367 Ok(expanded)
1368}
1369
1370fn write_turbine_value(result_ptr: *mut TurbineValue, value: Value) -> Result<()> {
1371 if result_ptr.is_null() {
1372 return Err(execution_error("null TurbineValue result pointer"));
1373 }
1374 unsafe {
1375 *result_ptr = TurbineValue::from_runtime_value(value)?;
1376 }
1377 Ok(())
1378}
1379
1380#[no_mangle]
1381pub extern "C" fn runmat_call_semantic_function_value(
1382 function_id: i64,
1383 args_ptr: *const TurbineValue,
1384 args_len: i32,
1385 result_ptr: *mut TurbineValue,
1386) -> i32 {
1387 let output = (|| -> Result<Value> {
1388 let function_registry = runtime_function_registry().ok_or_else(|| {
1389 execution_error("No runtime context available for TurbineValue semantic call")
1390 })?;
1391 let function_id = usize::try_from(function_id)
1392 .map_err(|_| execution_error(format!("Invalid semantic function id: {function_id}")))?;
1393 let args = read_turbine_value_args(args_ptr, args_len)?;
1394 run_immediate(Box::pin(runmat_vm::invoke_semantic_function_value(
1395 function_id,
1396 &args,
1397 1,
1398 &function_registry,
1399 )))?
1400 .map_err(TurbineError::ExecutionError)
1401 })();
1402
1403 match output.and_then(|value| write_turbine_value(result_ptr, value)) {
1404 Ok(()) => 0,
1405 Err(err) => {
1406 error!("TurbineValue semantic function call failed: {err}");
1407 1
1408 }
1409 }
1410}
1411
1412#[no_mangle]
1413pub extern "C" fn runmat_call_semantic_function_values(
1414 function_id: i64,
1415 args_ptr: *const TurbineValue,
1416 args_len: i32,
1417 out_count: i32,
1418 results_ptr: *mut TurbineValue,
1419) -> i32 {
1420 let requested_out_count = out_count;
1421 let output = (|| -> Result<Vec<Value>> {
1422 if out_count < 0 {
1423 return Err(execution_error("negative TurbineValue output count"));
1424 }
1425 if out_count > 0 && results_ptr.is_null() {
1426 return Err(execution_error("null TurbineValue results pointer"));
1427 }
1428 let function_registry = runtime_function_registry().ok_or_else(|| {
1429 execution_error("No runtime context available for TurbineValue semantic outputs call")
1430 })?;
1431 let function_id = usize::try_from(function_id)
1432 .map_err(|_| execution_error(format!("Invalid semantic function id: {function_id}")))?;
1433 let args = read_turbine_value_args(args_ptr, args_len)?;
1434 let out_count = out_count as usize;
1435 let output = run_immediate(Box::pin(runmat_vm::invoke_semantic_function_value(
1436 function_id,
1437 &args,
1438 out_count,
1439 &function_registry,
1440 )))?
1441 .map_err(TurbineError::ExecutionError)?;
1442 Ok(match output {
1443 Value::OutputList(values) => values,
1444 value => vec![value],
1445 })
1446 })();
1447
1448 let outputs = match output {
1449 Ok(outputs) => outputs,
1450 Err(err) => {
1451 error!("TurbineValue semantic function outputs call failed: {err}");
1452 return 1;
1453 }
1454 };
1455
1456 for index in 0..requested_out_count as usize {
1457 let value = outputs.get(index).cloned().unwrap_or(Value::Num(0.0));
1458 if let Err(err) = write_turbine_value(unsafe { results_ptr.add(index) }, value) {
1459 error!("TurbineValue semantic output write failed: {err}");
1460 return 1;
1461 }
1462 }
1463 0
1464}
1465
1466#[no_mangle]
1467pub extern "C" fn runmat_call_semantic_function_expanded_value(
1468 function_id: i64,
1469 args_ptr: *const TurbineValue,
1470 args_len: i32,
1471 specs_ptr: *const TurbineArgSpec,
1472 specs_len: i32,
1473 result_ptr: *mut TurbineValue,
1474) -> i32 {
1475 let output = (|| -> Result<Value> {
1476 let function_registry = runtime_function_registry().ok_or_else(|| {
1477 execution_error("No runtime context available for expanded TurbineValue semantic call")
1478 })?;
1479 let function_id = usize::try_from(function_id)
1480 .map_err(|_| execution_error(format!("Invalid semantic function id: {function_id}")))?;
1481 let args = read_turbine_value_args(args_ptr, args_len)?;
1482 let specs = read_turbine_arg_specs(specs_ptr, specs_len)?;
1483 let expanded_args = expand_turbine_args(args, &specs)?;
1484 run_immediate(Box::pin(runmat_vm::invoke_semantic_function_value(
1485 function_id,
1486 &expanded_args,
1487 1,
1488 &function_registry,
1489 )))?
1490 .map_err(TurbineError::ExecutionError)
1491 })();
1492
1493 match output.and_then(|value| write_turbine_value(result_ptr, value)) {
1494 Ok(()) => 0,
1495 Err(err) => {
1496 error!("Expanded TurbineValue semantic function call failed: {err}");
1497 1
1498 }
1499 }
1500}
1501
1502#[no_mangle]
1503pub extern "C" fn runmat_call_semantic_function_expanded_values(
1504 function_id: i64,
1505 args_ptr: *const TurbineValue,
1506 args_len: i32,
1507 specs_ptr: *const TurbineArgSpec,
1508 specs_len: i32,
1509 out_count: i32,
1510 results_ptr: *mut TurbineValue,
1511) -> i32 {
1512 let requested_out_count = out_count;
1513 let output = (|| -> Result<Vec<Value>> {
1514 if out_count < 0 {
1515 return Err(execution_error("negative TurbineValue output count"));
1516 }
1517 if out_count > 0 && results_ptr.is_null() {
1518 return Err(execution_error("null TurbineValue results pointer"));
1519 }
1520 let function_registry = runtime_function_registry().ok_or_else(|| {
1521 execution_error(
1522 "No runtime context available for expanded TurbineValue semantic outputs call",
1523 )
1524 })?;
1525 let function_id = usize::try_from(function_id)
1526 .map_err(|_| execution_error(format!("Invalid semantic function id: {function_id}")))?;
1527 let args = read_turbine_value_args(args_ptr, args_len)?;
1528 let specs = read_turbine_arg_specs(specs_ptr, specs_len)?;
1529 let expanded_args = expand_turbine_args(args, &specs)?;
1530 let out_count = out_count as usize;
1531 let output = run_immediate(Box::pin(runmat_vm::invoke_semantic_function_value(
1532 function_id,
1533 &expanded_args,
1534 out_count,
1535 &function_registry,
1536 )))?
1537 .map_err(TurbineError::ExecutionError)?;
1538 Ok(match output {
1539 Value::OutputList(values) => values,
1540 value => vec![value],
1541 })
1542 })();
1543
1544 let outputs = match output {
1545 Ok(outputs) => outputs,
1546 Err(err) => {
1547 error!("Expanded TurbineValue semantic function outputs call failed: {err}");
1548 return 1;
1549 }
1550 };
1551
1552 for index in 0..requested_out_count as usize {
1553 let value = outputs.get(index).cloned().unwrap_or(Value::Num(0.0));
1554 if let Err(err) = write_turbine_value(unsafe { results_ptr.add(index) }, value) {
1555 error!("Expanded TurbineValue semantic output write failed: {err}");
1556 return 1;
1557 }
1558 }
1559 0
1560}
1561
1562#[no_mangle]
1563pub extern "C" fn runmat_call_feval_expanded_values(
1564 args_ptr: *const TurbineValue,
1565 args_len: i32,
1566 specs_ptr: *const TurbineArgSpec,
1567 specs_len: i32,
1568 out_count: i32,
1569 results_ptr: *mut TurbineValue,
1570) -> i32 {
1571 let requested_out_count = out_count;
1572 let output = (|| -> Result<Vec<Value>> {
1573 if out_count < 0 {
1574 return Err(execution_error("negative TurbineValue output count"));
1575 }
1576 if out_count > 0 && results_ptr.is_null() {
1577 return Err(execution_error("null TurbineValue results pointer"));
1578 }
1579
1580 let mut args = read_turbine_value_args(args_ptr, args_len)?;
1581 if args.is_empty() {
1582 return Err(execution_error(
1583 "expanded Turbine feval call requires callable argument",
1584 ));
1585 }
1586 let callable = args.remove(0);
1587 let specs = read_turbine_arg_specs(specs_ptr, specs_len)?;
1588 let expanded_args = expand_turbine_args(args, &specs)?;
1589 let output = run_immediate(Box::pin(runmat_runtime::call_feval_async_with_outputs(
1590 callable,
1591 &expanded_args,
1592 out_count as usize,
1593 )))?
1594 .map_err(TurbineError::ExecutionError)?;
1595 Ok(match output {
1596 Value::OutputList(values) => values,
1597 value => vec![value],
1598 })
1599 })();
1600
1601 let outputs = match output {
1602 Ok(outputs) => outputs,
1603 Err(err) => {
1604 error!("Expanded Turbine feval outputs call failed: {err}");
1605 return 1;
1606 }
1607 };
1608
1609 for index in 0..requested_out_count as usize {
1610 let value = outputs.get(index).cloned().unwrap_or(Value::Num(0.0));
1611 if let Err(err) = write_turbine_value(unsafe { results_ptr.add(index) }, value) {
1612 error!("Expanded Turbine feval output write failed: {err}");
1613 return 1;
1614 }
1615 }
1616 0
1617}
1618
1619#[no_mangle]
1620pub extern "C" fn runmat_call_builtin_expanded_values(
1621 name_ptr: *const u8,
1622 name_len: i32,
1623 args_ptr: *const TurbineValue,
1624 args_len: i32,
1625 specs_ptr: *const TurbineArgSpec,
1626 specs_len: i32,
1627 out_count: i32,
1628 results_ptr: *mut TurbineValue,
1629) -> i32 {
1630 let requested_out_count = out_count;
1631 let output = (|| -> Result<Vec<Value>> {
1632 if name_len < 0 {
1633 return Err(execution_error("negative builtin name length"));
1634 }
1635 if name_ptr.is_null() {
1636 return Err(execution_error("null builtin name pointer"));
1637 }
1638 if out_count < 0 {
1639 return Err(execution_error("negative TurbineValue output count"));
1640 }
1641 if out_count > 0 && results_ptr.is_null() {
1642 return Err(execution_error("null TurbineValue results pointer"));
1643 }
1644
1645 let name = unsafe {
1646 std::str::from_utf8(std::slice::from_raw_parts(name_ptr, name_len as usize))
1647 .map_err(|_| execution_error("invalid UTF-8 in builtin name"))?
1648 };
1649 let args = read_turbine_value_args(args_ptr, args_len)?;
1650 let specs = read_turbine_arg_specs(specs_ptr, specs_len)?;
1651 let expanded_args = expand_turbine_args(args, &specs)?;
1652 let output = run_immediate(Box::pin(runmat_runtime::call_builtin_async_with_outputs(
1653 name,
1654 &expanded_args,
1655 out_count as usize,
1656 )))?
1657 .map_err(TurbineError::ExecutionError)?;
1658 Ok(match output {
1659 Value::OutputList(values) => values,
1660 value => vec![value],
1661 })
1662 })();
1663
1664 let outputs = match output {
1665 Ok(outputs) => outputs,
1666 Err(err) => {
1667 error!("Expanded Turbine builtin outputs call failed: {err}");
1668 return 1;
1669 }
1670 };
1671
1672 for index in 0..requested_out_count as usize {
1673 let value = outputs.get(index).cloned().unwrap_or(Value::Num(0.0));
1674 if let Err(err) = write_turbine_value(unsafe { results_ptr.add(index) }, value) {
1675 error!("Expanded Turbine builtin output write failed: {err}");
1676 return 1;
1677 }
1678 }
1679 0
1680}
1681
1682fn decode_callable_fallback_policy(policy: i32) -> Result<runmat_hir::CallableFallbackPolicy> {
1683 match policy {
1684 0 => Ok(runmat_hir::CallableFallbackPolicy::None),
1685 1 => Ok(runmat_hir::CallableFallbackPolicy::RuntimeNameResolution),
1686 2 => Ok(runmat_hir::CallableFallbackPolicy::ObjectDispatch),
1687 3 => Ok(runmat_hir::CallableFallbackPolicy::ExternalBoundary),
1688 _ => Err(execution_error(format!(
1689 "invalid callable fallback policy tag: {policy}"
1690 ))),
1691 }
1692}
1693
1694#[no_mangle]
1695pub extern "C" fn runmat_call_method_member_expanded_values(
1696 name_ptr: *const u8,
1697 name_len: i32,
1698 fallback_policy: i32,
1699 args_ptr: *const TurbineValue,
1700 args_len: i32,
1701 specs_ptr: *const TurbineArgSpec,
1702 specs_len: i32,
1703 out_count: i32,
1704 results_ptr: *mut TurbineValue,
1705) -> i32 {
1706 let requested_out_count = out_count;
1707 let output = (|| -> Result<Vec<Value>> {
1708 if name_len < 0 {
1709 return Err(execution_error("negative callable name length"));
1710 }
1711 if name_ptr.is_null() {
1712 return Err(execution_error("null callable name pointer"));
1713 }
1714 if out_count < 0 {
1715 return Err(execution_error("negative TurbineValue output count"));
1716 }
1717 if out_count > 0 && results_ptr.is_null() {
1718 return Err(execution_error("null TurbineValue results pointer"));
1719 }
1720
1721 let name = unsafe {
1722 std::str::from_utf8(std::slice::from_raw_parts(name_ptr, name_len as usize))
1723 .map_err(|_| execution_error("invalid UTF-8 in callable name"))?
1724 };
1725 let policy = decode_callable_fallback_policy(fallback_policy)?;
1726 let args = read_turbine_value_args(args_ptr, args_len)?;
1727 let specs = read_turbine_arg_specs(specs_ptr, specs_len)?;
1728 let mut expanded_args = expand_turbine_args(args, &specs)?;
1729 if expanded_args.is_empty() {
1730 return Err(execution_error(
1731 "method/member expanded call requires base receiver argument",
1732 ));
1733 }
1734 let base = expanded_args.remove(0);
1735 let output = run_immediate(Box::pin(
1736 runmat_vm::call_method_or_member_index_named_with_outputs(
1737 base,
1738 name.to_string(),
1739 expanded_args,
1740 out_count as usize,
1741 policy,
1742 ),
1743 ))?
1744 .map_err(TurbineError::ExecutionError)?;
1745 Ok(match output {
1746 Value::OutputList(values) => values,
1747 value => vec![value],
1748 })
1749 })();
1750
1751 let outputs = match output {
1752 Ok(outputs) => outputs,
1753 Err(err) => {
1754 error!("Expanded Turbine method/member outputs call failed: {err}");
1755 return 1;
1756 }
1757 };
1758
1759 for index in 0..requested_out_count as usize {
1760 let value = outputs.get(index).cloned().unwrap_or(Value::Num(0.0));
1761 if let Err(err) = write_turbine_value(unsafe { results_ptr.add(index) }, value) {
1762 error!("Expanded Turbine method/member output write failed: {err}");
1763 return 1;
1764 }
1765 }
1766 0
1767}
1768
1769#[no_mangle]
1783pub extern "C" fn runtime_builtin_f64_dispatch(
1784 name_ptr: *const u8,
1785 name_len: usize,
1786 args_ptr: *const f64,
1787 args_len: usize,
1788) -> f64 {
1789 if name_ptr.is_null() || (args_len > 0 && args_ptr.is_null()) {
1791 log::error!("Invalid pointers passed to runtime_builtin_f64_dispatch");
1792 return 0.0;
1793 }
1794
1795 let name = unsafe {
1797 match std::str::from_utf8(std::slice::from_raw_parts(name_ptr, name_len)) {
1798 Ok(s) => s,
1799 Err(_) => {
1800 log::error!("Invalid UTF-8 in function name");
1801 return 0.0;
1802 }
1803 }
1804 };
1805
1806 let args_slice = if args_len > 0 {
1808 unsafe { std::slice::from_raw_parts(args_ptr, args_len) }
1809 } else {
1810 &[]
1811 };
1812
1813 let value_args: Vec<runmat_builtins::Value> = args_slice
1815 .iter()
1816 .map(|&x| runmat_builtins::Value::Num(x))
1817 .collect();
1818
1819 match runmat_runtime::call_builtin(name, &value_args) {
1821 Ok(runmat_builtins::Value::Num(result)) => result,
1822 Ok(runmat_builtins::Value::Int(result)) => result.to_f64(),
1823 Ok(runmat_builtins::Value::Bool(result)) => {
1824 if result {
1825 1.0
1826 } else {
1827 0.0
1828 }
1829 }
1830 Ok(_) => {
1831 log::warn!("Builtin function '{name}' returned non-numeric result");
1832 0.0
1833 }
1834 Err(e) => {
1835 log::error!("Builtin function '{name}' failed: {e}");
1836 0.0
1837 }
1838 }
1839}
1840
1841#[cfg(test)]
1842mod tests {
1843 use super::*;
1844 use runmat_hir::FunctionId;
1845 use runmat_vm::FunctionBytecode;
1846 use std::collections::HashMap;
1847
1848 fn install_semantic_context(functions: Vec<FunctionBytecode>) -> RuntimeContextGuard {
1849 let mut bound_functions = HashMap::new();
1850 for function in functions {
1851 bound_functions.insert(function.function, function);
1852 }
1853 let registry = FunctionRegistry::new(bound_functions);
1854 enter_runtime_context(RuntimeContext::new(registry))
1855 }
1856
1857 fn bound_function(
1858 function: FunctionId,
1859 display_name: &str,
1860 instructions: Vec<Instr>,
1861 var_count: usize,
1862 input_slots: Vec<usize>,
1863 output_slots: Vec<usize>,
1864 ) -> FunctionBytecode {
1865 FunctionBytecode {
1866 function,
1867 display_name: display_name.to_string(),
1868 source_id: None,
1869 instructions,
1870 instr_spans: Vec::new(),
1871 call_arg_spans: Vec::new(),
1872 var_count,
1873 input_slots,
1874 varargin_slot: None,
1875 implicit_nargin_slot: None,
1876 output_slots,
1877 varargout_slot: None,
1878 implicit_nargout_slot: None,
1879 capture_slots: Vec::new(),
1880 ..FunctionBytecode::default()
1881 }
1882 }
1883
1884 #[test]
1885 fn named_function_hashing_stays_centralized() {
1886 let source = include_str!("lib.rs");
1887 let call_function_hash = ["\"CallFunction\"", ".hash"].concat();
1888 let call_function_multi_hash = ["\"CallFunctionMulti\"", ".hash"].concat();
1889
1890 assert_eq!(source.matches(&call_function_hash).count(), 0);
1891 assert_eq!(source.matches(&call_function_multi_hash).count(), 0);
1892 assert_eq!(
1893 source
1894 .matches(&["Self::", "hash_named_function_call("].concat())
1895 .count(),
1896 1
1897 );
1898 }
1899
1900 #[test]
1901 fn function_value_host_call_round_trips_scalar() {
1902 let function = FunctionId(1);
1903 let _context = install_semantic_context(vec![bound_function(
1904 function,
1905 "inc",
1906 vec![
1907 Instr::LoadVar(0),
1908 Instr::LoadConst(1.0),
1909 Instr::Add,
1910 Instr::StoreVar(1),
1911 ],
1912 2,
1913 vec![0],
1914 vec![1],
1915 )]);
1916
1917 let args = [TurbineValue::from_runtime_value(Value::Num(41.0)).unwrap()];
1918 let mut result = TurbineValue::empty();
1919 let status = runmat_call_semantic_function_value(
1920 function.0 as i64,
1921 args.as_ptr(),
1922 args.len() as i32,
1923 &mut result,
1924 );
1925
1926 assert_eq!(status, 0);
1927 assert_eq!(result.to_runtime_value().unwrap(), Value::Num(42.0));
1928 }
1929
1930 #[test]
1931 fn function_value_host_call_round_trips_handle_value() {
1932 let function = FunctionId(2);
1933 let _context = install_semantic_context(vec![bound_function(
1934 function,
1935 "label",
1936 vec![Instr::LoadString("ok".to_string()), Instr::StoreVar(0)],
1937 1,
1938 Vec::new(),
1939 vec![0],
1940 )]);
1941
1942 let mut result = TurbineValue::empty();
1943 let status = runmat_call_semantic_function_value(
1944 function.0 as i64,
1945 std::ptr::null(),
1946 0,
1947 &mut result,
1948 );
1949
1950 assert_eq!(status, 0);
1951 assert_eq!(
1952 result.to_runtime_value().unwrap(),
1953 Value::String("ok".to_string())
1954 );
1955 }
1956
1957 #[test]
1958 fn function_values_host_call_writes_multiple_outputs() {
1959 let function = FunctionId(3);
1960 let _context = install_semantic_context(vec![bound_function(
1961 function,
1962 "pair",
1963 vec![
1964 Instr::LoadVar(0),
1965 Instr::StoreVar(1),
1966 Instr::LoadString("done".to_string()),
1967 Instr::StoreVar(2),
1968 ],
1969 3,
1970 vec![0],
1971 vec![1, 2],
1972 )]);
1973
1974 let args = [TurbineValue::from_runtime_value(Value::Num(7.0)).unwrap()];
1975 let mut results = [TurbineValue::empty(), TurbineValue::empty()];
1976 let status = runmat_call_semantic_function_values(
1977 function.0 as i64,
1978 args.as_ptr(),
1979 args.len() as i32,
1980 results.len() as i32,
1981 results.as_mut_ptr(),
1982 );
1983
1984 assert_eq!(status, 0);
1985 assert_eq!(results[0].to_runtime_value().unwrap(), Value::Num(7.0));
1986 assert_eq!(
1987 results[1].to_runtime_value().unwrap(),
1988 Value::String("done".to_string())
1989 );
1990 }
1991}