runes-core 0.1.0

Core types and traits for the Runes language
Documentation
use std::collections::{HashMap, HashSet};

use crate::symbol::SymbolId;
use crate::value::Value;

/// A single lexical scope frame.
struct ScopeFrame {
    bindings: HashMap<SymbolId, Value>,
}

/// Lexical scope stack for variable binding during evaluation.
pub struct Scope {
    frames: Vec<ScopeFrame>,
}

impl Scope {
    /// Create a new scope with a single root frame.
    pub fn new() -> Self {
        Self {
            frames: vec![ScopeFrame {
                bindings: HashMap::new(),
            }],
        }
    }

    /// Push a new child scope frame.
    pub fn push(&mut self) {
        self.frames.push(ScopeFrame {
            bindings: HashMap::new(),
        });
    }

    /// Pop the innermost scope frame. Panics if only the root frame remains.
    pub fn pop(&mut self) {
        assert!(self.frames.len() > 1, "Cannot pop root scope frame");
        self.frames.pop();
    }

    /// Depth of the scope stack (1 = root only).
    pub fn depth(&self) -> usize {
        self.frames.len()
    }

    /// Define a variable in the current (innermost) scope.
    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);
    }

    /// Look up a variable, searching from innermost to outermost scope.
    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
    }

    /// Snapshot all visible bindings (innermost wins). Used for closure capture.
    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
    }

    /// Set an existing variable in the nearest enclosing scope that contains it.
    /// Returns `false` if the variable is not defined in any scope.
    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()
    }
}