1use std::collections::BTreeMap;
2use std::rc::Rc;
3use std::{cell::RefCell, path::PathBuf};
4
5use crate::chunk::CompiledFunctionRef;
6
7use super::{VmError, VmValue};
8
9#[derive(Debug, Clone)]
11pub struct VmClosure {
12 pub func: CompiledFunctionRef,
13 pub env: VmEnv,
14 pub source_dir: Option<PathBuf>,
18 pub module_functions: Option<ModuleFunctionRegistry>,
22 pub module_state: Option<ModuleState>,
35}
36
37pub type ModuleFunctionRegistry = Rc<RefCell<BTreeMap<String, Rc<VmClosure>>>>;
38pub type ModuleState = Rc<RefCell<VmEnv>>;
39
40#[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)>, }
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 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
154fn 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
172pub 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 .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}