Add LambdaCollector and Intrinsic Lookup
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
use std::collections::HashMap;
|
||||
use crate::ast::compiler::TypedNode;
|
||||
use crate::ast::compiler::bound_nodes::{BoundKind, Address};
|
||||
|
||||
/// A pass that collects all global function definitions (lambdas) into a registry.
|
||||
/// This allows the Specializer to retrieve the original AST of a function for monomorphization.
|
||||
pub struct LambdaCollector<'a> {
|
||||
registry: &'a mut HashMap<u32, TypedNode>,
|
||||
}
|
||||
|
||||
impl<'a> LambdaCollector<'a> {
|
||||
/// Performs a full traversal of the AST and populates the provided registry.
|
||||
pub fn collect(node: &TypedNode, registry: &'a mut HashMap<u32, TypedNode>) {
|
||||
let mut collector = Self { registry };
|
||||
collector.visit(node);
|
||||
}
|
||||
|
||||
fn visit(&mut self, node: &TypedNode) {
|
||||
match &node.kind {
|
||||
BoundKind::Block { exprs } => {
|
||||
for expr in exprs {
|
||||
self.visit(expr);
|
||||
}
|
||||
}
|
||||
|
||||
BoundKind::DefGlobal { global_index, value, .. } => {
|
||||
// If we define a global that is a lambda, register it as a template.
|
||||
if let BoundKind::Lambda { .. } = &value.kind {
|
||||
self.registry.insert(*global_index, (**value).clone());
|
||||
}
|
||||
self.visit(value);
|
||||
}
|
||||
|
||||
BoundKind::Set { addr, value } => {
|
||||
// Also track assignments to globals if they hold lambdas.
|
||||
if let Address::Global(global_index) = addr {
|
||||
if let BoundKind::Lambda { .. } = &value.kind {
|
||||
self.registry.insert(*global_index, (**value).clone());
|
||||
}
|
||||
}
|
||||
self.visit(value);
|
||||
}
|
||||
|
||||
BoundKind::If { cond, then_br, else_br } => {
|
||||
self.visit(cond);
|
||||
self.visit(then_br);
|
||||
if let Some(e) = else_br {
|
||||
self.visit(e);
|
||||
}
|
||||
}
|
||||
|
||||
BoundKind::Lambda { body, .. } => {
|
||||
// Nested functions are not yet supported for global specialization
|
||||
// but we traverse them to find potential global definitions inside (if allowed).
|
||||
self.visit(body);
|
||||
}
|
||||
|
||||
BoundKind::DefLocal { value, .. } => {
|
||||
self.visit(value);
|
||||
}
|
||||
|
||||
BoundKind::Call { callee, args } | BoundKind::TailCall { callee, args } => {
|
||||
self.visit(callee);
|
||||
for arg in args {
|
||||
self.visit(arg);
|
||||
}
|
||||
}
|
||||
|
||||
BoundKind::Tuple { elements } => {
|
||||
for el in elements {
|
||||
self.visit(el);
|
||||
}
|
||||
}
|
||||
|
||||
BoundKind::Map { entries } => {
|
||||
for (k, v) in entries {
|
||||
self.visit(k);
|
||||
self.visit(v);
|
||||
}
|
||||
}
|
||||
|
||||
BoundKind::Expansion { bound_expanded, .. } => {
|
||||
self.visit(bound_expanded);
|
||||
}
|
||||
|
||||
_ => {} // Leaf nodes (Constant, Get, Nop, etc.)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user