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
38#[derive(Clone)]
39pub(crate) struct InterruptHandler {
40 pub(crate) handle: i64,
41 pub(crate) signals: Vec<String>,
42 pub(crate) once: bool,
43 pub(crate) graceful_timeout_ms: Option<u64>,
44 pub(crate) handler: VmValue,
45}
46
47pub(crate) struct CallFrame {
49 pub(crate) chunk: ChunkRef,
50 pub(crate) ip: usize,
51 pub(crate) stack_base: usize,
52 pub(crate) saved_env: VmEnv,
53 pub(crate) initial_env: Option<VmEnv>,
61 pub(crate) initial_local_slots: Option<Vec<LocalSlot>>,
62 pub(crate) saved_iterator_depth: usize,
64 pub(crate) fn_name: String,
66 pub(crate) argc: usize,
68 pub(crate) saved_source_dir: Option<std::path::PathBuf>,
71 pub(crate) module_functions: Option<ModuleFunctionRegistry>,
73 pub(crate) module_state: Option<crate::value::ModuleState>,
79 pub(crate) local_slots: Vec<LocalSlot>,
81 pub(crate) local_scope_base: usize,
83 pub(crate) local_scope_depth: usize,
85}
86
87pub(crate) struct ExceptionHandler {
89 pub(crate) catch_ip: usize,
90 pub(crate) stack_depth: usize,
91 pub(crate) frame_depth: usize,
92 pub(crate) env_scope_depth: usize,
93 pub(crate) error_type: String,
95}
96
97pub(crate) enum IterState {
99 Vec {
100 items: Rc<Vec<VmValue>>,
101 idx: usize,
102 },
103 Dict {
104 entries: Rc<BTreeMap<String, VmValue>>,
105 keys: Vec<String>,
106 idx: usize,
107 },
108 Channel {
109 receiver: std::sync::Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
110 closed: std::sync::Arc<std::sync::atomic::AtomicBool>,
111 },
112 Generator {
113 gen: crate::value::VmGenerator,
114 },
115 Stream {
116 stream: crate::value::VmStream,
117 },
118 Range {
122 next: i64,
123 end: i64,
124 inclusive: bool,
125 done: bool,
126 },
127 VmIter {
128 handle: std::rc::Rc<std::cell::RefCell<crate::vm::iter::VmIter>>,
129 },
130}
131
132#[derive(Clone)]
133pub(crate) enum VmBuiltinDispatch {
134 Sync(VmBuiltinFn),
135 Async(VmAsyncBuiltinFn),
136}
137
138#[derive(Clone)]
139pub(crate) struct VmBuiltinEntry {
140 pub(crate) name: Rc<str>,
141 pub(crate) dispatch: VmBuiltinDispatch,
142}
143
144pub struct Vm {
146 pub(crate) stack: Vec<VmValue>,
147 pub(crate) env: VmEnv,
148 pub(crate) output: String,
149 pub(crate) builtins: Rc<BTreeMap<String, VmBuiltinFn>>,
150 pub(crate) async_builtins: Rc<BTreeMap<String, VmAsyncBuiltinFn>>,
151 pub(crate) builtin_metadata: Rc<BTreeMap<String, VmBuiltinMetadata>>,
152 pub(crate) builtins_by_id: Rc<BTreeMap<BuiltinId, VmBuiltinEntry>>,
155 pub(crate) builtin_id_collisions: Rc<HashSet<BuiltinId>>,
158 pub(crate) iterators: Vec<IterState>,
160 pub(crate) frames: Vec<CallFrame>,
162 pub(crate) exception_handlers: Vec<ExceptionHandler>,
164 pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
166 pub(crate) sync_runtime: Arc<crate::synchronization::VmSyncRuntime>,
168 pub(crate) shared_state_runtime: Rc<crate::shared_state::VmSharedStateRuntime>,
170 pub(crate) held_sync_guards: Vec<crate::synchronization::VmSyncHeldGuard>,
172 pub(crate) task_counter: u64,
174 pub(crate) runtime_context_counter: u64,
176 pub(crate) runtime_context: crate::runtime_context::RuntimeContext,
178 pub(crate) deadlines: Vec<(Instant, usize)>,
180 pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
185 pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
191 pub(crate) pending_function_bp: Option<String>,
196 pub(crate) step_mode: bool,
198 pub(crate) step_frame_depth: usize,
200 pub(crate) stopped: bool,
202 pub(crate) last_line: usize,
204 pub(crate) source_dir: Option<std::path::PathBuf>,
206 pub(crate) imported_paths: Vec<std::path::PathBuf>,
208 pub(crate) module_cache: Rc<BTreeMap<std::path::PathBuf, LoadedModule>>,
210 pub(crate) source_cache: Rc<BTreeMap<std::path::PathBuf, String>>,
212 pub(crate) source_file: Option<String>,
214 pub(crate) source_text: Option<String>,
216 pub(crate) bridge: Option<Rc<crate::bridge::HostBridge>>,
218 pub(crate) denied_builtins: Rc<HashSet<String>>,
220 pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
222 pub(crate) interrupt_signal_token: Option<std::sync::Arc<std::sync::Mutex<Option<String>>>>,
223 pub(crate) cancel_grace_instructions_remaining: Option<usize>,
228 pub(crate) interrupt_handlers: Vec<InterruptHandler>,
230 pub(crate) next_interrupt_handle: i64,
231 pub(crate) pending_interrupt_signal: Option<String>,
232 pub(crate) interrupted: bool,
233 pub(crate) dispatching_interrupt: bool,
234 pub(crate) interrupt_handler_deadline: Option<Instant>,
235 pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
237 pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<Result<VmValue, VmError>>>,
240 pub(crate) project_root: Option<std::path::PathBuf>,
243 pub(crate) globals: Rc<BTreeMap<String, VmValue>>,
246 pub(crate) debug_hook: Option<Box<DebugHook>>,
248}
249
250#[derive(Clone)]
258pub struct VmBaseline {
259 builtins: Rc<BTreeMap<String, VmBuiltinFn>>,
260 async_builtins: Rc<BTreeMap<String, VmAsyncBuiltinFn>>,
261 builtin_metadata: Rc<BTreeMap<String, VmBuiltinMetadata>>,
262 builtins_by_id: Rc<BTreeMap<BuiltinId, VmBuiltinEntry>>,
263 builtin_id_collisions: Rc<HashSet<BuiltinId>>,
264 source_dir: Option<std::path::PathBuf>,
265 source_file: Option<String>,
266 source_text: Option<String>,
267 project_root: Option<std::path::PathBuf>,
268 globals: Rc<BTreeMap<String, VmValue>>,
269 denied_builtins: Rc<HashSet<String>>,
270}
271
272impl VmBaseline {
273 pub fn from_vm(vm: &Vm) -> Self {
274 Self {
275 builtins: Rc::clone(&vm.builtins),
276 async_builtins: Rc::clone(&vm.async_builtins),
277 builtin_metadata: Rc::clone(&vm.builtin_metadata),
278 builtins_by_id: Rc::clone(&vm.builtins_by_id),
279 builtin_id_collisions: Rc::clone(&vm.builtin_id_collisions),
280 source_dir: vm.source_dir.clone(),
281 source_file: vm.source_file.clone(),
282 source_text: vm.source_text.clone(),
283 project_root: vm.project_root.clone(),
284 globals: Rc::clone(&vm.globals),
285 denied_builtins: Rc::clone(&vm.denied_builtins),
286 }
287 }
288
289 pub fn instantiate(&self) -> Vm {
290 let mut source_cache = BTreeMap::new();
291 if let (Some(file), Some(text)) = (&self.source_file, &self.source_text) {
292 source_cache.insert(std::path::PathBuf::from(file), text.clone());
293 }
294 if let Some(dir) = &self.source_dir {
295 crate::stdlib::set_thread_source_dir(dir);
296 }
297
298 let mut vm = Vm {
299 stack: Vec::with_capacity(256),
300 env: VmEnv::new(),
301 output: String::new(),
302 builtins: Rc::clone(&self.builtins),
303 async_builtins: Rc::clone(&self.async_builtins),
304 builtin_metadata: Rc::clone(&self.builtin_metadata),
305 builtins_by_id: Rc::clone(&self.builtins_by_id),
306 builtin_id_collisions: Rc::clone(&self.builtin_id_collisions),
307 iterators: Vec::new(),
308 frames: Vec::new(),
309 exception_handlers: Vec::new(),
310 spawned_tasks: BTreeMap::new(),
311 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
312 shared_state_runtime: Rc::new(crate::shared_state::VmSharedStateRuntime::new()),
313 held_sync_guards: Vec::new(),
314 task_counter: 0,
315 runtime_context_counter: 0,
316 runtime_context: crate::runtime_context::RuntimeContext::root(),
317 deadlines: Vec::new(),
318 breakpoints: BTreeMap::new(),
319 function_breakpoints: std::collections::BTreeSet::new(),
320 pending_function_bp: None,
321 step_mode: false,
322 step_frame_depth: 0,
323 stopped: false,
324 last_line: 0,
325 source_dir: self.source_dir.clone(),
326 imported_paths: Vec::new(),
327 module_cache: Rc::new(BTreeMap::new()),
328 source_cache: Rc::new(source_cache),
329 source_file: self.source_file.clone(),
330 source_text: self.source_text.clone(),
331 bridge: None,
332 denied_builtins: Rc::clone(&self.denied_builtins),
333 cancel_token: None,
334 interrupt_signal_token: None,
335 cancel_grace_instructions_remaining: None,
336 interrupt_handlers: Vec::new(),
337 next_interrupt_handle: 1,
338 pending_interrupt_signal: None,
339 interrupted: false,
340 dispatching_interrupt: false,
341 interrupt_handler_deadline: None,
342 error_stack_trace: Vec::new(),
343 yield_sender: None,
344 project_root: self.project_root.clone(),
345 globals: Rc::clone(&self.globals),
346 debug_hook: None,
347 };
348
349 crate::stdlib::rebind_execution_state_builtins(&mut vm);
350 vm
351 }
352}
353
354impl Vm {
355 pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
356 chunk
357 .local_slots
358 .iter()
359 .map(|_| LocalSlot {
360 value: VmValue::Nil,
361 initialized: false,
362 synced: false,
363 })
364 .collect()
365 }
366
367 pub(crate) fn bind_param_slots(
368 slots: &mut [LocalSlot],
369 func: &crate::chunk::CompiledFunction,
370 args: &[VmValue],
371 synced: bool,
372 ) {
373 let param_count = func.params.len();
374 for (i, _param) in func.params.iter().enumerate() {
375 if i >= slots.len() {
376 break;
377 }
378 if func.has_rest_param && i == param_count - 1 {
379 let rest_args = if i < args.len() {
380 args[i..].to_vec()
381 } else {
382 Vec::new()
383 };
384 slots[i].value = VmValue::List(Rc::new(rest_args));
385 slots[i].initialized = true;
386 slots[i].synced = synced;
387 } else if i < args.len() {
388 slots[i].value = args[i].clone();
389 slots[i].initialized = true;
390 slots[i].synced = synced;
391 }
392 }
393 }
394
395 pub(crate) fn visible_variables(&self) -> BTreeMap<String, VmValue> {
396 let mut vars = self.env.all_variables();
397 let Some(frame) = self.frames.last() else {
398 return vars;
399 };
400 for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
401 if slot.initialized && info.scope_depth <= frame.local_scope_depth {
402 vars.insert(info.name.clone(), slot.value.clone());
403 }
404 }
405 vars
406 }
407
408 pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
409 let frames = &mut self.frames;
410 let env = &mut self.env;
411 let Some(frame) = frames.last_mut() else {
412 return;
413 };
414 let local_scope_base = frame.local_scope_base;
415 let local_scope_depth = frame.local_scope_depth;
416 for (slot, info) in frame
417 .local_slots
418 .iter_mut()
419 .zip(frame.chunk.local_slots.iter())
420 {
421 if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
422 slot.synced = true;
423 let scope_idx = local_scope_base + info.scope_depth;
424 while env.scopes.len() <= scope_idx {
425 env.push_scope();
426 }
427 Rc::make_mut(&mut env.scopes[scope_idx].vars)
428 .insert(info.name.clone(), (slot.value.clone(), info.mutable));
429 }
430 }
431 }
432
433 pub(crate) fn closure_call_env_for_current_frame(
434 &self,
435 closure: &crate::value::VmClosure,
436 ) -> VmEnv {
437 if closure.module_state.is_some() {
438 return closure.env.clone();
439 }
440 let mut call_env = Self::closure_call_env(&self.env, closure);
441 let Some(frame) = self.frames.last() else {
442 return call_env;
443 };
444 for (slot, info) in frame
445 .local_slots
446 .iter()
447 .zip(frame.chunk.local_slots.iter())
448 .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
449 {
450 if matches!(slot.value, VmValue::Closure(_)) && !call_env.contains(&info.name) {
451 let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
452 }
453 }
454 call_env
455 }
456
457 pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
458 let frame = self.frames.last()?;
459 let idx = self.active_local_slot_index(name)?;
460 frame.local_slots.get(idx).map(|slot| slot.value.clone())
461 }
462
463 pub(crate) fn active_local_slot_index(&self, name: &str) -> Option<usize> {
468 let frame = self.frames.last()?;
469 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
470 if info.name == name && info.scope_depth <= frame.local_scope_depth {
471 if let Some(slot) = frame.local_slots.get(idx) {
472 if slot.initialized {
473 return Some(idx);
474 }
475 }
476 }
477 }
478 None
479 }
480
481 pub(crate) fn assign_active_local_slot(
482 &mut self,
483 name: &str,
484 value: VmValue,
485 debug: bool,
486 ) -> Result<bool, VmError> {
487 let Some(frame) = self.frames.last_mut() else {
488 return Ok(false);
489 };
490 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
491 if info.name == name && info.scope_depth <= frame.local_scope_depth {
492 if !debug && !info.mutable {
493 return Err(VmError::ImmutableAssignment(name.to_string()));
494 }
495 if let Some(slot) = frame.local_slots.get_mut(idx) {
496 slot.value = value;
497 slot.initialized = true;
498 slot.synced = false;
499 return Ok(true);
500 }
501 }
502 }
503 Ok(false)
504 }
505
506 pub fn new() -> Self {
507 Self {
508 stack: Vec::with_capacity(256),
509 env: VmEnv::new(),
510 output: String::new(),
511 builtins: Rc::new(BTreeMap::new()),
512 async_builtins: Rc::new(BTreeMap::new()),
513 builtin_metadata: Rc::new(BTreeMap::new()),
514 builtins_by_id: Rc::new(BTreeMap::new()),
515 builtin_id_collisions: Rc::new(HashSet::new()),
516 iterators: Vec::new(),
517 frames: Vec::new(),
518 exception_handlers: Vec::new(),
519 spawned_tasks: BTreeMap::new(),
520 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
521 shared_state_runtime: Rc::new(crate::shared_state::VmSharedStateRuntime::new()),
522 held_sync_guards: Vec::new(),
523 task_counter: 0,
524 runtime_context_counter: 0,
525 runtime_context: crate::runtime_context::RuntimeContext::root(),
526 deadlines: Vec::new(),
527 breakpoints: BTreeMap::new(),
528 function_breakpoints: std::collections::BTreeSet::new(),
529 pending_function_bp: None,
530 step_mode: false,
531 step_frame_depth: 0,
532 stopped: false,
533 last_line: 0,
534 source_dir: None,
535 imported_paths: Vec::new(),
536 module_cache: Rc::new(BTreeMap::new()),
537 source_cache: Rc::new(BTreeMap::new()),
538 source_file: None,
539 source_text: None,
540 bridge: None,
541 denied_builtins: Rc::new(HashSet::new()),
542 cancel_token: None,
543 interrupt_signal_token: None,
544 cancel_grace_instructions_remaining: None,
545 interrupt_handlers: Vec::new(),
546 next_interrupt_handle: 1,
547 pending_interrupt_signal: None,
548 interrupted: false,
549 dispatching_interrupt: false,
550 interrupt_handler_deadline: None,
551 error_stack_trace: Vec::new(),
552 yield_sender: None,
553 project_root: None,
554 globals: Rc::new(BTreeMap::new()),
555 debug_hook: None,
556 }
557 }
558
559 pub fn baseline(&self) -> VmBaseline {
560 VmBaseline::from_vm(self)
561 }
562
563 #[inline]
577 pub(crate) fn debugger_attached(&self) -> bool {
578 self.debug_hook.is_some()
579 || !self.breakpoints.is_empty()
580 || !self.function_breakpoints.is_empty()
581 }
582
583 pub fn set_bridge(&mut self, bridge: Rc<crate::bridge::HostBridge>) {
585 self.bridge = Some(bridge);
586 }
587
588 pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
591 self.denied_builtins = Rc::new(denied);
592 }
593
594 pub fn set_source_info(&mut self, file: &str, text: &str) {
596 self.source_file = Some(file.to_string());
597 self.source_text = Some(text.to_string());
598 Rc::make_mut(&mut self.source_cache)
599 .insert(std::path::PathBuf::from(file), text.to_string());
600 }
601
602 pub fn start(&mut self, chunk: &Chunk) {
604 let debugger = self.debugger_attached();
611 let initial_env = if debugger {
612 Some(self.env.clone())
613 } else {
614 None
615 };
616 let initial_local_slots = if debugger {
617 Some(Self::fresh_local_slots(chunk))
618 } else {
619 None
620 };
621 self.frames.push(CallFrame {
622 chunk: Rc::new(chunk.clone()),
623 ip: 0,
624 stack_base: self.stack.len(),
625 saved_env: self.env.clone(),
626 initial_env,
627 initial_local_slots,
628 saved_iterator_depth: self.iterators.len(),
629 fn_name: String::new(),
630 argc: 0,
631 saved_source_dir: None,
632 module_functions: None,
633 module_state: None,
634 local_slots: Self::fresh_local_slots(chunk),
635 local_scope_base: self.env.scope_depth().saturating_sub(1),
636 local_scope_depth: 0,
637 });
638 }
639
640 pub(crate) fn child_vm(&self) -> Vm {
643 Vm {
644 stack: Vec::with_capacity(64),
645 env: self.env.clone(),
646 output: String::new(),
647 builtins: Rc::clone(&self.builtins),
648 async_builtins: Rc::clone(&self.async_builtins),
649 builtin_metadata: Rc::clone(&self.builtin_metadata),
650 builtins_by_id: Rc::clone(&self.builtins_by_id),
651 builtin_id_collisions: Rc::clone(&self.builtin_id_collisions),
652 iterators: Vec::new(),
653 frames: Vec::new(),
654 exception_handlers: Vec::new(),
655 spawned_tasks: BTreeMap::new(),
656 sync_runtime: self.sync_runtime.clone(),
657 shared_state_runtime: self.shared_state_runtime.clone(),
658 held_sync_guards: Vec::new(),
659 task_counter: 0,
660 runtime_context_counter: self.runtime_context_counter,
661 runtime_context: self.runtime_context.clone(),
662 deadlines: self.deadlines.clone(),
663 breakpoints: BTreeMap::new(),
664 function_breakpoints: std::collections::BTreeSet::new(),
665 pending_function_bp: None,
666 step_mode: false,
667 step_frame_depth: 0,
668 stopped: false,
669 last_line: 0,
670 source_dir: self.source_dir.clone(),
671 imported_paths: Vec::new(),
672 module_cache: Rc::clone(&self.module_cache),
673 source_cache: Rc::clone(&self.source_cache),
674 source_file: self.source_file.clone(),
675 source_text: self.source_text.clone(),
676 bridge: self.bridge.clone(),
677 denied_builtins: Rc::clone(&self.denied_builtins),
678 cancel_token: self.cancel_token.clone(),
679 interrupt_signal_token: self.interrupt_signal_token.clone(),
680 cancel_grace_instructions_remaining: None,
681 interrupt_handlers: Vec::new(),
682 next_interrupt_handle: 1,
683 pending_interrupt_signal: None,
684 interrupted: self.interrupted,
685 dispatching_interrupt: false,
686 interrupt_handler_deadline: None,
687 error_stack_trace: Vec::new(),
688 yield_sender: None,
689 project_root: self.project_root.clone(),
690 globals: Rc::clone(&self.globals),
691 debug_hook: None,
692 }
693 }
694
695 pub(crate) fn child_vm_for_host(&self) -> Vm {
698 self.child_vm()
699 }
700
701 pub(crate) fn cancel_spawned_tasks(&mut self) {
705 for (_, task) in std::mem::take(&mut self.spawned_tasks) {
706 task.cancel_token
707 .store(true, std::sync::atomic::Ordering::SeqCst);
708 task.handle.abort();
709 }
710 }
711
712 pub fn set_source_dir(&mut self, dir: &std::path::Path) {
715 let dir = crate::stdlib::process::normalize_context_path(dir);
716 self.source_dir = Some(dir.clone());
717 crate::stdlib::set_thread_source_dir(&dir);
718 if self.project_root.is_none() {
720 self.project_root = crate::stdlib::process::find_project_root(&dir);
721 }
722 }
723
724 pub fn set_project_root(&mut self, root: &std::path::Path) {
727 self.project_root = Some(root.to_path_buf());
728 }
729
730 pub fn project_root(&self) -> Option<&std::path::Path> {
732 self.project_root.as_deref().or(self.source_dir.as_deref())
733 }
734
735 pub fn builtin_names(&self) -> Vec<String> {
737 let mut names: Vec<String> = self.builtins.keys().cloned().collect();
738 names.extend(self.async_builtins.keys().cloned());
739 names
740 }
741
742 pub fn builtin_metadata(&self) -> Vec<VmBuiltinMetadata> {
744 self.builtin_metadata.values().cloned().collect()
745 }
746
747 pub fn builtin_metadata_for(&self, name: &str) -> Option<&VmBuiltinMetadata> {
749 self.builtin_metadata.get(name)
750 }
751
752 pub fn set_global(&mut self, name: &str, value: VmValue) {
755 Rc::make_mut(&mut self.globals).insert(name.to_string(), value);
756 }
757
758 pub fn set_harness(&mut self, harness: crate::harness::Harness) {
764 self.set_global("harness", harness.into_vm_value());
765 }
766
767 pub fn output(&self) -> &str {
769 &self.output
770 }
771
772 pub fn take_output(&mut self) -> String {
776 std::mem::take(&mut self.output)
777 }
778
779 pub fn append_output(&mut self, text: &str) {
783 self.output.push_str(text);
784 }
785
786 pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
787 self.stack.pop().ok_or(VmError::StackUnderflow)
788 }
789
790 pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
791 self.stack.last().ok_or(VmError::StackUnderflow)
792 }
793
794 pub(crate) fn const_string(c: &Constant) -> Result<String, VmError> {
795 match c {
796 Constant::String(s) => Ok(s.clone()),
797 _ => Err(VmError::TypeError("expected string constant".into())),
798 }
799 }
800
801 pub(crate) fn const_str(c: &Constant) -> Result<&str, VmError> {
802 match c {
803 Constant::String(s) => Ok(s.as_str()),
804 _ => Err(VmError::TypeError("expected string constant".into())),
805 }
806 }
807
808 pub(crate) fn release_sync_guards_for_current_scope(&mut self) {
809 let depth = self.env.scope_depth();
810 self.held_sync_guards
811 .retain(|guard| guard.env_scope_depth < depth);
812 }
813
814 pub(crate) fn release_sync_guards_after_unwind(
815 &mut self,
816 frame_depth: usize,
817 env_scope_depth: usize,
818 ) {
819 self.held_sync_guards.retain(|guard| {
820 guard.frame_depth <= frame_depth && guard.env_scope_depth <= env_scope_depth
821 });
822 }
823
824 pub(crate) fn release_sync_guards_for_frame(&mut self, frame_depth: usize) {
825 self.held_sync_guards
826 .retain(|guard| guard.frame_depth != frame_depth);
827 }
828}
829
830impl Drop for Vm {
831 fn drop(&mut self) {
832 self.cancel_spawned_tasks();
833 }
834}
835
836impl Default for Vm {
837 fn default() -> Self {
838 Self::new()
839 }
840}
841
842#[cfg(test)]
843mod tests {
844 use std::rc::Rc;
845
846 use super::*;
847
848 fn baseline_with_stdlib(source: &str) -> VmBaseline {
849 let mut vm = Vm::new();
850 crate::register_vm_stdlib(&mut vm);
851 vm.set_source_info("baseline_test.harn", source);
852 vm.set_global("stable_global", VmValue::String(Rc::from("baseline")));
853 vm.baseline()
854 }
855
856 #[test]
857 fn vm_baseline_instantiates_clean_mutable_execution_state() {
858 let baseline = baseline_with_stdlib("pipeline main() { println(stable_global) }");
859
860 let mut dirty = baseline.instantiate();
861 dirty.stack.push(VmValue::Int(42));
862 dirty.output.push_str("dirty");
863 dirty.task_counter = 9;
864 dirty.runtime_context_counter = 7;
865 dirty
866 .error_stack_trace
867 .push(("main".to_string(), 1, 1, None));
868
869 let clean = baseline.instantiate();
870 assert!(clean.stack.is_empty());
871 assert!(clean.output.is_empty());
872 assert!(clean.frames.is_empty());
873 assert!(clean.exception_handlers.is_empty());
874 assert!(clean.spawned_tasks.is_empty());
875 assert!(clean.held_sync_guards.is_empty());
876 assert_eq!(clean.task_counter, 0);
877 assert_eq!(clean.runtime_context_counter, 0);
878 assert!(clean.deadlines.is_empty());
879 assert!(clean.cancel_token.is_none());
880 assert!(clean.interrupt_handlers.is_empty());
881 assert!(clean.error_stack_trace.is_empty());
882 assert!(clean.bridge.is_none());
883 assert!(clean
884 .globals
885 .get("stable_global")
886 .is_some_and(|value| value.display() == "baseline"));
887 }
888
889 #[tokio::test(flavor = "current_thread")]
890 async fn vm_baseline_rebinds_shared_state_builtins_per_instance() {
891 let local = tokio::task::LocalSet::new();
892 local
893 .run_until(async {
894 let source = r#"
895pipeline main() {
896 let cell = shared_cell({scope: "task_group", key: "turn", initial: 0})
897 println(shared_get(cell))
898 shared_set(cell, shared_get(cell) + 1)
899}"#;
900 let chunk = crate::compile_source(source).expect("compile");
901 let baseline = baseline_with_stdlib(source);
902
903 let mut first = baseline.instantiate();
904 first.execute(&chunk).await.expect("first execute");
905 assert_eq!(first.output(), "0\n");
906
907 let mut second = baseline.instantiate();
908 second.execute(&chunk).await.expect("second execute");
909 assert_eq!(
910 second.output(),
911 "0\n",
912 "shared state created by the first VM must not leak into the next baseline instance"
913 );
914 })
915 .await;
916 }
917}