Refactor: Implement late stack size calculation

This commit introduces a new mechanism for calculating the required
stack size for closures at bind time, rather than storing it in the AST.
This is achieved by adding a `calculate_stack_size` method to
`BoundNode`.

Key changes include:
- `BoundNode::calculate_stack_size`: Recursively traverses the bound AST
  to find the maximum `LocalSlot` index used.
- Recursion blocker for lambdas: Ensures that nested lambdas are not
  visited during stack size calculation for the outer closure,
  preventing incorrect stack size estimations.
- VM update: The `VM::run` method now accepts and uses the
  pre-calculated stack size for setting up call frames.
- `Closure` struct update: Stores the `stack_size` directly within the
  `Closure` struct.
- Binder and TypeChecker updates: Minor adjustments to accommodate the
  new strategy and error reporting.
- Optimizer enhancements: Constant and pure-lambda propagation for
  `Define` statements within blocks to ensure inlinability.

This refactoring addresses issues related to accurate stack size
management and improves the overall robustness of the binder and VM.
This commit is contained in:
Michael Schimmel
2026-03-10 20:05:32 +01:00
parent cb4d3525c2
commit 8c865681ff
8 changed files with 1063 additions and 896 deletions
+13
View File
@@ -500,6 +500,19 @@ impl Optimizer {
}
let opt = self.visit_node(e.clone(), sub, path);
if let BoundKind::Define { addr, value, .. } = &opt.kind
&& !info.assigned.contains(addr)
{
if let BoundKind::Constant(val) = &value.kind {
sub.add_value(*addr, val.clone());
} else if let BoundKind::Lambda { upvalues, .. } = &value.kind
&& upvalues.is_empty()
{
sub.add_ast_substitution(*addr, (**value).clone());
}
}
if self.enabled && matches!(opt.kind, BoundKind::Nop) && !is_last {
block_changed = true;
continue;