Refactor discover_globals to handle patterns

The `discover_globals` function has been refactored to better handle
pattern matching within definitions. It now uses a recursive helper
function `register_pattern` to correctly process identifiers and tuple
patterns. This ensures that all declared variables within a `Def` node
are registered with their corresponding scope and virtual ID.
Additionally, support for `Expansion` nodes has been added to ensure
that any nested global definitions within them are also discovered.
This commit is contained in:
2026-03-27 08:27:31 +01:00
parent 903c77a665
commit cb4162e420
+38 -18
View File
@@ -458,26 +458,43 @@ impl Environment {
fn discover_globals(&self, node: &SyntaxNode) {
match &node.kind {
SyntaxKind::Def { pattern, .. } => {
if let SyntaxKind::Identifier { symbol: sym, .. } = &pattern.kind {
let mut root_scopes = self.root_scopes.borrow_mut();
let last_idx = root_scopes.len() - 1;
let current_scope = &mut root_scopes[last_idx];
let mut root_scopes = self.root_scopes.borrow_mut();
let last_idx = root_scopes.len() - 1;
let current_scope = &mut root_scopes[last_idx];
if !current_scope.locals.contains_key(sym) {
let mut slot_count = self.root_slot_count.borrow_mut();
let slot = VirtualId(*slot_count);
current_scope.locals.insert(
sym.clone(),
LocalInfo {
addr: Address::Local(slot),
identity: node.identity.clone(),
_ty: StaticType::Any,
purity: Purity::Impure,
},
);
*slot_count += 1;
fn register_pattern(
pattern: &SyntaxNode,
scope: &mut CompilerScope,
slot_count: &mut u32,
identity: &crate::ast::types::NodeIdentity,
) {
match &pattern.kind {
SyntaxKind::Identifier { symbol: sym, .. } => {
if !scope.locals.contains_key(sym) {
let slot = VirtualId(*slot_count);
scope.locals.insert(
sym.clone(),
LocalInfo {
addr: Address::Local(slot),
identity: Rc::new(identity.clone()),
_ty: StaticType::Any,
purity: Purity::Impure,
},
);
*slot_count += 1;
}
}
SyntaxKind::Tuple { elements } => {
for el in elements {
register_pattern(el, scope, slot_count, identity);
}
}
_ => {}
}
}
let mut slot_count = self.root_slot_count.borrow_mut();
register_pattern(pattern, current_scope, &mut slot_count, &node.identity);
}
SyntaxKind::MacroDecl { name, params, body } => {
let mut registry = self.macro_registry.borrow_mut();
@@ -491,7 +508,7 @@ impl Environment {
_ => vec![],
}
}
let p_names = extract_names(params);
registry.define(name.name.clone(), p_names, body.as_ref().clone());
}
@@ -500,6 +517,9 @@ impl Environment {
self.discover_globals(expr);
}
}
SyntaxKind::Expansion { expanded, .. } => {
self.discover_globals(expanded);
}
_ => {}
}
}