Skip to main content

sim_lib_lang_lua/
env.rs

1use sim_kernel::{Result, Symbol, Value};
2use sim_lib_binding::{BindingCell, LexicalEnv};
3
4/// Lexical local environment used by the Lua core eval policy.
5#[derive(Clone, Debug, Default)]
6pub struct LuaEnv {
7    lexical: LexicalEnv,
8}
9
10impl LuaEnv {
11    /// Build an empty Lua local environment.
12    pub fn new() -> Self {
13        Self::default()
14    }
15
16    /// Open a nested scope whose lookups fall through to this one.
17    pub fn child(&self) -> Self {
18        Self {
19            lexical: self.lexical.child(),
20        }
21    }
22
23    /// Bind a Lua local value in the current frame.
24    pub fn define(&mut self, name: Symbol, value: Value) -> Result<()> {
25        self.lexical.define(name, value)
26    }
27
28    /// Return whether a Lua local is bound.
29    pub fn contains(&self, name: &Symbol) -> bool {
30        self.lexical.lookup(name).is_ok()
31    }
32
33    /// Assign an existing Lua local.
34    pub fn assign(&mut self, name: &Symbol, value: Value) -> Result<Value> {
35        self.capture(name)?.set(value.clone())?;
36        Ok(value)
37    }
38
39    /// Look up a Lua local value.
40    pub fn get(&self, name: &Symbol) -> Result<Value> {
41        self.lexical.lookup(name)
42    }
43
44    /// Capture an existing Lua local as a shared upvalue cell.
45    pub fn capture(&self, name: &Symbol) -> Result<BindingCell> {
46        self.lexical.capture_cell(name)
47    }
48}