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) capability_methods:
374 Arc<BTreeMap<(harn_builtin_meta::CapabilityId, String), VmBuiltinDispatch>>,
375 pub(crate) builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
376 pub(crate) builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
379 pub(crate) builtin_id_collisions: Arc<HashSet<BuiltinId>>,
382 pub(crate) iterators: Vec<IterState>,
384 pub(crate) frames: Vec<CallFrame>,
386 pub(crate) exception_handlers: Vec<ExceptionHandler>,
388 pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
390 pub(crate) process_exit_request: Arc<ProcessExitRequest>,
392 pub(crate) sync_runtime: Arc<crate::synchronization::VmSyncRuntime>,
394 pub(crate) shared_state_runtime: Arc<crate::shared_state::VmSharedStateRuntime>,
396 pub(crate) inline_cache_sets: Vec<Vec<crate::chunk::InlineCacheEntry>>,
400 pub(crate) inline_cache_set_by_chunk: HashMap<u64, usize>,
401 pub(crate) pool_registry: Arc<crate::stdlib::pool::PoolRegistry>,
403 pub(crate) llm_mock_context: crate::llm::mock::LlmMockContext,
405 pub(crate) package_snapshot_registry: Arc<crate::stdlib::PackageSnapshotRegistry>,
409 pub(crate) wait_for_graph: Arc<crate::wait_for_graph::VmWaitForGraph>,
411 pub(crate) held_sync_guards: Vec<crate::synchronization::VmSyncHeldGuard>,
413 pub(crate) inherited_held_keys: Arc<Vec<crate::synchronization::VmSyncHeldKey>>,
421 pub(crate) task_scopes: Vec<TaskScope>,
427 pub(crate) task_counter: u64,
429 pub(crate) runtime_context_counter: u64,
431 pub(crate) runtime_context: crate::runtime_context::RuntimeContext,
433 pub(crate) deadlines: Vec<(Instant, usize)>,
435 pub(crate) execution_deadline: Arc<ExecutionDeadlineState>,
437 pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
442 pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
448 pub(crate) pending_function_bp: Option<String>,
453 pub(crate) step_mode: bool,
455 pub(crate) step_frame_depth: usize,
457 pub(crate) stopped: bool,
459 pub(crate) last_line: usize,
461 pub(crate) source_dir: Option<std::path::PathBuf>,
463 pub(crate) package_execution_guard:
465 Option<Arc<harn_modules::package_execution::PackageExecutionGuard>>,
466 pub(crate) imported_paths: Vec<std::path::PathBuf>,
468 pub(crate) deferred_cyclic_imports: Vec<super::modules::DeferredCyclicImport>,
472 pub(crate) module_cache: ModuleCache,
474 pub(crate) prepared_module_cache: crate::PreparedModuleCache,
477 pub(crate) module_phase_recorder: Option<super::ModulePhaseRecorder>,
479 pub(crate) lazy_callable_modules: LazyCallableModuleCache,
483 pub(crate) source_cache: Arc<BTreeMap<std::path::PathBuf, Arc<str>>>,
487 pub(crate) graph_link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
492 pub(crate) source_file: Option<String>,
494 pub(crate) source_text: Option<String>,
496 pub(crate) coverage: Option<crate::coverage::Coverage>,
499 pub(crate) bridge: Option<Arc<crate::bridge::HostBridge>>,
501 pub(crate) denied_builtins: Arc<HashSet<String>>,
503 pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
505 pub(crate) interrupt_signal_token: Option<std::sync::Arc<std::sync::Mutex<Option<String>>>>,
506 pub(crate) cancel_grace_instructions_remaining: Option<usize>,
511 pub(crate) interrupt_handlers: Vec<InterruptHandler>,
513 pub(crate) next_interrupt_handle: i64,
514 pub(crate) pending_interrupt_signal: Option<String>,
515 pub(crate) interrupted: bool,
516 pub(crate) dispatching_interrupt: bool,
517 pub(crate) interrupt_handler_deadline: Option<Instant>,
518 pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
520 pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<Result<VmValue, VmError>>>,
523 pub(crate) project_root: Option<std::path::PathBuf>,
526 pub(crate) globals: Arc<crate::value::DictMap>,
529 pub(crate) root_harness: Option<VmValue>,
534 pub(crate) executed_effects:
538 Arc<Mutex<std::collections::BTreeSet<crate::orchestration::EffectRecord>>>,
539 pub(crate) debug_hook: Option<parking_lot::Mutex<Box<DebugHook>>>,
541 pub(crate) runtime_limits: RuntimeLimits,
543}
544
545#[derive(Clone)]
553pub struct VmBaseline {
554 builtins: Arc<BTreeMap<String, VmBuiltinFn>>,
555 async_builtins: Arc<BTreeMap<String, VmAsyncBuiltinFn>>,
556 capability_methods: Arc<BTreeMap<(harn_builtin_meta::CapabilityId, String), VmBuiltinDispatch>>,
557 builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
558 builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
559 builtin_id_collisions: Arc<HashSet<BuiltinId>>,
560 source_dir: Option<std::path::PathBuf>,
561 source_file: Option<String>,
562 source_text: Option<String>,
563 project_root: Option<std::path::PathBuf>,
564 globals: Arc<crate::value::DictMap>,
565 root_harness: Option<VmValue>,
566 denied_builtins: Arc<HashSet<String>>,
567 prepared_module_cache: crate::PreparedModuleCache,
568 graph_link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
571 runtime_limits: RuntimeLimits,
572}
573
574impl VmBaseline {
575 pub fn from_vm(vm: &Vm) -> Self {
576 Self {
577 builtins: Arc::clone(&vm.builtins),
578 async_builtins: Arc::clone(&vm.async_builtins),
579 capability_methods: Arc::clone(&vm.capability_methods),
580 builtin_metadata: Arc::clone(&vm.builtin_metadata),
581 builtins_by_id: Arc::clone(&vm.builtins_by_id),
582 builtin_id_collisions: Arc::clone(&vm.builtin_id_collisions),
583 source_dir: vm.source_dir.clone(),
584 source_file: vm.source_file.clone(),
585 source_text: vm.source_text.clone(),
586 project_root: vm.project_root.clone(),
587 globals: Arc::clone(&vm.globals),
588 root_harness: vm.root_harness.clone(),
589 denied_builtins: Arc::clone(&vm.denied_builtins),
590 prepared_module_cache: vm.prepared_module_cache.clone(),
591 graph_link_table: vm.graph_link_table.clone(),
592 runtime_limits: vm.runtime_limits,
593 }
594 }
595
596 pub fn instantiate(&self) -> Vm {
597 crate::initialize_runtime_assets();
598 let mut source_cache = BTreeMap::new();
599 if let (Some(file), Some(text)) = (&self.source_file, &self.source_text) {
600 source_cache.insert(std::path::PathBuf::from(file), Arc::from(text.as_str()));
601 }
602 if let Some(dir) = &self.source_dir {
603 crate::stdlib::set_thread_source_dir(dir);
604 }
605
606 let mut vm = Vm {
607 stack: Vec::with_capacity(256),
608 env: VmEnv::new(),
609 output: String::new(),
610 builtins: Arc::clone(&self.builtins),
611 async_builtins: Arc::clone(&self.async_builtins),
612 capability_methods: Arc::clone(&self.capability_methods),
613 builtin_metadata: Arc::clone(&self.builtin_metadata),
614 builtins_by_id: Arc::clone(&self.builtins_by_id),
615 builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
616 iterators: Vec::new(),
617 frames: Vec::new(),
618 exception_handlers: Vec::new(),
619 spawned_tasks: BTreeMap::new(),
620 process_exit_request: Arc::new(ProcessExitRequest::new()),
621 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
622 shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
623 inline_cache_sets: Vec::new(),
624 inline_cache_set_by_chunk: HashMap::new(),
625 pool_registry: crate::stdlib::pool::new_pool_registry(),
626 llm_mock_context: crate::llm::mock::LlmMockContext::for_new_vm(),
627 package_snapshot_registry: Arc::new(Default::default()),
628 wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
629 held_sync_guards: Vec::new(),
630 inherited_held_keys: Arc::new(Vec::new()),
631 task_scopes: Vec::new(),
632 task_counter: 0,
633 runtime_context_counter: 0,
634 runtime_context: crate::runtime_context::RuntimeContext::root(),
635 deadlines: Vec::new(),
636 execution_deadline: super::execution::new_execution_deadline_state(None),
637 breakpoints: BTreeMap::new(),
638 function_breakpoints: std::collections::BTreeSet::new(),
639 pending_function_bp: None,
640 step_mode: false,
641 step_frame_depth: 0,
642 stopped: false,
643 last_line: 0,
644 source_dir: self.source_dir.clone(),
645 package_execution_guard: None,
646 imported_paths: Vec::new(),
647 deferred_cyclic_imports: Vec::new(),
648 module_cache: Arc::new(BTreeMap::new()),
649 prepared_module_cache: self.prepared_module_cache.clone(),
650 module_phase_recorder: None,
651 lazy_callable_modules: Arc::new(crate::value::VmMutex::new(BTreeMap::new())),
652 source_cache: Arc::new(source_cache),
653 graph_link_table: self.graph_link_table.clone(),
654 source_file: self.source_file.clone(),
655 source_text: self.source_text.clone(),
656 coverage: crate::coverage::for_primary(self.source_file.as_deref()),
657 bridge: None,
658 denied_builtins: Arc::clone(&self.denied_builtins),
659 cancel_token: None,
660 interrupt_signal_token: None,
661 cancel_grace_instructions_remaining: None,
662 interrupt_handlers: Vec::new(),
663 next_interrupt_handle: 1,
664 pending_interrupt_signal: None,
665 interrupted: false,
666 dispatching_interrupt: false,
667 interrupt_handler_deadline: None,
668 error_stack_trace: Vec::new(),
669 yield_sender: None,
670 project_root: self.project_root.clone(),
671 globals: Arc::clone(&self.globals),
672 root_harness: self.root_harness.clone(),
673 executed_effects: Arc::new(Mutex::new(Default::default())),
674 debug_hook: None,
675 runtime_limits: self.runtime_limits,
676 };
677
678 crate::stdlib::rebind_execution_state_builtins(&mut vm);
679 vm
680 }
681}
682
683impl Vm {
684 pub(crate) fn ensure_execution_available(&self) -> Result<(), VmError> {
685 if self.execution_deadline.is_abandoned() {
686 return Err(VmError::AbandonedExecution);
687 }
688 Ok(())
689 }
690
691 pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
692 chunk
693 .local_slots
694 .iter()
695 .map(|_| LocalSlot {
696 value: VmValue::Nil,
697 initialized: false,
698 synced: false,
699 })
700 .collect()
701 }
702
703 pub(crate) fn bind_param_slots(
704 slots: &mut [LocalSlot],
705 func: &crate::chunk::CompiledFunction,
706 args: &[VmValue],
707 synced: bool,
708 ) {
709 Self::bind_param_slots_args(slots, func, &super::CallArgs::Slice(args), synced);
710 }
711
712 pub(crate) fn bind_param_slots_args(
713 slots: &mut [LocalSlot],
714 func: &crate::chunk::CompiledFunction,
715 args: &super::CallArgs<'_>,
716 synced: bool,
717 ) {
718 let param_count = func.params.len();
719 for (i, _param) in func.params.iter().enumerate() {
720 if i >= slots.len() {
721 break;
722 }
723 if func.has_rest_param && i == param_count - 1 {
724 let rest_args = args.to_vec_from(i);
725 slots[i].value = VmValue::List(std::sync::Arc::new(rest_args));
726 slots[i].initialized = true;
727 slots[i].synced = synced;
728 } else if let Some(arg) = args.get(i) {
729 slots[i].value = arg.clone();
730 slots[i].initialized = true;
731 slots[i].synced = synced;
732 }
733 }
734 }
735
736 pub(crate) fn visible_variables(&self) -> crate::value::DictMap {
737 let mut vars = self.env.all_variables();
738 let Some(frame) = self.frames.last() else {
739 return vars;
740 };
741 for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
742 if slot.initialized && info.scope_depth <= frame.local_scope_depth {
743 vars.insert(crate::value::intern_key(&info.name), slot.value.clone());
744 }
745 }
746 vars
747 }
748
749 pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
750 let frames = &mut self.frames;
751 let env = &mut self.env;
752 let Some(frame) = frames.last_mut() else {
753 return;
754 };
755 let local_scope_base = frame.local_scope_base;
756 let local_scope_depth = frame.local_scope_depth;
757 for (slot, info) in frame
758 .local_slots
759 .iter_mut()
760 .zip(frame.chunk.local_slots.iter())
761 {
762 if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
763 slot.synced = true;
764 let scope_idx = local_scope_base + info.scope_depth;
765 while env.scopes.len() <= scope_idx {
766 env.push_scope();
767 }
768 Arc::make_mut(&mut env.scopes[scope_idx].vars).insert(
772 info.name.clone(),
773 crate::value::Binding::Value {
774 value: slot.value.clone(),
775 mutable: info.mutable,
776 },
777 );
778 }
779 }
780 }
781
782 pub(crate) fn closure_call_env_for_current_frame(
783 &self,
784 closure: &crate::value::VmClosure,
785 ) -> VmEnv {
786 if closure.module_state().is_some() {
787 return closure.env.cloned_for_call();
788 }
789 let call_env = Self::closure_call_env(&self.env, closure);
790 if !closure.func.chunk.references_outer_names {
795 return call_env;
796 }
797 let mut call_env = call_env;
798 let Some(frame) = self.frames.last() else {
799 return call_env;
800 };
801 for (slot, info) in frame
802 .local_slots
803 .iter()
804 .zip(frame.chunk.local_slots.iter())
805 .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
806 {
807 if matches!(slot.value, VmValue::Closure(_)) && !call_env.contains(&info.name) {
808 let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
809 }
810 }
811 call_env
812 }
813
814 pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
815 let frame = self.frames.last()?;
816 let idx = self.active_local_slot_index(name)?;
817 frame.local_slots.get(idx).map(|slot| slot.value.clone())
818 }
819
820 pub(crate) fn active_local_slot_index(&self, name: &str) -> Option<usize> {
825 let frame = self.frames.last()?;
826 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
827 if info.name == name && info.scope_depth <= frame.local_scope_depth {
828 if let Some(slot) = frame.local_slots.get(idx) {
829 if slot.initialized {
830 return Some(idx);
831 }
832 }
833 }
834 }
835 None
836 }
837
838 pub(crate) fn assign_active_local_slot(
839 &mut self,
840 name: &str,
841 value: VmValue,
842 debug: bool,
843 ) -> Result<bool, VmError> {
844 let Some(frame) = self.frames.last_mut() else {
845 return Ok(false);
846 };
847 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
848 if info.name == name && info.scope_depth <= frame.local_scope_depth {
849 if !debug && !info.mutable {
850 return Err(VmError::ImmutableAssignment(name.to_string()));
851 }
852 if let Some(slot) = frame.local_slots.get_mut(idx) {
853 crate::value::recursion::dismantle(std::mem::replace(&mut slot.value, value));
854 slot.initialized = true;
855 slot.synced = false;
856 return Ok(true);
857 }
858 }
859 }
860 Ok(false)
861 }
862
863 pub fn new() -> Self {
864 crate::initialize_runtime_assets();
865 Self {
866 stack: Vec::with_capacity(256),
867 env: VmEnv::new(),
868 output: String::new(),
869 builtins: Arc::new(BTreeMap::new()),
870 async_builtins: Arc::new(BTreeMap::new()),
871 capability_methods: Arc::new(BTreeMap::new()),
872 builtin_metadata: Arc::new(BTreeMap::new()),
873 builtins_by_id: Arc::new(HashMap::new()),
874 builtin_id_collisions: Arc::new(HashSet::new()),
875 iterators: Vec::new(),
876 frames: Vec::new(),
877 exception_handlers: Vec::new(),
878 spawned_tasks: BTreeMap::new(),
879 process_exit_request: Arc::new(ProcessExitRequest::new()),
880 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
881 shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
882 inline_cache_sets: Vec::new(),
883 inline_cache_set_by_chunk: HashMap::new(),
884 pool_registry: crate::stdlib::pool::new_pool_registry(),
885 llm_mock_context: crate::llm::mock::LlmMockContext::for_new_vm(),
886 package_snapshot_registry: Arc::new(Default::default()),
887 wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
888 held_sync_guards: Vec::new(),
889 inherited_held_keys: Arc::new(Vec::new()),
890 task_scopes: Vec::new(),
891 task_counter: 0,
892 runtime_context_counter: 0,
893 runtime_context: crate::runtime_context::RuntimeContext::root(),
894 deadlines: Vec::new(),
895 execution_deadline: super::execution::new_execution_deadline_state(None),
896 breakpoints: BTreeMap::new(),
897 function_breakpoints: std::collections::BTreeSet::new(),
898 pending_function_bp: None,
899 step_mode: false,
900 step_frame_depth: 0,
901 stopped: false,
902 last_line: 0,
903 source_dir: None,
904 package_execution_guard: None,
905 imported_paths: Vec::new(),
906 deferred_cyclic_imports: Vec::new(),
907 module_cache: Arc::new(BTreeMap::new()),
908 prepared_module_cache: crate::PreparedModuleCache::default(),
909 module_phase_recorder: None,
910 lazy_callable_modules: Arc::new(crate::value::VmMutex::new(BTreeMap::new())),
911 source_cache: Arc::new(BTreeMap::new()),
912 graph_link_table: None,
913 source_file: None,
914 source_text: None,
915 coverage: crate::coverage::for_primary(None),
916 bridge: None,
917 denied_builtins: Arc::new(HashSet::new()),
918 cancel_token: None,
919 interrupt_signal_token: None,
920 cancel_grace_instructions_remaining: None,
921 interrupt_handlers: Vec::new(),
922 next_interrupt_handle: 1,
923 pending_interrupt_signal: None,
924 interrupted: false,
925 dispatching_interrupt: false,
926 interrupt_handler_deadline: None,
927 error_stack_trace: Vec::new(),
928 yield_sender: None,
929 project_root: None,
930 globals: Arc::new(crate::value::DictMap::new()),
931 root_harness: None,
932 executed_effects: Arc::new(Mutex::new(Default::default())),
933 debug_hook: None,
934 runtime_limits: RuntimeLimits::default(),
935 }
936 }
937
938 pub fn baseline(&self) -> VmBaseline {
939 VmBaseline::from_vm(self)
940 }
941
942 pub fn executed_effects(&self) -> Vec<crate::orchestration::EffectRecord> {
944 self.executed_effects
945 .lock()
946 .expect("executed effect recorder poisoned")
947 .iter()
948 .cloned()
949 .collect()
950 }
951
952 pub fn clear_executed_effects(&self) {
954 self.executed_effects
955 .lock()
956 .expect("executed effect recorder poisoned")
957 .clear();
958 }
959
960 pub(crate) fn record_capability_effects(
961 &self,
962 capability: harn_builtin_meta::CapabilityId,
963 method: &str,
964 args: &[VmValue],
965 ) {
966 Self::record_capability_effects_into(&self.executed_effects, capability, method, args);
967 }
968
969 pub(crate) fn record_capability_effects_into(
970 recorder: &Arc<Mutex<std::collections::BTreeSet<crate::orchestration::EffectRecord>>>,
971 capability: harn_builtin_meta::CapabilityId,
972 method: &str,
973 args: &[VmValue],
974 ) {
975 let Some(entry) = crate::stdlib::all_builtin_manifest().iter().find(|entry| {
976 matches!(
977 entry.contract.exposure,
978 harn_builtin_meta::BuiltinExposure::HarnessMethod {
979 capability: candidate,
980 method: candidate_method,
981 } if candidate == capability && candidate_method == method
982 )
983 }) else {
984 return;
985 };
986 let effects =
987 crate::orchestration::runtime_effects_from_contract(entry.contract.effects, args);
988 recorder
989 .lock()
990 .expect("executed effect recorder poisoned")
991 .extend(effects);
992 }
993
994 pub(crate) fn record_builtin_contract_effects(&self, name: &str, args: &[VmValue]) {
995 let Some(entry) = crate::stdlib::all_builtin_manifest()
996 .iter()
997 .find(|entry| entry.name == name)
998 else {
999 return;
1000 };
1001 if !matches!(
1002 entry.contract.exposure,
1003 harn_builtin_meta::BuiltinExposure::CapabilityFunction { .. }
1004 | harn_builtin_meta::BuiltinExposure::PrivilegedWire
1005 ) {
1006 return;
1007 }
1008 let effects =
1009 crate::orchestration::runtime_effects_from_contract(entry.contract.effects, args);
1010 self.executed_effects
1011 .lock()
1012 .expect("executed effect recorder poisoned")
1013 .extend(effects);
1014 }
1015
1016 pub fn set_prepared_module_cache(&mut self, cache: crate::PreparedModuleCache) {
1019 self.prepared_module_cache = cache;
1020 }
1021
1022 pub fn set_graph_link_table(
1030 &mut self,
1031 link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
1032 ) {
1033 self.graph_link_table = link_table;
1034 }
1035
1036 pub fn runtime_limits(&self) -> RuntimeLimits {
1038 self.runtime_limits
1039 }
1040
1041 pub fn runtime_limit_report(&self) -> crate::RuntimeLimitsReport {
1043 self.runtime_limits.report()
1044 }
1045
1046 #[inline]
1060 pub(crate) fn debugger_attached(&self) -> bool {
1061 self.debug_hook.is_some()
1062 || !self.breakpoints.is_empty()
1063 || !self.function_breakpoints.is_empty()
1064 }
1065
1066 pub fn set_bridge(&mut self, bridge: Arc<crate::bridge::HostBridge>) {
1068 self.bridge = Some(bridge);
1069 }
1070
1071 pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
1074 self.denied_builtins = Arc::new(denied);
1075 }
1076
1077 pub fn set_source_info(&mut self, file: &str, text: &str) {
1079 self.source_file = Some(file.to_string());
1080 self.source_text = Some(text.to_string());
1081 if let Some(cov) = self.coverage.as_mut() {
1082 cov.set_primary_file(file);
1083 }
1084 Arc::make_mut(&mut self.source_cache)
1085 .insert(std::path::PathBuf::from(file), Arc::from(text));
1086 }
1087
1088 pub fn start(&mut self, chunk: &Chunk) -> Result<(), VmError> {
1090 self.ensure_execution_available()?;
1091 let debugger = self.debugger_attached();
1098 let initial_env = if debugger {
1099 Some(self.env.clone())
1100 } else {
1101 None
1102 };
1103 let initial_local_slots = if debugger {
1104 Some(Self::fresh_local_slots(chunk))
1105 } else {
1106 None
1107 };
1108 let chunk = Arc::new(chunk.clone());
1109 let local_slots = Self::fresh_local_slots(&chunk);
1110 let inline_cache_set = self.inline_cache_set_index_for_chunk(&chunk);
1111 self.frames.push(CallFrame {
1112 chunk,
1113 inline_cache_set,
1114 ip: 0,
1115 stack_base: self.stack.len(),
1116 saved_env: self.env.clone(),
1117 initial_env,
1118 initial_local_slots,
1119 saved_iterator_depth: self.iterators.len(),
1120 fn_name: String::new(),
1121 argc: 0,
1122 saved_source_dir: None,
1123 module_functions: None,
1124 module_state: None,
1125 local_slots,
1126 local_scope_base: self.env.scope_depth().saturating_sub(1),
1127 local_scope_depth: 0,
1128 });
1129 Ok(())
1130 }
1131
1132 pub(crate) fn child_vm(&self) -> Vm {
1135 Vm {
1136 stack: Vec::with_capacity(64),
1137 env: self.env.clone(),
1138 output: String::new(),
1139 builtins: Arc::clone(&self.builtins),
1140 async_builtins: Arc::clone(&self.async_builtins),
1141 capability_methods: Arc::clone(&self.capability_methods),
1142 builtin_metadata: Arc::clone(&self.builtin_metadata),
1143 builtins_by_id: Arc::clone(&self.builtins_by_id),
1144 builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
1145 iterators: Vec::new(),
1146 frames: Vec::new(),
1147 exception_handlers: Vec::new(),
1148 spawned_tasks: BTreeMap::new(),
1149 process_exit_request: Arc::clone(&self.process_exit_request),
1150 sync_runtime: self.sync_runtime.clone(),
1151 shared_state_runtime: self.shared_state_runtime.clone(),
1152 inline_cache_sets: Vec::new(),
1153 inline_cache_set_by_chunk: HashMap::new(),
1154 pool_registry: self.pool_registry.clone(),
1155 llm_mock_context: self.llm_mock_context.clone(),
1156 package_snapshot_registry: self.package_snapshot_registry.clone(),
1157 wait_for_graph: self.wait_for_graph.clone(),
1158 held_sync_guards: Vec::new(),
1159 inherited_held_keys: Arc::new(Vec::new()),
1160 task_scopes: Vec::new(),
1161 task_counter: 0,
1162 runtime_context_counter: self.runtime_context_counter,
1163 runtime_context: self.runtime_context.clone(),
1164 deadlines: self.deadlines.clone(),
1165 execution_deadline: self.execution_deadline.fork(),
1166 breakpoints: BTreeMap::new(),
1167 function_breakpoints: std::collections::BTreeSet::new(),
1168 pending_function_bp: None,
1169 step_mode: false,
1170 step_frame_depth: 0,
1171 stopped: false,
1172 last_line: 0,
1173 source_dir: self.source_dir.clone(),
1174 package_execution_guard: self.package_execution_guard.clone(),
1175 imported_paths: Vec::new(),
1176 deferred_cyclic_imports: Vec::new(),
1177 module_cache: Arc::clone(&self.module_cache),
1178 prepared_module_cache: self.prepared_module_cache.clone(),
1179 module_phase_recorder: self.module_phase_recorder.clone(),
1180 lazy_callable_modules: Arc::clone(&self.lazy_callable_modules),
1181 source_cache: Arc::clone(&self.source_cache),
1182 graph_link_table: self.graph_link_table.clone(),
1183 source_file: self.source_file.clone(),
1184 source_text: self.source_text.clone(),
1185 coverage: crate::coverage::for_primary(self.source_file.as_deref()),
1186 bridge: self.bridge.clone(),
1187 denied_builtins: Arc::clone(&self.denied_builtins),
1188 cancel_token: self.cancel_token.clone(),
1189 interrupt_signal_token: self.interrupt_signal_token.clone(),
1190 cancel_grace_instructions_remaining: None,
1191 interrupt_handlers: Vec::new(),
1192 next_interrupt_handle: 1,
1193 pending_interrupt_signal: None,
1194 interrupted: self.interrupted,
1195 dispatching_interrupt: false,
1196 interrupt_handler_deadline: None,
1197 error_stack_trace: Vec::new(),
1198 yield_sender: None,
1199 project_root: self.project_root.clone(),
1200 globals: Arc::clone(&self.globals),
1201 root_harness: self.root_harness.clone(),
1202 executed_effects: Arc::clone(&self.executed_effects),
1203 debug_hook: None,
1204 runtime_limits: self.runtime_limits,
1205 }
1206 }
1207
1208 pub(crate) fn child_vm_for_host(&self) -> Vm {
1211 self.child_vm()
1212 }
1213
1214 pub(crate) fn request_process_exit(&self, code: i32) {
1215 self.process_exit_request.request(code);
1216 }
1217
1218 pub(crate) fn requested_process_exit(&self) -> Option<i32> {
1219 self.process_exit_request.code()
1220 }
1221
1222 pub(crate) fn cancel_spawned_tasks(&mut self) {
1226 for (_, task) in std::mem::take(&mut self.spawned_tasks) {
1227 task.cancel_token
1228 .store(true, std::sync::atomic::Ordering::SeqCst);
1229 task.handle.abort();
1230 }
1231 }
1232
1233 pub fn set_source_dir(&mut self, dir: &std::path::Path) {
1236 let dir = crate::stdlib::process::normalize_context_path(dir);
1237 self.source_dir = Some(dir.clone());
1238 crate::stdlib::set_thread_source_dir(&dir);
1239 if self.project_root.is_none() {
1241 self.project_root = crate::stdlib::process::find_project_root(&dir);
1242 }
1243 }
1244
1245 pub fn set_project_root(&mut self, root: &std::path::Path) {
1248 self.project_root = Some(root.to_path_buf());
1249 }
1250
1251 pub(crate) fn explicit_project_root(&self) -> Option<&std::path::Path> {
1254 self.project_root.as_deref()
1255 }
1256
1257 pub fn project_root(&self) -> Option<&std::path::Path> {
1259 self.project_root.as_deref().or(self.source_dir.as_deref())
1260 }
1261
1262 pub fn builtin_names(&self) -> Vec<String> {
1264 let mut names: Vec<String> = self.builtins.keys().cloned().collect();
1265 names.extend(self.async_builtins.keys().cloned());
1266 names
1267 }
1268
1269 pub fn builtin_metadata(&self) -> Vec<VmBuiltinMetadata> {
1271 self.builtin_metadata.values().cloned().collect()
1272 }
1273
1274 pub fn builtin_metadata_for(&self, name: &str) -> Option<&VmBuiltinMetadata> {
1276 self.builtin_metadata.get(name)
1277 }
1278
1279 pub fn set_global(&mut self, name: &str, value: VmValue) {
1282 Arc::make_mut(&mut self.globals).insert(crate::value::intern_key(name), value);
1283 }
1284
1285 pub fn global(&self, name: &str) -> Option<&VmValue> {
1287 self.globals.get(name)
1288 }
1289
1290 pub fn set_harness(&mut self, harness: crate::harness::Harness) {
1294 self.root_harness = Some(harness.into_vm_value());
1295 }
1296
1297 pub(crate) fn harness(&self) -> Option<&crate::harness::VmHarness> {
1298 match self.root_harness.as_ref() {
1299 Some(VmValue::Harness(handle)) => Some(handle),
1300 _ => None,
1301 }
1302 }
1303
1304 pub fn root_harness_value(&self) -> Option<VmValue> {
1307 self.root_harness.clone()
1308 }
1309
1310 pub fn output(&self) -> &str {
1312 &self.output
1313 }
1314
1315 pub fn take_output(&mut self) -> String {
1319 std::mem::take(&mut self.output)
1320 }
1321
1322 pub fn append_output(&mut self, text: &str) {
1326 self.output.push_str(text);
1327 }
1328
1329 pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
1330 self.stack.pop().ok_or(VmError::StackUnderflow)
1331 }
1332
1333 pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
1334 self.stack.last().ok_or(VmError::StackUnderflow)
1335 }
1336
1337 pub(crate) fn const_str(c: &Constant) -> Result<&str, VmError> {
1338 match c {
1339 Constant::String(s) => Ok(s.as_str()),
1340 _ => Err(VmError::TypeError("expected string constant".into())),
1341 }
1342 }
1343
1344 pub(crate) fn release_sync_guards_for_current_scope(&mut self) {
1345 let depth = self.env.scope_depth();
1346 self.held_sync_guards
1347 .retain(|guard| guard.env_scope_depth < depth);
1348 self.cancel_task_scopes_where(|s| s.env_scope_depth >= depth);
1351 }
1352
1353 pub(crate) fn release_sync_guards_after_unwind(
1354 &mut self,
1355 frame_depth: usize,
1356 env_scope_depth: usize,
1357 ) {
1358 self.held_sync_guards.retain(|guard| {
1359 guard.frame_depth <= frame_depth && guard.env_scope_depth <= env_scope_depth
1360 });
1361 self.cancel_task_scopes_where(|s| {
1364 !(s.frame_depth <= frame_depth && s.env_scope_depth <= env_scope_depth)
1365 });
1366 }
1367
1368 pub(crate) fn release_sync_guards_for_frame(&mut self, frame_depth: usize) {
1369 self.held_sync_guards
1370 .retain(|guard| guard.frame_depth != frame_depth);
1371 self.cancel_task_scopes_where(|s| s.frame_depth == frame_depth);
1374 }
1375
1376 pub(crate) fn adopt_sync_permit_for_current_scope(
1377 &mut self,
1378 permit: crate::value::VmSyncPermitHandle,
1379 ) {
1380 if permit.is_released()
1381 || self
1382 .held_sync_guards
1383 .iter()
1384 .any(|guard| guard._permit.same_lease(&permit))
1385 {
1386 return;
1387 }
1388 self.held_sync_guards
1389 .push(crate::synchronization::VmSyncHeldGuard {
1390 _permit: permit,
1391 frame_depth: self.frames.len(),
1392 env_scope_depth: self.env.scope_depth(),
1393 });
1394 }
1395
1396 pub(crate) fn deregister_task_from_scopes(&mut self, id: &str) {
1399 for scope in &mut self.task_scopes {
1400 scope.task_ids.retain(|t| t != id);
1401 }
1402 }
1403
1404 fn cancel_task_scopes_where<F: Fn(&TaskScope) -> bool>(&mut self, doomed: F) {
1407 let mut i = 0;
1408 while i < self.task_scopes.len() {
1409 if doomed(&self.task_scopes[i]) {
1410 let scope = self.task_scopes.remove(i);
1411 for id in &scope.task_ids {
1412 if let Some(task) = self.spawned_tasks.remove(id) {
1413 task.cancel_token
1414 .store(true, std::sync::atomic::Ordering::SeqCst);
1415 task.handle.abort();
1416 }
1417 }
1418 } else {
1419 i += 1;
1420 }
1421 }
1422 }
1423
1424 pub(crate) fn held_permits_for(&self, kind: &str, key: &str) -> u32 {
1428 let own: u32 = self
1429 .held_sync_guards
1430 .iter()
1431 .filter(|guard| {
1432 !guard._permit.is_released()
1433 && guard._permit.kind() == kind
1434 && guard._permit.key() == key
1435 })
1436 .map(|guard| guard._permit.permits())
1437 .sum();
1438 let inherited: u32 = self
1439 .inherited_held_keys
1440 .iter()
1441 .filter(|held| held.kind == kind && held.key == key)
1442 .map(|held| held.permits)
1443 .sum();
1444 own + inherited
1445 }
1446
1447 pub(crate) fn combined_held_keys(&self) -> Vec<crate::synchronization::VmSyncHeldKey> {
1450 let mut keys: Vec<crate::synchronization::VmSyncHeldKey> = self
1451 .held_sync_guards
1452 .iter()
1453 .filter_map(|guard| crate::synchronization::VmSyncHeldKey::from_permit(&guard._permit))
1454 .collect();
1455 keys.extend(self.inherited_held_keys.iter().cloned());
1456 keys
1457 }
1458
1459 pub(crate) fn child_vm_inline(&self) -> Vm {
1465 let mut child = self.child_vm();
1466 child.inherited_held_keys = Arc::new(self.combined_held_keys());
1467 child
1468 }
1469}
1470
1471impl Drop for Vm {
1472 fn drop(&mut self) {
1473 if let Some(coverage) = self.coverage.take() {
1474 crate::coverage::merge_into_global(coverage);
1475 }
1476 self.cancel_spawned_tasks();
1477 }
1478}
1479
1480impl Default for Vm {
1481 fn default() -> Self {
1482 Self::new()
1483 }
1484}
1485
1486#[cfg(test)]
1487#[path = "state_tests.rs"]
1488mod tests;