1use std::collections::{BTreeMap, HashSet};
2use std::rc::Rc;
3use std::sync::Arc;
4use std::time::Instant;
5
6use crate::chunk::{Chunk, ChunkRef, Constant};
7use crate::value::{
8 ModuleFunctionRegistry, VmAsyncBuiltinFn, VmBuiltinFn, VmEnv, VmError, VmTaskHandle, VmValue,
9};
10use crate::BuiltinId;
11
12use super::debug::DebugHook;
13use super::modules::LoadedModule;
14use super::VmBuiltinMetadata;
15
16pub(crate) struct ScopeSpan(u64);
18
19impl ScopeSpan {
20 pub(crate) fn new(kind: crate::tracing::SpanKind, name: String) -> Self {
21 Self(crate::tracing::span_start(kind, name))
22 }
23}
24
25impl Drop for ScopeSpan {
26 fn drop(&mut self) {
27 crate::tracing::span_end(self.0);
28 }
29}
30
31#[derive(Clone)]
32pub(crate) struct LocalSlot {
33 pub(crate) value: VmValue,
34 pub(crate) initialized: bool,
35 pub(crate) synced: bool,
36}
37
38pub(crate) struct CallFrame {
40 pub(crate) chunk: ChunkRef,
41 pub(crate) ip: usize,
42 pub(crate) stack_base: usize,
43 pub(crate) saved_env: VmEnv,
44 pub(crate) initial_env: Option<VmEnv>,
52 pub(crate) initial_local_slots: Option<Vec<LocalSlot>>,
53 pub(crate) saved_iterator_depth: usize,
55 pub(crate) fn_name: String,
57 pub(crate) argc: usize,
59 pub(crate) saved_source_dir: Option<std::path::PathBuf>,
62 pub(crate) module_functions: Option<ModuleFunctionRegistry>,
64 pub(crate) module_state: Option<crate::value::ModuleState>,
70 pub(crate) local_slots: Vec<LocalSlot>,
72 pub(crate) local_scope_base: usize,
74 pub(crate) local_scope_depth: usize,
76}
77
78pub(crate) struct ExceptionHandler {
80 pub(crate) catch_ip: usize,
81 pub(crate) stack_depth: usize,
82 pub(crate) frame_depth: usize,
83 pub(crate) env_scope_depth: usize,
84 pub(crate) error_type: String,
86}
87
88pub(crate) enum IterState {
90 Vec {
91 items: Rc<Vec<VmValue>>,
92 idx: usize,
93 },
94 Dict {
95 entries: Rc<BTreeMap<String, VmValue>>,
96 keys: Vec<String>,
97 idx: usize,
98 },
99 Channel {
100 receiver: std::sync::Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
101 closed: std::sync::Arc<std::sync::atomic::AtomicBool>,
102 },
103 Generator {
104 gen: crate::value::VmGenerator,
105 },
106 Stream {
107 stream: crate::value::VmStream,
108 },
109 Range {
113 next: i64,
114 stop: i64,
115 },
116 VmIter {
117 handle: std::rc::Rc<std::cell::RefCell<crate::vm::iter::VmIter>>,
118 },
119}
120
121#[derive(Clone)]
122pub(crate) enum VmBuiltinDispatch {
123 Sync(VmBuiltinFn),
124 Async(VmAsyncBuiltinFn),
125}
126
127#[derive(Clone)]
128pub(crate) struct VmBuiltinEntry {
129 pub(crate) name: Rc<str>,
130 pub(crate) dispatch: VmBuiltinDispatch,
131}
132
133pub struct Vm {
135 pub(crate) stack: Vec<VmValue>,
136 pub(crate) env: VmEnv,
137 pub(crate) output: String,
138 pub(crate) builtins: BTreeMap<String, VmBuiltinFn>,
139 pub(crate) async_builtins: BTreeMap<String, VmAsyncBuiltinFn>,
140 pub(crate) builtin_metadata: BTreeMap<String, VmBuiltinMetadata>,
141 pub(crate) builtins_by_id: BTreeMap<BuiltinId, VmBuiltinEntry>,
144 pub(crate) builtin_id_collisions: HashSet<BuiltinId>,
147 pub(crate) iterators: Vec<IterState>,
149 pub(crate) frames: Vec<CallFrame>,
151 pub(crate) exception_handlers: Vec<ExceptionHandler>,
153 pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
155 pub(crate) sync_runtime: Arc<crate::synchronization::VmSyncRuntime>,
157 pub(crate) shared_state_runtime: Rc<crate::shared_state::VmSharedStateRuntime>,
159 pub(crate) held_sync_guards: Vec<crate::synchronization::VmSyncHeldGuard>,
161 pub(crate) task_counter: u64,
163 pub(crate) runtime_context_counter: u64,
165 pub(crate) runtime_context: crate::runtime_context::RuntimeContext,
167 pub(crate) deadlines: Vec<(Instant, usize)>,
169 pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
174 pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
180 pub(crate) pending_function_bp: Option<String>,
185 pub(crate) step_mode: bool,
187 pub(crate) step_frame_depth: usize,
189 pub(crate) stopped: bool,
191 pub(crate) last_line: usize,
193 pub(crate) source_dir: Option<std::path::PathBuf>,
195 pub(crate) imported_paths: Vec<std::path::PathBuf>,
197 pub(crate) module_cache: BTreeMap<std::path::PathBuf, LoadedModule>,
199 pub(crate) source_cache: BTreeMap<std::path::PathBuf, String>,
201 pub(crate) source_file: Option<String>,
203 pub(crate) source_text: Option<String>,
205 pub(crate) bridge: Option<Rc<crate::bridge::HostBridge>>,
207 pub(crate) denied_builtins: HashSet<String>,
209 pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
211 pub(crate) cancel_grace_instructions_remaining: Option<usize>,
216 pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
218 pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<Result<VmValue, VmError>>>,
221 pub(crate) project_root: Option<std::path::PathBuf>,
224 pub(crate) globals: BTreeMap<String, VmValue>,
227 pub(crate) debug_hook: Option<Box<DebugHook>>,
229}
230
231impl Vm {
232 pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
233 chunk
234 .local_slots
235 .iter()
236 .map(|_| LocalSlot {
237 value: VmValue::Nil,
238 initialized: false,
239 synced: false,
240 })
241 .collect()
242 }
243
244 pub(crate) fn bind_param_slots(
245 slots: &mut [LocalSlot],
246 func: &crate::chunk::CompiledFunction,
247 args: &[VmValue],
248 synced: bool,
249 ) {
250 let param_count = func.params.len();
251 for (i, _param) in func.params.iter().enumerate() {
252 if i >= slots.len() {
253 break;
254 }
255 if func.has_rest_param && i == param_count - 1 {
256 let rest_args = if i < args.len() {
257 args[i..].to_vec()
258 } else {
259 Vec::new()
260 };
261 slots[i].value = VmValue::List(Rc::new(rest_args));
262 slots[i].initialized = true;
263 slots[i].synced = synced;
264 } else if i < args.len() {
265 slots[i].value = args[i].clone();
266 slots[i].initialized = true;
267 slots[i].synced = synced;
268 }
269 }
270 }
271
272 pub(crate) fn visible_variables(&self) -> BTreeMap<String, VmValue> {
273 let mut vars = self.env.all_variables();
274 let Some(frame) = self.frames.last() else {
275 return vars;
276 };
277 for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
278 if slot.initialized && info.scope_depth <= frame.local_scope_depth {
279 vars.insert(info.name.clone(), slot.value.clone());
280 }
281 }
282 vars
283 }
284
285 pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
286 let Some(frame) = self.frames.last_mut() else {
287 return;
288 };
289 let local_scope_base = frame.local_scope_base;
290 let local_scope_depth = frame.local_scope_depth;
291 let entries = frame
292 .local_slots
293 .iter_mut()
294 .zip(frame.chunk.local_slots.iter())
295 .filter_map(|(slot, info)| {
296 if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
297 slot.synced = true;
298 Some((
299 local_scope_base + info.scope_depth,
300 info.name.clone(),
301 slot.value.clone(),
302 info.mutable,
303 ))
304 } else {
305 None
306 }
307 })
308 .collect::<Vec<_>>();
309 for (scope_idx, name, value, mutable) in entries {
310 while self.env.scopes.len() <= scope_idx {
311 self.env.push_scope();
312 }
313 self.env.scopes[scope_idx]
314 .vars
315 .insert(name, (value, mutable));
316 }
317 }
318
319 pub(crate) fn closure_call_env_for_current_frame(
320 &self,
321 closure: &crate::value::VmClosure,
322 ) -> VmEnv {
323 if closure.module_state.is_some() {
324 return closure.env.clone();
325 }
326 let mut call_env = Self::closure_call_env(&self.env, closure);
327 let Some(frame) = self.frames.last() else {
328 return call_env;
329 };
330 for (slot, info) in frame
331 .local_slots
332 .iter()
333 .zip(frame.chunk.local_slots.iter())
334 .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
335 {
336 if matches!(slot.value, VmValue::Closure(_)) && call_env.get(&info.name).is_none() {
337 let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
338 }
339 }
340 call_env
341 }
342
343 pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
344 let frame = self.frames.last()?;
345 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
346 if info.name == name && info.scope_depth <= frame.local_scope_depth {
347 let slot = frame.local_slots.get(idx)?;
348 if slot.initialized {
349 return Some(slot.value.clone());
350 }
351 }
352 }
353 None
354 }
355
356 pub(crate) fn assign_active_local_slot(
357 &mut self,
358 name: &str,
359 value: VmValue,
360 debug: bool,
361 ) -> Result<bool, VmError> {
362 let Some(frame) = self.frames.last_mut() else {
363 return Ok(false);
364 };
365 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
366 if info.name == name && info.scope_depth <= frame.local_scope_depth {
367 if !debug && !info.mutable {
368 return Err(VmError::ImmutableAssignment(name.to_string()));
369 }
370 if let Some(slot) = frame.local_slots.get_mut(idx) {
371 slot.value = value;
372 slot.initialized = true;
373 slot.synced = false;
374 return Ok(true);
375 }
376 }
377 }
378 Ok(false)
379 }
380
381 pub fn new() -> Self {
382 Self {
383 stack: Vec::with_capacity(256),
384 env: VmEnv::new(),
385 output: String::new(),
386 builtins: BTreeMap::new(),
387 async_builtins: BTreeMap::new(),
388 builtin_metadata: BTreeMap::new(),
389 builtins_by_id: BTreeMap::new(),
390 builtin_id_collisions: HashSet::new(),
391 iterators: Vec::new(),
392 frames: Vec::new(),
393 exception_handlers: Vec::new(),
394 spawned_tasks: BTreeMap::new(),
395 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
396 shared_state_runtime: Rc::new(crate::shared_state::VmSharedStateRuntime::new()),
397 held_sync_guards: Vec::new(),
398 task_counter: 0,
399 runtime_context_counter: 0,
400 runtime_context: crate::runtime_context::RuntimeContext::root(),
401 deadlines: Vec::new(),
402 breakpoints: BTreeMap::new(),
403 function_breakpoints: std::collections::BTreeSet::new(),
404 pending_function_bp: None,
405 step_mode: false,
406 step_frame_depth: 0,
407 stopped: false,
408 last_line: 0,
409 source_dir: None,
410 imported_paths: Vec::new(),
411 module_cache: BTreeMap::new(),
412 source_cache: BTreeMap::new(),
413 source_file: None,
414 source_text: None,
415 bridge: None,
416 denied_builtins: HashSet::new(),
417 cancel_token: None,
418 cancel_grace_instructions_remaining: None,
419 error_stack_trace: Vec::new(),
420 yield_sender: None,
421 project_root: None,
422 globals: BTreeMap::new(),
423 debug_hook: None,
424 }
425 }
426
427 pub fn set_bridge(&mut self, bridge: Rc<crate::bridge::HostBridge>) {
429 self.bridge = Some(bridge);
430 }
431
432 pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
435 self.denied_builtins = denied;
436 }
437
438 pub fn set_source_info(&mut self, file: &str, text: &str) {
440 self.source_file = Some(file.to_string());
441 self.source_text = Some(text.to_string());
442 self.source_cache
443 .insert(std::path::PathBuf::from(file), text.to_string());
444 }
445
446 pub fn start(&mut self, chunk: &Chunk) {
448 let initial_env = self.env.clone();
449 self.frames.push(CallFrame {
450 chunk: Rc::new(chunk.clone()),
451 ip: 0,
452 stack_base: self.stack.len(),
453 saved_env: self.env.clone(),
454 initial_env: Some(initial_env),
459 initial_local_slots: Some(Self::fresh_local_slots(chunk)),
460 saved_iterator_depth: self.iterators.len(),
461 fn_name: String::new(),
462 argc: 0,
463 saved_source_dir: None,
464 module_functions: None,
465 module_state: None,
466 local_slots: Self::fresh_local_slots(chunk),
467 local_scope_base: self.env.scope_depth().saturating_sub(1),
468 local_scope_depth: 0,
469 });
470 }
471
472 pub(crate) fn child_vm(&self) -> Vm {
475 Vm {
476 stack: Vec::with_capacity(64),
477 env: self.env.clone(),
478 output: String::new(),
479 builtins: self.builtins.clone(),
480 async_builtins: self.async_builtins.clone(),
481 builtin_metadata: self.builtin_metadata.clone(),
482 builtins_by_id: self.builtins_by_id.clone(),
483 builtin_id_collisions: self.builtin_id_collisions.clone(),
484 iterators: Vec::new(),
485 frames: Vec::new(),
486 exception_handlers: Vec::new(),
487 spawned_tasks: BTreeMap::new(),
488 sync_runtime: self.sync_runtime.clone(),
489 shared_state_runtime: self.shared_state_runtime.clone(),
490 held_sync_guards: Vec::new(),
491 task_counter: 0,
492 runtime_context_counter: self.runtime_context_counter,
493 runtime_context: self.runtime_context.clone(),
494 deadlines: self.deadlines.clone(),
495 breakpoints: BTreeMap::new(),
496 function_breakpoints: std::collections::BTreeSet::new(),
497 pending_function_bp: None,
498 step_mode: false,
499 step_frame_depth: 0,
500 stopped: false,
501 last_line: 0,
502 source_dir: self.source_dir.clone(),
503 imported_paths: Vec::new(),
504 module_cache: self.module_cache.clone(),
505 source_cache: self.source_cache.clone(),
506 source_file: self.source_file.clone(),
507 source_text: self.source_text.clone(),
508 bridge: self.bridge.clone(),
509 denied_builtins: self.denied_builtins.clone(),
510 cancel_token: self.cancel_token.clone(),
511 cancel_grace_instructions_remaining: None,
512 error_stack_trace: Vec::new(),
513 yield_sender: None,
514 project_root: self.project_root.clone(),
515 globals: self.globals.clone(),
516 debug_hook: None,
517 }
518 }
519
520 pub(crate) fn child_vm_for_host(&self) -> Vm {
523 self.child_vm()
524 }
525
526 pub(crate) fn cancel_spawned_tasks(&mut self) {
530 for (_, task) in std::mem::take(&mut self.spawned_tasks) {
531 task.cancel_token
532 .store(true, std::sync::atomic::Ordering::SeqCst);
533 task.handle.abort();
534 }
535 }
536
537 pub fn set_source_dir(&mut self, dir: &std::path::Path) {
540 let dir = crate::stdlib::process::normalize_context_path(dir);
541 self.source_dir = Some(dir.clone());
542 crate::stdlib::set_thread_source_dir(&dir);
543 if self.project_root.is_none() {
545 self.project_root = crate::stdlib::process::find_project_root(&dir);
546 }
547 }
548
549 pub fn set_project_root(&mut self, root: &std::path::Path) {
552 self.project_root = Some(root.to_path_buf());
553 }
554
555 pub fn project_root(&self) -> Option<&std::path::Path> {
557 self.project_root.as_deref().or(self.source_dir.as_deref())
558 }
559
560 pub fn builtin_names(&self) -> Vec<String> {
562 let mut names: Vec<String> = self.builtins.keys().cloned().collect();
563 names.extend(self.async_builtins.keys().cloned());
564 names
565 }
566
567 pub fn builtin_metadata(&self) -> Vec<VmBuiltinMetadata> {
569 self.builtin_metadata.values().cloned().collect()
570 }
571
572 pub fn builtin_metadata_for(&self, name: &str) -> Option<&VmBuiltinMetadata> {
574 self.builtin_metadata.get(name)
575 }
576
577 pub fn set_global(&mut self, name: &str, value: VmValue) {
580 self.globals.insert(name.to_string(), value);
581 }
582
583 pub fn output(&self) -> &str {
585 &self.output
586 }
587
588 pub fn take_output(&mut self) -> String {
592 std::mem::take(&mut self.output)
593 }
594
595 pub fn append_output(&mut self, text: &str) {
599 self.output.push_str(text);
600 }
601
602 pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
603 self.stack.pop().ok_or(VmError::StackUnderflow)
604 }
605
606 pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
607 self.stack.last().ok_or(VmError::StackUnderflow)
608 }
609
610 pub(crate) fn const_string(c: &Constant) -> Result<String, VmError> {
611 match c {
612 Constant::String(s) => Ok(s.clone()),
613 _ => Err(VmError::TypeError("expected string constant".into())),
614 }
615 }
616
617 pub(crate) fn release_sync_guards_for_current_scope(&mut self) {
618 let depth = self.env.scope_depth();
619 self.held_sync_guards
620 .retain(|guard| guard.env_scope_depth < depth);
621 }
622
623 pub(crate) fn release_sync_guards_after_unwind(
624 &mut self,
625 frame_depth: usize,
626 env_scope_depth: usize,
627 ) {
628 self.held_sync_guards.retain(|guard| {
629 guard.frame_depth <= frame_depth && guard.env_scope_depth <= env_scope_depth
630 });
631 }
632
633 pub(crate) fn release_sync_guards_for_frame(&mut self, frame_depth: usize) {
634 self.held_sync_guards
635 .retain(|guard| guard.frame_depth != frame_depth);
636 }
637}
638
639impl Drop for Vm {
640 fn drop(&mut self) {
641 self.cancel_spawned_tasks();
642 }
643}
644
645impl Default for Vm {
646 fn default() -> Self {
647 Self::new()
648 }
649}