1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::Arc;
3use std::time::Instant;
4
5use crate::chunk::{Chunk, ChunkRef, Constant};
6use crate::runtime_limits::RuntimeLimits;
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
38impl Drop for LocalSlot {
39 fn drop(&mut self) {
40 if crate::value::recursion::is_recursive_container(&self.value) {
48 crate::value::recursion::dismantle(std::mem::replace(&mut self.value, VmValue::Nil));
49 }
50 }
51}
52
53#[derive(Clone)]
54pub(crate) struct InterruptHandler {
55 pub(crate) handle: i64,
56 pub(crate) signals: Vec<String>,
57 pub(crate) once: bool,
58 pub(crate) graceful_timeout_ms: Option<u64>,
59 pub(crate) handler: VmValue,
60}
61
62pub(crate) struct CallFrame {
64 pub(crate) chunk: ChunkRef,
65 pub(crate) inline_cache_set: usize,
69 pub(crate) ip: usize,
70 pub(crate) stack_base: usize,
71 pub(crate) saved_env: VmEnv,
72 pub(crate) initial_env: Option<VmEnv>,
80 pub(crate) initial_local_slots: Option<Vec<LocalSlot>>,
81 pub(crate) saved_iterator_depth: usize,
83 pub(crate) fn_name: String,
85 pub(crate) argc: usize,
87 pub(crate) saved_source_dir: Option<std::path::PathBuf>,
90 pub(crate) module_functions: Option<ModuleFunctionRegistry>,
92 pub(crate) module_state: Option<crate::value::ModuleState>,
98 pub(crate) local_slots: Vec<LocalSlot>,
100 pub(crate) local_scope_base: usize,
102 pub(crate) local_scope_depth: usize,
104}
105
106pub(crate) struct InlineCacheSite {
107 pub(crate) cache_set: usize,
108 pub(crate) slot_count: usize,
109 pub(crate) slot: Option<usize>,
110}
111
112impl CallFrame {
113 #[inline]
114 pub(crate) fn inline_cache_site_for_previous_op(&self) -> InlineCacheSite {
115 let op_offset = self.ip.saturating_sub(1);
116 InlineCacheSite {
117 cache_set: self.inline_cache_set,
118 slot_count: self.chunk.inline_cache_slot_count(),
119 slot: self.chunk.inline_cache_slot(op_offset),
120 }
121 }
122}
123
124pub(crate) struct ExceptionHandler {
126 pub(crate) catch_ip: usize,
127 pub(crate) stack_depth: usize,
128 pub(crate) frame_depth: usize,
129 pub(crate) env_scope_depth: usize,
130 pub(crate) error_type: Option<crate::value::HarnStr>,
132}
133
134pub(crate) struct TaskScope {
137 pub(crate) task_ids: Vec<String>,
140 pub(crate) frame_depth: usize,
142 pub(crate) env_scope_depth: usize,
144}
145
146pub(crate) enum IterState {
148 Vec {
149 items: Arc<Vec<VmValue>>,
150 idx: usize,
151 },
152 Dict {
153 entries: Arc<crate::value::DictMap>,
154 keys: Vec<String>,
155 idx: usize,
156 },
157 Channel {
158 receiver: std::sync::Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
159 close: std::sync::Arc<crate::value::VmChannelCloseState>,
160 },
161 Generator {
162 gen: Arc<crate::value::VmGenerator>,
163 },
164 Stream {
165 stream: Arc<crate::value::VmStream>,
166 },
167 Range {
171 next: i64,
172 end: i64,
173 inclusive: bool,
174 done: bool,
175 },
176 VmIter {
177 handle: crate::vm::iter::VmIterHandle,
178 },
179}
180
181#[derive(Clone)]
182pub(crate) enum VmBuiltinDispatch {
183 Sync(VmBuiltinFn),
184 Async(VmAsyncBuiltinFn),
185}
186
187#[derive(Clone)]
188pub(crate) struct VmBuiltinEntry {
189 pub(crate) name: Arc<str>,
190 pub(crate) dispatch: VmBuiltinDispatch,
191}
192
193pub struct Vm {
195 pub(crate) stack: Vec<VmValue>,
196 pub(crate) env: VmEnv,
197 pub(crate) output: String,
198 pub(crate) builtins: Arc<BTreeMap<String, VmBuiltinFn>>,
199 pub(crate) async_builtins: Arc<BTreeMap<String, VmAsyncBuiltinFn>>,
200 pub(crate) builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
201 pub(crate) builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
204 pub(crate) builtin_id_collisions: Arc<HashSet<BuiltinId>>,
207 pub(crate) iterators: Vec<IterState>,
209 pub(crate) frames: Vec<CallFrame>,
211 pub(crate) exception_handlers: Vec<ExceptionHandler>,
213 pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
215 pub(crate) sync_runtime: Arc<crate::synchronization::VmSyncRuntime>,
217 pub(crate) shared_state_runtime: Arc<crate::shared_state::VmSharedStateRuntime>,
219 pub(crate) inline_cache_sets: Vec<Vec<crate::chunk::InlineCacheEntry>>,
223 pub(crate) inline_cache_set_by_chunk: HashMap<u64, usize>,
224 pub(crate) pool_registry: Arc<crate::stdlib::pool::PoolRegistry>,
226 pub(crate) wait_for_graph: Arc<crate::wait_for_graph::VmWaitForGraph>,
228 pub(crate) held_sync_guards: Vec<crate::synchronization::VmSyncHeldGuard>,
230 pub(crate) inherited_held_keys: Arc<Vec<crate::synchronization::VmSyncHeldKey>>,
238 pub(crate) task_scopes: Vec<TaskScope>,
244 pub(crate) task_counter: u64,
246 pub(crate) runtime_context_counter: u64,
248 pub(crate) runtime_context: crate::runtime_context::RuntimeContext,
250 pub(crate) deadlines: Vec<(Instant, usize)>,
252 pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
257 pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
263 pub(crate) pending_function_bp: Option<String>,
268 pub(crate) step_mode: bool,
270 pub(crate) step_frame_depth: usize,
272 pub(crate) stopped: bool,
274 pub(crate) last_line: usize,
276 pub(crate) source_dir: Option<std::path::PathBuf>,
278 pub(crate) imported_paths: Vec<std::path::PathBuf>,
280 pub(crate) deferred_cyclic_imports: Vec<super::modules::DeferredCyclicImport>,
284 pub(crate) module_cache: Arc<BTreeMap<std::path::PathBuf, LoadedModule>>,
286 pub(crate) source_cache: Arc<BTreeMap<std::path::PathBuf, String>>,
288 pub(crate) source_file: Option<String>,
290 pub(crate) source_text: Option<String>,
292 pub(crate) coverage: Option<crate::coverage::Coverage>,
295 pub(crate) bridge: Option<Arc<crate::bridge::HostBridge>>,
297 pub(crate) denied_builtins: Arc<HashSet<String>>,
299 pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
301 pub(crate) interrupt_signal_token: Option<std::sync::Arc<std::sync::Mutex<Option<String>>>>,
302 pub(crate) cancel_grace_instructions_remaining: Option<usize>,
307 pub(crate) interrupt_handlers: Vec<InterruptHandler>,
309 pub(crate) next_interrupt_handle: i64,
310 pub(crate) pending_interrupt_signal: Option<String>,
311 pub(crate) interrupted: bool,
312 pub(crate) dispatching_interrupt: bool,
313 pub(crate) interrupt_handler_deadline: Option<Instant>,
314 pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
316 pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<Result<VmValue, VmError>>>,
319 pub(crate) project_root: Option<std::path::PathBuf>,
322 pub(crate) globals: Arc<crate::value::DictMap>,
325 pub(crate) debug_hook: Option<parking_lot::Mutex<Box<DebugHook>>>,
327 pub(crate) runtime_limits: RuntimeLimits,
329}
330
331#[derive(Clone)]
339pub struct VmBaseline {
340 builtins: Arc<BTreeMap<String, VmBuiltinFn>>,
341 async_builtins: Arc<BTreeMap<String, VmAsyncBuiltinFn>>,
342 builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
343 builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
344 builtin_id_collisions: Arc<HashSet<BuiltinId>>,
345 source_dir: Option<std::path::PathBuf>,
346 source_file: Option<String>,
347 source_text: Option<String>,
348 project_root: Option<std::path::PathBuf>,
349 globals: Arc<crate::value::DictMap>,
350 denied_builtins: Arc<HashSet<String>>,
351 runtime_limits: RuntimeLimits,
352}
353
354impl VmBaseline {
355 pub fn from_vm(vm: &Vm) -> Self {
356 Self {
357 builtins: Arc::clone(&vm.builtins),
358 async_builtins: Arc::clone(&vm.async_builtins),
359 builtin_metadata: Arc::clone(&vm.builtin_metadata),
360 builtins_by_id: Arc::clone(&vm.builtins_by_id),
361 builtin_id_collisions: Arc::clone(&vm.builtin_id_collisions),
362 source_dir: vm.source_dir.clone(),
363 source_file: vm.source_file.clone(),
364 source_text: vm.source_text.clone(),
365 project_root: vm.project_root.clone(),
366 globals: Arc::clone(&vm.globals),
367 denied_builtins: Arc::clone(&vm.denied_builtins),
368 runtime_limits: vm.runtime_limits,
369 }
370 }
371
372 pub fn instantiate(&self) -> Vm {
373 let mut source_cache = BTreeMap::new();
374 if let (Some(file), Some(text)) = (&self.source_file, &self.source_text) {
375 source_cache.insert(std::path::PathBuf::from(file), text.clone());
376 }
377 if let Some(dir) = &self.source_dir {
378 crate::stdlib::set_thread_source_dir(dir);
379 }
380
381 let mut vm = Vm {
382 stack: Vec::with_capacity(256),
383 env: VmEnv::new(),
384 output: String::new(),
385 builtins: Arc::clone(&self.builtins),
386 async_builtins: Arc::clone(&self.async_builtins),
387 builtin_metadata: Arc::clone(&self.builtin_metadata),
388 builtins_by_id: Arc::clone(&self.builtins_by_id),
389 builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
390 iterators: Vec::new(),
391 frames: Vec::new(),
392 exception_handlers: Vec::new(),
393 spawned_tasks: BTreeMap::new(),
394 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
395 shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
396 inline_cache_sets: Vec::new(),
397 inline_cache_set_by_chunk: HashMap::new(),
398 pool_registry: crate::stdlib::pool::new_pool_registry(),
399 wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
400 held_sync_guards: Vec::new(),
401 inherited_held_keys: Arc::new(Vec::new()),
402 task_scopes: Vec::new(),
403 task_counter: 0,
404 runtime_context_counter: 0,
405 runtime_context: crate::runtime_context::RuntimeContext::root(),
406 deadlines: Vec::new(),
407 breakpoints: BTreeMap::new(),
408 function_breakpoints: std::collections::BTreeSet::new(),
409 pending_function_bp: None,
410 step_mode: false,
411 step_frame_depth: 0,
412 stopped: false,
413 last_line: 0,
414 source_dir: self.source_dir.clone(),
415 imported_paths: Vec::new(),
416 deferred_cyclic_imports: Vec::new(),
417 module_cache: Arc::new(BTreeMap::new()),
418 source_cache: Arc::new(source_cache),
419 source_file: self.source_file.clone(),
420 source_text: self.source_text.clone(),
421 coverage: crate::coverage::for_primary(self.source_file.as_deref()),
422 bridge: None,
423 denied_builtins: Arc::clone(&self.denied_builtins),
424 cancel_token: None,
425 interrupt_signal_token: None,
426 cancel_grace_instructions_remaining: None,
427 interrupt_handlers: Vec::new(),
428 next_interrupt_handle: 1,
429 pending_interrupt_signal: None,
430 interrupted: false,
431 dispatching_interrupt: false,
432 interrupt_handler_deadline: None,
433 error_stack_trace: Vec::new(),
434 yield_sender: None,
435 project_root: self.project_root.clone(),
436 globals: Arc::clone(&self.globals),
437 debug_hook: None,
438 runtime_limits: self.runtime_limits,
439 };
440
441 crate::stdlib::rebind_execution_state_builtins(&mut vm);
442 vm
443 }
444}
445
446impl Vm {
447 pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
448 chunk
449 .local_slots
450 .iter()
451 .map(|_| LocalSlot {
452 value: VmValue::Nil,
453 initialized: false,
454 synced: false,
455 })
456 .collect()
457 }
458
459 pub(crate) fn bind_param_slots(
460 slots: &mut [LocalSlot],
461 func: &crate::chunk::CompiledFunction,
462 args: &[VmValue],
463 synced: bool,
464 ) {
465 Self::bind_param_slots_args(slots, func, &super::CallArgs::Slice(args), synced);
466 }
467
468 pub(crate) fn bind_param_slots_args(
469 slots: &mut [LocalSlot],
470 func: &crate::chunk::CompiledFunction,
471 args: &super::CallArgs<'_>,
472 synced: bool,
473 ) {
474 let param_count = func.params.len();
475 for (i, _param) in func.params.iter().enumerate() {
476 if i >= slots.len() {
477 break;
478 }
479 if func.has_rest_param && i == param_count - 1 {
480 let rest_args = args.to_vec_from(i);
481 slots[i].value = VmValue::List(std::sync::Arc::new(rest_args));
482 slots[i].initialized = true;
483 slots[i].synced = synced;
484 } else if let Some(arg) = args.get(i) {
485 slots[i].value = arg.clone();
486 slots[i].initialized = true;
487 slots[i].synced = synced;
488 }
489 }
490 }
491
492 pub(crate) fn visible_variables(&self) -> crate::value::DictMap {
493 let mut vars = self.env.all_variables();
494 let Some(frame) = self.frames.last() else {
495 return vars;
496 };
497 for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
498 if slot.initialized && info.scope_depth <= frame.local_scope_depth {
499 vars.insert(crate::value::intern_key(&info.name), slot.value.clone());
500 }
501 }
502 vars
503 }
504
505 pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
506 let frames = &mut self.frames;
507 let env = &mut self.env;
508 let Some(frame) = frames.last_mut() else {
509 return;
510 };
511 let local_scope_base = frame.local_scope_base;
512 let local_scope_depth = frame.local_scope_depth;
513 for (slot, info) in frame
514 .local_slots
515 .iter_mut()
516 .zip(frame.chunk.local_slots.iter())
517 {
518 if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
519 slot.synced = true;
520 let scope_idx = local_scope_base + info.scope_depth;
521 while env.scopes.len() <= scope_idx {
522 env.push_scope();
523 }
524 Arc::make_mut(&mut env.scopes[scope_idx].vars).insert(
528 info.name.clone(),
529 crate::value::Binding::Value {
530 value: slot.value.clone(),
531 mutable: info.mutable,
532 },
533 );
534 }
535 }
536 }
537
538 pub(crate) fn closure_call_env_for_current_frame(
539 &self,
540 closure: &crate::value::VmClosure,
541 ) -> VmEnv {
542 if closure.module_state().is_some() {
543 return closure.env.cloned_for_call();
544 }
545 let call_env = Self::closure_call_env(&self.env, closure);
546 if !closure.func.chunk.references_outer_names {
551 return call_env;
552 }
553 let mut call_env = call_env;
554 let Some(frame) = self.frames.last() else {
555 return call_env;
556 };
557 for (slot, info) in frame
558 .local_slots
559 .iter()
560 .zip(frame.chunk.local_slots.iter())
561 .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
562 {
563 if matches!(slot.value, VmValue::Closure(_)) && !call_env.contains(&info.name) {
564 let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
565 }
566 }
567 call_env
568 }
569
570 pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
571 let frame = self.frames.last()?;
572 let idx = self.active_local_slot_index(name)?;
573 frame.local_slots.get(idx).map(|slot| slot.value.clone())
574 }
575
576 pub(crate) fn active_local_slot_index(&self, name: &str) -> Option<usize> {
581 let frame = self.frames.last()?;
582 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
583 if info.name == name && info.scope_depth <= frame.local_scope_depth {
584 if let Some(slot) = frame.local_slots.get(idx) {
585 if slot.initialized {
586 return Some(idx);
587 }
588 }
589 }
590 }
591 None
592 }
593
594 pub(crate) fn assign_active_local_slot(
595 &mut self,
596 name: &str,
597 value: VmValue,
598 debug: bool,
599 ) -> Result<bool, VmError> {
600 let Some(frame) = self.frames.last_mut() else {
601 return Ok(false);
602 };
603 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
604 if info.name == name && info.scope_depth <= frame.local_scope_depth {
605 if !debug && !info.mutable {
606 return Err(VmError::ImmutableAssignment(name.to_string()));
607 }
608 if let Some(slot) = frame.local_slots.get_mut(idx) {
609 crate::value::recursion::dismantle(std::mem::replace(&mut slot.value, value));
610 slot.initialized = true;
611 slot.synced = false;
612 return Ok(true);
613 }
614 }
615 }
616 Ok(false)
617 }
618
619 pub fn new() -> Self {
620 Self {
621 stack: Vec::with_capacity(256),
622 env: VmEnv::new(),
623 output: String::new(),
624 builtins: Arc::new(BTreeMap::new()),
625 async_builtins: Arc::new(BTreeMap::new()),
626 builtin_metadata: Arc::new(BTreeMap::new()),
627 builtins_by_id: Arc::new(HashMap::new()),
628 builtin_id_collisions: Arc::new(HashSet::new()),
629 iterators: Vec::new(),
630 frames: Vec::new(),
631 exception_handlers: Vec::new(),
632 spawned_tasks: BTreeMap::new(),
633 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
634 shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
635 inline_cache_sets: Vec::new(),
636 inline_cache_set_by_chunk: HashMap::new(),
637 pool_registry: crate::stdlib::pool::new_pool_registry(),
638 wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
639 held_sync_guards: Vec::new(),
640 inherited_held_keys: Arc::new(Vec::new()),
641 task_scopes: Vec::new(),
642 task_counter: 0,
643 runtime_context_counter: 0,
644 runtime_context: crate::runtime_context::RuntimeContext::root(),
645 deadlines: Vec::new(),
646 breakpoints: BTreeMap::new(),
647 function_breakpoints: std::collections::BTreeSet::new(),
648 pending_function_bp: None,
649 step_mode: false,
650 step_frame_depth: 0,
651 stopped: false,
652 last_line: 0,
653 source_dir: None,
654 imported_paths: Vec::new(),
655 deferred_cyclic_imports: Vec::new(),
656 module_cache: Arc::new(BTreeMap::new()),
657 source_cache: Arc::new(BTreeMap::new()),
658 source_file: None,
659 source_text: None,
660 coverage: crate::coverage::for_primary(None),
661 bridge: None,
662 denied_builtins: Arc::new(HashSet::new()),
663 cancel_token: None,
664 interrupt_signal_token: None,
665 cancel_grace_instructions_remaining: None,
666 interrupt_handlers: Vec::new(),
667 next_interrupt_handle: 1,
668 pending_interrupt_signal: None,
669 interrupted: false,
670 dispatching_interrupt: false,
671 interrupt_handler_deadline: None,
672 error_stack_trace: Vec::new(),
673 yield_sender: None,
674 project_root: None,
675 globals: Arc::new(crate::value::DictMap::new()),
676 debug_hook: None,
677 runtime_limits: RuntimeLimits::default(),
678 }
679 }
680
681 pub fn baseline(&self) -> VmBaseline {
682 VmBaseline::from_vm(self)
683 }
684
685 pub fn runtime_limits(&self) -> RuntimeLimits {
687 self.runtime_limits
688 }
689
690 pub fn runtime_limit_report(&self) -> crate::RuntimeLimitsReport {
692 self.runtime_limits.report()
693 }
694
695 #[inline]
709 pub(crate) fn debugger_attached(&self) -> bool {
710 self.debug_hook.is_some()
711 || !self.breakpoints.is_empty()
712 || !self.function_breakpoints.is_empty()
713 }
714
715 pub fn set_bridge(&mut self, bridge: Arc<crate::bridge::HostBridge>) {
717 self.bridge = Some(bridge);
718 }
719
720 pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
723 self.denied_builtins = Arc::new(denied);
724 }
725
726 pub fn set_source_info(&mut self, file: &str, text: &str) {
728 self.source_file = Some(file.to_string());
729 self.source_text = Some(text.to_string());
730 if let Some(cov) = self.coverage.as_mut() {
731 cov.set_primary_file(file);
732 }
733 Arc::make_mut(&mut self.source_cache)
734 .insert(std::path::PathBuf::from(file), text.to_string());
735 }
736
737 pub fn start(&mut self, chunk: &Chunk) {
739 let debugger = self.debugger_attached();
746 let initial_env = if debugger {
747 Some(self.env.clone())
748 } else {
749 None
750 };
751 let initial_local_slots = if debugger {
752 Some(Self::fresh_local_slots(chunk))
753 } else {
754 None
755 };
756 let chunk = Arc::new(chunk.clone());
757 let local_slots = Self::fresh_local_slots(&chunk);
758 let inline_cache_set = self.inline_cache_set_index_for_chunk(&chunk);
759 self.frames.push(CallFrame {
760 chunk,
761 inline_cache_set,
762 ip: 0,
763 stack_base: self.stack.len(),
764 saved_env: self.env.clone(),
765 initial_env,
766 initial_local_slots,
767 saved_iterator_depth: self.iterators.len(),
768 fn_name: String::new(),
769 argc: 0,
770 saved_source_dir: None,
771 module_functions: None,
772 module_state: None,
773 local_slots,
774 local_scope_base: self.env.scope_depth().saturating_sub(1),
775 local_scope_depth: 0,
776 });
777 }
778
779 pub(crate) fn child_vm(&self) -> Vm {
782 Vm {
783 stack: Vec::with_capacity(64),
784 env: self.env.clone(),
785 output: String::new(),
786 builtins: Arc::clone(&self.builtins),
787 async_builtins: Arc::clone(&self.async_builtins),
788 builtin_metadata: Arc::clone(&self.builtin_metadata),
789 builtins_by_id: Arc::clone(&self.builtins_by_id),
790 builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
791 iterators: Vec::new(),
792 frames: Vec::new(),
793 exception_handlers: Vec::new(),
794 spawned_tasks: BTreeMap::new(),
795 sync_runtime: self.sync_runtime.clone(),
796 shared_state_runtime: self.shared_state_runtime.clone(),
797 inline_cache_sets: Vec::new(),
798 inline_cache_set_by_chunk: HashMap::new(),
799 pool_registry: self.pool_registry.clone(),
800 wait_for_graph: self.wait_for_graph.clone(),
801 held_sync_guards: Vec::new(),
802 inherited_held_keys: Arc::new(Vec::new()),
803 task_scopes: Vec::new(),
804 task_counter: 0,
805 runtime_context_counter: self.runtime_context_counter,
806 runtime_context: self.runtime_context.clone(),
807 deadlines: self.deadlines.clone(),
808 breakpoints: BTreeMap::new(),
809 function_breakpoints: std::collections::BTreeSet::new(),
810 pending_function_bp: None,
811 step_mode: false,
812 step_frame_depth: 0,
813 stopped: false,
814 last_line: 0,
815 source_dir: self.source_dir.clone(),
816 imported_paths: Vec::new(),
817 deferred_cyclic_imports: Vec::new(),
818 module_cache: Arc::clone(&self.module_cache),
819 source_cache: Arc::clone(&self.source_cache),
820 source_file: self.source_file.clone(),
821 source_text: self.source_text.clone(),
822 coverage: crate::coverage::for_primary(self.source_file.as_deref()),
823 bridge: self.bridge.clone(),
824 denied_builtins: Arc::clone(&self.denied_builtins),
825 cancel_token: self.cancel_token.clone(),
826 interrupt_signal_token: self.interrupt_signal_token.clone(),
827 cancel_grace_instructions_remaining: None,
828 interrupt_handlers: Vec::new(),
829 next_interrupt_handle: 1,
830 pending_interrupt_signal: None,
831 interrupted: self.interrupted,
832 dispatching_interrupt: false,
833 interrupt_handler_deadline: None,
834 error_stack_trace: Vec::new(),
835 yield_sender: None,
836 project_root: self.project_root.clone(),
837 globals: Arc::clone(&self.globals),
838 debug_hook: None,
839 runtime_limits: self.runtime_limits,
840 }
841 }
842
843 pub(crate) fn child_vm_for_host(&self) -> Vm {
846 self.child_vm()
847 }
848
849 pub(crate) fn cancel_spawned_tasks(&mut self) {
853 for (_, task) in std::mem::take(&mut self.spawned_tasks) {
854 task.cancel_token
855 .store(true, std::sync::atomic::Ordering::SeqCst);
856 task.handle.abort();
857 }
858 }
859
860 pub fn set_source_dir(&mut self, dir: &std::path::Path) {
863 let dir = crate::stdlib::process::normalize_context_path(dir);
864 self.source_dir = Some(dir.clone());
865 crate::stdlib::set_thread_source_dir(&dir);
866 if self.project_root.is_none() {
868 self.project_root = crate::stdlib::process::find_project_root(&dir);
869 }
870 }
871
872 pub fn set_project_root(&mut self, root: &std::path::Path) {
875 self.project_root = Some(root.to_path_buf());
876 }
877
878 pub(crate) fn explicit_project_root(&self) -> Option<&std::path::Path> {
881 self.project_root.as_deref()
882 }
883
884 pub fn project_root(&self) -> Option<&std::path::Path> {
886 self.project_root.as_deref().or(self.source_dir.as_deref())
887 }
888
889 pub fn builtin_names(&self) -> Vec<String> {
891 let mut names: Vec<String> = self.builtins.keys().cloned().collect();
892 names.extend(self.async_builtins.keys().cloned());
893 names
894 }
895
896 pub fn builtin_metadata(&self) -> Vec<VmBuiltinMetadata> {
898 self.builtin_metadata.values().cloned().collect()
899 }
900
901 pub fn builtin_metadata_for(&self, name: &str) -> Option<&VmBuiltinMetadata> {
903 self.builtin_metadata.get(name)
904 }
905
906 pub fn set_global(&mut self, name: &str, value: VmValue) {
909 Arc::make_mut(&mut self.globals).insert(crate::value::intern_key(name), value);
910 }
911
912 pub fn global(&self, name: &str) -> Option<&VmValue> {
918 self.globals.get(name)
919 }
920
921 pub fn set_harness(&mut self, harness: crate::harness::Harness) {
927 self.set_global("harness", harness.into_vm_value());
928 }
929
930 pub fn output(&self) -> &str {
932 &self.output
933 }
934
935 pub fn take_output(&mut self) -> String {
939 std::mem::take(&mut self.output)
940 }
941
942 pub fn append_output(&mut self, text: &str) {
946 self.output.push_str(text);
947 }
948
949 pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
950 self.stack.pop().ok_or(VmError::StackUnderflow)
951 }
952
953 pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
954 self.stack.last().ok_or(VmError::StackUnderflow)
955 }
956
957 pub(crate) fn const_str(c: &Constant) -> Result<&str, VmError> {
958 match c {
959 Constant::String(s) => Ok(s.as_str()),
960 _ => Err(VmError::TypeError("expected string constant".into())),
961 }
962 }
963
964 pub(crate) fn release_sync_guards_for_current_scope(&mut self) {
965 let depth = self.env.scope_depth();
966 self.held_sync_guards
967 .retain(|guard| guard.env_scope_depth < depth);
968 self.cancel_task_scopes_where(|s| s.env_scope_depth >= depth);
971 }
972
973 pub(crate) fn release_sync_guards_after_unwind(
974 &mut self,
975 frame_depth: usize,
976 env_scope_depth: usize,
977 ) {
978 self.held_sync_guards.retain(|guard| {
979 guard.frame_depth <= frame_depth && guard.env_scope_depth <= env_scope_depth
980 });
981 self.cancel_task_scopes_where(|s| {
984 !(s.frame_depth <= frame_depth && s.env_scope_depth <= env_scope_depth)
985 });
986 }
987
988 pub(crate) fn release_sync_guards_for_frame(&mut self, frame_depth: usize) {
989 self.held_sync_guards
990 .retain(|guard| guard.frame_depth != frame_depth);
991 self.cancel_task_scopes_where(|s| s.frame_depth == frame_depth);
994 }
995
996 pub(crate) fn adopt_sync_permit_for_current_scope(
997 &mut self,
998 permit: crate::value::VmSyncPermitHandle,
999 ) {
1000 if permit.is_released()
1001 || self
1002 .held_sync_guards
1003 .iter()
1004 .any(|guard| guard._permit.same_lease(&permit))
1005 {
1006 return;
1007 }
1008 self.held_sync_guards
1009 .push(crate::synchronization::VmSyncHeldGuard {
1010 _permit: permit,
1011 frame_depth: self.frames.len(),
1012 env_scope_depth: self.env.scope_depth(),
1013 });
1014 }
1015
1016 pub(crate) fn deregister_task_from_scopes(&mut self, id: &str) {
1019 for scope in &mut self.task_scopes {
1020 scope.task_ids.retain(|t| t != id);
1021 }
1022 }
1023
1024 fn cancel_task_scopes_where<F: Fn(&TaskScope) -> bool>(&mut self, doomed: F) {
1027 let mut i = 0;
1028 while i < self.task_scopes.len() {
1029 if doomed(&self.task_scopes[i]) {
1030 let scope = self.task_scopes.remove(i);
1031 for id in &scope.task_ids {
1032 if let Some(task) = self.spawned_tasks.remove(id) {
1033 task.cancel_token
1034 .store(true, std::sync::atomic::Ordering::SeqCst);
1035 task.handle.abort();
1036 }
1037 }
1038 } else {
1039 i += 1;
1040 }
1041 }
1042 }
1043
1044 pub(crate) fn held_permits_for(&self, kind: &str, key: &str) -> u32 {
1048 let own: u32 = self
1049 .held_sync_guards
1050 .iter()
1051 .filter(|guard| {
1052 !guard._permit.is_released()
1053 && guard._permit.kind() == kind
1054 && guard._permit.key() == key
1055 })
1056 .map(|guard| guard._permit.permits())
1057 .sum();
1058 let inherited: u32 = self
1059 .inherited_held_keys
1060 .iter()
1061 .filter(|held| held.kind == kind && held.key == key)
1062 .map(|held| held.permits)
1063 .sum();
1064 own + inherited
1065 }
1066
1067 pub(crate) fn combined_held_keys(&self) -> Vec<crate::synchronization::VmSyncHeldKey> {
1070 let mut keys: Vec<crate::synchronization::VmSyncHeldKey> = self
1071 .held_sync_guards
1072 .iter()
1073 .filter_map(|guard| crate::synchronization::VmSyncHeldKey::from_permit(&guard._permit))
1074 .collect();
1075 keys.extend(self.inherited_held_keys.iter().cloned());
1076 keys
1077 }
1078
1079 pub(crate) fn child_vm_inline(&self) -> Vm {
1085 let mut child = self.child_vm();
1086 child.inherited_held_keys = Arc::new(self.combined_held_keys());
1087 child
1088 }
1089}
1090
1091impl Drop for Vm {
1092 fn drop(&mut self) {
1093 if let Some(coverage) = self.coverage.take() {
1094 crate::coverage::merge_into_global(coverage);
1095 }
1096 self.cancel_spawned_tasks();
1097 }
1098}
1099
1100impl Default for Vm {
1101 fn default() -> Self {
1102 Self::new()
1103 }
1104}
1105
1106#[cfg(test)]
1107mod tests {
1108
1109 use super::*;
1110
1111 fn baseline_with_stdlib(source: &str) -> VmBaseline {
1112 let mut vm = Vm::new();
1113 crate::register_vm_stdlib(&mut vm);
1114 vm.set_source_info("baseline_test.harn", source);
1115 vm.set_global(
1116 "stable_global",
1117 VmValue::String(arcstr::ArcStr::from("baseline")),
1118 );
1119 vm.baseline()
1120 }
1121
1122 #[test]
1123 fn vm_baseline_instantiates_clean_mutable_execution_state() {
1124 let baseline = baseline_with_stdlib("pipeline main() { __io_println(stable_global) }");
1125
1126 let mut dirty = baseline.instantiate();
1127 dirty.stack.push(VmValue::Int(42));
1128 dirty.output.push_str("dirty");
1129 dirty.task_counter = 9;
1130 dirty.runtime_context_counter = 7;
1131 dirty
1132 .error_stack_trace
1133 .push(("main".to_string(), 1, 1, None));
1134
1135 let clean = baseline.instantiate();
1136 assert!(clean.stack.is_empty());
1137 assert!(clean.output.is_empty());
1138 assert!(clean.frames.is_empty());
1139 assert!(clean.exception_handlers.is_empty());
1140 assert!(clean.spawned_tasks.is_empty());
1141 assert!(clean.held_sync_guards.is_empty());
1142 assert_eq!(clean.task_counter, 0);
1143 assert_eq!(clean.runtime_context_counter, 0);
1144 assert!(clean.deadlines.is_empty());
1145 assert!(clean.cancel_token.is_none());
1146 assert!(clean.interrupt_handlers.is_empty());
1147 assert!(clean.error_stack_trace.is_empty());
1148 assert!(clean.bridge.is_none());
1149 assert!(clean
1150 .globals
1151 .get("stable_global")
1152 .is_some_and(|value| value.display() == "baseline"));
1153 }
1154
1155 #[tokio::test]
1156 async fn inline_child_inherits_held_lock_keys_but_concurrent_child_does_not() {
1157 let mut parent = Vm::new();
1158 let permit = parent
1159 .sync_runtime
1160 .acquire("mutex", "v:test", 1, 1, None, None)
1161 .await
1162 .unwrap()
1163 .unwrap();
1164 parent
1165 .held_sync_guards
1166 .push(crate::synchronization::VmSyncHeldGuard {
1167 _permit: permit,
1168 frame_depth: 0,
1169 env_scope_depth: 0,
1170 });
1171 assert_eq!(parent.held_permits_for("mutex", "v:test"), 1);
1172
1173 let inline = parent.child_vm_inline();
1178 assert_eq!(inline.held_permits_for("mutex", "v:test"), 1);
1179 assert_eq!(
1180 inline.child_vm_inline().held_permits_for("mutex", "v:test"),
1181 1
1182 );
1183
1184 let concurrent = parent.child_vm();
1188 assert_eq!(concurrent.held_permits_for("mutex", "v:test"), 0);
1189 }
1190
1191 #[test]
1192 fn vm_reports_effective_runtime_limits() {
1193 let vm = Vm::new();
1194
1195 assert_eq!(vm.runtime_limits(), RuntimeLimits::default());
1196 assert_eq!(
1197 vm.runtime_limit_report().entries.len(),
1198 crate::RUNTIME_LIMIT_DESCRIPTIONS.len()
1199 );
1200 assert_eq!(vm.child_vm().runtime_limits(), vm.runtime_limits());
1201 assert_eq!(
1202 vm.baseline().instantiate().runtime_limits(),
1203 vm.runtime_limits()
1204 );
1205 }
1206
1207 #[tokio::test(flavor = "current_thread")]
1208 async fn vm_baseline_rebinds_shared_state_builtins_per_instance() {
1209 let local = tokio::task::LocalSet::new();
1210 local
1211 .run_until(async {
1212 let source = r#"
1213pipeline main() {
1214 const cell = shared_cell({scope: "task_group", key: "turn", initial: 0})
1215 __io_println(shared_get(cell))
1216 shared_set(cell, shared_get(cell) + 1)
1217}"#;
1218 let chunk = crate::compile_source(source).expect("compile");
1219 let baseline = baseline_with_stdlib(source);
1220
1221 let mut first = baseline.instantiate();
1222 first.execute(&chunk).await.expect("first execute");
1223 assert_eq!(first.output(), "0\n");
1224
1225 let mut second = baseline.instantiate();
1226 second.execute(&chunk).await.expect("second execute");
1227 assert_eq!(
1228 second.output(),
1229 "0\n",
1230 "shared state created by the first VM must not leak into the next baseline instance"
1231 );
1232 })
1233 .await;
1234 }
1235}