Skip to main content

aether/
environment.rs

1// src/environment.rs
2//! Environment for variable storage and scoping
3//! 优化版本: 减少Rc/RefCell开销, 使用索引代替指针
4
5use crate::value::Value;
6use std::cell::RefCell;
7use std::collections::HashMap;
8use std::rc::Rc;
9
10/// Environment for storing variables
11#[derive(Debug, Clone)]
12pub struct Environment {
13    /// Variables in this scope (使用预分配容量优化)
14    store: HashMap<String, Value>,
15
16    /// Parent environment (for nested scopes)
17    parent: Option<Rc<RefCell<Environment>>>,
18}
19
20impl Environment {
21    /// Create a new global environment (with pre-allocated capacity)
22    pub fn new() -> Self {
23        Environment {
24            store: HashMap::with_capacity(16), // 预分配容量减少rehash
25            parent: None,
26        }
27    }
28
29    /// Create a new environment with a parent
30    pub fn with_parent(parent: Rc<RefCell<Environment>>) -> Self {
31        Environment {
32            store: HashMap::with_capacity(8), // 子环境通常变量较少
33            parent: Some(parent),
34        }
35    }
36
37    /// Set a variable in the current scope
38    pub fn set(&mut self, name: String, value: Value) {
39        self.store.insert(name, value);
40    }
41
42    /// Get a variable from this scope or parent scopes (优化路径)
43    pub fn get(&self, name: &str) -> Option<Value> {
44        // 快速路径: 直接在当前作用域查找
45        if let Some(value) = self.store.get(name) {
46            return Some(value.clone());
47        }
48
49        // 慢速路径: 递归查找父作用域
50        self.get_from_parent(name)
51    }
52
53    /// 从父作用域获取变量 (分离热路径和冷路径)
54    #[inline(never)]
55    fn get_from_parent(&self, name: &str) -> Option<Value> {
56        self.parent.as_ref()?.borrow().get(name)
57    }
58
59    /// Check if a variable exists in this scope or parent scopes
60    pub fn has(&self, name: &str) -> bool {
61        self.store.contains_key(name) || self.parent.as_ref().is_some_and(|p| p.borrow().has(name))
62    }
63
64    /// Update a variable in the scope where it was defined
65    /// Returns true if the variable was found and updated
66    pub fn update(&mut self, name: &str, value: Value) -> bool {
67        if self.store.contains_key(name) {
68            self.store.insert(name.to_string(), value);
69            return true;
70        }
71
72        if let Some(parent) = &self.parent {
73            return parent.borrow_mut().update(name, value);
74        }
75
76        false
77    }
78
79    /// Get all variable names in this scope
80    pub fn keys(&self) -> Vec<String> {
81        self.store.keys().cloned().collect()
82    }
83
84    /// Clear all variables in this scope (not parent scopes)
85    pub fn clear(&mut self) {
86        self.store.clear();
87    }
88}
89
90impl Default for Environment {
91    fn default() -> Self {
92        Self::new()
93    }
94}