Refactor global slot allocation

Introduce `allocate_slot` helper function to centralize the logic for
allocating new global slots. This improves code clarity and reduces
duplication by consolidating common operations like updating scopes,
types, purity, and values.
This commit is contained in:
2026-03-27 13:18:59 +01:00
parent 325e690cd9
commit 9b7c0b68a4
+23 -51
View File
@@ -590,37 +590,34 @@ impl Environment {
Ok(typed_ast_opt.unwrap())
}
/// Allocates a new global slot and registers a value in the fixed RTL scope (scope index 0).
/// This is the single source of truth for all global slot allocation.
fn allocate_slot(&self, name: &str, ty: StaticType, purity: Purity, val: Value) {
let mut root_scopes = self.root_scopes.borrow_mut();
let mut slot_count = self.root_slot_count.borrow_mut();
let global_idx = GlobalIdx(*slot_count);
root_scopes[0].locals.insert(
Symbol::from(name),
LocalInfo {
addr: Address::Global(global_idx),
identity: NodeIdentity::new(SourceLocation { line: 0, col: 0 }),
_ty: ty.clone(),
purity,
},
);
*slot_count += 1;
self.root_types.borrow_mut().push(ty);
self.root_purity.borrow_mut().push(purity);
self.root_values.borrow_mut().push(val);
}
pub fn register_native(
&self,
name: &str,
ty: StaticType,
func: Rc<NativeFunction>,
) {
let mut types = self.root_types.borrow_mut();
let mut values = self.root_values.borrow_mut();
let mut purity = self.root_purity.borrow_mut();
let identity = NodeIdentity::new(SourceLocation { line: 0, col: 0 });
// populate root_scopes[0]
let mut root_scopes = self.root_scopes.borrow_mut();
let mut slot_count = self.root_slot_count.borrow_mut();
let global_idx = GlobalIdx(*slot_count);
root_scopes[0].locals.insert(
Symbol::from(name),
LocalInfo {
addr: Address::Global(global_idx),
identity,
_ty: ty.clone(),
purity: func.purity,
},
);
*slot_count += 1;
types.push(ty);
purity.push(func.purity);
values.push(Value::Function(func));
self.allocate_slot(name, ty, func.purity, Value::Function(func));
}
pub fn register_native_fn(
@@ -648,32 +645,7 @@ impl Environment {
}
pub fn register_constant(&self, name: &str, ty: StaticType, val: Value) -> RtlRegistration {
let mut types = self.root_types.borrow_mut();
let mut values = self.root_values.borrow_mut();
let mut purity = self.root_purity.borrow_mut();
let identity = NodeIdentity::new(SourceLocation { line: 0, col: 0 });
// populate root_scopes[0]
let mut root_scopes = self.root_scopes.borrow_mut();
let mut slot_count = self.root_slot_count.borrow_mut();
let global_idx = GlobalIdx(*slot_count);
root_scopes[0].locals.insert(
Symbol::from(name),
LocalInfo {
addr: Address::Global(global_idx),
identity,
_ty: ty.clone(),
purity: Purity::Pure,
},
);
*slot_count += 1;
types.push(ty);
purity.push(Purity::Pure);
values.push(val);
self.allocate_slot(name, ty, Purity::Pure, val);
RtlRegistration {
name: name.to_string(),
rtl_docs: Rc::clone(&self.rtl_docs),