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: std::rc::Rc<crate::value::VmGenerator>,
114 },
115 Stream {
116 stream: std::rc::Rc<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(crate) type DeferredBuiltinRegistrar = fn(&mut Vm);
145
146pub struct Vm {
148 pub(crate) stack: Vec<VmValue>,
149 pub(crate) env: VmEnv,
150 pub(crate) output: String,
151 pub(crate) builtins: Rc<BTreeMap<String, VmBuiltinFn>>,
152 pub(crate) async_builtins: Rc<BTreeMap<String, VmAsyncBuiltinFn>>,
153 pub(crate) builtin_metadata: Rc<BTreeMap<String, VmBuiltinMetadata>>,
154 pub(crate) builtins_by_id: Rc<BTreeMap<BuiltinId, VmBuiltinEntry>>,
157 pub(crate) builtin_id_collisions: Rc<HashSet<BuiltinId>>,
160 pub(crate) deferred_builtin_registrars: Rc<BTreeMap<String, DeferredBuiltinRegistrar>>,
162 pub(crate) iterators: Vec<IterState>,
164 pub(crate) frames: Vec<CallFrame>,
166 pub(crate) exception_handlers: Vec<ExceptionHandler>,
168 pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
170 pub(crate) sync_runtime: Arc<crate::synchronization::VmSyncRuntime>,
172 pub(crate) shared_state_runtime: Rc<crate::shared_state::VmSharedStateRuntime>,
174 pub(crate) held_sync_guards: Vec<crate::synchronization::VmSyncHeldGuard>,
176 pub(crate) task_counter: u64,
178 pub(crate) runtime_context_counter: u64,
180 pub(crate) runtime_context: crate::runtime_context::RuntimeContext,
182 pub(crate) deadlines: Vec<(Instant, usize)>,
184 pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
189 pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
195 pub(crate) pending_function_bp: Option<String>,
200 pub(crate) step_mode: bool,
202 pub(crate) step_frame_depth: usize,
204 pub(crate) stopped: bool,
206 pub(crate) last_line: usize,
208 pub(crate) source_dir: Option<std::path::PathBuf>,
210 pub(crate) imported_paths: Vec<std::path::PathBuf>,
212 pub(crate) module_cache: Rc<BTreeMap<std::path::PathBuf, LoadedModule>>,
214 pub(crate) source_cache: Rc<BTreeMap<std::path::PathBuf, String>>,
216 pub(crate) source_file: Option<String>,
218 pub(crate) source_text: Option<String>,
220 pub(crate) bridge: Option<Rc<crate::bridge::HostBridge>>,
222 pub(crate) denied_builtins: Rc<HashSet<String>>,
224 pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
226 pub(crate) interrupt_signal_token: Option<std::sync::Arc<std::sync::Mutex<Option<String>>>>,
227 pub(crate) cancel_grace_instructions_remaining: Option<usize>,
232 pub(crate) interrupt_handlers: Vec<InterruptHandler>,
234 pub(crate) next_interrupt_handle: i64,
235 pub(crate) pending_interrupt_signal: Option<String>,
236 pub(crate) interrupted: bool,
237 pub(crate) dispatching_interrupt: bool,
238 pub(crate) interrupt_handler_deadline: Option<Instant>,
239 pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
241 pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<Result<VmValue, VmError>>>,
244 pub(crate) project_root: Option<std::path::PathBuf>,
247 pub(crate) globals: Rc<BTreeMap<String, VmValue>>,
250 pub(crate) debug_hook: Option<Box<DebugHook>>,
252}
253
254#[derive(Clone)]
262pub struct VmBaseline {
263 builtins: Rc<BTreeMap<String, VmBuiltinFn>>,
264 async_builtins: Rc<BTreeMap<String, VmAsyncBuiltinFn>>,
265 builtin_metadata: Rc<BTreeMap<String, VmBuiltinMetadata>>,
266 builtins_by_id: Rc<BTreeMap<BuiltinId, VmBuiltinEntry>>,
267 builtin_id_collisions: Rc<HashSet<BuiltinId>>,
268 deferred_builtin_registrars: Rc<BTreeMap<String, DeferredBuiltinRegistrar>>,
269 source_dir: Option<std::path::PathBuf>,
270 source_file: Option<String>,
271 source_text: Option<String>,
272 project_root: Option<std::path::PathBuf>,
273 globals: Rc<BTreeMap<String, VmValue>>,
274 denied_builtins: Rc<HashSet<String>>,
275}
276
277impl VmBaseline {
278 pub fn from_vm(vm: &Vm) -> Self {
279 Self {
280 builtins: Rc::clone(&vm.builtins),
281 async_builtins: Rc::clone(&vm.async_builtins),
282 builtin_metadata: Rc::clone(&vm.builtin_metadata),
283 builtins_by_id: Rc::clone(&vm.builtins_by_id),
284 builtin_id_collisions: Rc::clone(&vm.builtin_id_collisions),
285 deferred_builtin_registrars: Rc::clone(&vm.deferred_builtin_registrars),
286 source_dir: vm.source_dir.clone(),
287 source_file: vm.source_file.clone(),
288 source_text: vm.source_text.clone(),
289 project_root: vm.project_root.clone(),
290 globals: Rc::clone(&vm.globals),
291 denied_builtins: Rc::clone(&vm.denied_builtins),
292 }
293 }
294
295 pub fn instantiate(&self) -> Vm {
296 let mut source_cache = BTreeMap::new();
297 if let (Some(file), Some(text)) = (&self.source_file, &self.source_text) {
298 source_cache.insert(std::path::PathBuf::from(file), text.clone());
299 }
300 if let Some(dir) = &self.source_dir {
301 crate::stdlib::set_thread_source_dir(dir);
302 }
303
304 let mut vm = Vm {
305 stack: Vec::with_capacity(256),
306 env: VmEnv::new(),
307 output: String::new(),
308 builtins: Rc::clone(&self.builtins),
309 async_builtins: Rc::clone(&self.async_builtins),
310 builtin_metadata: Rc::clone(&self.builtin_metadata),
311 builtins_by_id: Rc::clone(&self.builtins_by_id),
312 builtin_id_collisions: Rc::clone(&self.builtin_id_collisions),
313 deferred_builtin_registrars: Rc::clone(&self.deferred_builtin_registrars),
314 iterators: Vec::new(),
315 frames: Vec::new(),
316 exception_handlers: Vec::new(),
317 spawned_tasks: BTreeMap::new(),
318 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
319 shared_state_runtime: Rc::new(crate::shared_state::VmSharedStateRuntime::new()),
320 held_sync_guards: Vec::new(),
321 task_counter: 0,
322 runtime_context_counter: 0,
323 runtime_context: crate::runtime_context::RuntimeContext::root(),
324 deadlines: Vec::new(),
325 breakpoints: BTreeMap::new(),
326 function_breakpoints: std::collections::BTreeSet::new(),
327 pending_function_bp: None,
328 step_mode: false,
329 step_frame_depth: 0,
330 stopped: false,
331 last_line: 0,
332 source_dir: self.source_dir.clone(),
333 imported_paths: Vec::new(),
334 module_cache: Rc::new(BTreeMap::new()),
335 source_cache: Rc::new(source_cache),
336 source_file: self.source_file.clone(),
337 source_text: self.source_text.clone(),
338 bridge: None,
339 denied_builtins: Rc::clone(&self.denied_builtins),
340 cancel_token: None,
341 interrupt_signal_token: None,
342 cancel_grace_instructions_remaining: None,
343 interrupt_handlers: Vec::new(),
344 next_interrupt_handle: 1,
345 pending_interrupt_signal: None,
346 interrupted: false,
347 dispatching_interrupt: false,
348 interrupt_handler_deadline: None,
349 error_stack_trace: Vec::new(),
350 yield_sender: None,
351 project_root: self.project_root.clone(),
352 globals: Rc::clone(&self.globals),
353 debug_hook: None,
354 };
355
356 crate::stdlib::rebind_execution_state_builtins(&mut vm);
357 vm
358 }
359}
360
361impl Vm {
362 pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
363 chunk
364 .local_slots
365 .iter()
366 .map(|_| LocalSlot {
367 value: VmValue::Nil,
368 initialized: false,
369 synced: false,
370 })
371 .collect()
372 }
373
374 pub(crate) fn bind_param_slots(
375 slots: &mut [LocalSlot],
376 func: &crate::chunk::CompiledFunction,
377 args: &[VmValue],
378 synced: bool,
379 ) {
380 let param_count = func.params.len();
381 for (i, _param) in func.params.iter().enumerate() {
382 if i >= slots.len() {
383 break;
384 }
385 if func.has_rest_param && i == param_count - 1 {
386 let rest_args = if i < args.len() {
387 args[i..].to_vec()
388 } else {
389 Vec::new()
390 };
391 slots[i].value = VmValue::List(Rc::new(rest_args));
392 slots[i].initialized = true;
393 slots[i].synced = synced;
394 } else if i < args.len() {
395 slots[i].value = args[i].clone();
396 slots[i].initialized = true;
397 slots[i].synced = synced;
398 }
399 }
400 }
401
402 pub(crate) fn visible_variables(&self) -> BTreeMap<String, VmValue> {
403 let mut vars = self.env.all_variables();
404 let Some(frame) = self.frames.last() else {
405 return vars;
406 };
407 for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
408 if slot.initialized && info.scope_depth <= frame.local_scope_depth {
409 vars.insert(info.name.clone(), slot.value.clone());
410 }
411 }
412 vars
413 }
414
415 pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
416 let frames = &mut self.frames;
417 let env = &mut self.env;
418 let Some(frame) = frames.last_mut() else {
419 return;
420 };
421 let local_scope_base = frame.local_scope_base;
422 let local_scope_depth = frame.local_scope_depth;
423 for (slot, info) in frame
424 .local_slots
425 .iter_mut()
426 .zip(frame.chunk.local_slots.iter())
427 {
428 if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
429 slot.synced = true;
430 let scope_idx = local_scope_base + info.scope_depth;
431 while env.scopes.len() <= scope_idx {
432 env.push_scope();
433 }
434 Rc::make_mut(&mut env.scopes[scope_idx].vars)
435 .insert(info.name.clone(), (slot.value.clone(), info.mutable));
436 }
437 }
438 }
439
440 pub(crate) fn closure_call_env_for_current_frame(
441 &self,
442 closure: &crate::value::VmClosure,
443 ) -> VmEnv {
444 if closure.module_state.is_some() {
445 return closure.env.clone();
446 }
447 let mut call_env = Self::closure_call_env(&self.env, closure);
448 let Some(frame) = self.frames.last() else {
449 return call_env;
450 };
451 for (slot, info) in frame
452 .local_slots
453 .iter()
454 .zip(frame.chunk.local_slots.iter())
455 .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
456 {
457 if matches!(slot.value, VmValue::Closure(_)) && !call_env.contains(&info.name) {
458 let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
459 }
460 }
461 call_env
462 }
463
464 pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
465 let frame = self.frames.last()?;
466 let idx = self.active_local_slot_index(name)?;
467 frame.local_slots.get(idx).map(|slot| slot.value.clone())
468 }
469
470 pub(crate) fn active_local_slot_index(&self, name: &str) -> Option<usize> {
475 let frame = self.frames.last()?;
476 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
477 if info.name == name && info.scope_depth <= frame.local_scope_depth {
478 if let Some(slot) = frame.local_slots.get(idx) {
479 if slot.initialized {
480 return Some(idx);
481 }
482 }
483 }
484 }
485 None
486 }
487
488 pub(crate) fn assign_active_local_slot(
489 &mut self,
490 name: &str,
491 value: VmValue,
492 debug: bool,
493 ) -> Result<bool, VmError> {
494 let Some(frame) = self.frames.last_mut() else {
495 return Ok(false);
496 };
497 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
498 if info.name == name && info.scope_depth <= frame.local_scope_depth {
499 if !debug && !info.mutable {
500 return Err(VmError::ImmutableAssignment(name.to_string()));
501 }
502 if let Some(slot) = frame.local_slots.get_mut(idx) {
503 slot.value = value;
504 slot.initialized = true;
505 slot.synced = false;
506 return Ok(true);
507 }
508 }
509 }
510 Ok(false)
511 }
512
513 pub fn new() -> Self {
514 Self {
515 stack: Vec::with_capacity(256),
516 env: VmEnv::new(),
517 output: String::new(),
518 builtins: Rc::new(BTreeMap::new()),
519 async_builtins: Rc::new(BTreeMap::new()),
520 builtin_metadata: Rc::new(BTreeMap::new()),
521 builtins_by_id: Rc::new(BTreeMap::new()),
522 builtin_id_collisions: Rc::new(HashSet::new()),
523 deferred_builtin_registrars: Rc::new(BTreeMap::new()),
524 iterators: Vec::new(),
525 frames: Vec::new(),
526 exception_handlers: Vec::new(),
527 spawned_tasks: BTreeMap::new(),
528 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
529 shared_state_runtime: Rc::new(crate::shared_state::VmSharedStateRuntime::new()),
530 held_sync_guards: Vec::new(),
531 task_counter: 0,
532 runtime_context_counter: 0,
533 runtime_context: crate::runtime_context::RuntimeContext::root(),
534 deadlines: Vec::new(),
535 breakpoints: BTreeMap::new(),
536 function_breakpoints: std::collections::BTreeSet::new(),
537 pending_function_bp: None,
538 step_mode: false,
539 step_frame_depth: 0,
540 stopped: false,
541 last_line: 0,
542 source_dir: None,
543 imported_paths: Vec::new(),
544 module_cache: Rc::new(BTreeMap::new()),
545 source_cache: Rc::new(BTreeMap::new()),
546 source_file: None,
547 source_text: None,
548 bridge: None,
549 denied_builtins: Rc::new(HashSet::new()),
550 cancel_token: None,
551 interrupt_signal_token: None,
552 cancel_grace_instructions_remaining: None,
553 interrupt_handlers: Vec::new(),
554 next_interrupt_handle: 1,
555 pending_interrupt_signal: None,
556 interrupted: false,
557 dispatching_interrupt: false,
558 interrupt_handler_deadline: None,
559 error_stack_trace: Vec::new(),
560 yield_sender: None,
561 project_root: None,
562 globals: Rc::new(BTreeMap::new()),
563 debug_hook: None,
564 }
565 }
566
567 pub fn baseline(&self) -> VmBaseline {
568 VmBaseline::from_vm(self)
569 }
570
571 #[inline]
585 pub(crate) fn debugger_attached(&self) -> bool {
586 self.debug_hook.is_some()
587 || !self.breakpoints.is_empty()
588 || !self.function_breakpoints.is_empty()
589 }
590
591 pub fn set_bridge(&mut self, bridge: Rc<crate::bridge::HostBridge>) {
593 self.bridge = Some(bridge);
594 }
595
596 pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
599 self.denied_builtins = Rc::new(denied);
600 }
601
602 pub fn set_source_info(&mut self, file: &str, text: &str) {
604 self.source_file = Some(file.to_string());
605 self.source_text = Some(text.to_string());
606 Rc::make_mut(&mut self.source_cache)
607 .insert(std::path::PathBuf::from(file), text.to_string());
608 }
609
610 pub fn start(&mut self, chunk: &Chunk) {
612 let debugger = self.debugger_attached();
619 let initial_env = if debugger {
620 Some(self.env.clone())
621 } else {
622 None
623 };
624 let initial_local_slots = if debugger {
625 Some(Self::fresh_local_slots(chunk))
626 } else {
627 None
628 };
629 self.frames.push(CallFrame {
630 chunk: Rc::new(chunk.clone()),
631 ip: 0,
632 stack_base: self.stack.len(),
633 saved_env: self.env.clone(),
634 initial_env,
635 initial_local_slots,
636 saved_iterator_depth: self.iterators.len(),
637 fn_name: String::new(),
638 argc: 0,
639 saved_source_dir: None,
640 module_functions: None,
641 module_state: None,
642 local_slots: Self::fresh_local_slots(chunk),
643 local_scope_base: self.env.scope_depth().saturating_sub(1),
644 local_scope_depth: 0,
645 });
646 }
647
648 pub(crate) fn child_vm(&self) -> Vm {
651 Vm {
652 stack: Vec::with_capacity(64),
653 env: self.env.clone(),
654 output: String::new(),
655 builtins: Rc::clone(&self.builtins),
656 async_builtins: Rc::clone(&self.async_builtins),
657 builtin_metadata: Rc::clone(&self.builtin_metadata),
658 builtins_by_id: Rc::clone(&self.builtins_by_id),
659 builtin_id_collisions: Rc::clone(&self.builtin_id_collisions),
660 deferred_builtin_registrars: Rc::clone(&self.deferred_builtin_registrars),
661 iterators: Vec::new(),
662 frames: Vec::new(),
663 exception_handlers: Vec::new(),
664 spawned_tasks: BTreeMap::new(),
665 sync_runtime: self.sync_runtime.clone(),
666 shared_state_runtime: self.shared_state_runtime.clone(),
667 held_sync_guards: Vec::new(),
668 task_counter: 0,
669 runtime_context_counter: self.runtime_context_counter,
670 runtime_context: self.runtime_context.clone(),
671 deadlines: self.deadlines.clone(),
672 breakpoints: BTreeMap::new(),
673 function_breakpoints: std::collections::BTreeSet::new(),
674 pending_function_bp: None,
675 step_mode: false,
676 step_frame_depth: 0,
677 stopped: false,
678 last_line: 0,
679 source_dir: self.source_dir.clone(),
680 imported_paths: Vec::new(),
681 module_cache: Rc::clone(&self.module_cache),
682 source_cache: Rc::clone(&self.source_cache),
683 source_file: self.source_file.clone(),
684 source_text: self.source_text.clone(),
685 bridge: self.bridge.clone(),
686 denied_builtins: Rc::clone(&self.denied_builtins),
687 cancel_token: self.cancel_token.clone(),
688 interrupt_signal_token: self.interrupt_signal_token.clone(),
689 cancel_grace_instructions_remaining: None,
690 interrupt_handlers: Vec::new(),
691 next_interrupt_handle: 1,
692 pending_interrupt_signal: None,
693 interrupted: self.interrupted,
694 dispatching_interrupt: false,
695 interrupt_handler_deadline: None,
696 error_stack_trace: Vec::new(),
697 yield_sender: None,
698 project_root: self.project_root.clone(),
699 globals: Rc::clone(&self.globals),
700 debug_hook: None,
701 }
702 }
703
704 pub(crate) fn child_vm_for_host(&self) -> Vm {
707 self.child_vm()
708 }
709
710 pub(crate) fn cancel_spawned_tasks(&mut self) {
714 for (_, task) in std::mem::take(&mut self.spawned_tasks) {
715 task.cancel_token
716 .store(true, std::sync::atomic::Ordering::SeqCst);
717 task.handle.abort();
718 }
719 }
720
721 pub fn set_source_dir(&mut self, dir: &std::path::Path) {
724 let dir = crate::stdlib::process::normalize_context_path(dir);
725 self.source_dir = Some(dir.clone());
726 crate::stdlib::set_thread_source_dir(&dir);
727 if self.project_root.is_none() {
729 self.project_root = crate::stdlib::process::find_project_root(&dir);
730 }
731 }
732
733 pub fn set_project_root(&mut self, root: &std::path::Path) {
736 self.project_root = Some(root.to_path_buf());
737 }
738
739 pub fn project_root(&self) -> Option<&std::path::Path> {
741 self.project_root.as_deref().or(self.source_dir.as_deref())
742 }
743
744 pub fn builtin_names(&self) -> Vec<String> {
746 let mut names: Vec<String> = self.builtins.keys().cloned().collect();
747 names.extend(self.async_builtins.keys().cloned());
748 names
749 }
750
751 pub fn builtin_metadata(&self) -> Vec<VmBuiltinMetadata> {
753 self.builtin_metadata.values().cloned().collect()
754 }
755
756 pub fn builtin_metadata_for(&self, name: &str) -> Option<&VmBuiltinMetadata> {
758 self.builtin_metadata.get(name)
759 }
760
761 pub fn set_global(&mut self, name: &str, value: VmValue) {
764 Rc::make_mut(&mut self.globals).insert(name.to_string(), value);
765 }
766
767 pub fn set_harness(&mut self, harness: crate::harness::Harness) {
773 self.set_global("harness", harness.into_vm_value());
774 }
775
776 pub fn output(&self) -> &str {
778 &self.output
779 }
780
781 pub fn take_output(&mut self) -> String {
785 std::mem::take(&mut self.output)
786 }
787
788 pub fn append_output(&mut self, text: &str) {
792 self.output.push_str(text);
793 }
794
795 pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
796 self.stack.pop().ok_or(VmError::StackUnderflow)
797 }
798
799 pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
800 self.stack.last().ok_or(VmError::StackUnderflow)
801 }
802
803 pub(crate) fn const_string(c: &Constant) -> Result<String, VmError> {
804 match c {
805 Constant::String(s) => Ok(s.clone()),
806 _ => Err(VmError::TypeError("expected string constant".into())),
807 }
808 }
809
810 pub(crate) fn const_str(c: &Constant) -> Result<&str, VmError> {
811 match c {
812 Constant::String(s) => Ok(s.as_str()),
813 _ => Err(VmError::TypeError("expected string constant".into())),
814 }
815 }
816
817 pub(crate) fn release_sync_guards_for_current_scope(&mut self) {
818 let depth = self.env.scope_depth();
819 self.held_sync_guards
820 .retain(|guard| guard.env_scope_depth < depth);
821 }
822
823 pub(crate) fn release_sync_guards_after_unwind(
824 &mut self,
825 frame_depth: usize,
826 env_scope_depth: usize,
827 ) {
828 self.held_sync_guards.retain(|guard| {
829 guard.frame_depth <= frame_depth && guard.env_scope_depth <= env_scope_depth
830 });
831 }
832
833 pub(crate) fn release_sync_guards_for_frame(&mut self, frame_depth: usize) {
834 self.held_sync_guards
835 .retain(|guard| guard.frame_depth != frame_depth);
836 }
837}
838
839impl Drop for Vm {
840 fn drop(&mut self) {
841 self.cancel_spawned_tasks();
842 }
843}
844
845impl Default for Vm {
846 fn default() -> Self {
847 Self::new()
848 }
849}
850
851#[cfg(test)]
852mod tests {
853 use std::rc::Rc;
854
855 use super::*;
856
857 fn baseline_with_stdlib(source: &str) -> VmBaseline {
858 let mut vm = Vm::new();
859 crate::register_vm_stdlib(&mut vm);
860 vm.set_source_info("baseline_test.harn", source);
861 vm.set_global("stable_global", VmValue::String(Rc::from("baseline")));
862 vm.baseline()
863 }
864
865 #[test]
866 fn vm_baseline_instantiates_clean_mutable_execution_state() {
867 let baseline = baseline_with_stdlib("pipeline main() { __io_println(stable_global) }");
868
869 let mut dirty = baseline.instantiate();
870 dirty.stack.push(VmValue::Int(42));
871 dirty.output.push_str("dirty");
872 dirty.task_counter = 9;
873 dirty.runtime_context_counter = 7;
874 dirty
875 .error_stack_trace
876 .push(("main".to_string(), 1, 1, None));
877
878 let clean = baseline.instantiate();
879 assert!(clean.stack.is_empty());
880 assert!(clean.output.is_empty());
881 assert!(clean.frames.is_empty());
882 assert!(clean.exception_handlers.is_empty());
883 assert!(clean.spawned_tasks.is_empty());
884 assert!(clean.held_sync_guards.is_empty());
885 assert_eq!(clean.task_counter, 0);
886 assert_eq!(clean.runtime_context_counter, 0);
887 assert!(clean.deadlines.is_empty());
888 assert!(clean.cancel_token.is_none());
889 assert!(clean.interrupt_handlers.is_empty());
890 assert!(clean.error_stack_trace.is_empty());
891 assert!(clean.bridge.is_none());
892 assert!(clean
893 .globals
894 .get("stable_global")
895 .is_some_and(|value| value.display() == "baseline"));
896 }
897
898 #[tokio::test(flavor = "current_thread")]
899 async fn vm_baseline_rebinds_shared_state_builtins_per_instance() {
900 let local = tokio::task::LocalSet::new();
901 local
902 .run_until(async {
903 let source = r#"
904pipeline main() {
905 let cell = shared_cell({scope: "task_group", key: "turn", initial: 0})
906 __io_println(shared_get(cell))
907 shared_set(cell, shared_get(cell) + 1)
908}"#;
909 let chunk = crate::compile_source(source).expect("compile");
910 let baseline = baseline_with_stdlib(source);
911
912 let mut first = baseline.instantiate();
913 first.execute(&chunk).await.expect("first execute");
914 assert_eq!(first.output(), "0\n");
915
916 let mut second = baseline.instantiate();
917 second.execute(&chunk).await.expect("second execute");
918 assert_eq!(
919 second.output(),
920 "0\n",
921 "shared state created by the first VM must not leak into the next baseline instance"
922 );
923 })
924 .await;
925 }
926}