1use std::collections::BTreeMap;
2use std::path::PathBuf;
3use std::sync::{Arc, Weak};
4
5use crate::chunk::CompiledFunctionRef;
6
7use super::{VmError, VmMutex, 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<WeakModuleFunctionRegistry>,
22 pub module_state: Option<WeakModuleState>,
35}
36
37pub type ModuleFunctionRegistry = Arc<VmMutex<BTreeMap<String, Arc<VmClosure>>>>;
38pub type WeakModuleFunctionRegistry = Weak<VmMutex<BTreeMap<String, Arc<VmClosure>>>>;
39pub type ModuleState = Arc<VmMutex<VmEnv>>;
40pub type WeakModuleState = Weak<VmMutex<VmEnv>>;
41
42impl VmClosure {
43 pub(crate) fn module_functions(&self) -> Option<ModuleFunctionRegistry> {
44 self.module_functions
45 .as_ref()
46 .and_then(WeakModuleFunctionRegistry::upgrade)
47 }
48
49 pub(crate) fn module_state(&self) -> Option<ModuleState> {
50 self.module_state
51 .as_ref()
52 .and_then(WeakModuleState::upgrade)
53 }
54}
55
56#[derive(Debug, Clone)]
68pub struct VmEnv {
69 pub(crate) scopes: Vec<Scope>,
70}
71
72#[derive(Debug, Clone)]
73pub(crate) struct Scope {
74 pub(crate) vars: Arc<BTreeMap<String, (VmValue, bool)>>, }
76
77impl Scope {
78 #[inline]
79 fn empty() -> Self {
80 Self {
81 vars: Arc::new(BTreeMap::new()),
82 }
83 }
84}
85
86impl Default for VmEnv {
87 fn default() -> Self {
88 Self::new()
89 }
90}
91
92impl VmEnv {
93 pub fn new() -> Self {
94 Self {
95 scopes: vec![Scope::empty()],
96 }
97 }
98
99 pub fn push_scope(&mut self) {
100 self.scopes.push(Scope::empty());
101 }
102
103 pub fn pop_scope(&mut self) {
104 if self.scopes.len() > 1 {
105 self.scopes.pop();
106 }
107 }
108
109 pub fn scope_depth(&self) -> usize {
110 self.scopes.len()
111 }
112
113 pub fn truncate_scopes(&mut self, target_depth: usize) {
114 let min_depth = target_depth.max(1);
115 while self.scopes.len() > min_depth {
116 self.scopes.pop();
117 }
118 }
119
120 pub fn get(&self, name: &str) -> Option<VmValue> {
121 for scope in self.scopes.iter().rev() {
122 if let Some((val, _)) = scope.vars.get(name) {
123 return Some(val.clone());
124 }
125 }
126 None
127 }
128
129 pub(crate) fn contains(&self, name: &str) -> bool {
130 self.scopes
131 .iter()
132 .rev()
133 .any(|scope| scope.vars.contains_key(name))
134 }
135
136 pub fn define(&mut self, name: &str, value: VmValue, mutable: bool) -> Result<(), VmError> {
137 if let Some(scope) = self.scopes.last_mut() {
138 if let Some((_, existing_mutable)) = scope.vars.get(name) {
139 if !existing_mutable && !mutable {
140 return Err(VmError::Runtime(format!(
141 "Cannot redeclare immutable variable '{name}' in the same scope (use 'var' for mutable bindings)"
142 )));
143 }
144 }
145 Arc::make_mut(&mut scope.vars).insert(name.to_string(), (value, mutable));
146 }
147 Ok(())
148 }
149
150 pub fn all_variables(&self) -> BTreeMap<String, VmValue> {
151 let mut vars = BTreeMap::new();
152 for scope in &self.scopes {
153 for (name, (value, _)) in scope.vars.iter() {
154 vars.insert(name.clone(), value.clone());
155 }
156 }
157 vars
158 }
159
160 pub fn assign(&mut self, name: &str, value: VmValue) -> Result<(), VmError> {
161 for scope in self.scopes.iter_mut().rev() {
162 if let Some((_, mutable)) = scope.vars.get(name) {
163 if !mutable {
164 return Err(VmError::ImmutableAssignment(name.to_string()));
165 }
166 Arc::make_mut(&mut scope.vars).insert(name.to_string(), (value, true));
167 return Ok(());
168 }
169 }
170 Err(VmError::UndefinedVariable(name.to_string()))
171 }
172
173 pub fn assign_debug(&mut self, name: &str, value: VmValue) -> Result<(), VmError> {
181 for scope in self.scopes.iter_mut().rev() {
182 if let Some((_, mutable)) = scope.vars.get(name) {
183 let mutable = *mutable;
184 Arc::make_mut(&mut scope.vars).insert(name.to_string(), (value, mutable));
185 return Ok(());
186 }
187 }
188 Err(VmError::UndefinedVariable(name.to_string()))
189 }
190}
191
192fn levenshtein(a: &str, b: &str) -> usize {
194 let a: Vec<char> = a.chars().collect();
195 let b: Vec<char> = b.chars().collect();
196 let (m, n) = (a.len(), b.len());
197 let mut prev = (0..=n).collect::<Vec<_>>();
198 let mut curr = vec![0; n + 1];
199 for i in 1..=m {
200 curr[0] = i;
201 for j in 1..=n {
202 let cost = usize::from(a[i - 1] != b[j - 1]);
203 curr[j] = (prev[j] + 1).min(curr[j - 1] + 1).min(prev[j - 1] + cost);
204 }
205 std::mem::swap(&mut prev, &mut curr);
206 }
207 prev[n]
208}
209
210pub fn closest_match<'a>(name: &str, candidates: impl Iterator<Item = &'a str>) -> Option<String> {
213 let max_dist = match name.len() {
214 0..=2 => 1,
215 3..=5 => 2,
216 _ => 3,
217 };
218 candidates
219 .filter(|c| *c != name && !c.starts_with("__"))
220 .map(|c| (c, levenshtein(name, c)))
221 .filter(|(_, d)| *d <= max_dist)
222 .min_by(|(a, da), (b, db)| {
224 da.cmp(db)
225 .then_with(|| {
226 let a_diff = (a.len() as isize - name.len() as isize).unsigned_abs();
227 let b_diff = (b.len() as isize - name.len() as isize).unsigned_abs();
228 a_diff.cmp(&b_diff)
229 })
230 .then_with(|| a.cmp(b))
231 })
232 .map(|(c, _)| c.to_string())
233}