1use std::collections::{BTreeMap, HashSet};
2use std::rc::Rc;
3use std::time::Instant;
4
5use crate::chunk::{Chunk, ChunkRef, Constant};
6use crate::value::{
7 ModuleFunctionRegistry, VmAsyncBuiltinFn, VmBuiltinFn, VmEnv, VmError, VmTaskHandle, VmValue,
8};
9use crate::BuiltinId;
10
11use super::debug::DebugHook;
12use super::modules::LoadedModule;
13
14pub(crate) struct ScopeSpan(u64);
16
17impl ScopeSpan {
18 pub(crate) fn new(kind: crate::tracing::SpanKind, name: String) -> Self {
19 Self(crate::tracing::span_start(kind, name))
20 }
21}
22
23impl Drop for ScopeSpan {
24 fn drop(&mut self) {
25 crate::tracing::span_end(self.0);
26 }
27}
28
29#[derive(Clone)]
30pub(crate) struct LocalSlot {
31 pub(crate) value: VmValue,
32 pub(crate) initialized: bool,
33 pub(crate) synced: bool,
34}
35
36pub(crate) struct CallFrame {
38 pub(crate) chunk: ChunkRef,
39 pub(crate) ip: usize,
40 pub(crate) stack_base: usize,
41 pub(crate) saved_env: VmEnv,
42 pub(crate) initial_env: Option<VmEnv>,
50 pub(crate) initial_local_slots: Option<Vec<LocalSlot>>,
51 pub(crate) saved_iterator_depth: usize,
53 pub(crate) fn_name: String,
55 pub(crate) argc: usize,
57 pub(crate) saved_source_dir: Option<std::path::PathBuf>,
60 pub(crate) module_functions: Option<ModuleFunctionRegistry>,
62 pub(crate) module_state: Option<crate::value::ModuleState>,
68 pub(crate) local_slots: Vec<LocalSlot>,
70 pub(crate) local_scope_base: usize,
72 pub(crate) local_scope_depth: usize,
74}
75
76pub(crate) struct ExceptionHandler {
78 pub(crate) catch_ip: usize,
79 pub(crate) stack_depth: usize,
80 pub(crate) frame_depth: usize,
81 pub(crate) env_scope_depth: usize,
82 pub(crate) error_type: String,
84}
85
86pub(crate) enum IterState {
88 Vec {
89 items: Rc<Vec<VmValue>>,
90 idx: usize,
91 },
92 Dict {
93 entries: Rc<BTreeMap<String, VmValue>>,
94 keys: Vec<String>,
95 idx: usize,
96 },
97 Channel {
98 receiver: std::sync::Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
99 closed: std::sync::Arc<std::sync::atomic::AtomicBool>,
100 },
101 Generator {
102 gen: crate::value::VmGenerator,
103 },
104 Range {
108 next: i64,
109 stop: i64,
110 },
111 VmIter {
112 handle: std::rc::Rc<std::cell::RefCell<crate::vm::iter::VmIter>>,
113 },
114}
115
116#[derive(Clone)]
117pub(crate) enum VmBuiltinDispatch {
118 Sync(VmBuiltinFn),
119 Async(VmAsyncBuiltinFn),
120}
121
122#[derive(Clone)]
123pub(crate) struct VmBuiltinEntry {
124 pub(crate) name: Rc<str>,
125 pub(crate) dispatch: VmBuiltinDispatch,
126}
127
128pub struct Vm {
130 pub(crate) stack: Vec<VmValue>,
131 pub(crate) env: VmEnv,
132 pub(crate) output: String,
133 pub(crate) builtins: BTreeMap<String, VmBuiltinFn>,
134 pub(crate) async_builtins: BTreeMap<String, VmAsyncBuiltinFn>,
135 pub(crate) builtins_by_id: BTreeMap<BuiltinId, VmBuiltinEntry>,
138 pub(crate) builtin_id_collisions: HashSet<BuiltinId>,
141 pub(crate) iterators: Vec<IterState>,
143 pub(crate) frames: Vec<CallFrame>,
145 pub(crate) exception_handlers: Vec<ExceptionHandler>,
147 pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
149 pub(crate) task_counter: u64,
151 pub(crate) deadlines: Vec<(Instant, usize)>,
153 pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
158 pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
164 pub(crate) pending_function_bp: Option<String>,
169 pub(crate) step_mode: bool,
171 pub(crate) step_frame_depth: usize,
173 pub(crate) stopped: bool,
175 pub(crate) last_line: usize,
177 pub(crate) source_dir: Option<std::path::PathBuf>,
179 pub(crate) imported_paths: Vec<std::path::PathBuf>,
181 pub(crate) module_cache: BTreeMap<std::path::PathBuf, LoadedModule>,
183 pub(crate) source_file: Option<String>,
185 pub(crate) source_text: Option<String>,
187 pub(crate) bridge: Option<Rc<crate::bridge::HostBridge>>,
189 pub(crate) denied_builtins: HashSet<String>,
191 pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
193 pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
195 pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<VmValue>>,
198 pub(crate) project_root: Option<std::path::PathBuf>,
201 pub(crate) globals: BTreeMap<String, VmValue>,
204 pub(crate) debug_hook: Option<Box<DebugHook>>,
206}
207
208impl Vm {
209 pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
210 chunk
211 .local_slots
212 .iter()
213 .map(|_| LocalSlot {
214 value: VmValue::Nil,
215 initialized: false,
216 synced: false,
217 })
218 .collect()
219 }
220
221 pub(crate) fn bind_param_slots(
222 slots: &mut [LocalSlot],
223 func: &crate::chunk::CompiledFunction,
224 args: &[VmValue],
225 synced: bool,
226 ) {
227 let default_start = func.default_start.unwrap_or(func.params.len());
228 let param_count = func.params.len();
229 for (i, _param) in func.params.iter().enumerate() {
230 if i >= slots.len() {
231 break;
232 }
233 if func.has_rest_param && i == param_count - 1 {
234 let rest_args = if i < args.len() {
235 args[i..].to_vec()
236 } else {
237 Vec::new()
238 };
239 slots[i].value = VmValue::List(Rc::new(rest_args));
240 slots[i].initialized = true;
241 slots[i].synced = synced;
242 } else if i < args.len() {
243 slots[i].value = args[i].clone();
244 slots[i].initialized = true;
245 slots[i].synced = synced;
246 } else if i < default_start {
247 slots[i].value = VmValue::Nil;
248 slots[i].initialized = true;
249 slots[i].synced = synced;
250 }
251 }
252 }
253
254 pub(crate) fn visible_variables(&self) -> BTreeMap<String, VmValue> {
255 let mut vars = self.env.all_variables();
256 let Some(frame) = self.frames.last() else {
257 return vars;
258 };
259 for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
260 if slot.initialized && info.scope_depth <= frame.local_scope_depth {
261 vars.insert(info.name.clone(), slot.value.clone());
262 }
263 }
264 vars
265 }
266
267 pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
268 let Some(frame) = self.frames.last_mut() else {
269 return;
270 };
271 let local_scope_base = frame.local_scope_base;
272 let local_scope_depth = frame.local_scope_depth;
273 let entries = frame
274 .local_slots
275 .iter_mut()
276 .zip(frame.chunk.local_slots.iter())
277 .filter_map(|(slot, info)| {
278 if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
279 slot.synced = true;
280 Some((
281 local_scope_base + info.scope_depth,
282 info.name.clone(),
283 slot.value.clone(),
284 info.mutable,
285 ))
286 } else {
287 None
288 }
289 })
290 .collect::<Vec<_>>();
291 for (scope_idx, name, value, mutable) in entries {
292 while self.env.scopes.len() <= scope_idx {
293 self.env.push_scope();
294 }
295 self.env.scopes[scope_idx]
296 .vars
297 .insert(name, (value, mutable));
298 }
299 }
300
301 pub(crate) fn closure_call_env_for_current_frame(
302 &self,
303 closure: &crate::value::VmClosure,
304 ) -> VmEnv {
305 if closure.module_state.is_some() {
306 return closure.env.clone();
307 }
308 let mut call_env = Self::closure_call_env(&self.env, closure);
309 let Some(frame) = self.frames.last() else {
310 return call_env;
311 };
312 for (slot, info) in frame
313 .local_slots
314 .iter()
315 .zip(frame.chunk.local_slots.iter())
316 .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
317 {
318 if matches!(slot.value, VmValue::Closure(_)) && call_env.get(&info.name).is_none() {
319 let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
320 }
321 }
322 call_env
323 }
324
325 pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
326 let frame = self.frames.last()?;
327 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
328 if info.name == name && info.scope_depth <= frame.local_scope_depth {
329 let slot = frame.local_slots.get(idx)?;
330 if slot.initialized {
331 return Some(slot.value.clone());
332 }
333 }
334 }
335 None
336 }
337
338 pub(crate) fn assign_active_local_slot(
339 &mut self,
340 name: &str,
341 value: VmValue,
342 debug: bool,
343 ) -> Result<bool, VmError> {
344 let Some(frame) = self.frames.last_mut() else {
345 return Ok(false);
346 };
347 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
348 if info.name == name && info.scope_depth <= frame.local_scope_depth {
349 if !debug && !info.mutable {
350 return Err(VmError::ImmutableAssignment(name.to_string()));
351 }
352 if let Some(slot) = frame.local_slots.get_mut(idx) {
353 slot.value = value;
354 slot.initialized = true;
355 slot.synced = false;
356 return Ok(true);
357 }
358 }
359 }
360 Ok(false)
361 }
362
363 pub fn new() -> Self {
364 Self {
365 stack: Vec::with_capacity(256),
366 env: VmEnv::new(),
367 output: String::new(),
368 builtins: BTreeMap::new(),
369 async_builtins: BTreeMap::new(),
370 builtins_by_id: BTreeMap::new(),
371 builtin_id_collisions: HashSet::new(),
372 iterators: Vec::new(),
373 frames: Vec::new(),
374 exception_handlers: Vec::new(),
375 spawned_tasks: BTreeMap::new(),
376 task_counter: 0,
377 deadlines: Vec::new(),
378 breakpoints: BTreeMap::new(),
379 function_breakpoints: std::collections::BTreeSet::new(),
380 pending_function_bp: None,
381 step_mode: false,
382 step_frame_depth: 0,
383 stopped: false,
384 last_line: 0,
385 source_dir: None,
386 imported_paths: Vec::new(),
387 module_cache: BTreeMap::new(),
388 source_file: None,
389 source_text: None,
390 bridge: None,
391 denied_builtins: HashSet::new(),
392 cancel_token: None,
393 error_stack_trace: Vec::new(),
394 yield_sender: None,
395 project_root: None,
396 globals: BTreeMap::new(),
397 debug_hook: None,
398 }
399 }
400
401 pub fn set_bridge(&mut self, bridge: Rc<crate::bridge::HostBridge>) {
403 self.bridge = Some(bridge);
404 }
405
406 pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
409 self.denied_builtins = denied;
410 }
411
412 pub fn set_source_info(&mut self, file: &str, text: &str) {
414 self.source_file = Some(file.to_string());
415 self.source_text = Some(text.to_string());
416 }
417
418 pub fn start(&mut self, chunk: &Chunk) {
420 let initial_env = self.env.clone();
421 self.frames.push(CallFrame {
422 chunk: Rc::new(chunk.clone()),
423 ip: 0,
424 stack_base: self.stack.len(),
425 saved_env: self.env.clone(),
426 initial_env: Some(initial_env),
431 initial_local_slots: Some(Self::fresh_local_slots(chunk)),
432 saved_iterator_depth: self.iterators.len(),
433 fn_name: String::new(),
434 argc: 0,
435 saved_source_dir: None,
436 module_functions: None,
437 module_state: None,
438 local_slots: Self::fresh_local_slots(chunk),
439 local_scope_base: self.env.scope_depth().saturating_sub(1),
440 local_scope_depth: 0,
441 });
442 }
443
444 pub(crate) fn child_vm(&self) -> Vm {
447 Vm {
448 stack: Vec::with_capacity(64),
449 env: self.env.clone(),
450 output: String::new(),
451 builtins: self.builtins.clone(),
452 async_builtins: self.async_builtins.clone(),
453 builtins_by_id: self.builtins_by_id.clone(),
454 builtin_id_collisions: self.builtin_id_collisions.clone(),
455 iterators: Vec::new(),
456 frames: Vec::new(),
457 exception_handlers: Vec::new(),
458 spawned_tasks: BTreeMap::new(),
459 task_counter: 0,
460 deadlines: self.deadlines.clone(),
461 breakpoints: BTreeMap::new(),
462 function_breakpoints: std::collections::BTreeSet::new(),
463 pending_function_bp: None,
464 step_mode: false,
465 step_frame_depth: 0,
466 stopped: false,
467 last_line: 0,
468 source_dir: self.source_dir.clone(),
469 imported_paths: Vec::new(),
470 module_cache: self.module_cache.clone(),
471 source_file: self.source_file.clone(),
472 source_text: self.source_text.clone(),
473 bridge: self.bridge.clone(),
474 denied_builtins: self.denied_builtins.clone(),
475 cancel_token: self.cancel_token.clone(),
476 error_stack_trace: Vec::new(),
477 yield_sender: None,
478 project_root: self.project_root.clone(),
479 globals: self.globals.clone(),
480 debug_hook: None,
481 }
482 }
483
484 pub(crate) fn child_vm_for_host(&self) -> Vm {
487 self.child_vm()
488 }
489
490 pub fn set_source_dir(&mut self, dir: &std::path::Path) {
493 let dir = crate::stdlib::process::normalize_context_path(dir);
494 self.source_dir = Some(dir.clone());
495 crate::stdlib::set_thread_source_dir(&dir);
496 if self.project_root.is_none() {
498 self.project_root = crate::stdlib::process::find_project_root(&dir);
499 }
500 }
501
502 pub fn set_project_root(&mut self, root: &std::path::Path) {
505 self.project_root = Some(root.to_path_buf());
506 }
507
508 pub fn project_root(&self) -> Option<&std::path::Path> {
510 self.project_root.as_deref().or(self.source_dir.as_deref())
511 }
512
513 pub fn builtin_names(&self) -> Vec<String> {
515 let mut names: Vec<String> = self.builtins.keys().cloned().collect();
516 names.extend(self.async_builtins.keys().cloned());
517 names
518 }
519
520 pub fn set_global(&mut self, name: &str, value: VmValue) {
523 self.globals.insert(name.to_string(), value);
524 }
525
526 pub fn output(&self) -> &str {
528 &self.output
529 }
530
531 pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
532 self.stack.pop().ok_or(VmError::StackUnderflow)
533 }
534
535 pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
536 self.stack.last().ok_or(VmError::StackUnderflow)
537 }
538
539 pub(crate) fn const_string(c: &Constant) -> Result<String, VmError> {
540 match c {
541 Constant::String(s) => Ok(s.clone()),
542 _ => Err(VmError::TypeError("expected string constant".into())),
543 }
544 }
545}
546
547impl Default for Vm {
548 fn default() -> Self {
549 Self::new()
550 }
551}