use std::collections::{HashMap, HashSet};
use crate::symbol::SymbolId;
use crate::value::Value;
struct ScopeFrame {
bindings: HashMap<SymbolId, Value>,
}
pub struct Scope {
frames: Vec<ScopeFrame>,
}
impl Scope {
pub fn new() -> Self {
Self {
frames: vec![ScopeFrame {
bindings: HashMap::new(),
}],
}
}
pub fn push(&mut self) {
self.frames.push(ScopeFrame {
bindings: HashMap::new(),
});
}
pub fn pop(&mut self) {
assert!(self.frames.len() > 1, "Cannot pop root scope frame");
self.frames.pop();
}
pub fn depth(&self) -> usize {
self.frames.len()
}
pub fn define(&mut self, name: SymbolId, value: Value) {
self.frames
.last_mut()
.expect("Scope must have at least one frame")
.bindings
.insert(name, value);
}
pub fn get(&self, name: SymbolId) -> Option<&Value> {
for frame in self.frames.iter().rev() {
if let Some(val) = frame.bindings.get(&name) {
return Some(val);
}
}
None
}
pub fn snapshot(&self) -> Vec<(SymbolId, Value)> {
let mut seen = HashSet::new();
let mut bindings = Vec::new();
for frame in self.frames.iter().rev() {
for (sym, val) in &frame.bindings {
if seen.insert(*sym) {
bindings.push((*sym, val.clone()));
}
}
}
bindings
}
pub fn set(&mut self, name: SymbolId, value: Value) -> bool {
for frame in self.frames.iter_mut().rev() {
if frame.bindings.contains_key(&name) {
frame.bindings.insert(name, value);
return true;
}
}
false
}
}
impl Default for Scope {
fn default() -> Self {
Self::new()
}
}