1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::path::PathBuf;
3use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::sync::{Arc, Mutex};
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::ModuleCache;
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: ModuleCache,
40}
41
42pub(crate) type LazyCallableResolution = Arc<ResolvedLazyCallable>;
43pub(crate) struct LazyCallableCacheSlot {
44 pub(crate) execution_guard: Option<Arc<harn_modules::package_execution::PackageExecutionGuard>>,
45 pub(crate) resolution: Arc<tokio::sync::OnceCell<LazyCallableResolution>>,
46}
47pub(crate) type LazyCallableModuleCache =
48 Arc<VmMutex<BTreeMap<PathBuf, Vec<LazyCallableCacheSlot>>>>;
49
50pub(crate) struct ScopeSpan(u64);
52
53impl ScopeSpan {
54 pub(crate) fn new(kind: crate::tracing::SpanKind, name: String) -> Self {
55 Self(crate::tracing::span_start(kind, name))
56 }
57}
58
59pub(crate) struct ExecutionDeadlineState {
64 origin: Instant,
65 deadline_offset: AtomicU64,
67 abandoned: AtomicBool,
71}
72
73impl ExecutionDeadlineState {
74 pub(crate) fn new(origin: Instant, deadline: Option<Instant>) -> Arc<Self> {
75 Arc::new(Self {
76 origin,
77 deadline_offset: AtomicU64::new(Self::encode(origin, deadline)),
78 abandoned: AtomicBool::new(false),
79 })
80 }
81
82 #[inline]
83 pub(crate) fn is_active(&self) -> bool {
84 self.deadline_offset.load(Ordering::Acquire) != 0
85 }
86
87 #[inline]
88 pub(crate) fn is_abandoned(&self) -> bool {
89 self.abandoned.load(Ordering::Acquire)
90 }
91
92 pub(crate) fn fork(&self) -> Arc<Self> {
93 let state = Self::new(self.origin, self.current());
94 state
95 .abandoned
96 .store(self.is_abandoned(), Ordering::Release);
97 state
98 }
99
100 pub(crate) fn current(&self) -> Option<Instant> {
101 let encoded = self.deadline_offset.load(Ordering::Acquire);
102 (encoded != 0)
103 .then(|| self.origin + std::time::Duration::from_nanos(encoded.saturating_sub(1)))
104 }
105
106 pub(crate) fn install(self: &Arc<Self>, deadline: Instant) -> ExecutionDeadlineGuard {
107 let previous = self.deadline_offset.load(Ordering::Acquire);
108 let requested = Self::encode(self.origin, Some(deadline));
109 let active = if previous == 0 {
110 requested
111 } else {
112 previous.min(requested)
113 };
114 self.deadline_offset.store(active, Ordering::Release);
115 ExecutionDeadlineGuard {
116 state: Arc::clone(self),
117 previous,
118 completed: false,
119 }
120 }
121
122 fn encode(origin: Instant, deadline: Option<Instant>) -> u64 {
123 deadline.map_or(0, |deadline| {
124 let nanos = deadline.saturating_duration_since(origin).as_nanos();
125 u64::try_from(nanos)
126 .unwrap_or(u64::MAX - 1)
127 .saturating_add(1)
128 })
129 }
130}
131
132pub(crate) struct ExecutionDeadlineGuard {
133 state: Arc<ExecutionDeadlineState>,
134 previous: u64,
135 completed: bool,
136}
137
138impl ExecutionDeadlineGuard {
139 pub(crate) fn complete(mut self) {
142 self.completed = true;
143 }
144}
145
146impl Drop for ExecutionDeadlineGuard {
147 fn drop(&mut self) {
148 self.state
149 .deadline_offset
150 .store(self.previous, Ordering::Release);
151 if !self.completed {
152 self.state.abandoned.store(true, Ordering::Release);
153 }
154 }
155}
156
157impl Drop for ScopeSpan {
158 fn drop(&mut self) {
159 crate::tracing::span_end(self.0);
160 }
161}
162
163#[derive(Clone)]
164pub(crate) struct LocalSlot {
165 pub(crate) value: VmValue,
166 pub(crate) initialized: bool,
167 pub(crate) synced: bool,
168}
169
170impl Drop for LocalSlot {
171 fn drop(&mut self) {
172 if crate::value::recursion::is_recursive_container(&self.value) {
180 crate::value::recursion::dismantle(std::mem::replace(&mut self.value, VmValue::Nil));
181 }
182 }
183}
184
185#[derive(Clone)]
186pub(crate) struct InterruptHandler {
187 pub(crate) handle: i64,
188 pub(crate) signals: Vec<String>,
189 pub(crate) once: bool,
190 pub(crate) graceful_timeout_ms: Option<u64>,
191 pub(crate) handler: VmValue,
192}
193
194pub(crate) struct CallFrame {
196 pub(crate) chunk: ChunkRef,
197 pub(crate) inline_cache_set: usize,
201 pub(crate) ip: usize,
202 pub(crate) stack_base: usize,
203 pub(crate) saved_env: VmEnv,
204 pub(crate) initial_env: Option<VmEnv>,
212 pub(crate) initial_local_slots: Option<Vec<LocalSlot>>,
213 pub(crate) saved_iterator_depth: usize,
215 pub(crate) fn_name: String,
217 pub(crate) argc: usize,
219 pub(crate) saved_source_dir: Option<std::path::PathBuf>,
222 pub(crate) module_functions: Option<ModuleFunctionRegistry>,
224 pub(crate) module_state: Option<crate::value::ModuleState>,
230 pub(crate) local_slots: Vec<LocalSlot>,
232 pub(crate) local_scope_base: usize,
234 pub(crate) local_scope_depth: usize,
236}
237
238pub(crate) struct InlineCacheSite {
239 pub(crate) cache_set: usize,
240 pub(crate) slot_count: usize,
241 pub(crate) slot: Option<usize>,
242}
243
244impl CallFrame {
245 #[inline]
246 pub(crate) fn inline_cache_site_for_previous_op(&self) -> InlineCacheSite {
247 let op_offset = self.ip.saturating_sub(1);
248 InlineCacheSite {
249 cache_set: self.inline_cache_set,
250 slot_count: self.chunk.inline_cache_slot_count(),
251 slot: self.chunk.inline_cache_slot(op_offset),
252 }
253 }
254}
255
256pub(crate) struct ExceptionHandler {
258 pub(crate) catch_ip: usize,
259 pub(crate) stack_depth: usize,
260 pub(crate) frame_depth: usize,
261 pub(crate) env_scope_depth: usize,
262 pub(crate) error_type: Option<crate::value::HarnStr>,
264}
265
266pub(crate) struct TaskScope {
269 pub(crate) task_ids: Vec<String>,
272 pub(crate) frame_depth: usize,
274 pub(crate) env_scope_depth: usize,
276}
277
278pub(crate) struct ProcessExitRequest {
282 code: Mutex<Option<i32>>,
283 requested: AtomicBool,
284}
285
286impl ProcessExitRequest {
287 fn new() -> Self {
288 Self {
289 code: Mutex::new(None),
290 requested: AtomicBool::new(false),
291 }
292 }
293
294 fn request(&self, code: i32) {
295 let mut recorded = self
296 .code
297 .lock()
298 .expect("process exit request lock poisoned");
299 if recorded.is_none() {
300 *recorded = Some(code);
301 self.requested.store(true, Ordering::Release);
302 }
303 }
304
305 fn code(&self) -> Option<i32> {
306 if !self.requested.load(Ordering::Acquire) {
307 return None;
308 }
309 *self
310 .code
311 .lock()
312 .expect("process exit request lock poisoned")
313 }
314}
315
316pub(crate) enum IterState {
318 Vec {
319 items: Arc<Vec<VmValue>>,
320 idx: usize,
321 },
322 Dict {
323 entries: Arc<crate::value::DictMap>,
324 keys: Vec<String>,
325 idx: usize,
326 },
327 Channel {
328 receiver: std::sync::Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
329 close: std::sync::Arc<crate::value::VmChannelCloseState>,
330 },
331 Generator {
332 gen: Arc<crate::value::VmGenerator>,
333 },
334 Stream {
335 stream: Arc<crate::value::VmStream>,
336 },
337 Range {
341 next: i64,
342 end: i64,
343 inclusive: bool,
344 done: bool,
345 },
346 VmIter {
347 handle: crate::vm::iter::VmIterHandle,
348 },
349}
350
351#[derive(Clone)]
352pub(crate) enum VmBuiltinDispatch {
353 Sync(VmBuiltinFn),
354 Async(VmAsyncBuiltinFn),
355}
356
357#[derive(Clone)]
358pub(crate) struct VmBuiltinEntry {
359 pub(crate) name: Arc<str>,
360 pub(crate) dispatch: VmBuiltinDispatch,
361}
362
363pub struct Vm {
365 pub(crate) stack: Vec<VmValue>,
366 pub(crate) env: VmEnv,
367 pub(crate) output: String,
368 pub(crate) builtins: Arc<BTreeMap<String, VmBuiltinFn>>,
369 pub(crate) async_builtins: Arc<BTreeMap<String, VmAsyncBuiltinFn>>,
370 pub(crate) builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
371 pub(crate) builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
374 pub(crate) builtin_id_collisions: Arc<HashSet<BuiltinId>>,
377 pub(crate) iterators: Vec<IterState>,
379 pub(crate) frames: Vec<CallFrame>,
381 pub(crate) exception_handlers: Vec<ExceptionHandler>,
383 pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
385 pub(crate) process_exit_request: Arc<ProcessExitRequest>,
387 pub(crate) sync_runtime: Arc<crate::synchronization::VmSyncRuntime>,
389 pub(crate) shared_state_runtime: Arc<crate::shared_state::VmSharedStateRuntime>,
391 pub(crate) inline_cache_sets: Vec<Vec<crate::chunk::InlineCacheEntry>>,
395 pub(crate) inline_cache_set_by_chunk: HashMap<u64, usize>,
396 pub(crate) pool_registry: Arc<crate::stdlib::pool::PoolRegistry>,
398 pub(crate) llm_mock_context: crate::llm::mock::LlmMockContext,
400 pub(crate) package_snapshot_registry: Arc<crate::stdlib::PackageSnapshotRegistry>,
404 pub(crate) wait_for_graph: Arc<crate::wait_for_graph::VmWaitForGraph>,
406 pub(crate) held_sync_guards: Vec<crate::synchronization::VmSyncHeldGuard>,
408 pub(crate) inherited_held_keys: Arc<Vec<crate::synchronization::VmSyncHeldKey>>,
416 pub(crate) task_scopes: Vec<TaskScope>,
422 pub(crate) task_counter: u64,
424 pub(crate) runtime_context_counter: u64,
426 pub(crate) runtime_context: crate::runtime_context::RuntimeContext,
428 pub(crate) deadlines: Vec<(Instant, usize)>,
430 pub(crate) execution_deadline: Arc<ExecutionDeadlineState>,
432 pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
437 pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
443 pub(crate) pending_function_bp: Option<String>,
448 pub(crate) step_mode: bool,
450 pub(crate) step_frame_depth: usize,
452 pub(crate) stopped: bool,
454 pub(crate) last_line: usize,
456 pub(crate) source_dir: Option<std::path::PathBuf>,
458 pub(crate) package_execution_guard:
460 Option<Arc<harn_modules::package_execution::PackageExecutionGuard>>,
461 pub(crate) imported_paths: Vec<std::path::PathBuf>,
463 pub(crate) deferred_cyclic_imports: Vec<super::modules::DeferredCyclicImport>,
467 pub(crate) module_cache: ModuleCache,
469 pub(crate) prepared_module_cache: crate::PreparedModuleCache,
472 pub(crate) module_phase_recorder: Option<super::ModulePhaseRecorder>,
474 pub(crate) lazy_callable_modules: LazyCallableModuleCache,
478 pub(crate) source_cache: Arc<BTreeMap<std::path::PathBuf, Arc<str>>>,
482 pub(crate) graph_link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
487 pub(crate) source_file: Option<String>,
489 pub(crate) source_text: Option<String>,
491 pub(crate) coverage: Option<crate::coverage::Coverage>,
494 pub(crate) bridge: Option<Arc<crate::bridge::HostBridge>>,
496 pub(crate) denied_builtins: Arc<HashSet<String>>,
498 pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
500 pub(crate) interrupt_signal_token: Option<std::sync::Arc<std::sync::Mutex<Option<String>>>>,
501 pub(crate) cancel_grace_instructions_remaining: Option<usize>,
506 pub(crate) interrupt_handlers: Vec<InterruptHandler>,
508 pub(crate) next_interrupt_handle: i64,
509 pub(crate) pending_interrupt_signal: Option<String>,
510 pub(crate) interrupted: bool,
511 pub(crate) dispatching_interrupt: bool,
512 pub(crate) interrupt_handler_deadline: Option<Instant>,
513 pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
515 pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<Result<VmValue, VmError>>>,
518 pub(crate) project_root: Option<std::path::PathBuf>,
521 pub(crate) globals: Arc<crate::value::DictMap>,
524 pub(crate) debug_hook: Option<parking_lot::Mutex<Box<DebugHook>>>,
526 pub(crate) runtime_limits: RuntimeLimits,
528}
529
530#[derive(Clone)]
538pub struct VmBaseline {
539 builtins: Arc<BTreeMap<String, VmBuiltinFn>>,
540 async_builtins: Arc<BTreeMap<String, VmAsyncBuiltinFn>>,
541 builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
542 builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
543 builtin_id_collisions: Arc<HashSet<BuiltinId>>,
544 source_dir: Option<std::path::PathBuf>,
545 source_file: Option<String>,
546 source_text: Option<String>,
547 project_root: Option<std::path::PathBuf>,
548 globals: Arc<crate::value::DictMap>,
549 denied_builtins: Arc<HashSet<String>>,
550 prepared_module_cache: crate::PreparedModuleCache,
551 graph_link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
554 runtime_limits: RuntimeLimits,
555}
556
557impl VmBaseline {
558 pub fn from_vm(vm: &Vm) -> Self {
559 Self {
560 builtins: Arc::clone(&vm.builtins),
561 async_builtins: Arc::clone(&vm.async_builtins),
562 builtin_metadata: Arc::clone(&vm.builtin_metadata),
563 builtins_by_id: Arc::clone(&vm.builtins_by_id),
564 builtin_id_collisions: Arc::clone(&vm.builtin_id_collisions),
565 source_dir: vm.source_dir.clone(),
566 source_file: vm.source_file.clone(),
567 source_text: vm.source_text.clone(),
568 project_root: vm.project_root.clone(),
569 globals: Arc::clone(&vm.globals),
570 denied_builtins: Arc::clone(&vm.denied_builtins),
571 prepared_module_cache: vm.prepared_module_cache.clone(),
572 graph_link_table: vm.graph_link_table.clone(),
573 runtime_limits: vm.runtime_limits,
574 }
575 }
576
577 pub fn instantiate(&self) -> Vm {
578 crate::initialize_runtime_assets();
579 let mut source_cache = BTreeMap::new();
580 if let (Some(file), Some(text)) = (&self.source_file, &self.source_text) {
581 source_cache.insert(std::path::PathBuf::from(file), Arc::from(text.as_str()));
582 }
583 if let Some(dir) = &self.source_dir {
584 crate::stdlib::set_thread_source_dir(dir);
585 }
586
587 let mut vm = Vm {
588 stack: Vec::with_capacity(256),
589 env: VmEnv::new(),
590 output: String::new(),
591 builtins: Arc::clone(&self.builtins),
592 async_builtins: Arc::clone(&self.async_builtins),
593 builtin_metadata: Arc::clone(&self.builtin_metadata),
594 builtins_by_id: Arc::clone(&self.builtins_by_id),
595 builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
596 iterators: Vec::new(),
597 frames: Vec::new(),
598 exception_handlers: Vec::new(),
599 spawned_tasks: BTreeMap::new(),
600 process_exit_request: Arc::new(ProcessExitRequest::new()),
601 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
602 shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
603 inline_cache_sets: Vec::new(),
604 inline_cache_set_by_chunk: HashMap::new(),
605 pool_registry: crate::stdlib::pool::new_pool_registry(),
606 llm_mock_context: crate::llm::mock::LlmMockContext::for_new_vm(),
607 package_snapshot_registry: Arc::new(Default::default()),
608 wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
609 held_sync_guards: Vec::new(),
610 inherited_held_keys: Arc::new(Vec::new()),
611 task_scopes: Vec::new(),
612 task_counter: 0,
613 runtime_context_counter: 0,
614 runtime_context: crate::runtime_context::RuntimeContext::root(),
615 deadlines: Vec::new(),
616 execution_deadline: super::execution::new_execution_deadline_state(None),
617 breakpoints: BTreeMap::new(),
618 function_breakpoints: std::collections::BTreeSet::new(),
619 pending_function_bp: None,
620 step_mode: false,
621 step_frame_depth: 0,
622 stopped: false,
623 last_line: 0,
624 source_dir: self.source_dir.clone(),
625 package_execution_guard: None,
626 imported_paths: Vec::new(),
627 deferred_cyclic_imports: Vec::new(),
628 module_cache: Arc::new(BTreeMap::new()),
629 prepared_module_cache: self.prepared_module_cache.clone(),
630 module_phase_recorder: None,
631 lazy_callable_modules: Arc::new(crate::value::VmMutex::new(BTreeMap::new())),
632 source_cache: Arc::new(source_cache),
633 graph_link_table: self.graph_link_table.clone(),
634 source_file: self.source_file.clone(),
635 source_text: self.source_text.clone(),
636 coverage: crate::coverage::for_primary(self.source_file.as_deref()),
637 bridge: None,
638 denied_builtins: Arc::clone(&self.denied_builtins),
639 cancel_token: None,
640 interrupt_signal_token: None,
641 cancel_grace_instructions_remaining: None,
642 interrupt_handlers: Vec::new(),
643 next_interrupt_handle: 1,
644 pending_interrupt_signal: None,
645 interrupted: false,
646 dispatching_interrupt: false,
647 interrupt_handler_deadline: None,
648 error_stack_trace: Vec::new(),
649 yield_sender: None,
650 project_root: self.project_root.clone(),
651 globals: Arc::clone(&self.globals),
652 debug_hook: None,
653 runtime_limits: self.runtime_limits,
654 };
655
656 crate::stdlib::rebind_execution_state_builtins(&mut vm);
657 vm
658 }
659}
660
661impl Vm {
662 pub(crate) fn ensure_execution_available(&self) -> Result<(), VmError> {
663 if self.execution_deadline.is_abandoned() {
664 return Err(VmError::AbandonedExecution);
665 }
666 Ok(())
667 }
668
669 pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
670 chunk
671 .local_slots
672 .iter()
673 .map(|_| LocalSlot {
674 value: VmValue::Nil,
675 initialized: false,
676 synced: false,
677 })
678 .collect()
679 }
680
681 pub(crate) fn bind_param_slots(
682 slots: &mut [LocalSlot],
683 func: &crate::chunk::CompiledFunction,
684 args: &[VmValue],
685 synced: bool,
686 ) {
687 Self::bind_param_slots_args(slots, func, &super::CallArgs::Slice(args), synced);
688 }
689
690 pub(crate) fn bind_param_slots_args(
691 slots: &mut [LocalSlot],
692 func: &crate::chunk::CompiledFunction,
693 args: &super::CallArgs<'_>,
694 synced: bool,
695 ) {
696 let param_count = func.params.len();
697 for (i, _param) in func.params.iter().enumerate() {
698 if i >= slots.len() {
699 break;
700 }
701 if func.has_rest_param && i == param_count - 1 {
702 let rest_args = args.to_vec_from(i);
703 slots[i].value = VmValue::List(std::sync::Arc::new(rest_args));
704 slots[i].initialized = true;
705 slots[i].synced = synced;
706 } else if let Some(arg) = args.get(i) {
707 slots[i].value = arg.clone();
708 slots[i].initialized = true;
709 slots[i].synced = synced;
710 }
711 }
712 }
713
714 pub(crate) fn visible_variables(&self) -> crate::value::DictMap {
715 let mut vars = self.env.all_variables();
716 let Some(frame) = self.frames.last() else {
717 return vars;
718 };
719 for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
720 if slot.initialized && info.scope_depth <= frame.local_scope_depth {
721 vars.insert(crate::value::intern_key(&info.name), slot.value.clone());
722 }
723 }
724 vars
725 }
726
727 pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
728 let frames = &mut self.frames;
729 let env = &mut self.env;
730 let Some(frame) = frames.last_mut() else {
731 return;
732 };
733 let local_scope_base = frame.local_scope_base;
734 let local_scope_depth = frame.local_scope_depth;
735 for (slot, info) in frame
736 .local_slots
737 .iter_mut()
738 .zip(frame.chunk.local_slots.iter())
739 {
740 if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
741 slot.synced = true;
742 let scope_idx = local_scope_base + info.scope_depth;
743 while env.scopes.len() <= scope_idx {
744 env.push_scope();
745 }
746 Arc::make_mut(&mut env.scopes[scope_idx].vars).insert(
750 info.name.clone(),
751 crate::value::Binding::Value {
752 value: slot.value.clone(),
753 mutable: info.mutable,
754 },
755 );
756 }
757 }
758 }
759
760 pub(crate) fn closure_call_env_for_current_frame(
761 &self,
762 closure: &crate::value::VmClosure,
763 ) -> VmEnv {
764 if closure.module_state().is_some() {
765 return closure.env.cloned_for_call();
766 }
767 let call_env = Self::closure_call_env(&self.env, closure);
768 if !closure.func.chunk.references_outer_names {
773 return call_env;
774 }
775 let mut call_env = call_env;
776 let Some(frame) = self.frames.last() else {
777 return call_env;
778 };
779 for (slot, info) in frame
780 .local_slots
781 .iter()
782 .zip(frame.chunk.local_slots.iter())
783 .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
784 {
785 if matches!(slot.value, VmValue::Closure(_)) && !call_env.contains(&info.name) {
786 let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
787 }
788 }
789 call_env
790 }
791
792 pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
793 let frame = self.frames.last()?;
794 let idx = self.active_local_slot_index(name)?;
795 frame.local_slots.get(idx).map(|slot| slot.value.clone())
796 }
797
798 pub(crate) fn active_local_slot_index(&self, name: &str) -> Option<usize> {
803 let frame = self.frames.last()?;
804 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
805 if info.name == name && info.scope_depth <= frame.local_scope_depth {
806 if let Some(slot) = frame.local_slots.get(idx) {
807 if slot.initialized {
808 return Some(idx);
809 }
810 }
811 }
812 }
813 None
814 }
815
816 pub(crate) fn assign_active_local_slot(
817 &mut self,
818 name: &str,
819 value: VmValue,
820 debug: bool,
821 ) -> Result<bool, VmError> {
822 let Some(frame) = self.frames.last_mut() else {
823 return Ok(false);
824 };
825 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
826 if info.name == name && info.scope_depth <= frame.local_scope_depth {
827 if !debug && !info.mutable {
828 return Err(VmError::ImmutableAssignment(name.to_string()));
829 }
830 if let Some(slot) = frame.local_slots.get_mut(idx) {
831 crate::value::recursion::dismantle(std::mem::replace(&mut slot.value, value));
832 slot.initialized = true;
833 slot.synced = false;
834 return Ok(true);
835 }
836 }
837 }
838 Ok(false)
839 }
840
841 pub fn new() -> Self {
842 crate::initialize_runtime_assets();
843 Self {
844 stack: Vec::with_capacity(256),
845 env: VmEnv::new(),
846 output: String::new(),
847 builtins: Arc::new(BTreeMap::new()),
848 async_builtins: Arc::new(BTreeMap::new()),
849 builtin_metadata: Arc::new(BTreeMap::new()),
850 builtins_by_id: Arc::new(HashMap::new()),
851 builtin_id_collisions: Arc::new(HashSet::new()),
852 iterators: Vec::new(),
853 frames: Vec::new(),
854 exception_handlers: Vec::new(),
855 spawned_tasks: BTreeMap::new(),
856 process_exit_request: Arc::new(ProcessExitRequest::new()),
857 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
858 shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
859 inline_cache_sets: Vec::new(),
860 inline_cache_set_by_chunk: HashMap::new(),
861 pool_registry: crate::stdlib::pool::new_pool_registry(),
862 llm_mock_context: crate::llm::mock::LlmMockContext::for_new_vm(),
863 package_snapshot_registry: Arc::new(Default::default()),
864 wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
865 held_sync_guards: Vec::new(),
866 inherited_held_keys: Arc::new(Vec::new()),
867 task_scopes: Vec::new(),
868 task_counter: 0,
869 runtime_context_counter: 0,
870 runtime_context: crate::runtime_context::RuntimeContext::root(),
871 deadlines: Vec::new(),
872 execution_deadline: super::execution::new_execution_deadline_state(None),
873 breakpoints: BTreeMap::new(),
874 function_breakpoints: std::collections::BTreeSet::new(),
875 pending_function_bp: None,
876 step_mode: false,
877 step_frame_depth: 0,
878 stopped: false,
879 last_line: 0,
880 source_dir: None,
881 package_execution_guard: None,
882 imported_paths: Vec::new(),
883 deferred_cyclic_imports: Vec::new(),
884 module_cache: Arc::new(BTreeMap::new()),
885 prepared_module_cache: crate::PreparedModuleCache::default(),
886 module_phase_recorder: None,
887 lazy_callable_modules: Arc::new(crate::value::VmMutex::new(BTreeMap::new())),
888 source_cache: Arc::new(BTreeMap::new()),
889 graph_link_table: None,
890 source_file: None,
891 source_text: None,
892 coverage: crate::coverage::for_primary(None),
893 bridge: None,
894 denied_builtins: Arc::new(HashSet::new()),
895 cancel_token: None,
896 interrupt_signal_token: None,
897 cancel_grace_instructions_remaining: None,
898 interrupt_handlers: Vec::new(),
899 next_interrupt_handle: 1,
900 pending_interrupt_signal: None,
901 interrupted: false,
902 dispatching_interrupt: false,
903 interrupt_handler_deadline: None,
904 error_stack_trace: Vec::new(),
905 yield_sender: None,
906 project_root: None,
907 globals: Arc::new(crate::value::DictMap::new()),
908 debug_hook: None,
909 runtime_limits: RuntimeLimits::default(),
910 }
911 }
912
913 pub fn baseline(&self) -> VmBaseline {
914 VmBaseline::from_vm(self)
915 }
916
917 pub fn set_prepared_module_cache(&mut self, cache: crate::PreparedModuleCache) {
920 self.prepared_module_cache = cache;
921 }
922
923 pub fn set_graph_link_table(
931 &mut self,
932 link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
933 ) {
934 self.graph_link_table = link_table;
935 }
936
937 pub fn runtime_limits(&self) -> RuntimeLimits {
939 self.runtime_limits
940 }
941
942 pub fn runtime_limit_report(&self) -> crate::RuntimeLimitsReport {
944 self.runtime_limits.report()
945 }
946
947 #[inline]
961 pub(crate) fn debugger_attached(&self) -> bool {
962 self.debug_hook.is_some()
963 || !self.breakpoints.is_empty()
964 || !self.function_breakpoints.is_empty()
965 }
966
967 pub fn set_bridge(&mut self, bridge: Arc<crate::bridge::HostBridge>) {
969 self.bridge = Some(bridge);
970 }
971
972 pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
975 self.denied_builtins = Arc::new(denied);
976 }
977
978 pub fn set_source_info(&mut self, file: &str, text: &str) {
980 self.source_file = Some(file.to_string());
981 self.source_text = Some(text.to_string());
982 if let Some(cov) = self.coverage.as_mut() {
983 cov.set_primary_file(file);
984 }
985 Arc::make_mut(&mut self.source_cache)
986 .insert(std::path::PathBuf::from(file), Arc::from(text));
987 }
988
989 pub fn start(&mut self, chunk: &Chunk) -> Result<(), VmError> {
991 self.ensure_execution_available()?;
992 let debugger = self.debugger_attached();
999 let initial_env = if debugger {
1000 Some(self.env.clone())
1001 } else {
1002 None
1003 };
1004 let initial_local_slots = if debugger {
1005 Some(Self::fresh_local_slots(chunk))
1006 } else {
1007 None
1008 };
1009 let chunk = Arc::new(chunk.clone());
1010 let local_slots = Self::fresh_local_slots(&chunk);
1011 let inline_cache_set = self.inline_cache_set_index_for_chunk(&chunk);
1012 self.frames.push(CallFrame {
1013 chunk,
1014 inline_cache_set,
1015 ip: 0,
1016 stack_base: self.stack.len(),
1017 saved_env: self.env.clone(),
1018 initial_env,
1019 initial_local_slots,
1020 saved_iterator_depth: self.iterators.len(),
1021 fn_name: String::new(),
1022 argc: 0,
1023 saved_source_dir: None,
1024 module_functions: None,
1025 module_state: None,
1026 local_slots,
1027 local_scope_base: self.env.scope_depth().saturating_sub(1),
1028 local_scope_depth: 0,
1029 });
1030 Ok(())
1031 }
1032
1033 pub(crate) fn child_vm(&self) -> Vm {
1036 Vm {
1037 stack: Vec::with_capacity(64),
1038 env: self.env.clone(),
1039 output: String::new(),
1040 builtins: Arc::clone(&self.builtins),
1041 async_builtins: Arc::clone(&self.async_builtins),
1042 builtin_metadata: Arc::clone(&self.builtin_metadata),
1043 builtins_by_id: Arc::clone(&self.builtins_by_id),
1044 builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
1045 iterators: Vec::new(),
1046 frames: Vec::new(),
1047 exception_handlers: Vec::new(),
1048 spawned_tasks: BTreeMap::new(),
1049 process_exit_request: Arc::clone(&self.process_exit_request),
1050 sync_runtime: self.sync_runtime.clone(),
1051 shared_state_runtime: self.shared_state_runtime.clone(),
1052 inline_cache_sets: Vec::new(),
1053 inline_cache_set_by_chunk: HashMap::new(),
1054 pool_registry: self.pool_registry.clone(),
1055 llm_mock_context: self.llm_mock_context.clone(),
1056 package_snapshot_registry: self.package_snapshot_registry.clone(),
1057 wait_for_graph: self.wait_for_graph.clone(),
1058 held_sync_guards: Vec::new(),
1059 inherited_held_keys: Arc::new(Vec::new()),
1060 task_scopes: Vec::new(),
1061 task_counter: 0,
1062 runtime_context_counter: self.runtime_context_counter,
1063 runtime_context: self.runtime_context.clone(),
1064 deadlines: self.deadlines.clone(),
1065 execution_deadline: self.execution_deadline.fork(),
1066 breakpoints: BTreeMap::new(),
1067 function_breakpoints: std::collections::BTreeSet::new(),
1068 pending_function_bp: None,
1069 step_mode: false,
1070 step_frame_depth: 0,
1071 stopped: false,
1072 last_line: 0,
1073 source_dir: self.source_dir.clone(),
1074 package_execution_guard: self.package_execution_guard.clone(),
1075 imported_paths: Vec::new(),
1076 deferred_cyclic_imports: Vec::new(),
1077 module_cache: Arc::clone(&self.module_cache),
1078 prepared_module_cache: self.prepared_module_cache.clone(),
1079 module_phase_recorder: self.module_phase_recorder.clone(),
1080 lazy_callable_modules: Arc::clone(&self.lazy_callable_modules),
1081 source_cache: Arc::clone(&self.source_cache),
1082 graph_link_table: self.graph_link_table.clone(),
1083 source_file: self.source_file.clone(),
1084 source_text: self.source_text.clone(),
1085 coverage: crate::coverage::for_primary(self.source_file.as_deref()),
1086 bridge: self.bridge.clone(),
1087 denied_builtins: Arc::clone(&self.denied_builtins),
1088 cancel_token: self.cancel_token.clone(),
1089 interrupt_signal_token: self.interrupt_signal_token.clone(),
1090 cancel_grace_instructions_remaining: None,
1091 interrupt_handlers: Vec::new(),
1092 next_interrupt_handle: 1,
1093 pending_interrupt_signal: None,
1094 interrupted: self.interrupted,
1095 dispatching_interrupt: false,
1096 interrupt_handler_deadline: None,
1097 error_stack_trace: Vec::new(),
1098 yield_sender: None,
1099 project_root: self.project_root.clone(),
1100 globals: Arc::clone(&self.globals),
1101 debug_hook: None,
1102 runtime_limits: self.runtime_limits,
1103 }
1104 }
1105
1106 pub(crate) fn child_vm_for_host(&self) -> Vm {
1109 self.child_vm()
1110 }
1111
1112 pub(crate) fn request_process_exit(&self, code: i32) {
1113 self.process_exit_request.request(code);
1114 }
1115
1116 pub(crate) fn requested_process_exit(&self) -> Option<i32> {
1117 self.process_exit_request.code()
1118 }
1119
1120 pub(crate) fn cancel_spawned_tasks(&mut self) {
1124 for (_, task) in std::mem::take(&mut self.spawned_tasks) {
1125 task.cancel_token
1126 .store(true, std::sync::atomic::Ordering::SeqCst);
1127 task.handle.abort();
1128 }
1129 }
1130
1131 pub fn set_source_dir(&mut self, dir: &std::path::Path) {
1134 let dir = crate::stdlib::process::normalize_context_path(dir);
1135 self.source_dir = Some(dir.clone());
1136 crate::stdlib::set_thread_source_dir(&dir);
1137 if self.project_root.is_none() {
1139 self.project_root = crate::stdlib::process::find_project_root(&dir);
1140 }
1141 }
1142
1143 pub fn set_project_root(&mut self, root: &std::path::Path) {
1146 self.project_root = Some(root.to_path_buf());
1147 }
1148
1149 pub(crate) fn explicit_project_root(&self) -> Option<&std::path::Path> {
1152 self.project_root.as_deref()
1153 }
1154
1155 pub fn project_root(&self) -> Option<&std::path::Path> {
1157 self.project_root.as_deref().or(self.source_dir.as_deref())
1158 }
1159
1160 pub fn builtin_names(&self) -> Vec<String> {
1162 let mut names: Vec<String> = self.builtins.keys().cloned().collect();
1163 names.extend(self.async_builtins.keys().cloned());
1164 names
1165 }
1166
1167 pub fn builtin_metadata(&self) -> Vec<VmBuiltinMetadata> {
1169 self.builtin_metadata.values().cloned().collect()
1170 }
1171
1172 pub fn builtin_metadata_for(&self, name: &str) -> Option<&VmBuiltinMetadata> {
1174 self.builtin_metadata.get(name)
1175 }
1176
1177 pub fn set_global(&mut self, name: &str, value: VmValue) {
1180 Arc::make_mut(&mut self.globals).insert(crate::value::intern_key(name), value);
1181 }
1182
1183 pub fn global(&self, name: &str) -> Option<&VmValue> {
1189 self.globals.get(name)
1190 }
1191
1192 pub fn set_harness(&mut self, harness: crate::harness::Harness) {
1198 self.set_global("harness", harness.into_vm_value());
1199 }
1200
1201 pub fn output(&self) -> &str {
1203 &self.output
1204 }
1205
1206 pub fn take_output(&mut self) -> String {
1210 std::mem::take(&mut self.output)
1211 }
1212
1213 pub fn append_output(&mut self, text: &str) {
1217 self.output.push_str(text);
1218 }
1219
1220 pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
1221 self.stack.pop().ok_or(VmError::StackUnderflow)
1222 }
1223
1224 pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
1225 self.stack.last().ok_or(VmError::StackUnderflow)
1226 }
1227
1228 pub(crate) fn const_str(c: &Constant) -> Result<&str, VmError> {
1229 match c {
1230 Constant::String(s) => Ok(s.as_str()),
1231 _ => Err(VmError::TypeError("expected string constant".into())),
1232 }
1233 }
1234
1235 pub(crate) fn release_sync_guards_for_current_scope(&mut self) {
1236 let depth = self.env.scope_depth();
1237 self.held_sync_guards
1238 .retain(|guard| guard.env_scope_depth < depth);
1239 self.cancel_task_scopes_where(|s| s.env_scope_depth >= depth);
1242 }
1243
1244 pub(crate) fn release_sync_guards_after_unwind(
1245 &mut self,
1246 frame_depth: usize,
1247 env_scope_depth: usize,
1248 ) {
1249 self.held_sync_guards.retain(|guard| {
1250 guard.frame_depth <= frame_depth && guard.env_scope_depth <= env_scope_depth
1251 });
1252 self.cancel_task_scopes_where(|s| {
1255 !(s.frame_depth <= frame_depth && s.env_scope_depth <= env_scope_depth)
1256 });
1257 }
1258
1259 pub(crate) fn release_sync_guards_for_frame(&mut self, frame_depth: usize) {
1260 self.held_sync_guards
1261 .retain(|guard| guard.frame_depth != frame_depth);
1262 self.cancel_task_scopes_where(|s| s.frame_depth == frame_depth);
1265 }
1266
1267 pub(crate) fn adopt_sync_permit_for_current_scope(
1268 &mut self,
1269 permit: crate::value::VmSyncPermitHandle,
1270 ) {
1271 if permit.is_released()
1272 || self
1273 .held_sync_guards
1274 .iter()
1275 .any(|guard| guard._permit.same_lease(&permit))
1276 {
1277 return;
1278 }
1279 self.held_sync_guards
1280 .push(crate::synchronization::VmSyncHeldGuard {
1281 _permit: permit,
1282 frame_depth: self.frames.len(),
1283 env_scope_depth: self.env.scope_depth(),
1284 });
1285 }
1286
1287 pub(crate) fn deregister_task_from_scopes(&mut self, id: &str) {
1290 for scope in &mut self.task_scopes {
1291 scope.task_ids.retain(|t| t != id);
1292 }
1293 }
1294
1295 fn cancel_task_scopes_where<F: Fn(&TaskScope) -> bool>(&mut self, doomed: F) {
1298 let mut i = 0;
1299 while i < self.task_scopes.len() {
1300 if doomed(&self.task_scopes[i]) {
1301 let scope = self.task_scopes.remove(i);
1302 for id in &scope.task_ids {
1303 if let Some(task) = self.spawned_tasks.remove(id) {
1304 task.cancel_token
1305 .store(true, std::sync::atomic::Ordering::SeqCst);
1306 task.handle.abort();
1307 }
1308 }
1309 } else {
1310 i += 1;
1311 }
1312 }
1313 }
1314
1315 pub(crate) fn held_permits_for(&self, kind: &str, key: &str) -> u32 {
1319 let own: u32 = self
1320 .held_sync_guards
1321 .iter()
1322 .filter(|guard| {
1323 !guard._permit.is_released()
1324 && guard._permit.kind() == kind
1325 && guard._permit.key() == key
1326 })
1327 .map(|guard| guard._permit.permits())
1328 .sum();
1329 let inherited: u32 = self
1330 .inherited_held_keys
1331 .iter()
1332 .filter(|held| held.kind == kind && held.key == key)
1333 .map(|held| held.permits)
1334 .sum();
1335 own + inherited
1336 }
1337
1338 pub(crate) fn combined_held_keys(&self) -> Vec<crate::synchronization::VmSyncHeldKey> {
1341 let mut keys: Vec<crate::synchronization::VmSyncHeldKey> = self
1342 .held_sync_guards
1343 .iter()
1344 .filter_map(|guard| crate::synchronization::VmSyncHeldKey::from_permit(&guard._permit))
1345 .collect();
1346 keys.extend(self.inherited_held_keys.iter().cloned());
1347 keys
1348 }
1349
1350 pub(crate) fn child_vm_inline(&self) -> Vm {
1356 let mut child = self.child_vm();
1357 child.inherited_held_keys = Arc::new(self.combined_held_keys());
1358 child
1359 }
1360}
1361
1362impl Drop for Vm {
1363 fn drop(&mut self) {
1364 if let Some(coverage) = self.coverage.take() {
1365 crate::coverage::merge_into_global(coverage);
1366 }
1367 self.cancel_spawned_tasks();
1368 }
1369}
1370
1371impl Default for Vm {
1372 fn default() -> Self {
1373 Self::new()
1374 }
1375}
1376
1377#[cfg(test)]
1378#[path = "state_tests.rs"]
1379mod tests;