Refactor native function registration and instantiation

Introduces `register_native` for direct registration of `NativeFunction`
and `register_native_fn` for convenience from closures. The
`Environment::run`
method is removed, and its functionality is now handled by
`Environment::instantiate`,
which packages the linked AST into an invokable `NativeFunction`. This
streamlines
the execution path and better separates compilation/linking from runtime
execution.
This commit is contained in:
Michael Schimmel
2026-02-22 11:56:46 +01:00
parent a726b79d8a
commit cb94f20c0b
7 changed files with 143 additions and 65 deletions
+91 -34
View File
@@ -7,7 +7,7 @@ use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use crate::ast::compiler::bound_nodes::{Address, BoundNode};
use crate::ast::compiler::bound_nodes::{Address, BoundKind, BoundNode};
use crate::ast::compiler::dumper::Dumper;
use crate::ast::compiler::lambda_collector::LambdaCollector;
use crate::ast::compiler::macros::{MacroEvaluator, MacroExpander, MacroRegistry};
@@ -118,8 +118,7 @@ impl Environment {
&self,
name: &str,
ty: StaticType,
purity_level: Purity,
func: impl Fn(Vec<Value>) -> Value + 'static,
func: Rc<crate::ast::types::NativeFunction>,
) {
let mut names = self.global_names.borrow_mut();
let mut types = self.global_types.borrow_mut();
@@ -129,8 +128,26 @@ impl Environment {
let idx = values.len() as u32;
names.insert(Symbol::from(name), idx);
types.insert(idx, ty);
purity.insert(idx, purity_level);
values.push(Value::make_function(purity_level, func));
purity.insert(idx, func.purity);
values.push(Value::Function(func));
}
/// Utility to register a native function from a closure.
pub fn register_native_fn(
&self,
name: &str,
ty: StaticType,
purity_level: Purity,
func: impl Fn(Vec<Value>) -> Value + 'static,
) {
self.register_native(
name,
ty,
Rc::new(crate::ast::types::NativeFunction {
func: Rc::new(func),
purity: purity_level,
}),
);
}
pub fn register_constant(&self, name: &str, ty: StaticType, val: Value) {
@@ -190,7 +207,7 @@ impl Environment {
Ok(typed_ast)
}
/// Backend: Optimization (TCO, etc.)
/// Backend Phase 1: Optimization (TCO, etc.) and Lowering
pub fn link(&self, node: TypedNode) -> ExecNode {
// 1. Specialize (Always performed for correctness)
let specialized = self.specialize_node(node);
@@ -206,6 +223,72 @@ impl Environment {
TCO::optimize(optimized)
}
/// Backend Phase 2: Packaging into an invokable NativeFunction
pub fn instantiate(&self, node: ExecNode) -> Rc<crate::ast::types::NativeFunction> {
let global_values = self.global_values.clone();
// OPTIMIZATION: Fast path for top-level Lambdas.
// If the script root is a Lambda with no captures (root functions usually have none),
// we can pre-create the closure and call it directly.
if let BoundKind::Lambda {
params,
upvalues,
body,
positional_count,
} = &node.kind
&& upvalues.is_empty()
{
let closure = Rc::new(crate::ast::vm::Closure::new(
params.ty.original.clone(),
body.ty.original.clone(),
body.clone(),
vec![],
*positional_count,
));
return Rc::new(crate::ast::types::NativeFunction {
purity: Purity::Impure,
func: Rc::new(move |args| {
let mut vm = VM::new(global_values.clone());
let res = match vm.run_with_args(&closure, args) {
Ok(v) => v,
Err(e) => panic!("Myc Runtime Error: {}", e),
};
vm.resolve_tail_calls(res)
}),
});
}
// FALLBACK: Generic script body (Block, If, etc.)
let exec_node = Rc::new(node);
Rc::new(crate::ast::types::NativeFunction {
purity: Purity::Impure,
func: Rc::new(move |args| {
let mut vm = VM::new(global_values.clone());
// 1. Execute the main body (Block, etc.)
let res = match vm.run(&exec_node) {
Ok(v) => v,
Err(e) => panic!("Myc Runtime Error: {}", e),
};
// 2. Auto-apply: If the script returned a closure, we apply arguments to it.
let mut final_res = res;
if let Value::Object(obj) = &final_res {
if let Some(closure) = obj.as_any().downcast_ref::<crate::ast::vm::Closure>() {
final_res = match vm.run_with_args(closure, args) {
Ok(v) => v,
Err(e) => panic!("Myc Runtime Error (Closure): {}", e),
};
}
}
// 3. Resolve Tail Calls
vm.resolve_tail_calls(final_res)
}),
})
}
fn specialize_node(&self, node: TypedNode) -> TypedNode {
let registry = Rc::new(EnvFunctionRegistry {
registry: self.function_registry.clone(),
@@ -281,33 +364,6 @@ impl Environment {
specializer.specialize(node)
}
/// Runtime: Execute the linked AST in the VM
pub fn run(&self, node: &ExecNode) -> Result<Value, String> {
let mut vm = VM::new(self.global_values.clone());
let mut result = vm.run(node)?;
// Handle potential script body closure
if let Value::Object(obj) = &result
&& let Some(closure) = obj.as_any().downcast_ref::<crate::ast::vm::Closure>()
{
result = vm.run(&closure.exec_node)?;
}
// IMPORTANT: Resolve any pending tail call requests from the top-level execution
while let Value::TailCallRequest(payload) = result {
let (next_obj, next_args) = *payload;
if let Some(closure) = next_obj.as_any().downcast_ref::<crate::ast::vm::Closure>() {
result = vm.run_with_args(closure, next_args)?;
} else {
return Err(format!(
"Tail call target is not a closure: {}",
next_obj.type_name()
));
}
}
Ok(result)
}
pub fn run_script(&self, source: &str) -> Result<Value, String> {
if self.debug_mode {
let (res, logs) = self.run_debug(source)?;
@@ -318,7 +374,8 @@ impl Environment {
} else {
let compiled = self.compile(source)?;
let linked = self.link(compiled);
self.run(&linked)
let func = self.instantiate(linked);
Ok((func.func)(vec![]))
}
}