1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::path::PathBuf;
3use std::sync::atomic::{AtomicBool, 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;
16pub(crate) use super::execution_deadline::{ExecutionDeadlinePauseGuard, ExecutionDeadlineState};
17use super::modules::ModuleCache;
18use super::VmBuiltinMetadata;
19
20pub(crate) struct ResolvedLazyCallable {
34 pub(crate) exports: BTreeMap<String, Arc<VmClosure>>,
35 #[allow(dead_code)]
40 pub(crate) retained_module_graph: ModuleCache,
41}
42
43pub(crate) type LazyCallableResolution = Arc<ResolvedLazyCallable>;
44pub(crate) struct LazyCallableCacheSlot {
45 pub(crate) execution_guard: Option<Arc<harn_modules::package_execution::PackageExecutionGuard>>,
46 pub(crate) resolution: Arc<tokio::sync::OnceCell<LazyCallableResolution>>,
47}
48pub(crate) type LazyCallableModuleCache =
49 Arc<VmMutex<BTreeMap<PathBuf, Vec<LazyCallableCacheSlot>>>>;
50
51pub(crate) struct ScopeSpan(u64);
53
54impl ScopeSpan {
55 pub(crate) fn new(kind: crate::tracing::SpanKind, name: String) -> Self {
56 Self(crate::tracing::span_start(kind, name))
57 }
58}
59
60impl Drop for ScopeSpan {
61 fn drop(&mut self) {
62 crate::tracing::span_end(self.0);
63 }
64}
65
66#[derive(Clone)]
67pub(crate) struct LocalSlot {
68 pub(crate) value: VmValue,
69 pub(crate) initialized: bool,
70 pub(crate) synced: bool,
71}
72
73impl Drop for LocalSlot {
74 fn drop(&mut self) {
75 if crate::value::recursion::is_recursive_container(&self.value) {
83 crate::value::recursion::dismantle(std::mem::replace(&mut self.value, VmValue::Nil));
84 }
85 }
86}
87
88#[derive(Clone)]
89pub(crate) struct InterruptHandler {
90 pub(crate) handle: i64,
91 pub(crate) signals: Vec<String>,
92 pub(crate) once: bool,
93 pub(crate) graceful_timeout_ms: Option<u64>,
94 pub(crate) handler: VmValue,
95}
96
97pub(crate) struct CallFrame {
99 pub(crate) chunk: ChunkRef,
100 pub(crate) inline_cache_set: usize,
104 pub(crate) ip: usize,
105 pub(crate) stack_base: usize,
106 pub(crate) saved_env: VmEnv,
107 pub(crate) initial_env: Option<VmEnv>,
115 pub(crate) initial_local_slots: Option<Vec<LocalSlot>>,
116 pub(crate) saved_iterator_depth: usize,
118 pub(crate) fn_name: crate::value::HarnStr,
121 pub(crate) argc: usize,
123 pub(crate) saved_source_dir: Option<std::path::PathBuf>,
126 pub(crate) module_functions: Option<ModuleFunctionRegistry>,
128 pub(crate) module_state: Option<crate::value::ModuleState>,
134 pub(crate) local_slots: Vec<LocalSlot>,
136 pub(crate) local_scope_base: usize,
138 pub(crate) local_scope_depth: usize,
140}
141
142pub(crate) struct InlineCacheSite {
143 pub(crate) cache_set: usize,
144 pub(crate) slot_count: usize,
145 pub(crate) slot: Option<usize>,
146}
147
148impl CallFrame {
149 #[inline]
150 pub(crate) fn inline_cache_site_for_previous_op(&self) -> InlineCacheSite {
151 let op_offset = self.ip.saturating_sub(1);
152 InlineCacheSite {
153 cache_set: self.inline_cache_set,
154 slot_count: self.chunk.inline_cache_slot_count(),
155 slot: self.chunk.inline_cache_slot(op_offset),
156 }
157 }
158}
159
160pub(crate) struct ExceptionHandler {
162 pub(crate) catch_ip: usize,
163 pub(crate) stack_depth: usize,
164 pub(crate) frame_depth: usize,
165 pub(crate) env_scope_depth: usize,
166 pub(crate) error_type: Option<crate::value::HarnStr>,
168}
169
170pub(crate) struct TaskScope {
173 pub(crate) task_ids: Vec<String>,
176 pub(crate) frame_depth: usize,
178 pub(crate) env_scope_depth: usize,
180}
181
182pub(crate) struct ProcessExitRequest {
186 code: Mutex<Option<i32>>,
187 requested: AtomicBool,
188}
189
190impl ProcessExitRequest {
191 fn new() -> Self {
192 Self {
193 code: Mutex::new(None),
194 requested: AtomicBool::new(false),
195 }
196 }
197
198 fn request(&self, code: i32) {
199 let mut recorded = self
200 .code
201 .lock()
202 .expect("process exit request lock poisoned");
203 if recorded.is_none() {
204 *recorded = Some(code);
205 self.requested.store(true, Ordering::Release);
206 }
207 }
208
209 fn code(&self) -> Option<i32> {
210 if !self.requested.load(Ordering::Acquire) {
211 return None;
212 }
213 *self
214 .code
215 .lock()
216 .expect("process exit request lock poisoned")
217 }
218}
219
220pub(crate) enum IterState {
222 Vec {
223 items: Arc<Vec<VmValue>>,
224 idx: usize,
225 },
226 Dict {
227 entries: Arc<crate::value::DictMap>,
228 keys: Vec<crate::value::HarnStr>,
229 idx: usize,
230 },
231 Channel {
232 receiver: std::sync::Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
233 close: std::sync::Arc<crate::value::VmChannelCloseState>,
234 },
235 Generator {
236 gen: Arc<crate::value::VmGenerator>,
237 },
238 Stream {
239 stream: Arc<crate::value::VmStream>,
240 },
241 Range {
245 next: i64,
246 end: i64,
247 inclusive: bool,
248 done: bool,
249 },
250 VmIter {
251 handle: crate::vm::iter::VmIterHandle,
252 },
253}
254
255#[derive(Clone)]
256pub(crate) enum VmBuiltinDispatch {
257 Sync(VmBuiltinFn),
258 Async(VmAsyncBuiltinFn),
259}
260
261#[derive(Clone)]
262pub(crate) struct VmBuiltinEntry {
263 pub(crate) name: Arc<str>,
264 pub(crate) dispatch: VmBuiltinDispatch,
265 pub(crate) recorded_effects: Option<&'static [harn_builtin_meta::EffectSpec]>,
269}
270
271pub struct Vm {
273 pub(crate) stack: Vec<VmValue>,
274 pub(crate) env: VmEnv,
275 pub(crate) output: String,
276 pub(crate) builtins: Arc<BTreeMap<String, VmBuiltinFn>>,
277 pub(crate) async_builtins: Arc<BTreeMap<String, VmAsyncBuiltinFn>>,
278 pub(crate) capability_methods:
282 Arc<BTreeMap<harn_builtin_meta::CapabilityId, BTreeMap<String, VmBuiltinDispatch>>>,
283 pub(crate) builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
284 pub(crate) builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
287 pub(crate) builtin_id_collisions: Arc<HashSet<BuiltinId>>,
290 pub(crate) iterators: Vec<IterState>,
292 pub(crate) frames: Vec<CallFrame>,
294 pub(crate) exception_handlers: Vec<ExceptionHandler>,
296 pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
298 pub(crate) process_exit_request: Arc<ProcessExitRequest>,
300 pub(crate) sync_runtime: Arc<crate::synchronization::VmSyncRuntime>,
302 pub(crate) shared_state_runtime: Arc<crate::shared_state::VmSharedStateRuntime>,
304 pub(crate) inline_cache_sets: Vec<Vec<crate::chunk::InlineCacheEntry>>,
308 pub(crate) inline_cache_set_by_chunk: HashMap<u64, usize>,
309 pub(crate) pool_registry: Arc<crate::stdlib::pool::PoolRegistry>,
311 pub(crate) llm_mock_context: crate::llm::mock::LlmMockContext,
313 pub(crate) package_snapshot_registry: Arc<crate::stdlib::PackageSnapshotRegistry>,
317 pub(crate) wait_for_graph: Arc<crate::wait_for_graph::VmWaitForGraph>,
319 pub(crate) held_sync_guards: Vec<crate::synchronization::VmSyncHeldGuard>,
321 pub(crate) inherited_held_keys: Arc<Vec<crate::synchronization::VmSyncHeldKey>>,
329 pub(crate) task_scopes: Vec<TaskScope>,
335 pub(crate) task_counter: u64,
337 pub(crate) runtime_context_counter: u64,
339 pub(crate) runtime_context: crate::runtime_context::RuntimeContext,
341 pub(crate) deadlines: Vec<(Instant, usize)>,
343 pub(crate) execution_deadline: Arc<ExecutionDeadlineState>,
345 pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
350 pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
356 pub(crate) pending_function_bp: Option<String>,
361 pub(crate) step_mode: bool,
363 pub(crate) step_frame_depth: usize,
365 pub(crate) stopped: bool,
367 pub(crate) last_line: usize,
369 pub(crate) source_dir: Option<std::path::PathBuf>,
371 pub(crate) package_execution_guard:
373 Option<Arc<harn_modules::package_execution::PackageExecutionGuard>>,
374 pub(crate) imported_paths: Vec<std::path::PathBuf>,
376 pub(crate) deferred_cyclic_imports: Vec<super::modules::DeferredCyclicImport>,
380 pub(crate) module_cache: ModuleCache,
382 pub(crate) prepared_module_cache: crate::PreparedModuleCache,
385 pub(crate) module_provenance: crate::module_artifact::ModuleProvenance,
388 pub(crate) module_phase_recorder: Option<super::ModulePhaseRecorder>,
390 pub(crate) lazy_callable_modules: LazyCallableModuleCache,
394 pub(crate) source_cache: Arc<BTreeMap<std::path::PathBuf, Arc<str>>>,
398 pub(crate) graph_link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
403 pub(crate) linked_program_repository:
407 Option<Arc<crate::linked_program::LinkedProgramRepository>>,
408 pub(crate) source_file: Option<String>,
410 pub(crate) source_text: Option<String>,
412 pub(crate) coverage: Option<crate::coverage::Coverage>,
415 pub(crate) bridge: Option<Arc<crate::bridge::HostBridge>>,
417 pub(crate) denied_builtins: Arc<HashSet<String>>,
419 pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
421 pub(crate) interrupt_signal_token: Option<std::sync::Arc<std::sync::Mutex<Option<String>>>>,
422 pub(crate) cancel_grace_instructions_remaining: Option<usize>,
427 pub(crate) interrupt_handlers: Vec<InterruptHandler>,
429 pub(crate) next_interrupt_handle: i64,
430 pub(crate) pending_interrupt_signal: Option<String>,
431 pub(crate) interrupted: bool,
432 pub(crate) dispatching_interrupt: bool,
433 pub(crate) interrupt_handler_deadline: Option<Instant>,
434 pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
436 pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<Result<VmValue, VmError>>>,
439 pub(crate) project_root: Option<std::path::PathBuf>,
442 pub(crate) globals: Arc<crate::value::DictMap>,
445 pub(crate) root_harness: Option<VmValue>,
450 pub(crate) runtime_effects: crate::orchestration::RuntimeEffectState,
452 pub(crate) debug_hook: Option<parking_lot::Mutex<Box<DebugHook>>>,
454 pub(crate) runtime_limits: RuntimeLimits,
456}
457
458#[derive(Clone)]
466pub struct VmBaseline {
467 builtins: Arc<BTreeMap<String, VmBuiltinFn>>,
468 async_builtins: Arc<BTreeMap<String, VmAsyncBuiltinFn>>,
469 capability_methods:
470 Arc<BTreeMap<harn_builtin_meta::CapabilityId, BTreeMap<String, VmBuiltinDispatch>>>,
471 builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
472 builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
473 builtin_id_collisions: Arc<HashSet<BuiltinId>>,
474 source_dir: Option<std::path::PathBuf>,
475 source_file: Option<String>,
476 source_text: Option<String>,
477 project_root: Option<std::path::PathBuf>,
478 globals: Arc<crate::value::DictMap>,
479 root_harness: Option<VmValue>,
480 denied_builtins: Arc<HashSet<String>>,
481 prepared_module_cache: crate::PreparedModuleCache,
482 module_provenance: crate::module_artifact::ModuleProvenance,
483 graph_link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
486 linked_program_repository: Option<Arc<crate::linked_program::LinkedProgramRepository>>,
487 runtime_limits: RuntimeLimits,
488}
489
490impl VmBaseline {
491 pub fn from_vm(vm: &Vm) -> Self {
492 Self {
493 builtins: Arc::clone(&vm.builtins),
494 async_builtins: Arc::clone(&vm.async_builtins),
495 capability_methods: Arc::clone(&vm.capability_methods),
496 builtin_metadata: Arc::clone(&vm.builtin_metadata),
497 builtins_by_id: Arc::clone(&vm.builtins_by_id),
498 builtin_id_collisions: Arc::clone(&vm.builtin_id_collisions),
499 source_dir: vm.source_dir.clone(),
500 source_file: vm.source_file.clone(),
501 source_text: vm.source_text.clone(),
502 project_root: vm.project_root.clone(),
503 globals: Arc::clone(&vm.globals),
504 root_harness: vm.root_harness.clone(),
505 denied_builtins: Arc::clone(&vm.denied_builtins),
506 prepared_module_cache: vm.prepared_module_cache.clone(),
507 module_provenance: vm.module_provenance,
508 graph_link_table: vm.graph_link_table.clone(),
509 linked_program_repository: vm.linked_program_repository.clone(),
510 runtime_limits: vm.runtime_limits,
511 }
512 }
513
514 pub fn instantiate(&self) -> Vm {
515 crate::initialize_runtime_assets();
516 let mut source_cache = BTreeMap::new();
517 if let (Some(file), Some(text)) = (&self.source_file, &self.source_text) {
518 source_cache.insert(std::path::PathBuf::from(file), Arc::from(text.as_str()));
519 }
520 if let Some(dir) = &self.source_dir {
521 crate::stdlib::set_thread_source_dir(dir);
522 }
523
524 let mut vm = Vm {
525 stack: Vec::with_capacity(256),
526 env: VmEnv::new(),
527 output: String::new(),
528 builtins: Arc::clone(&self.builtins),
529 async_builtins: Arc::clone(&self.async_builtins),
530 capability_methods: Arc::clone(&self.capability_methods),
531 builtin_metadata: Arc::clone(&self.builtin_metadata),
532 builtins_by_id: Arc::clone(&self.builtins_by_id),
533 builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
534 iterators: Vec::new(),
535 frames: Vec::new(),
536 exception_handlers: Vec::new(),
537 spawned_tasks: BTreeMap::new(),
538 process_exit_request: Arc::new(ProcessExitRequest::new()),
539 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
540 shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
541 inline_cache_sets: Vec::new(),
542 inline_cache_set_by_chunk: HashMap::new(),
543 pool_registry: crate::stdlib::pool::new_pool_registry(),
544 llm_mock_context: crate::llm::mock::LlmMockContext::for_new_vm(),
545 package_snapshot_registry: Arc::new(Default::default()),
546 wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
547 held_sync_guards: Vec::new(),
548 inherited_held_keys: Arc::new(Vec::new()),
549 task_scopes: Vec::new(),
550 task_counter: 0,
551 runtime_context_counter: 0,
552 runtime_context: crate::runtime_context::RuntimeContext::root(),
553 deadlines: Vec::new(),
554 execution_deadline: super::execution::new_execution_deadline_state(None),
555 breakpoints: BTreeMap::new(),
556 function_breakpoints: std::collections::BTreeSet::new(),
557 pending_function_bp: None,
558 step_mode: false,
559 step_frame_depth: 0,
560 stopped: false,
561 last_line: 0,
562 source_dir: self.source_dir.clone(),
563 package_execution_guard: None,
564 imported_paths: Vec::new(),
565 deferred_cyclic_imports: Vec::new(),
566 module_cache: Arc::new(BTreeMap::new()),
567 prepared_module_cache: self.prepared_module_cache.clone(),
568 module_provenance: self.module_provenance,
569 module_phase_recorder: None,
570 lazy_callable_modules: Arc::new(crate::value::VmMutex::new(BTreeMap::new())),
571 source_cache: Arc::new(source_cache),
572 graph_link_table: self.graph_link_table.clone(),
573 linked_program_repository: self.linked_program_repository.clone(),
574 source_file: self.source_file.clone(),
575 source_text: self.source_text.clone(),
576 coverage: crate::coverage::for_primary(self.source_file.as_deref()),
577 bridge: None,
578 denied_builtins: Arc::clone(&self.denied_builtins),
579 cancel_token: None,
580 interrupt_signal_token: None,
581 cancel_grace_instructions_remaining: None,
582 interrupt_handlers: Vec::new(),
583 next_interrupt_handle: 1,
584 pending_interrupt_signal: None,
585 interrupted: false,
586 dispatching_interrupt: false,
587 interrupt_handler_deadline: None,
588 error_stack_trace: Vec::new(),
589 yield_sender: None,
590 project_root: self.project_root.clone(),
591 globals: Arc::clone(&self.globals),
592 root_harness: self.root_harness.clone(),
593 runtime_effects: crate::orchestration::RuntimeEffectState::fresh(),
594 debug_hook: None,
595 runtime_limits: self.runtime_limits,
596 };
597
598 crate::stdlib::rebind_execution_state_builtins(&mut vm);
599 vm
600 }
601}
602
603impl Vm {
604 pub(crate) fn ensure_execution_available(&self) -> Result<(), VmError> {
605 if self.execution_deadline.is_abandoned() {
606 return Err(VmError::AbandonedExecution);
607 }
608 Ok(())
609 }
610
611 pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
612 chunk
613 .local_slots
614 .iter()
615 .map(|_| LocalSlot {
616 value: VmValue::Nil,
617 initialized: false,
618 synced: false,
619 })
620 .collect()
621 }
622
623 pub(crate) fn bind_param_slots(
624 slots: &mut [LocalSlot],
625 func: &crate::chunk::CompiledFunction,
626 args: &[VmValue],
627 synced: bool,
628 ) {
629 Self::bind_param_slots_args(slots, func, &super::CallArgs::Slice(args), synced);
630 }
631
632 pub(crate) fn bind_param_slots_args(
633 slots: &mut [LocalSlot],
634 func: &crate::chunk::CompiledFunction,
635 args: &super::CallArgs<'_>,
636 synced: bool,
637 ) {
638 let param_count = func.params.len();
639 for (i, _param) in func.params.iter().enumerate() {
640 if i >= slots.len() {
641 break;
642 }
643 if func.has_rest_param && i == param_count - 1 {
644 let rest_args = args.to_vec_from(i);
645 slots[i].value = VmValue::List(std::sync::Arc::new(rest_args));
646 slots[i].initialized = true;
647 slots[i].synced = synced;
648 } else if let Some(arg) = args.get(i) {
649 slots[i].value = arg.clone();
650 slots[i].initialized = true;
651 slots[i].synced = synced;
652 }
653 }
654 }
655
656 pub(crate) fn visible_variables(&self) -> crate::value::DictMap {
657 let mut vars = self.env.all_variables();
658 let Some(frame) = self.frames.last() else {
659 return vars;
660 };
661 for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
662 if slot.initialized && info.scope_depth <= frame.local_scope_depth {
663 vars.insert(crate::value::intern_key(&info.name), slot.value.clone());
664 }
665 }
666 vars
667 }
668
669 pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
670 let frames = &mut self.frames;
671 let env = &mut self.env;
672 let Some(frame) = frames.last_mut() else {
673 return;
674 };
675 let local_scope_base = frame.local_scope_base;
676 let local_scope_depth = frame.local_scope_depth;
677 for (slot, info) in frame
678 .local_slots
679 .iter_mut()
680 .zip(frame.chunk.local_slots.iter())
681 {
682 if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
683 slot.synced = true;
684 let scope_idx = local_scope_base + info.scope_depth;
685 while env.scopes.len() <= scope_idx {
686 env.push_scope();
687 }
688 Arc::make_mut(&mut env.scopes[scope_idx].vars).insert(
692 info.name.clone(),
693 crate::value::Binding::Value {
694 value: slot.value.clone(),
695 mutable: info.mutable,
696 },
697 );
698 }
699 }
700 }
701
702 pub(crate) fn closure_call_env_for_current_frame(
703 &self,
704 closure: &crate::value::VmClosure,
705 ) -> VmEnv {
706 if closure.module_state().is_some() {
707 return closure.env.cloned_for_call();
708 }
709 let call_env = Self::closure_call_env(&self.env, closure);
710 if !closure.func.chunk.references_outer_names {
715 return call_env;
716 }
717 let mut call_env = call_env;
718 let Some(frame) = self.frames.last() else {
719 return call_env;
720 };
721 for (slot, info) in frame
722 .local_slots
723 .iter()
724 .zip(frame.chunk.local_slots.iter())
725 .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
726 {
727 if matches!(slot.value, VmValue::Closure(_)) && !call_env.contains(&info.name) {
728 let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
729 }
730 }
731 call_env
732 }
733
734 pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
735 let frame = self.frames.last()?;
736 let idx = self.active_local_slot_index(name)?;
737 frame.local_slots.get(idx).map(|slot| slot.value.clone())
738 }
739
740 pub(crate) fn active_local_slot_index(&self, name: &str) -> Option<usize> {
745 let frame = self.frames.last()?;
746 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
747 if info.name == name && info.scope_depth <= frame.local_scope_depth {
748 if let Some(slot) = frame.local_slots.get(idx) {
749 if slot.initialized {
750 return Some(idx);
751 }
752 }
753 }
754 }
755 None
756 }
757
758 pub(crate) fn assign_active_local_slot(
759 &mut self,
760 name: &str,
761 value: VmValue,
762 debug: bool,
763 ) -> Result<bool, VmError> {
764 let Some(frame) = self.frames.last_mut() else {
765 return Ok(false);
766 };
767 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
768 if info.name == name && info.scope_depth <= frame.local_scope_depth {
769 if !debug && !info.mutable {
770 return Err(VmError::ImmutableAssignment(name.to_string()));
771 }
772 if let Some(slot) = frame.local_slots.get_mut(idx) {
773 crate::value::recursion::dismantle(std::mem::replace(&mut slot.value, value));
774 slot.initialized = true;
775 slot.synced = false;
776 return Ok(true);
777 }
778 }
779 }
780 Ok(false)
781 }
782
783 pub fn new() -> Self {
784 crate::initialize_runtime_assets();
785 Self {
786 stack: Vec::with_capacity(256),
787 env: VmEnv::new(),
788 output: String::new(),
789 builtins: Arc::new(BTreeMap::new()),
790 async_builtins: Arc::new(BTreeMap::new()),
791 capability_methods: Arc::new(BTreeMap::new()),
792 builtin_metadata: Arc::new(BTreeMap::new()),
793 builtins_by_id: Arc::new(HashMap::new()),
794 builtin_id_collisions: Arc::new(HashSet::new()),
795 iterators: Vec::new(),
796 frames: Vec::new(),
797 exception_handlers: Vec::new(),
798 spawned_tasks: BTreeMap::new(),
799 process_exit_request: Arc::new(ProcessExitRequest::new()),
800 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
801 shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
802 inline_cache_sets: Vec::new(),
803 inline_cache_set_by_chunk: HashMap::new(),
804 pool_registry: crate::stdlib::pool::new_pool_registry(),
805 llm_mock_context: crate::llm::mock::LlmMockContext::for_new_vm(),
806 package_snapshot_registry: Arc::new(Default::default()),
807 wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
808 held_sync_guards: Vec::new(),
809 inherited_held_keys: Arc::new(Vec::new()),
810 task_scopes: Vec::new(),
811 task_counter: 0,
812 runtime_context_counter: 0,
813 runtime_context: crate::runtime_context::RuntimeContext::root(),
814 deadlines: Vec::new(),
815 execution_deadline: super::execution::new_execution_deadline_state(None),
816 breakpoints: BTreeMap::new(),
817 function_breakpoints: std::collections::BTreeSet::new(),
818 pending_function_bp: None,
819 step_mode: false,
820 step_frame_depth: 0,
821 stopped: false,
822 last_line: 0,
823 source_dir: None,
824 package_execution_guard: None,
825 imported_paths: Vec::new(),
826 deferred_cyclic_imports: Vec::new(),
827 module_cache: Arc::new(BTreeMap::new()),
828 prepared_module_cache: crate::PreparedModuleCache::default(),
829 module_provenance: crate::module_artifact::ModuleProvenance::User,
830 module_phase_recorder: None,
831 lazy_callable_modules: Arc::new(crate::value::VmMutex::new(BTreeMap::new())),
832 source_cache: Arc::new(BTreeMap::new()),
833 graph_link_table: None,
834 linked_program_repository: None,
835 source_file: None,
836 source_text: None,
837 coverage: crate::coverage::for_primary(None),
838 bridge: None,
839 denied_builtins: Arc::new(HashSet::new()),
840 cancel_token: None,
841 interrupt_signal_token: None,
842 cancel_grace_instructions_remaining: None,
843 interrupt_handlers: Vec::new(),
844 next_interrupt_handle: 1,
845 pending_interrupt_signal: None,
846 interrupted: false,
847 dispatching_interrupt: false,
848 interrupt_handler_deadline: None,
849 error_stack_trace: Vec::new(),
850 yield_sender: None,
851 project_root: None,
852 globals: Arc::new(crate::value::DictMap::new()),
853 root_harness: None,
854 runtime_effects: crate::orchestration::RuntimeEffectState::fresh(),
855 debug_hook: None,
856 runtime_limits: RuntimeLimits::default(),
857 }
858 }
859
860 pub fn baseline(&self) -> VmBaseline {
861 VmBaseline::from_vm(self)
862 }
863
864 pub fn executed_effects(&self) -> Vec<crate::orchestration::EffectRecord> {
866 self.runtime_effects.snapshot()
867 }
868
869 pub fn clear_executed_effects(&mut self) {
871 self.runtime_effects.clear();
872 }
873
874 pub(crate) fn record_capability_effects(
875 &mut self,
876 capability: harn_builtin_meta::CapabilityId,
877 method: &str,
878 args: &[VmValue],
879 ) {
880 self.runtime_effects
881 .record_capability(capability, method, args);
882 }
883
884 pub(crate) fn record_builtin_contract_effects(&mut self, name: &str, args: &[VmValue]) {
885 let Some(entry) = crate::stdlib::recorded_effect_builtin_manifest_entry(name) else {
886 return;
887 };
888 self.record_builtin_effect_specs(entry.contract.effects, args);
889 }
890
891 pub(crate) fn record_builtin_effect_specs(
892 &mut self,
893 specs: &'static [harn_builtin_meta::EffectSpec],
894 args: &[VmValue],
895 ) {
896 self.runtime_effects.record_specs(specs, args);
897 }
898
899 pub fn set_prepared_module_cache(&mut self, cache: crate::PreparedModuleCache) {
902 self.prepared_module_cache = cache;
903 }
904
905 pub fn set_graph_link_table(
913 &mut self,
914 link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
915 ) {
916 self.graph_link_table = link_table;
917 }
918
919 pub fn set_linked_program_runtime(
923 &mut self,
924 runtime: &crate::linked_program::LinkedProgramRuntime,
925 ) {
926 self.linked_program_repository = Some(Arc::clone(&runtime.repository));
927 self.graph_link_table = None;
928 }
929
930 pub fn runtime_limits(&self) -> RuntimeLimits {
932 self.runtime_limits
933 }
934
935 pub fn runtime_limit_report(&self) -> crate::RuntimeLimitsReport {
937 self.runtime_limits.report()
938 }
939
940 #[inline]
954 pub(crate) fn debugger_attached(&self) -> bool {
955 self.debug_hook.is_some()
956 || !self.breakpoints.is_empty()
957 || !self.function_breakpoints.is_empty()
958 }
959
960 pub fn set_bridge(&mut self, bridge: Arc<crate::bridge::HostBridge>) {
962 self.bridge = Some(bridge);
963 }
964
965 pub fn set_denied_builtins(&mut self, mut denied: HashSet<String>) {
968 let denied_canonical_names = denied
972 .iter()
973 .filter_map(|name| crate::stdlib::builtin_manifest_entry(name))
974 .map(|entry| entry.canonical_name)
975 .collect::<HashSet<_>>();
976 if !denied_canonical_names.is_empty() {
977 denied.extend(
978 crate::stdlib::all_builtin_manifest()
979 .iter()
980 .filter(|entry| denied_canonical_names.contains(entry.canonical_name))
981 .map(|entry| entry.name.to_string()),
982 );
983 }
984 self.denied_builtins = Arc::new(denied);
985 }
986
987 pub fn set_source_info(&mut self, file: &str, text: &str) {
989 self.source_file = Some(file.to_string());
990 self.source_text = Some(text.to_string());
991 if let Some(cov) = self.coverage.as_mut() {
992 cov.set_primary_file(file);
993 }
994 Arc::make_mut(&mut self.source_cache)
995 .insert(std::path::PathBuf::from(file), Arc::from(text));
996 }
997
998 pub fn start(&mut self, chunk: &Chunk) -> Result<(), VmError> {
1000 self.ensure_execution_available()?;
1001 let debugger = self.debugger_attached();
1008 let initial_env = if debugger {
1009 Some(self.env.clone())
1010 } else {
1011 None
1012 };
1013 let initial_local_slots = if debugger {
1014 Some(Self::fresh_local_slots(chunk))
1015 } else {
1016 None
1017 };
1018 let chunk = Arc::new(chunk.clone());
1019 let local_slots = Self::fresh_local_slots(&chunk);
1020 let inline_cache_set = self.inline_cache_set_index_for_chunk(&chunk);
1021 self.frames.push(CallFrame {
1022 chunk,
1023 inline_cache_set,
1024 ip: 0,
1025 stack_base: self.stack.len(),
1026 saved_env: self.env.clone(),
1027 initial_env,
1028 initial_local_slots,
1029 saved_iterator_depth: self.iterators.len(),
1030 fn_name: crate::value::HarnStr::new(),
1031 argc: 0,
1032 saved_source_dir: None,
1033 module_functions: None,
1034 module_state: None,
1035 local_slots,
1036 local_scope_base: self.env.scope_depth().saturating_sub(1),
1037 local_scope_depth: 0,
1038 });
1039 Ok(())
1040 }
1041
1042 pub(crate) fn child_vm(&self) -> Vm {
1045 Vm {
1046 stack: Vec::with_capacity(64),
1047 env: self.env.clone(),
1048 output: String::new(),
1049 builtins: Arc::clone(&self.builtins),
1050 async_builtins: Arc::clone(&self.async_builtins),
1051 capability_methods: Arc::clone(&self.capability_methods),
1052 builtin_metadata: Arc::clone(&self.builtin_metadata),
1053 builtins_by_id: Arc::clone(&self.builtins_by_id),
1054 builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
1055 iterators: Vec::new(),
1056 frames: Vec::new(),
1057 exception_handlers: Vec::new(),
1058 spawned_tasks: BTreeMap::new(),
1059 process_exit_request: Arc::clone(&self.process_exit_request),
1060 sync_runtime: self.sync_runtime.clone(),
1061 shared_state_runtime: self.shared_state_runtime.clone(),
1062 inline_cache_sets: Vec::new(),
1063 inline_cache_set_by_chunk: HashMap::new(),
1064 pool_registry: self.pool_registry.clone(),
1065 llm_mock_context: self.llm_mock_context.clone(),
1066 package_snapshot_registry: self.package_snapshot_registry.clone(),
1067 wait_for_graph: self.wait_for_graph.clone(),
1068 held_sync_guards: Vec::new(),
1069 inherited_held_keys: Arc::new(Vec::new()),
1070 task_scopes: Vec::new(),
1071 task_counter: 0,
1072 runtime_context_counter: self.runtime_context_counter,
1073 runtime_context: self.runtime_context.clone(),
1074 deadlines: self.deadlines.clone(),
1075 execution_deadline: self.execution_deadline.fork(),
1076 breakpoints: BTreeMap::new(),
1077 function_breakpoints: std::collections::BTreeSet::new(),
1078 pending_function_bp: None,
1079 step_mode: false,
1080 step_frame_depth: 0,
1081 stopped: false,
1082 last_line: 0,
1083 source_dir: self.source_dir.clone(),
1084 package_execution_guard: self.package_execution_guard.clone(),
1085 imported_paths: Vec::new(),
1086 deferred_cyclic_imports: Vec::new(),
1087 module_cache: Arc::clone(&self.module_cache),
1088 prepared_module_cache: self.prepared_module_cache.clone(),
1089 module_provenance: self.module_provenance,
1090 module_phase_recorder: self.module_phase_recorder.clone(),
1091 lazy_callable_modules: Arc::clone(&self.lazy_callable_modules),
1092 source_cache: Arc::clone(&self.source_cache),
1093 graph_link_table: self.graph_link_table.clone(),
1094 linked_program_repository: self.linked_program_repository.clone(),
1095 source_file: self.source_file.clone(),
1096 source_text: self.source_text.clone(),
1097 coverage: crate::coverage::for_primary(self.source_file.as_deref()),
1098 bridge: self.bridge.clone(),
1099 denied_builtins: Arc::clone(&self.denied_builtins),
1100 cancel_token: self.cancel_token.clone(),
1101 interrupt_signal_token: self.interrupt_signal_token.clone(),
1102 cancel_grace_instructions_remaining: None,
1103 interrupt_handlers: Vec::new(),
1104 next_interrupt_handle: 1,
1105 pending_interrupt_signal: None,
1106 interrupted: self.interrupted,
1107 dispatching_interrupt: false,
1108 interrupt_handler_deadline: None,
1109 error_stack_trace: Vec::new(),
1110 yield_sender: None,
1111 project_root: self.project_root.clone(),
1112 globals: Arc::clone(&self.globals),
1113 root_harness: self.root_harness.clone(),
1114 runtime_effects: crate::orchestration::RuntimeEffectState::with_shared_recorder(
1115 Arc::clone(&self.runtime_effects.recorder),
1116 ),
1117 debug_hook: None,
1118 runtime_limits: self.runtime_limits,
1119 }
1120 }
1121
1122 pub(crate) fn child_vm_for_host(&self) -> Vm {
1125 self.child_vm()
1126 }
1127
1128 pub(crate) fn interrupt_sources(
1133 &self,
1134 ) -> (
1135 Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
1136 Option<std::time::Instant>,
1137 ) {
1138 let scope_deadline = self.deadlines.last().map(|(deadline, _)| *deadline);
1139 let deadline = match (scope_deadline, self.interrupt_handler_deadline) {
1140 (Some(scope), Some(interrupt)) => Some(scope.min(interrupt)),
1141 (scope, interrupt) => scope.or(interrupt),
1142 };
1143 (self.cancel_token.clone(), deadline)
1144 }
1145
1146 pub(crate) fn request_process_exit(&self, code: i32) {
1147 self.process_exit_request.request(code);
1148 }
1149
1150 pub(crate) fn requested_process_exit(&self) -> Option<i32> {
1151 self.process_exit_request.code()
1152 }
1153
1154 pub(crate) fn cancel_spawned_tasks(&mut self) {
1158 for (_, task) in std::mem::take(&mut self.spawned_tasks) {
1159 task.cancel_token
1160 .store(true, std::sync::atomic::Ordering::SeqCst);
1161 task.handle.abort();
1162 }
1163 }
1164
1165 pub fn set_source_dir(&mut self, dir: &std::path::Path) {
1168 let dir = crate::stdlib::process::normalize_context_path(dir);
1169 self.source_dir = Some(dir.clone());
1170 crate::stdlib::set_thread_source_dir(&dir);
1171 if self.project_root.is_none() {
1173 self.project_root = crate::stdlib::process::find_project_root(&dir);
1174 }
1175 }
1176
1177 pub fn set_project_root(&mut self, root: &std::path::Path) {
1180 self.project_root = Some(root.to_path_buf());
1181 }
1182
1183 pub(crate) fn explicit_project_root(&self) -> Option<&std::path::Path> {
1186 self.project_root.as_deref()
1187 }
1188
1189 pub fn project_root(&self) -> Option<&std::path::Path> {
1191 self.project_root.as_deref().or(self.source_dir.as_deref())
1192 }
1193
1194 pub fn set_global(&mut self, name: &str, value: VmValue) {
1197 Arc::make_mut(&mut self.globals).insert(crate::value::intern_key(name), value);
1198 }
1199
1200 pub fn global(&self, name: &str) -> Option<&VmValue> {
1202 self.globals.get(name)
1203 }
1204
1205 pub fn set_harness(&mut self, harness: crate::harness::Harness) {
1209 self.root_harness = Some(harness.into_vm_value());
1210 }
1211
1212 pub(crate) fn harness(&self) -> Option<&crate::harness::VmHarness> {
1213 match self.root_harness.as_ref() {
1214 Some(VmValue::Harness(handle)) => Some(handle),
1215 _ => None,
1216 }
1217 }
1218
1219 pub fn root_harness_value(&self) -> Option<VmValue> {
1222 self.root_harness.clone()
1223 }
1224
1225 pub fn output(&self) -> &str {
1227 &self.output
1228 }
1229
1230 pub fn take_output(&mut self) -> String {
1234 std::mem::take(&mut self.output)
1235 }
1236
1237 pub fn append_output(&mut self, text: &str) {
1241 self.output.push_str(text);
1242 }
1243
1244 pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
1245 self.stack.pop().ok_or(VmError::StackUnderflow)
1246 }
1247
1248 pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
1249 self.stack.last().ok_or(VmError::StackUnderflow)
1250 }
1251
1252 pub(crate) fn const_str(c: &Constant) -> Result<&str, VmError> {
1253 match c {
1254 Constant::String(s) => Ok(s.as_str()),
1255 _ => Err(VmError::TypeError("expected string constant".into())),
1256 }
1257 }
1258
1259 pub(crate) fn release_sync_guards_for_current_scope(&mut self) {
1260 let depth = self.env.scope_depth();
1261 self.held_sync_guards
1262 .retain(|guard| guard.env_scope_depth < depth);
1263 self.cancel_task_scopes_where(|s| s.env_scope_depth >= depth);
1266 }
1267
1268 pub(crate) fn release_sync_guards_after_unwind(
1269 &mut self,
1270 frame_depth: usize,
1271 env_scope_depth: usize,
1272 ) {
1273 self.held_sync_guards.retain(|guard| {
1274 guard.frame_depth <= frame_depth && guard.env_scope_depth <= env_scope_depth
1275 });
1276 self.cancel_task_scopes_where(|s| {
1279 !(s.frame_depth <= frame_depth && s.env_scope_depth <= env_scope_depth)
1280 });
1281 }
1282
1283 pub(crate) fn release_sync_guards_for_frame(&mut self, frame_depth: usize) {
1284 self.held_sync_guards
1285 .retain(|guard| guard.frame_depth != frame_depth);
1286 self.cancel_task_scopes_where(|s| s.frame_depth == frame_depth);
1289 }
1290
1291 pub(crate) fn adopt_sync_permit_for_current_scope(
1292 &mut self,
1293 permit: crate::value::VmSyncPermitHandle,
1294 ) {
1295 if permit.is_released()
1296 || self
1297 .held_sync_guards
1298 .iter()
1299 .any(|guard| guard._permit.same_lease(&permit))
1300 {
1301 return;
1302 }
1303 self.held_sync_guards
1304 .push(crate::synchronization::VmSyncHeldGuard {
1305 _permit: permit,
1306 frame_depth: self.frames.len(),
1307 env_scope_depth: self.env.scope_depth(),
1308 });
1309 }
1310
1311 pub(crate) fn deregister_task_from_scopes(&mut self, id: &str) {
1314 for scope in &mut self.task_scopes {
1315 scope.task_ids.retain(|t| t != id);
1316 }
1317 }
1318
1319 fn cancel_task_scopes_where<F: Fn(&TaskScope) -> bool>(&mut self, doomed: F) {
1322 let mut i = 0;
1323 while i < self.task_scopes.len() {
1324 if doomed(&self.task_scopes[i]) {
1325 let scope = self.task_scopes.remove(i);
1326 for id in &scope.task_ids {
1327 if let Some(task) = self.spawned_tasks.remove(id) {
1328 task.cancel_token
1329 .store(true, std::sync::atomic::Ordering::SeqCst);
1330 task.handle.abort();
1331 }
1332 }
1333 } else {
1334 i += 1;
1335 }
1336 }
1337 }
1338
1339 pub(crate) fn held_permits_for(&self, kind: &str, key: &str) -> u32 {
1343 let own: u32 = self
1344 .held_sync_guards
1345 .iter()
1346 .filter(|guard| {
1347 !guard._permit.is_released()
1348 && guard._permit.kind() == kind
1349 && guard._permit.key() == key
1350 })
1351 .map(|guard| guard._permit.permits())
1352 .sum();
1353 let inherited: u32 = self
1354 .inherited_held_keys
1355 .iter()
1356 .filter(|held| held.kind == kind && held.key == key)
1357 .map(|held| held.permits)
1358 .sum();
1359 own + inherited
1360 }
1361
1362 pub(crate) fn combined_held_keys(&self) -> Vec<crate::synchronization::VmSyncHeldKey> {
1365 let mut keys: Vec<crate::synchronization::VmSyncHeldKey> = self
1366 .held_sync_guards
1367 .iter()
1368 .filter_map(|guard| crate::synchronization::VmSyncHeldKey::from_permit(&guard._permit))
1369 .collect();
1370 keys.extend(self.inherited_held_keys.iter().cloned());
1371 keys
1372 }
1373
1374 pub(crate) fn child_vm_inline(&self) -> Vm {
1380 let mut child = self.child_vm();
1381 child.inherited_held_keys = Arc::new(self.combined_held_keys());
1382 child.execution_deadline = Arc::clone(&self.execution_deadline);
1383 child
1384 }
1385}
1386
1387impl Drop for Vm {
1388 fn drop(&mut self) {
1389 if let Some(coverage) = self.coverage.take() {
1390 crate::coverage::merge_into_global(coverage);
1391 }
1392 self.cancel_spawned_tasks();
1393 }
1394}
1395
1396impl Default for Vm {
1397 fn default() -> Self {
1398 Self::new()
1399 }
1400}
1401
1402#[cfg(test)]
1403#[path = "state_tests.rs"]
1404mod tests;