1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::path::PathBuf;
3use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::sync::Arc;
5use std::time::Instant;
6
7use crate::chunk::{Chunk, ChunkRef, Constant};
8use crate::runtime_limits::RuntimeLimits;
9use crate::value::{
10 ModuleFunctionRegistry, VmAsyncBuiltinFn, VmBuiltinFn, VmClosure, VmEnv, VmError, VmMutex,
11 VmTaskHandle, VmValue,
12};
13use crate::BuiltinId;
14
15use super::debug::DebugHook;
16use super::modules::LoadedModule;
17use super::VmBuiltinMetadata;
18
19pub(crate) struct ResolvedLazyCallable {
33 pub(crate) exports: BTreeMap<String, Arc<VmClosure>>,
34 #[allow(dead_code)]
39 pub(crate) retained_module_graph: Arc<BTreeMap<PathBuf, LoadedModule>>,
40}
41
42pub(crate) type LazyCallableResolution = Arc<ResolvedLazyCallable>;
43pub(crate) type LazyCallableModuleCache =
44 Arc<VmMutex<BTreeMap<PathBuf, Arc<tokio::sync::OnceCell<LazyCallableResolution>>>>>;
45
46pub(crate) struct ScopeSpan(u64);
48
49impl ScopeSpan {
50 pub(crate) fn new(kind: crate::tracing::SpanKind, name: String) -> Self {
51 Self(crate::tracing::span_start(kind, name))
52 }
53}
54
55pub(crate) struct ExecutionDeadlineState {
60 origin: Instant,
61 deadline_offset: AtomicU64,
63 abandoned: AtomicBool,
67}
68
69impl ExecutionDeadlineState {
70 pub(crate) fn new(origin: Instant, deadline: Option<Instant>) -> Arc<Self> {
71 Arc::new(Self {
72 origin,
73 deadline_offset: AtomicU64::new(Self::encode(origin, deadline)),
74 abandoned: AtomicBool::new(false),
75 })
76 }
77
78 #[inline]
79 pub(crate) fn is_active(&self) -> bool {
80 self.deadline_offset.load(Ordering::Acquire) != 0
81 }
82
83 #[inline]
84 pub(crate) fn is_abandoned(&self) -> bool {
85 self.abandoned.load(Ordering::Acquire)
86 }
87
88 pub(crate) fn fork(&self) -> Arc<Self> {
89 let state = Self::new(self.origin, self.current());
90 state
91 .abandoned
92 .store(self.is_abandoned(), Ordering::Release);
93 state
94 }
95
96 pub(crate) fn current(&self) -> Option<Instant> {
97 let encoded = self.deadline_offset.load(Ordering::Acquire);
98 (encoded != 0)
99 .then(|| self.origin + std::time::Duration::from_nanos(encoded.saturating_sub(1)))
100 }
101
102 pub(crate) fn install(self: &Arc<Self>, deadline: Instant) -> ExecutionDeadlineGuard {
103 let previous = self.deadline_offset.load(Ordering::Acquire);
104 let requested = Self::encode(self.origin, Some(deadline));
105 let active = if previous == 0 {
106 requested
107 } else {
108 previous.min(requested)
109 };
110 self.deadline_offset.store(active, Ordering::Release);
111 ExecutionDeadlineGuard {
112 state: Arc::clone(self),
113 previous,
114 completed: false,
115 }
116 }
117
118 fn encode(origin: Instant, deadline: Option<Instant>) -> u64 {
119 deadline.map_or(0, |deadline| {
120 let nanos = deadline.saturating_duration_since(origin).as_nanos();
121 u64::try_from(nanos)
122 .unwrap_or(u64::MAX - 1)
123 .saturating_add(1)
124 })
125 }
126}
127
128pub(crate) struct ExecutionDeadlineGuard {
129 state: Arc<ExecutionDeadlineState>,
130 previous: u64,
131 completed: bool,
132}
133
134impl ExecutionDeadlineGuard {
135 pub(crate) fn complete(mut self) {
138 self.completed = true;
139 }
140}
141
142impl Drop for ExecutionDeadlineGuard {
143 fn drop(&mut self) {
144 self.state
145 .deadline_offset
146 .store(self.previous, Ordering::Release);
147 if !self.completed {
148 self.state.abandoned.store(true, Ordering::Release);
149 crate::orchestration::clear_pipeline_on_finish();
150 }
151 }
152}
153
154impl Drop for ScopeSpan {
155 fn drop(&mut self) {
156 crate::tracing::span_end(self.0);
157 }
158}
159
160#[derive(Clone)]
161pub(crate) struct LocalSlot {
162 pub(crate) value: VmValue,
163 pub(crate) initialized: bool,
164 pub(crate) synced: bool,
165}
166
167impl Drop for LocalSlot {
168 fn drop(&mut self) {
169 if crate::value::recursion::is_recursive_container(&self.value) {
177 crate::value::recursion::dismantle(std::mem::replace(&mut self.value, VmValue::Nil));
178 }
179 }
180}
181
182#[derive(Clone)]
183pub(crate) struct InterruptHandler {
184 pub(crate) handle: i64,
185 pub(crate) signals: Vec<String>,
186 pub(crate) once: bool,
187 pub(crate) graceful_timeout_ms: Option<u64>,
188 pub(crate) handler: VmValue,
189}
190
191pub(crate) struct CallFrame {
193 pub(crate) chunk: ChunkRef,
194 pub(crate) inline_cache_set: usize,
198 pub(crate) ip: usize,
199 pub(crate) stack_base: usize,
200 pub(crate) saved_env: VmEnv,
201 pub(crate) initial_env: Option<VmEnv>,
209 pub(crate) initial_local_slots: Option<Vec<LocalSlot>>,
210 pub(crate) saved_iterator_depth: usize,
212 pub(crate) fn_name: String,
214 pub(crate) argc: usize,
216 pub(crate) saved_source_dir: Option<std::path::PathBuf>,
219 pub(crate) module_functions: Option<ModuleFunctionRegistry>,
221 pub(crate) module_state: Option<crate::value::ModuleState>,
227 pub(crate) local_slots: Vec<LocalSlot>,
229 pub(crate) local_scope_base: usize,
231 pub(crate) local_scope_depth: usize,
233}
234
235pub(crate) struct InlineCacheSite {
236 pub(crate) cache_set: usize,
237 pub(crate) slot_count: usize,
238 pub(crate) slot: Option<usize>,
239}
240
241impl CallFrame {
242 #[inline]
243 pub(crate) fn inline_cache_site_for_previous_op(&self) -> InlineCacheSite {
244 let op_offset = self.ip.saturating_sub(1);
245 InlineCacheSite {
246 cache_set: self.inline_cache_set,
247 slot_count: self.chunk.inline_cache_slot_count(),
248 slot: self.chunk.inline_cache_slot(op_offset),
249 }
250 }
251}
252
253pub(crate) struct ExceptionHandler {
255 pub(crate) catch_ip: usize,
256 pub(crate) stack_depth: usize,
257 pub(crate) frame_depth: usize,
258 pub(crate) env_scope_depth: usize,
259 pub(crate) error_type: Option<crate::value::HarnStr>,
261}
262
263pub(crate) struct TaskScope {
266 pub(crate) task_ids: Vec<String>,
269 pub(crate) frame_depth: usize,
271 pub(crate) env_scope_depth: usize,
273}
274
275pub(crate) enum IterState {
277 Vec {
278 items: Arc<Vec<VmValue>>,
279 idx: usize,
280 },
281 Dict {
282 entries: Arc<crate::value::DictMap>,
283 keys: Vec<String>,
284 idx: usize,
285 },
286 Channel {
287 receiver: std::sync::Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
288 close: std::sync::Arc<crate::value::VmChannelCloseState>,
289 },
290 Generator {
291 gen: Arc<crate::value::VmGenerator>,
292 },
293 Stream {
294 stream: Arc<crate::value::VmStream>,
295 },
296 Range {
300 next: i64,
301 end: i64,
302 inclusive: bool,
303 done: bool,
304 },
305 VmIter {
306 handle: crate::vm::iter::VmIterHandle,
307 },
308}
309
310#[derive(Clone)]
311pub(crate) enum VmBuiltinDispatch {
312 Sync(VmBuiltinFn),
313 Async(VmAsyncBuiltinFn),
314}
315
316#[derive(Clone)]
317pub(crate) struct VmBuiltinEntry {
318 pub(crate) name: Arc<str>,
319 pub(crate) dispatch: VmBuiltinDispatch,
320}
321
322pub struct Vm {
324 pub(crate) stack: Vec<VmValue>,
325 pub(crate) env: VmEnv,
326 pub(crate) output: String,
327 pub(crate) builtins: Arc<BTreeMap<String, VmBuiltinFn>>,
328 pub(crate) async_builtins: Arc<BTreeMap<String, VmAsyncBuiltinFn>>,
329 pub(crate) builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
330 pub(crate) builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
333 pub(crate) builtin_id_collisions: Arc<HashSet<BuiltinId>>,
336 pub(crate) iterators: Vec<IterState>,
338 pub(crate) frames: Vec<CallFrame>,
340 pub(crate) exception_handlers: Vec<ExceptionHandler>,
342 pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
344 pub(crate) sync_runtime: Arc<crate::synchronization::VmSyncRuntime>,
346 pub(crate) shared_state_runtime: Arc<crate::shared_state::VmSharedStateRuntime>,
348 pub(crate) inline_cache_sets: Vec<Vec<crate::chunk::InlineCacheEntry>>,
352 pub(crate) inline_cache_set_by_chunk: HashMap<u64, usize>,
353 pub(crate) pool_registry: Arc<crate::stdlib::pool::PoolRegistry>,
355 pub(crate) wait_for_graph: Arc<crate::wait_for_graph::VmWaitForGraph>,
357 pub(crate) held_sync_guards: Vec<crate::synchronization::VmSyncHeldGuard>,
359 pub(crate) inherited_held_keys: Arc<Vec<crate::synchronization::VmSyncHeldKey>>,
367 pub(crate) task_scopes: Vec<TaskScope>,
373 pub(crate) task_counter: u64,
375 pub(crate) runtime_context_counter: u64,
377 pub(crate) runtime_context: crate::runtime_context::RuntimeContext,
379 pub(crate) deadlines: Vec<(Instant, usize)>,
381 pub(crate) execution_deadline: Arc<ExecutionDeadlineState>,
383 pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
388 pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
394 pub(crate) pending_function_bp: Option<String>,
399 pub(crate) step_mode: bool,
401 pub(crate) step_frame_depth: usize,
403 pub(crate) stopped: bool,
405 pub(crate) last_line: usize,
407 pub(crate) source_dir: Option<std::path::PathBuf>,
409 pub(crate) imported_paths: Vec<std::path::PathBuf>,
411 pub(crate) deferred_cyclic_imports: Vec<super::modules::DeferredCyclicImport>,
415 pub(crate) module_cache: Arc<BTreeMap<std::path::PathBuf, LoadedModule>>,
417 pub(crate) prepared_module_cache: crate::PreparedModuleCache,
420 pub(crate) lazy_callable_modules: LazyCallableModuleCache,
424 pub(crate) source_cache: Arc<BTreeMap<std::path::PathBuf, String>>,
426 pub(crate) source_file: Option<String>,
428 pub(crate) source_text: Option<String>,
430 pub(crate) coverage: Option<crate::coverage::Coverage>,
433 pub(crate) bridge: Option<Arc<crate::bridge::HostBridge>>,
435 pub(crate) denied_builtins: Arc<HashSet<String>>,
437 pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
439 pub(crate) interrupt_signal_token: Option<std::sync::Arc<std::sync::Mutex<Option<String>>>>,
440 pub(crate) cancel_grace_instructions_remaining: Option<usize>,
445 pub(crate) interrupt_handlers: Vec<InterruptHandler>,
447 pub(crate) next_interrupt_handle: i64,
448 pub(crate) pending_interrupt_signal: Option<String>,
449 pub(crate) interrupted: bool,
450 pub(crate) dispatching_interrupt: bool,
451 pub(crate) interrupt_handler_deadline: Option<Instant>,
452 pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
454 pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<Result<VmValue, VmError>>>,
457 pub(crate) project_root: Option<std::path::PathBuf>,
460 pub(crate) globals: Arc<crate::value::DictMap>,
463 pub(crate) debug_hook: Option<parking_lot::Mutex<Box<DebugHook>>>,
465 pub(crate) runtime_limits: RuntimeLimits,
467}
468
469#[derive(Clone)]
477pub struct VmBaseline {
478 builtins: Arc<BTreeMap<String, VmBuiltinFn>>,
479 async_builtins: Arc<BTreeMap<String, VmAsyncBuiltinFn>>,
480 builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
481 builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
482 builtin_id_collisions: Arc<HashSet<BuiltinId>>,
483 source_dir: Option<std::path::PathBuf>,
484 source_file: Option<String>,
485 source_text: Option<String>,
486 project_root: Option<std::path::PathBuf>,
487 globals: Arc<crate::value::DictMap>,
488 denied_builtins: Arc<HashSet<String>>,
489 prepared_module_cache: crate::PreparedModuleCache,
490 runtime_limits: RuntimeLimits,
491}
492
493impl VmBaseline {
494 pub fn from_vm(vm: &Vm) -> Self {
495 Self {
496 builtins: Arc::clone(&vm.builtins),
497 async_builtins: Arc::clone(&vm.async_builtins),
498 builtin_metadata: Arc::clone(&vm.builtin_metadata),
499 builtins_by_id: Arc::clone(&vm.builtins_by_id),
500 builtin_id_collisions: Arc::clone(&vm.builtin_id_collisions),
501 source_dir: vm.source_dir.clone(),
502 source_file: vm.source_file.clone(),
503 source_text: vm.source_text.clone(),
504 project_root: vm.project_root.clone(),
505 globals: Arc::clone(&vm.globals),
506 denied_builtins: Arc::clone(&vm.denied_builtins),
507 prepared_module_cache: vm.prepared_module_cache.clone(),
508 runtime_limits: vm.runtime_limits,
509 }
510 }
511
512 pub fn instantiate(&self) -> Vm {
513 let mut source_cache = BTreeMap::new();
514 if let (Some(file), Some(text)) = (&self.source_file, &self.source_text) {
515 source_cache.insert(std::path::PathBuf::from(file), text.clone());
516 }
517 if let Some(dir) = &self.source_dir {
518 crate::stdlib::set_thread_source_dir(dir);
519 }
520
521 let mut vm = Vm {
522 stack: Vec::with_capacity(256),
523 env: VmEnv::new(),
524 output: String::new(),
525 builtins: Arc::clone(&self.builtins),
526 async_builtins: Arc::clone(&self.async_builtins),
527 builtin_metadata: Arc::clone(&self.builtin_metadata),
528 builtins_by_id: Arc::clone(&self.builtins_by_id),
529 builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
530 iterators: Vec::new(),
531 frames: Vec::new(),
532 exception_handlers: Vec::new(),
533 spawned_tasks: BTreeMap::new(),
534 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
535 shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
536 inline_cache_sets: Vec::new(),
537 inline_cache_set_by_chunk: HashMap::new(),
538 pool_registry: crate::stdlib::pool::new_pool_registry(),
539 wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
540 held_sync_guards: Vec::new(),
541 inherited_held_keys: Arc::new(Vec::new()),
542 task_scopes: Vec::new(),
543 task_counter: 0,
544 runtime_context_counter: 0,
545 runtime_context: crate::runtime_context::RuntimeContext::root(),
546 deadlines: Vec::new(),
547 execution_deadline: super::execution::new_execution_deadline_state(None),
548 breakpoints: BTreeMap::new(),
549 function_breakpoints: std::collections::BTreeSet::new(),
550 pending_function_bp: None,
551 step_mode: false,
552 step_frame_depth: 0,
553 stopped: false,
554 last_line: 0,
555 source_dir: self.source_dir.clone(),
556 imported_paths: Vec::new(),
557 deferred_cyclic_imports: Vec::new(),
558 module_cache: Arc::new(BTreeMap::new()),
559 prepared_module_cache: self.prepared_module_cache.clone(),
560 lazy_callable_modules: Arc::new(crate::value::VmMutex::new(BTreeMap::new())),
561 source_cache: Arc::new(source_cache),
562 source_file: self.source_file.clone(),
563 source_text: self.source_text.clone(),
564 coverage: crate::coverage::for_primary(self.source_file.as_deref()),
565 bridge: None,
566 denied_builtins: Arc::clone(&self.denied_builtins),
567 cancel_token: None,
568 interrupt_signal_token: None,
569 cancel_grace_instructions_remaining: None,
570 interrupt_handlers: Vec::new(),
571 next_interrupt_handle: 1,
572 pending_interrupt_signal: None,
573 interrupted: false,
574 dispatching_interrupt: false,
575 interrupt_handler_deadline: None,
576 error_stack_trace: Vec::new(),
577 yield_sender: None,
578 project_root: self.project_root.clone(),
579 globals: Arc::clone(&self.globals),
580 debug_hook: None,
581 runtime_limits: self.runtime_limits,
582 };
583
584 crate::stdlib::rebind_execution_state_builtins(&mut vm);
585 vm
586 }
587}
588
589impl Vm {
590 pub(crate) fn ensure_execution_available(&self) -> Result<(), VmError> {
591 if self.execution_deadline.is_abandoned() {
592 return Err(VmError::AbandonedExecution);
593 }
594 Ok(())
595 }
596
597 pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
598 chunk
599 .local_slots
600 .iter()
601 .map(|_| LocalSlot {
602 value: VmValue::Nil,
603 initialized: false,
604 synced: false,
605 })
606 .collect()
607 }
608
609 pub(crate) fn bind_param_slots(
610 slots: &mut [LocalSlot],
611 func: &crate::chunk::CompiledFunction,
612 args: &[VmValue],
613 synced: bool,
614 ) {
615 Self::bind_param_slots_args(slots, func, &super::CallArgs::Slice(args), synced);
616 }
617
618 pub(crate) fn bind_param_slots_args(
619 slots: &mut [LocalSlot],
620 func: &crate::chunk::CompiledFunction,
621 args: &super::CallArgs<'_>,
622 synced: bool,
623 ) {
624 let param_count = func.params.len();
625 for (i, _param) in func.params.iter().enumerate() {
626 if i >= slots.len() {
627 break;
628 }
629 if func.has_rest_param && i == param_count - 1 {
630 let rest_args = args.to_vec_from(i);
631 slots[i].value = VmValue::List(std::sync::Arc::new(rest_args));
632 slots[i].initialized = true;
633 slots[i].synced = synced;
634 } else if let Some(arg) = args.get(i) {
635 slots[i].value = arg.clone();
636 slots[i].initialized = true;
637 slots[i].synced = synced;
638 }
639 }
640 }
641
642 pub(crate) fn visible_variables(&self) -> crate::value::DictMap {
643 let mut vars = self.env.all_variables();
644 let Some(frame) = self.frames.last() else {
645 return vars;
646 };
647 for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
648 if slot.initialized && info.scope_depth <= frame.local_scope_depth {
649 vars.insert(crate::value::intern_key(&info.name), slot.value.clone());
650 }
651 }
652 vars
653 }
654
655 pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
656 let frames = &mut self.frames;
657 let env = &mut self.env;
658 let Some(frame) = frames.last_mut() else {
659 return;
660 };
661 let local_scope_base = frame.local_scope_base;
662 let local_scope_depth = frame.local_scope_depth;
663 for (slot, info) in frame
664 .local_slots
665 .iter_mut()
666 .zip(frame.chunk.local_slots.iter())
667 {
668 if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
669 slot.synced = true;
670 let scope_idx = local_scope_base + info.scope_depth;
671 while env.scopes.len() <= scope_idx {
672 env.push_scope();
673 }
674 Arc::make_mut(&mut env.scopes[scope_idx].vars).insert(
678 info.name.clone(),
679 crate::value::Binding::Value {
680 value: slot.value.clone(),
681 mutable: info.mutable,
682 },
683 );
684 }
685 }
686 }
687
688 pub(crate) fn closure_call_env_for_current_frame(
689 &self,
690 closure: &crate::value::VmClosure,
691 ) -> VmEnv {
692 if closure.module_state().is_some() {
693 return closure.env.cloned_for_call();
694 }
695 let call_env = Self::closure_call_env(&self.env, closure);
696 if !closure.func.chunk.references_outer_names {
701 return call_env;
702 }
703 let mut call_env = call_env;
704 let Some(frame) = self.frames.last() else {
705 return call_env;
706 };
707 for (slot, info) in frame
708 .local_slots
709 .iter()
710 .zip(frame.chunk.local_slots.iter())
711 .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
712 {
713 if matches!(slot.value, VmValue::Closure(_)) && !call_env.contains(&info.name) {
714 let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
715 }
716 }
717 call_env
718 }
719
720 pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
721 let frame = self.frames.last()?;
722 let idx = self.active_local_slot_index(name)?;
723 frame.local_slots.get(idx).map(|slot| slot.value.clone())
724 }
725
726 pub(crate) fn active_local_slot_index(&self, name: &str) -> Option<usize> {
731 let frame = self.frames.last()?;
732 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
733 if info.name == name && info.scope_depth <= frame.local_scope_depth {
734 if let Some(slot) = frame.local_slots.get(idx) {
735 if slot.initialized {
736 return Some(idx);
737 }
738 }
739 }
740 }
741 None
742 }
743
744 pub(crate) fn assign_active_local_slot(
745 &mut self,
746 name: &str,
747 value: VmValue,
748 debug: bool,
749 ) -> Result<bool, VmError> {
750 let Some(frame) = self.frames.last_mut() else {
751 return Ok(false);
752 };
753 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
754 if info.name == name && info.scope_depth <= frame.local_scope_depth {
755 if !debug && !info.mutable {
756 return Err(VmError::ImmutableAssignment(name.to_string()));
757 }
758 if let Some(slot) = frame.local_slots.get_mut(idx) {
759 crate::value::recursion::dismantle(std::mem::replace(&mut slot.value, value));
760 slot.initialized = true;
761 slot.synced = false;
762 return Ok(true);
763 }
764 }
765 }
766 Ok(false)
767 }
768
769 pub fn new() -> Self {
770 Self {
771 stack: Vec::with_capacity(256),
772 env: VmEnv::new(),
773 output: String::new(),
774 builtins: Arc::new(BTreeMap::new()),
775 async_builtins: Arc::new(BTreeMap::new()),
776 builtin_metadata: Arc::new(BTreeMap::new()),
777 builtins_by_id: Arc::new(HashMap::new()),
778 builtin_id_collisions: Arc::new(HashSet::new()),
779 iterators: Vec::new(),
780 frames: Vec::new(),
781 exception_handlers: Vec::new(),
782 spawned_tasks: BTreeMap::new(),
783 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
784 shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
785 inline_cache_sets: Vec::new(),
786 inline_cache_set_by_chunk: HashMap::new(),
787 pool_registry: crate::stdlib::pool::new_pool_registry(),
788 wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
789 held_sync_guards: Vec::new(),
790 inherited_held_keys: Arc::new(Vec::new()),
791 task_scopes: Vec::new(),
792 task_counter: 0,
793 runtime_context_counter: 0,
794 runtime_context: crate::runtime_context::RuntimeContext::root(),
795 deadlines: Vec::new(),
796 execution_deadline: super::execution::new_execution_deadline_state(None),
797 breakpoints: BTreeMap::new(),
798 function_breakpoints: std::collections::BTreeSet::new(),
799 pending_function_bp: None,
800 step_mode: false,
801 step_frame_depth: 0,
802 stopped: false,
803 last_line: 0,
804 source_dir: None,
805 imported_paths: Vec::new(),
806 deferred_cyclic_imports: Vec::new(),
807 module_cache: Arc::new(BTreeMap::new()),
808 prepared_module_cache: crate::PreparedModuleCache::default(),
809 lazy_callable_modules: Arc::new(crate::value::VmMutex::new(BTreeMap::new())),
810 source_cache: Arc::new(BTreeMap::new()),
811 source_file: None,
812 source_text: None,
813 coverage: crate::coverage::for_primary(None),
814 bridge: None,
815 denied_builtins: Arc::new(HashSet::new()),
816 cancel_token: None,
817 interrupt_signal_token: None,
818 cancel_grace_instructions_remaining: None,
819 interrupt_handlers: Vec::new(),
820 next_interrupt_handle: 1,
821 pending_interrupt_signal: None,
822 interrupted: false,
823 dispatching_interrupt: false,
824 interrupt_handler_deadline: None,
825 error_stack_trace: Vec::new(),
826 yield_sender: None,
827 project_root: None,
828 globals: Arc::new(crate::value::DictMap::new()),
829 debug_hook: None,
830 runtime_limits: RuntimeLimits::default(),
831 }
832 }
833
834 pub fn baseline(&self) -> VmBaseline {
835 VmBaseline::from_vm(self)
836 }
837
838 pub fn set_prepared_module_cache(&mut self, cache: crate::PreparedModuleCache) {
841 self.prepared_module_cache = cache;
842 }
843
844 pub fn runtime_limits(&self) -> RuntimeLimits {
846 self.runtime_limits
847 }
848
849 pub fn runtime_limit_report(&self) -> crate::RuntimeLimitsReport {
851 self.runtime_limits.report()
852 }
853
854 #[inline]
868 pub(crate) fn debugger_attached(&self) -> bool {
869 self.debug_hook.is_some()
870 || !self.breakpoints.is_empty()
871 || !self.function_breakpoints.is_empty()
872 }
873
874 pub fn set_bridge(&mut self, bridge: Arc<crate::bridge::HostBridge>) {
876 self.bridge = Some(bridge);
877 }
878
879 pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
882 self.denied_builtins = Arc::new(denied);
883 }
884
885 pub fn set_source_info(&mut self, file: &str, text: &str) {
887 self.source_file = Some(file.to_string());
888 self.source_text = Some(text.to_string());
889 if let Some(cov) = self.coverage.as_mut() {
890 cov.set_primary_file(file);
891 }
892 Arc::make_mut(&mut self.source_cache)
893 .insert(std::path::PathBuf::from(file), text.to_string());
894 }
895
896 pub fn start(&mut self, chunk: &Chunk) -> Result<(), VmError> {
898 self.ensure_execution_available()?;
899 let debugger = self.debugger_attached();
906 let initial_env = if debugger {
907 Some(self.env.clone())
908 } else {
909 None
910 };
911 let initial_local_slots = if debugger {
912 Some(Self::fresh_local_slots(chunk))
913 } else {
914 None
915 };
916 let chunk = Arc::new(chunk.clone());
917 let local_slots = Self::fresh_local_slots(&chunk);
918 let inline_cache_set = self.inline_cache_set_index_for_chunk(&chunk);
919 self.frames.push(CallFrame {
920 chunk,
921 inline_cache_set,
922 ip: 0,
923 stack_base: self.stack.len(),
924 saved_env: self.env.clone(),
925 initial_env,
926 initial_local_slots,
927 saved_iterator_depth: self.iterators.len(),
928 fn_name: String::new(),
929 argc: 0,
930 saved_source_dir: None,
931 module_functions: None,
932 module_state: None,
933 local_slots,
934 local_scope_base: self.env.scope_depth().saturating_sub(1),
935 local_scope_depth: 0,
936 });
937 Ok(())
938 }
939
940 pub(crate) fn child_vm(&self) -> Vm {
943 Vm {
944 stack: Vec::with_capacity(64),
945 env: self.env.clone(),
946 output: String::new(),
947 builtins: Arc::clone(&self.builtins),
948 async_builtins: Arc::clone(&self.async_builtins),
949 builtin_metadata: Arc::clone(&self.builtin_metadata),
950 builtins_by_id: Arc::clone(&self.builtins_by_id),
951 builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
952 iterators: Vec::new(),
953 frames: Vec::new(),
954 exception_handlers: Vec::new(),
955 spawned_tasks: BTreeMap::new(),
956 sync_runtime: self.sync_runtime.clone(),
957 shared_state_runtime: self.shared_state_runtime.clone(),
958 inline_cache_sets: Vec::new(),
959 inline_cache_set_by_chunk: HashMap::new(),
960 pool_registry: self.pool_registry.clone(),
961 wait_for_graph: self.wait_for_graph.clone(),
962 held_sync_guards: Vec::new(),
963 inherited_held_keys: Arc::new(Vec::new()),
964 task_scopes: Vec::new(),
965 task_counter: 0,
966 runtime_context_counter: self.runtime_context_counter,
967 runtime_context: self.runtime_context.clone(),
968 deadlines: self.deadlines.clone(),
969 execution_deadline: self.execution_deadline.fork(),
970 breakpoints: BTreeMap::new(),
971 function_breakpoints: std::collections::BTreeSet::new(),
972 pending_function_bp: None,
973 step_mode: false,
974 step_frame_depth: 0,
975 stopped: false,
976 last_line: 0,
977 source_dir: self.source_dir.clone(),
978 imported_paths: Vec::new(),
979 deferred_cyclic_imports: Vec::new(),
980 module_cache: Arc::clone(&self.module_cache),
981 prepared_module_cache: self.prepared_module_cache.clone(),
982 lazy_callable_modules: Arc::clone(&self.lazy_callable_modules),
983 source_cache: Arc::clone(&self.source_cache),
984 source_file: self.source_file.clone(),
985 source_text: self.source_text.clone(),
986 coverage: crate::coverage::for_primary(self.source_file.as_deref()),
987 bridge: self.bridge.clone(),
988 denied_builtins: Arc::clone(&self.denied_builtins),
989 cancel_token: self.cancel_token.clone(),
990 interrupt_signal_token: self.interrupt_signal_token.clone(),
991 cancel_grace_instructions_remaining: None,
992 interrupt_handlers: Vec::new(),
993 next_interrupt_handle: 1,
994 pending_interrupt_signal: None,
995 interrupted: self.interrupted,
996 dispatching_interrupt: false,
997 interrupt_handler_deadline: None,
998 error_stack_trace: Vec::new(),
999 yield_sender: None,
1000 project_root: self.project_root.clone(),
1001 globals: Arc::clone(&self.globals),
1002 debug_hook: None,
1003 runtime_limits: self.runtime_limits,
1004 }
1005 }
1006
1007 pub(crate) fn child_vm_for_host(&self) -> Vm {
1010 self.child_vm()
1011 }
1012
1013 pub(crate) fn cancel_spawned_tasks(&mut self) {
1017 for (_, task) in std::mem::take(&mut self.spawned_tasks) {
1018 task.cancel_token
1019 .store(true, std::sync::atomic::Ordering::SeqCst);
1020 task.handle.abort();
1021 }
1022 }
1023
1024 pub fn set_source_dir(&mut self, dir: &std::path::Path) {
1027 let dir = crate::stdlib::process::normalize_context_path(dir);
1028 self.source_dir = Some(dir.clone());
1029 crate::stdlib::set_thread_source_dir(&dir);
1030 if self.project_root.is_none() {
1032 self.project_root = crate::stdlib::process::find_project_root(&dir);
1033 }
1034 }
1035
1036 pub fn set_project_root(&mut self, root: &std::path::Path) {
1039 self.project_root = Some(root.to_path_buf());
1040 }
1041
1042 pub(crate) fn explicit_project_root(&self) -> Option<&std::path::Path> {
1045 self.project_root.as_deref()
1046 }
1047
1048 pub fn project_root(&self) -> Option<&std::path::Path> {
1050 self.project_root.as_deref().or(self.source_dir.as_deref())
1051 }
1052
1053 pub fn builtin_names(&self) -> Vec<String> {
1055 let mut names: Vec<String> = self.builtins.keys().cloned().collect();
1056 names.extend(self.async_builtins.keys().cloned());
1057 names
1058 }
1059
1060 pub fn builtin_metadata(&self) -> Vec<VmBuiltinMetadata> {
1062 self.builtin_metadata.values().cloned().collect()
1063 }
1064
1065 pub fn builtin_metadata_for(&self, name: &str) -> Option<&VmBuiltinMetadata> {
1067 self.builtin_metadata.get(name)
1068 }
1069
1070 pub fn set_global(&mut self, name: &str, value: VmValue) {
1073 Arc::make_mut(&mut self.globals).insert(crate::value::intern_key(name), value);
1074 }
1075
1076 pub fn global(&self, name: &str) -> Option<&VmValue> {
1082 self.globals.get(name)
1083 }
1084
1085 pub fn set_harness(&mut self, harness: crate::harness::Harness) {
1091 self.set_global("harness", harness.into_vm_value());
1092 }
1093
1094 pub fn output(&self) -> &str {
1096 &self.output
1097 }
1098
1099 pub fn take_output(&mut self) -> String {
1103 std::mem::take(&mut self.output)
1104 }
1105
1106 pub fn append_output(&mut self, text: &str) {
1110 self.output.push_str(text);
1111 }
1112
1113 pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
1114 self.stack.pop().ok_or(VmError::StackUnderflow)
1115 }
1116
1117 pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
1118 self.stack.last().ok_or(VmError::StackUnderflow)
1119 }
1120
1121 pub(crate) fn const_str(c: &Constant) -> Result<&str, VmError> {
1122 match c {
1123 Constant::String(s) => Ok(s.as_str()),
1124 _ => Err(VmError::TypeError("expected string constant".into())),
1125 }
1126 }
1127
1128 pub(crate) fn release_sync_guards_for_current_scope(&mut self) {
1129 let depth = self.env.scope_depth();
1130 self.held_sync_guards
1131 .retain(|guard| guard.env_scope_depth < depth);
1132 self.cancel_task_scopes_where(|s| s.env_scope_depth >= depth);
1135 }
1136
1137 pub(crate) fn release_sync_guards_after_unwind(
1138 &mut self,
1139 frame_depth: usize,
1140 env_scope_depth: usize,
1141 ) {
1142 self.held_sync_guards.retain(|guard| {
1143 guard.frame_depth <= frame_depth && guard.env_scope_depth <= env_scope_depth
1144 });
1145 self.cancel_task_scopes_where(|s| {
1148 !(s.frame_depth <= frame_depth && s.env_scope_depth <= env_scope_depth)
1149 });
1150 }
1151
1152 pub(crate) fn release_sync_guards_for_frame(&mut self, frame_depth: usize) {
1153 self.held_sync_guards
1154 .retain(|guard| guard.frame_depth != frame_depth);
1155 self.cancel_task_scopes_where(|s| s.frame_depth == frame_depth);
1158 }
1159
1160 pub(crate) fn adopt_sync_permit_for_current_scope(
1161 &mut self,
1162 permit: crate::value::VmSyncPermitHandle,
1163 ) {
1164 if permit.is_released()
1165 || self
1166 .held_sync_guards
1167 .iter()
1168 .any(|guard| guard._permit.same_lease(&permit))
1169 {
1170 return;
1171 }
1172 self.held_sync_guards
1173 .push(crate::synchronization::VmSyncHeldGuard {
1174 _permit: permit,
1175 frame_depth: self.frames.len(),
1176 env_scope_depth: self.env.scope_depth(),
1177 });
1178 }
1179
1180 pub(crate) fn deregister_task_from_scopes(&mut self, id: &str) {
1183 for scope in &mut self.task_scopes {
1184 scope.task_ids.retain(|t| t != id);
1185 }
1186 }
1187
1188 fn cancel_task_scopes_where<F: Fn(&TaskScope) -> bool>(&mut self, doomed: F) {
1191 let mut i = 0;
1192 while i < self.task_scopes.len() {
1193 if doomed(&self.task_scopes[i]) {
1194 let scope = self.task_scopes.remove(i);
1195 for id in &scope.task_ids {
1196 if let Some(task) = self.spawned_tasks.remove(id) {
1197 task.cancel_token
1198 .store(true, std::sync::atomic::Ordering::SeqCst);
1199 task.handle.abort();
1200 }
1201 }
1202 } else {
1203 i += 1;
1204 }
1205 }
1206 }
1207
1208 pub(crate) fn held_permits_for(&self, kind: &str, key: &str) -> u32 {
1212 let own: u32 = self
1213 .held_sync_guards
1214 .iter()
1215 .filter(|guard| {
1216 !guard._permit.is_released()
1217 && guard._permit.kind() == kind
1218 && guard._permit.key() == key
1219 })
1220 .map(|guard| guard._permit.permits())
1221 .sum();
1222 let inherited: u32 = self
1223 .inherited_held_keys
1224 .iter()
1225 .filter(|held| held.kind == kind && held.key == key)
1226 .map(|held| held.permits)
1227 .sum();
1228 own + inherited
1229 }
1230
1231 pub(crate) fn combined_held_keys(&self) -> Vec<crate::synchronization::VmSyncHeldKey> {
1234 let mut keys: Vec<crate::synchronization::VmSyncHeldKey> = self
1235 .held_sync_guards
1236 .iter()
1237 .filter_map(|guard| crate::synchronization::VmSyncHeldKey::from_permit(&guard._permit))
1238 .collect();
1239 keys.extend(self.inherited_held_keys.iter().cloned());
1240 keys
1241 }
1242
1243 pub(crate) fn child_vm_inline(&self) -> Vm {
1249 let mut child = self.child_vm();
1250 child.inherited_held_keys = Arc::new(self.combined_held_keys());
1251 child
1252 }
1253}
1254
1255impl Drop for Vm {
1256 fn drop(&mut self) {
1257 if let Some(coverage) = self.coverage.take() {
1258 crate::coverage::merge_into_global(coverage);
1259 }
1260 self.cancel_spawned_tasks();
1261 }
1262}
1263
1264impl Default for Vm {
1265 fn default() -> Self {
1266 Self::new()
1267 }
1268}
1269
1270#[cfg(test)]
1271mod tests {
1272
1273 use super::*;
1274
1275 fn baseline_with_stdlib(source: &str) -> VmBaseline {
1276 let mut vm = Vm::new();
1277 crate::register_vm_stdlib(&mut vm);
1278 vm.set_source_info("baseline_test.harn", source);
1279 vm.set_global(
1280 "stable_global",
1281 VmValue::String(arcstr::ArcStr::from("baseline")),
1282 );
1283 vm.baseline()
1284 }
1285
1286 #[test]
1287 fn vm_baseline_instantiates_clean_mutable_execution_state() {
1288 let baseline = baseline_with_stdlib("pipeline main() { __io_println(stable_global) }");
1289
1290 let mut dirty = baseline.instantiate();
1291 dirty.stack.push(VmValue::Int(42));
1292 dirty.output.push_str("dirty");
1293 dirty.task_counter = 9;
1294 dirty.runtime_context_counter = 7;
1295 dirty
1296 .error_stack_trace
1297 .push(("main".to_string(), 1, 1, None));
1298
1299 let clean = baseline.instantiate();
1300 assert!(clean.stack.is_empty());
1301 assert!(clean.output.is_empty());
1302 assert!(clean.frames.is_empty());
1303 assert!(clean.exception_handlers.is_empty());
1304 assert!(clean.spawned_tasks.is_empty());
1305 assert!(clean.held_sync_guards.is_empty());
1306 assert_eq!(clean.task_counter, 0);
1307 assert_eq!(clean.runtime_context_counter, 0);
1308 assert!(clean.deadlines.is_empty());
1309 assert!(clean.cancel_token.is_none());
1310 assert!(clean.interrupt_handlers.is_empty());
1311 assert!(clean.error_stack_trace.is_empty());
1312 assert!(clean.bridge.is_none());
1313 assert!(clean
1314 .globals
1315 .get("stable_global")
1316 .is_some_and(|value| value.display() == "baseline"));
1317 }
1318
1319 #[tokio::test]
1320 async fn inline_child_inherits_held_lock_keys_but_concurrent_child_does_not() {
1321 let mut parent = Vm::new();
1322 let permit = parent
1323 .sync_runtime
1324 .acquire("mutex", "v:test", 1, 1, None, None)
1325 .await
1326 .unwrap()
1327 .unwrap();
1328 parent
1329 .held_sync_guards
1330 .push(crate::synchronization::VmSyncHeldGuard {
1331 _permit: permit,
1332 frame_depth: 0,
1333 env_scope_depth: 0,
1334 });
1335 assert_eq!(parent.held_permits_for("mutex", "v:test"), 1);
1336
1337 let inline = parent.child_vm_inline();
1342 assert_eq!(inline.held_permits_for("mutex", "v:test"), 1);
1343 assert_eq!(
1344 inline.child_vm_inline().held_permits_for("mutex", "v:test"),
1345 1
1346 );
1347
1348 let concurrent = parent.child_vm();
1352 assert_eq!(concurrent.held_permits_for("mutex", "v:test"), 0);
1353 }
1354
1355 #[test]
1356 fn vm_reports_effective_runtime_limits() {
1357 let vm = Vm::new();
1358
1359 assert_eq!(vm.runtime_limits(), RuntimeLimits::default());
1360 assert_eq!(
1361 vm.runtime_limit_report().entries.len(),
1362 crate::RUNTIME_LIMIT_DESCRIPTIONS.len()
1363 );
1364 assert_eq!(vm.child_vm().runtime_limits(), vm.runtime_limits());
1365 assert_eq!(
1366 vm.baseline().instantiate().runtime_limits(),
1367 vm.runtime_limits()
1368 );
1369 }
1370
1371 #[tokio::test(flavor = "current_thread")]
1372 async fn vm_baseline_rebinds_shared_state_builtins_per_instance() {
1373 let local = tokio::task::LocalSet::new();
1374 local
1375 .run_until(async {
1376 let source = r#"
1377pipeline main() {
1378 const cell = shared_cell({scope: "task_group", key: "turn", initial: 0})
1379 __io_println(shared_get(cell))
1380 shared_set(cell, shared_get(cell) + 1)
1381}"#;
1382 let chunk = crate::compile_source(source).expect("compile");
1383 let baseline = baseline_with_stdlib(source);
1384
1385 let mut first = baseline.instantiate();
1386 first.execute(&chunk).await.expect("first execute");
1387 assert_eq!(first.output(), "0\n");
1388
1389 let mut second = baseline.instantiate();
1390 second.execute(&chunk).await.expect("second execute");
1391 assert_eq!(
1392 second.output(),
1393 "0\n",
1394 "shared state created by the first VM must not leak into the next baseline instance"
1395 );
1396 })
1397 .await;
1398 }
1399}