Skip to main content

harn_vm/value/
env.rs

1use std::collections::BTreeMap;
2use std::rc::Rc;
3use std::{cell::RefCell, path::PathBuf};
4
5use crate::chunk::CompiledFunction;
6
7use super::{VmError, VmValue};
8
9/// A compiled closure value.
10#[derive(Debug, Clone)]
11pub struct VmClosure {
12    pub func: CompiledFunction,
13    pub env: VmEnv,
14    /// Source directory for this closure's originating module.
15    /// When set, `render()` and other source-relative builtins resolve
16    /// paths relative to this directory instead of the entry pipeline.
17    pub source_dir: Option<PathBuf>,
18    /// Module-local named functions that should resolve before builtin fallback.
19    /// This lets selectively imported functions keep private sibling helpers
20    /// without exporting them into the caller's environment.
21    pub module_functions: Option<ModuleFunctionRegistry>,
22    /// Shared, mutable module-level env: holds top-level `var` / `let`
23    /// bindings declared at the module root (caches, counters, lazily
24    /// initialized registries). All closures created from the same
25    /// module import point at the same `Rc<RefCell<VmEnv>>`, so a
26    /// mutation inside one function is visible to every other function
27    /// in that module on subsequent calls. `closure.env` still holds
28    /// the per-closure lexical snapshot (captured function args from
29    /// enclosing scopes, etc.) and is unchanged by this — `module_state`
30    /// is a separate lookup layer consulted after the local env and
31    /// before globals. Created in `import_declarations` after the
32    /// module's init chunk runs, so the initial values from `var x = ...`
33    /// land in it.
34    pub module_state: Option<ModuleState>,
35}
36
37pub type ModuleFunctionRegistry = Rc<RefCell<BTreeMap<String, Rc<VmClosure>>>>;
38pub type ModuleState = Rc<RefCell<VmEnv>>;
39
40/// VM environment for variable storage.
41#[derive(Debug, Clone)]
42pub struct VmEnv {
43    pub(crate) scopes: Vec<Scope>,
44}
45
46#[derive(Debug, Clone)]
47pub(crate) struct Scope {
48    pub(crate) vars: BTreeMap<String, (VmValue, bool)>, // (value, mutable)
49}
50
51impl Default for VmEnv {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57impl VmEnv {
58    pub fn new() -> Self {
59        Self {
60            scopes: vec![Scope {
61                vars: BTreeMap::new(),
62            }],
63        }
64    }
65
66    pub fn push_scope(&mut self) {
67        self.scopes.push(Scope {
68            vars: BTreeMap::new(),
69        });
70    }
71
72    pub fn pop_scope(&mut self) {
73        if self.scopes.len() > 1 {
74            self.scopes.pop();
75        }
76    }
77
78    pub fn scope_depth(&self) -> usize {
79        self.scopes.len()
80    }
81
82    pub fn truncate_scopes(&mut self, target_depth: usize) {
83        let min_depth = target_depth.max(1);
84        while self.scopes.len() > min_depth {
85            self.scopes.pop();
86        }
87    }
88
89    pub fn get(&self, name: &str) -> Option<VmValue> {
90        for scope in self.scopes.iter().rev() {
91            if let Some((val, _)) = scope.vars.get(name) {
92                return Some(val.clone());
93            }
94        }
95        None
96    }
97
98    pub fn define(&mut self, name: &str, value: VmValue, mutable: bool) -> Result<(), VmError> {
99        if let Some(scope) = self.scopes.last_mut() {
100            if let Some((_, existing_mutable)) = scope.vars.get(name) {
101                if !existing_mutable && !mutable {
102                    return Err(VmError::Runtime(format!(
103                        "Cannot redeclare immutable variable '{name}' in the same scope (use 'var' for mutable bindings)"
104                    )));
105                }
106            }
107            scope.vars.insert(name.to_string(), (value, mutable));
108        }
109        Ok(())
110    }
111
112    pub fn all_variables(&self) -> BTreeMap<String, VmValue> {
113        let mut vars = BTreeMap::new();
114        for scope in &self.scopes {
115            for (name, (value, _)) in &scope.vars {
116                vars.insert(name.clone(), value.clone());
117            }
118        }
119        vars
120    }
121
122    pub fn assign(&mut self, name: &str, value: VmValue) -> Result<(), VmError> {
123        for scope in self.scopes.iter_mut().rev() {
124            if let Some((_, mutable)) = scope.vars.get(name) {
125                if !mutable {
126                    return Err(VmError::ImmutableAssignment(name.to_string()));
127                }
128                scope.vars.insert(name.to_string(), (value, true));
129                return Ok(());
130            }
131        }
132        Err(VmError::UndefinedVariable(name.to_string()))
133    }
134
135    /// Debugger-only variant of `assign` that rebinds the name even if
136    /// the existing binding was declared with `let`. Pipeline authors
137    /// overwhelmingly use `let`, so a strict mutability check would
138    /// make the DAP `setVariable` request useless for "what-if"
139    /// iteration — which is the whole point of the feature. Preserves
140    /// the original mutability flag so the VM's runtime behavior is
141    /// unchanged after the debugger overrides.
142    pub fn assign_debug(&mut self, name: &str, value: VmValue) -> Result<(), VmError> {
143        for scope in self.scopes.iter_mut().rev() {
144            if let Some((_, mutable)) = scope.vars.get(name) {
145                let mutable = *mutable;
146                scope.vars.insert(name.to_string(), (value, mutable));
147                return Ok(());
148            }
149        }
150        Err(VmError::UndefinedVariable(name.to_string()))
151    }
152}
153
154/// Compute Levenshtein edit distance between two strings.
155fn levenshtein(a: &str, b: &str) -> usize {
156    let a: Vec<char> = a.chars().collect();
157    let b: Vec<char> = b.chars().collect();
158    let (m, n) = (a.len(), b.len());
159    let mut prev = (0..=n).collect::<Vec<_>>();
160    let mut curr = vec![0; n + 1];
161    for i in 1..=m {
162        curr[0] = i;
163        for j in 1..=n {
164            let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
165            curr[j] = (prev[j] + 1).min(curr[j - 1] + 1).min(prev[j - 1] + cost);
166        }
167        std::mem::swap(&mut prev, &mut curr);
168    }
169    prev[n]
170}
171
172/// Find the closest match from a list of candidates using Levenshtein distance.
173/// Returns `Some(suggestion)` if a candidate is within `max_dist` edits.
174pub fn closest_match<'a>(name: &str, candidates: impl Iterator<Item = &'a str>) -> Option<String> {
175    let max_dist = match name.len() {
176        0..=2 => 1,
177        3..=5 => 2,
178        _ => 3,
179    };
180    candidates
181        .filter(|c| *c != name && !c.starts_with("__"))
182        .map(|c| (c, levenshtein(name, c)))
183        .filter(|(_, d)| *d <= max_dist)
184        // Prefer smallest distance, then closest length to original, then alphabetical
185        .min_by(|(a, da), (b, db)| {
186            da.cmp(db)
187                .then_with(|| {
188                    let a_diff = (a.len() as isize - name.len() as isize).unsigned_abs();
189                    let b_diff = (b.len() as isize - name.len() as isize).unsigned_abs();
190                    a_diff.cmp(&b_diff)
191                })
192                .then_with(|| a.cmp(b))
193        })
194        .map(|(c, _)| c.to_string())
195}