Refactor: Use Rc/RefCell for shared mutable state
This commit replaces `Arc<Mutex<T>>` with `Rc<RefCell<T>>` for managing shared mutable state within the AST and VM. This change is primarily an internal refactoring to leverage Rust's standard library more effectively for single-threaded scenarios, improving performance by avoiding the overhead of mutexes. The following types and their usage have been updated: - `Environment.global_names` and `Environment.global_values` - `Binder.globals` - `bound_nodes::BoundKind::Lambda.body` (now `Rc<Node>`) - `ast::types::NodeIdentity` (now `Rc<NodeIdentity>`) - `ast::types::Value::List`, `Value::Record`, `Value::Function`, `Value::Object`, `Value::Cell` - `ast::nodes::Scope` and `ast::nodes::Context` - `ast::vm::Closure.function_node` and `Closure.upvalues` - `ast::vm::VM.globals` This change does not alter the external behavior of the library but streamlines internal data management.
This commit is contained in:
+10
-9
@@ -1,4 +1,5 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::rc::Rc;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use crate::ast::types::{Value, StaticType};
|
||||
use crate::ast::parser::Parser;
|
||||
@@ -6,8 +7,8 @@ use crate::ast::compiler::binder::Binder;
|
||||
use crate::ast::vm::VM;
|
||||
|
||||
pub struct Environment {
|
||||
pub global_names: Arc<Mutex<HashMap<String, (u32, StaticType)>>>,
|
||||
pub global_values: Arc<Mutex<Vec<Value>>>,
|
||||
pub global_names: Rc<RefCell<HashMap<String, (u32, StaticType)>>>,
|
||||
pub global_values: Rc<RefCell<Vec<Value>>>,
|
||||
}
|
||||
|
||||
impl Default for Environment {
|
||||
@@ -19,20 +20,20 @@ impl Default for Environment {
|
||||
impl Environment {
|
||||
pub fn new() -> Self {
|
||||
let env = Self {
|
||||
global_names: Arc::new(Mutex::new(HashMap::new())),
|
||||
global_values: Arc::new(Mutex::new(Vec::new())),
|
||||
global_names: Rc::new(RefCell::new(HashMap::new())),
|
||||
global_values: Rc::new(RefCell::new(Vec::new())),
|
||||
};
|
||||
env.register_stdlib();
|
||||
env
|
||||
}
|
||||
|
||||
pub fn register_native(&self, name: &str, ty: StaticType, func: fn(Vec<Value>) -> Value) {
|
||||
let mut names = self.global_names.lock().unwrap();
|
||||
let mut values = self.global_values.lock().unwrap();
|
||||
pub fn register_native(&self, name: &str, ty: StaticType, func: impl Fn(Vec<Value>) -> Value + 'static) {
|
||||
let mut names = self.global_names.borrow_mut();
|
||||
let mut values = self.global_values.borrow_mut();
|
||||
|
||||
let idx = values.len() as u32;
|
||||
names.insert(name.to_string(), (idx, ty));
|
||||
values.push(Value::Function(Arc::new(func)));
|
||||
values.push(Value::Function(Rc::new(func)));
|
||||
}
|
||||
|
||||
fn register_stdlib(&self) {
|
||||
|
||||
Reference in New Issue
Block a user