Skip to main content

harn_vm/vm/
state.rs

1use std::collections::{BTreeMap, HashSet};
2use std::rc::Rc;
3use std::sync::Arc;
4use std::time::Instant;
5
6use crate::chunk::{Chunk, ChunkRef, Constant};
7use crate::value::{
8    ModuleFunctionRegistry, VmAsyncBuiltinFn, VmBuiltinFn, VmEnv, VmError, VmTaskHandle, VmValue,
9};
10use crate::BuiltinId;
11
12use super::debug::DebugHook;
13use super::modules::LoadedModule;
14use super::VmBuiltinMetadata;
15
16/// RAII guard that starts a tracing span on creation and ends it on drop.
17pub(crate) struct ScopeSpan(u64);
18
19impl ScopeSpan {
20    pub(crate) fn new(kind: crate::tracing::SpanKind, name: String) -> Self {
21        Self(crate::tracing::span_start(kind, name))
22    }
23}
24
25impl Drop for ScopeSpan {
26    fn drop(&mut self) {
27        crate::tracing::span_end(self.0);
28    }
29}
30
31#[derive(Clone)]
32pub(crate) struct LocalSlot {
33    pub(crate) value: VmValue,
34    pub(crate) initialized: bool,
35    pub(crate) synced: bool,
36}
37
38#[derive(Clone)]
39pub(crate) struct InterruptHandler {
40    pub(crate) handle: i64,
41    pub(crate) signals: Vec<String>,
42    pub(crate) once: bool,
43    pub(crate) graceful_timeout_ms: Option<u64>,
44    pub(crate) handler: VmValue,
45}
46
47/// Call frame for function execution.
48pub(crate) struct CallFrame {
49    pub(crate) chunk: ChunkRef,
50    pub(crate) ip: usize,
51    pub(crate) stack_base: usize,
52    pub(crate) saved_env: VmEnv,
53    /// Env snapshot captured at call-time, *after* argument binding. Used
54    /// by the debugger's `restartFrame` to rewind this frame to its
55    /// entry state (re-binding args from the original values) without
56    /// re-entering the call site. Cheap to clone because `VmEnv` is
57    /// already cloned into `saved_env` on every call. `None` for
58    /// scratch frames (evaluate, import init) where restart isn't
59    /// meaningful.
60    pub(crate) initial_env: Option<VmEnv>,
61    pub(crate) initial_local_slots: Option<Vec<LocalSlot>>,
62    /// Iterator stack depth to restore when this frame unwinds.
63    pub(crate) saved_iterator_depth: usize,
64    /// Function name for stack traces (empty for top-level pipeline).
65    pub(crate) fn_name: String,
66    /// Number of arguments actually passed by the caller (for default arg support).
67    pub(crate) argc: usize,
68    /// Saved VM_SOURCE_DIR to restore when this frame is popped.
69    /// Set when entering a closure that originated from an imported module.
70    pub(crate) saved_source_dir: Option<std::path::PathBuf>,
71    /// Module-local named functions available to symbolic calls within this frame.
72    pub(crate) module_functions: Option<ModuleFunctionRegistry>,
73    /// Shared module-level env for top-level `var` / `let` bindings of
74    /// this frame's originating module. Looked up after `self.env` and
75    /// before `self.globals` by `GetVar` / `SetVar`, giving each module
76    /// its own live static state that persists across calls. See the
77    /// `module_state` field on `VmClosure` for the full rationale.
78    pub(crate) module_state: Option<crate::value::ModuleState>,
79    /// Slot-indexed locals for compiler-resolved names in this frame.
80    pub(crate) local_slots: Vec<LocalSlot>,
81    /// Env scope index that corresponds to compiler local scope depth 0.
82    pub(crate) local_scope_base: usize,
83    /// Current compiler local scope depth, updated by PushScope/PopScope.
84    pub(crate) local_scope_depth: usize,
85}
86
87/// Exception handler for try/catch.
88pub(crate) struct ExceptionHandler {
89    pub(crate) catch_ip: usize,
90    pub(crate) stack_depth: usize,
91    pub(crate) frame_depth: usize,
92    pub(crate) env_scope_depth: usize,
93    /// If non-empty, this catch only handles errors whose enum_name matches.
94    pub(crate) error_type: String,
95}
96
97/// Iterator state for for-in loops.
98pub(crate) enum IterState {
99    Vec {
100        items: Rc<Vec<VmValue>>,
101        idx: usize,
102    },
103    Dict {
104        entries: Rc<BTreeMap<String, VmValue>>,
105        keys: Vec<String>,
106        idx: usize,
107    },
108    Channel {
109        receiver: std::sync::Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
110        closed: std::sync::Arc<std::sync::atomic::AtomicBool>,
111    },
112    Generator {
113        gen: crate::value::VmGenerator,
114    },
115    Stream {
116        stream: crate::value::VmStream,
117    },
118    /// Step through a lazy range without materializing a Vec.
119    /// Inclusive ranges keep `end` as an actual value so `i64::MAX to i64::MAX`
120    /// still yields one item instead of overflowing a one-past-end sentinel.
121    Range {
122        next: i64,
123        end: i64,
124        inclusive: bool,
125        done: bool,
126    },
127    VmIter {
128        handle: std::rc::Rc<std::cell::RefCell<crate::vm::iter::VmIter>>,
129    },
130}
131
132#[derive(Clone)]
133pub(crate) enum VmBuiltinDispatch {
134    Sync(VmBuiltinFn),
135    Async(VmAsyncBuiltinFn),
136}
137
138#[derive(Clone)]
139pub(crate) struct VmBuiltinEntry {
140    pub(crate) name: Rc<str>,
141    pub(crate) dispatch: VmBuiltinDispatch,
142}
143
144/// The Harn bytecode virtual machine.
145pub struct Vm {
146    pub(crate) stack: Vec<VmValue>,
147    pub(crate) env: VmEnv,
148    pub(crate) output: String,
149    pub(crate) builtins: Rc<BTreeMap<String, VmBuiltinFn>>,
150    pub(crate) async_builtins: Rc<BTreeMap<String, VmAsyncBuiltinFn>>,
151    pub(crate) builtin_metadata: Rc<BTreeMap<String, VmBuiltinMetadata>>,
152    /// Numeric side index for builtins. Name-keyed maps remain authoritative;
153    /// this index is the hot path for direct builtin bytecode and callback refs.
154    pub(crate) builtins_by_id: Rc<BTreeMap<BuiltinId, VmBuiltinEntry>>,
155    /// IDs with detected name collisions. Collided names safely fall back to
156    /// the authoritative name-keyed lookup path.
157    pub(crate) builtin_id_collisions: Rc<HashSet<BuiltinId>>,
158    /// Iterator state for for-in loops.
159    pub(crate) iterators: Vec<IterState>,
160    /// Call frame stack.
161    pub(crate) frames: Vec<CallFrame>,
162    /// Exception handler stack.
163    pub(crate) exception_handlers: Vec<ExceptionHandler>,
164    /// Spawned async task handles.
165    pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
166    /// Shared process-local synchronization primitives inherited by child VMs.
167    pub(crate) sync_runtime: Arc<crate::synchronization::VmSyncRuntime>,
168    /// Shared process-local cells, maps, and mailboxes inherited by child VMs.
169    pub(crate) shared_state_runtime: Rc<crate::shared_state::VmSharedStateRuntime>,
170    /// Permits acquired by lexical synchronization blocks in this VM.
171    pub(crate) held_sync_guards: Vec<crate::synchronization::VmSyncHeldGuard>,
172    /// Counter for generating unique task IDs.
173    pub(crate) task_counter: u64,
174    /// Counter for logical runtime-context task groups.
175    pub(crate) runtime_context_counter: u64,
176    /// Logical runtime task context visible through `runtime_context()`.
177    pub(crate) runtime_context: crate::runtime_context::RuntimeContext,
178    /// Active deadline stack: (deadline_instant, frame_depth).
179    pub(crate) deadlines: Vec<(Instant, usize)>,
180    /// Breakpoints, keyed by source-file path so a breakpoint at line N
181    /// in `auto.harn` doesn't also fire when execution hits line N in an
182    /// imported lib. The empty-string key is a wildcard used by callers
183    /// that don't track source paths (legacy `set_breakpoints` API).
184    pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
185    /// Function-name breakpoints. Any closure call whose
186    /// `CompiledFunction.name` matches an entry here raises a stop on
187    /// entry, regardless of the call site's file or line. Lets the IDE
188    /// break on `llm_call` / `host_run_pipeline` / any user pipeline
189    /// function without pinning down a source location first.
190    pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
191    /// Latched on `push_closure_frame` when the callee's name matches
192    /// `function_breakpoints`; consumed by the next step so the stop is
193    /// reported with reason="function breakpoint" and the breakpoint
194    /// name available for the DAP `stopped` event.
195    pub(crate) pending_function_bp: Option<String>,
196    /// Whether the VM is in step mode.
197    pub(crate) step_mode: bool,
198    /// The frame depth at which stepping started (for step-over).
199    pub(crate) step_frame_depth: usize,
200    /// Whether the VM is currently stopped at a debug point.
201    pub(crate) stopped: bool,
202    /// Last source line executed (to detect line changes).
203    pub(crate) last_line: usize,
204    /// Source directory for resolving imports.
205    pub(crate) source_dir: Option<std::path::PathBuf>,
206    /// Modules currently being imported (cycle prevention).
207    pub(crate) imported_paths: Vec<std::path::PathBuf>,
208    /// Loaded module cache keyed by canonical or synthetic module path.
209    pub(crate) module_cache: Rc<BTreeMap<std::path::PathBuf, LoadedModule>>,
210    /// Source text keyed by canonical or synthetic module path for debugger retrieval.
211    pub(crate) source_cache: Rc<BTreeMap<std::path::PathBuf, String>>,
212    /// Source file path for error reporting.
213    pub(crate) source_file: Option<String>,
214    /// Source text for error reporting.
215    pub(crate) source_text: Option<String>,
216    /// Optional bridge for delegating unknown builtins in bridge mode.
217    pub(crate) bridge: Option<Rc<crate::bridge::HostBridge>>,
218    /// Builtins denied by sandbox mode (`--deny` / `--allow` flags).
219    pub(crate) denied_builtins: Rc<HashSet<String>>,
220    /// Cancellation token for cooperative graceful shutdown (set by parent).
221    pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
222    pub(crate) interrupt_signal_token: Option<std::sync::Arc<std::sync::Mutex<Option<String>>>>,
223    /// Remaining instruction-boundary checks before a requested host
224    /// cancellation is forcefully raised. This gives `is_cancelled()` loops a
225    /// deterministic chance to return cleanly without letting non-cooperative
226    /// CPU-bound code run forever.
227    pub(crate) cancel_grace_instructions_remaining: Option<usize>,
228    /// User-visible interrupt handlers registered through `std/signal`.
229    pub(crate) interrupt_handlers: Vec<InterruptHandler>,
230    pub(crate) next_interrupt_handle: i64,
231    pub(crate) pending_interrupt_signal: Option<String>,
232    pub(crate) interrupted: bool,
233    pub(crate) dispatching_interrupt: bool,
234    pub(crate) interrupt_handler_deadline: Option<Instant>,
235    /// Captured stack trace from the most recent error (fn_name, line, col).
236    pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
237    /// Yield channel sender for generator execution. When set, `Op::Yield`
238    /// sends values through this channel instead of being a no-op.
239    pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<Result<VmValue, VmError>>>,
240    /// Project root directory (detected via harn.toml).
241    /// Used as base directory for metadata, store, and checkpoint operations.
242    pub(crate) project_root: Option<std::path::PathBuf>,
243    /// Global constants (e.g. `pi`, `e`). Checked as a fallback in `GetVar`
244    /// after the environment, so user-defined variables can shadow them.
245    pub(crate) globals: Rc<BTreeMap<String, VmValue>>,
246    /// Optional debugger hook invoked when execution advances to a new source line.
247    pub(crate) debug_hook: Option<Box<DebugHook>>,
248}
249
250/// Reusable VM baseline for hosts that need many clean executions with the
251/// same stable builtin/source setup.
252///
253/// The baseline intentionally does not snapshot execution state. Each
254/// instantiation gets fresh stacks, frames, tasks, cancellation fields, sync
255/// primitives, shared cells/maps/mailboxes, and debug state. Builtin tables are
256/// shared through `Rc` until a per-execution rebind needs copy-on-write.
257#[derive(Clone)]
258pub struct VmBaseline {
259    builtins: Rc<BTreeMap<String, VmBuiltinFn>>,
260    async_builtins: Rc<BTreeMap<String, VmAsyncBuiltinFn>>,
261    builtin_metadata: Rc<BTreeMap<String, VmBuiltinMetadata>>,
262    builtins_by_id: Rc<BTreeMap<BuiltinId, VmBuiltinEntry>>,
263    builtin_id_collisions: Rc<HashSet<BuiltinId>>,
264    source_dir: Option<std::path::PathBuf>,
265    source_file: Option<String>,
266    source_text: Option<String>,
267    project_root: Option<std::path::PathBuf>,
268    globals: Rc<BTreeMap<String, VmValue>>,
269    denied_builtins: Rc<HashSet<String>>,
270}
271
272impl VmBaseline {
273    pub fn from_vm(vm: &Vm) -> Self {
274        Self {
275            builtins: Rc::clone(&vm.builtins),
276            async_builtins: Rc::clone(&vm.async_builtins),
277            builtin_metadata: Rc::clone(&vm.builtin_metadata),
278            builtins_by_id: Rc::clone(&vm.builtins_by_id),
279            builtin_id_collisions: Rc::clone(&vm.builtin_id_collisions),
280            source_dir: vm.source_dir.clone(),
281            source_file: vm.source_file.clone(),
282            source_text: vm.source_text.clone(),
283            project_root: vm.project_root.clone(),
284            globals: Rc::clone(&vm.globals),
285            denied_builtins: Rc::clone(&vm.denied_builtins),
286        }
287    }
288
289    pub fn instantiate(&self) -> Vm {
290        let mut source_cache = BTreeMap::new();
291        if let (Some(file), Some(text)) = (&self.source_file, &self.source_text) {
292            source_cache.insert(std::path::PathBuf::from(file), text.clone());
293        }
294        if let Some(dir) = &self.source_dir {
295            crate::stdlib::set_thread_source_dir(dir);
296        }
297
298        let mut vm = Vm {
299            stack: Vec::with_capacity(256),
300            env: VmEnv::new(),
301            output: String::new(),
302            builtins: Rc::clone(&self.builtins),
303            async_builtins: Rc::clone(&self.async_builtins),
304            builtin_metadata: Rc::clone(&self.builtin_metadata),
305            builtins_by_id: Rc::clone(&self.builtins_by_id),
306            builtin_id_collisions: Rc::clone(&self.builtin_id_collisions),
307            iterators: Vec::new(),
308            frames: Vec::new(),
309            exception_handlers: Vec::new(),
310            spawned_tasks: BTreeMap::new(),
311            sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
312            shared_state_runtime: Rc::new(crate::shared_state::VmSharedStateRuntime::new()),
313            held_sync_guards: Vec::new(),
314            task_counter: 0,
315            runtime_context_counter: 0,
316            runtime_context: crate::runtime_context::RuntimeContext::root(),
317            deadlines: Vec::new(),
318            breakpoints: BTreeMap::new(),
319            function_breakpoints: std::collections::BTreeSet::new(),
320            pending_function_bp: None,
321            step_mode: false,
322            step_frame_depth: 0,
323            stopped: false,
324            last_line: 0,
325            source_dir: self.source_dir.clone(),
326            imported_paths: Vec::new(),
327            module_cache: Rc::new(BTreeMap::new()),
328            source_cache: Rc::new(source_cache),
329            source_file: self.source_file.clone(),
330            source_text: self.source_text.clone(),
331            bridge: None,
332            denied_builtins: Rc::clone(&self.denied_builtins),
333            cancel_token: None,
334            interrupt_signal_token: None,
335            cancel_grace_instructions_remaining: None,
336            interrupt_handlers: Vec::new(),
337            next_interrupt_handle: 1,
338            pending_interrupt_signal: None,
339            interrupted: false,
340            dispatching_interrupt: false,
341            interrupt_handler_deadline: None,
342            error_stack_trace: Vec::new(),
343            yield_sender: None,
344            project_root: self.project_root.clone(),
345            globals: Rc::clone(&self.globals),
346            debug_hook: None,
347        };
348
349        crate::stdlib::rebind_execution_state_builtins(&mut vm);
350        vm
351    }
352}
353
354impl Vm {
355    pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
356        chunk
357            .local_slots
358            .iter()
359            .map(|_| LocalSlot {
360                value: VmValue::Nil,
361                initialized: false,
362                synced: false,
363            })
364            .collect()
365    }
366
367    pub(crate) fn bind_param_slots(
368        slots: &mut [LocalSlot],
369        func: &crate::chunk::CompiledFunction,
370        args: &[VmValue],
371        synced: bool,
372    ) {
373        let param_count = func.params.len();
374        for (i, _param) in func.params.iter().enumerate() {
375            if i >= slots.len() {
376                break;
377            }
378            if func.has_rest_param && i == param_count - 1 {
379                let rest_args = if i < args.len() {
380                    args[i..].to_vec()
381                } else {
382                    Vec::new()
383                };
384                slots[i].value = VmValue::List(Rc::new(rest_args));
385                slots[i].initialized = true;
386                slots[i].synced = synced;
387            } else if i < args.len() {
388                slots[i].value = args[i].clone();
389                slots[i].initialized = true;
390                slots[i].synced = synced;
391            }
392        }
393    }
394
395    pub(crate) fn visible_variables(&self) -> BTreeMap<String, VmValue> {
396        let mut vars = self.env.all_variables();
397        let Some(frame) = self.frames.last() else {
398            return vars;
399        };
400        for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
401            if slot.initialized && info.scope_depth <= frame.local_scope_depth {
402                vars.insert(info.name.clone(), slot.value.clone());
403            }
404        }
405        vars
406    }
407
408    pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
409        let frames = &mut self.frames;
410        let env = &mut self.env;
411        let Some(frame) = frames.last_mut() else {
412            return;
413        };
414        let local_scope_base = frame.local_scope_base;
415        let local_scope_depth = frame.local_scope_depth;
416        for (slot, info) in frame
417            .local_slots
418            .iter_mut()
419            .zip(frame.chunk.local_slots.iter())
420        {
421            if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
422                slot.synced = true;
423                let scope_idx = local_scope_base + info.scope_depth;
424                while env.scopes.len() <= scope_idx {
425                    env.push_scope();
426                }
427                Rc::make_mut(&mut env.scopes[scope_idx].vars)
428                    .insert(info.name.clone(), (slot.value.clone(), info.mutable));
429            }
430        }
431    }
432
433    pub(crate) fn closure_call_env_for_current_frame(
434        &self,
435        closure: &crate::value::VmClosure,
436    ) -> VmEnv {
437        if closure.module_state.is_some() {
438            return closure.env.clone();
439        }
440        let mut call_env = Self::closure_call_env(&self.env, closure);
441        let Some(frame) = self.frames.last() else {
442            return call_env;
443        };
444        for (slot, info) in frame
445            .local_slots
446            .iter()
447            .zip(frame.chunk.local_slots.iter())
448            .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
449        {
450            if matches!(slot.value, VmValue::Closure(_)) && !call_env.contains(&info.name) {
451                let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
452            }
453        }
454        call_env
455    }
456
457    pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
458        let frame = self.frames.last()?;
459        let idx = self.active_local_slot_index(name)?;
460        frame.local_slots.get(idx).map(|slot| slot.value.clone())
461    }
462
463    /// Returns the slot index of an initialized active local with the given
464    /// name, walking from innermost to outermost scope. Used by hot paths
465    /// (subscript-store, etc.) that want to mutate the slot value in place
466    /// without paying a defensive `VmValue::clone` first.
467    pub(crate) fn active_local_slot_index(&self, name: &str) -> Option<usize> {
468        let frame = self.frames.last()?;
469        for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
470            if info.name == name && info.scope_depth <= frame.local_scope_depth {
471                if let Some(slot) = frame.local_slots.get(idx) {
472                    if slot.initialized {
473                        return Some(idx);
474                    }
475                }
476            }
477        }
478        None
479    }
480
481    pub(crate) fn assign_active_local_slot(
482        &mut self,
483        name: &str,
484        value: VmValue,
485        debug: bool,
486    ) -> Result<bool, VmError> {
487        let Some(frame) = self.frames.last_mut() else {
488            return Ok(false);
489        };
490        for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
491            if info.name == name && info.scope_depth <= frame.local_scope_depth {
492                if !debug && !info.mutable {
493                    return Err(VmError::ImmutableAssignment(name.to_string()));
494                }
495                if let Some(slot) = frame.local_slots.get_mut(idx) {
496                    slot.value = value;
497                    slot.initialized = true;
498                    slot.synced = false;
499                    return Ok(true);
500                }
501            }
502        }
503        Ok(false)
504    }
505
506    pub fn new() -> Self {
507        Self {
508            stack: Vec::with_capacity(256),
509            env: VmEnv::new(),
510            output: String::new(),
511            builtins: Rc::new(BTreeMap::new()),
512            async_builtins: Rc::new(BTreeMap::new()),
513            builtin_metadata: Rc::new(BTreeMap::new()),
514            builtins_by_id: Rc::new(BTreeMap::new()),
515            builtin_id_collisions: Rc::new(HashSet::new()),
516            iterators: Vec::new(),
517            frames: Vec::new(),
518            exception_handlers: Vec::new(),
519            spawned_tasks: BTreeMap::new(),
520            sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
521            shared_state_runtime: Rc::new(crate::shared_state::VmSharedStateRuntime::new()),
522            held_sync_guards: Vec::new(),
523            task_counter: 0,
524            runtime_context_counter: 0,
525            runtime_context: crate::runtime_context::RuntimeContext::root(),
526            deadlines: Vec::new(),
527            breakpoints: BTreeMap::new(),
528            function_breakpoints: std::collections::BTreeSet::new(),
529            pending_function_bp: None,
530            step_mode: false,
531            step_frame_depth: 0,
532            stopped: false,
533            last_line: 0,
534            source_dir: None,
535            imported_paths: Vec::new(),
536            module_cache: Rc::new(BTreeMap::new()),
537            source_cache: Rc::new(BTreeMap::new()),
538            source_file: None,
539            source_text: None,
540            bridge: None,
541            denied_builtins: Rc::new(HashSet::new()),
542            cancel_token: None,
543            interrupt_signal_token: None,
544            cancel_grace_instructions_remaining: None,
545            interrupt_handlers: Vec::new(),
546            next_interrupt_handle: 1,
547            pending_interrupt_signal: None,
548            interrupted: false,
549            dispatching_interrupt: false,
550            interrupt_handler_deadline: None,
551            error_stack_trace: Vec::new(),
552            yield_sender: None,
553            project_root: None,
554            globals: Rc::new(BTreeMap::new()),
555            debug_hook: None,
556        }
557    }
558
559    pub fn baseline(&self) -> VmBaseline {
560        VmBaseline::from_vm(self)
561    }
562
563    /// Returns true if any debugging affordance is active — DAP hook,
564    /// line breakpoints, or function breakpoints. Call-site code uses
565    /// this to decide whether to capture per-frame restart snapshots
566    /// (`initial_env`, `initial_local_slots`); without a debugger those
567    /// snapshots are dead weight, so skipping them removes two
568    /// allocations from every function call hot path.
569    ///
570    /// All three signals are stable across a function call's lifetime
571    /// (they're set before pipeline execution starts), so the gate is
572    /// consistent between frame creation and any later `restart_frame`
573    /// invocation. The three `is_empty` checks compile to a handful of
574    /// branch-predicted memory probes — cheaper than a single
575    /// `BTreeMap` clone, which is what we're avoiding.
576    #[inline]
577    pub(crate) fn debugger_attached(&self) -> bool {
578        self.debug_hook.is_some()
579            || !self.breakpoints.is_empty()
580            || !self.function_breakpoints.is_empty()
581    }
582
583    /// Set the bridge for delegating unknown builtins in bridge mode.
584    pub fn set_bridge(&mut self, bridge: Rc<crate::bridge::HostBridge>) {
585        self.bridge = Some(bridge);
586    }
587
588    /// Set builtins that are denied in sandbox mode.
589    /// When called, the given builtin names will produce a permission error.
590    pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
591        self.denied_builtins = Rc::new(denied);
592    }
593
594    /// Set source info for error reporting (file path and source text).
595    pub fn set_source_info(&mut self, file: &str, text: &str) {
596        self.source_file = Some(file.to_string());
597        self.source_text = Some(text.to_string());
598        Rc::make_mut(&mut self.source_cache)
599            .insert(std::path::PathBuf::from(file), text.to_string());
600    }
601
602    /// Initialize execution (push the initial frame).
603    pub fn start(&mut self, chunk: &Chunk) {
604        // The top-level pipeline frame captures env at start so
605        // restartFrame on the outermost frame rewinds to the
606        // pre-pipeline state — basically "restart session" in
607        // debugger terms. Skipped when no debugger is attached:
608        // the snapshot is dead weight in that case and dominates
609        // call-overhead bench numbers (~5-10%).
610        let debugger = self.debugger_attached();
611        let initial_env = if debugger {
612            Some(self.env.clone())
613        } else {
614            None
615        };
616        let initial_local_slots = if debugger {
617            Some(Self::fresh_local_slots(chunk))
618        } else {
619            None
620        };
621        self.frames.push(CallFrame {
622            chunk: Rc::new(chunk.clone()),
623            ip: 0,
624            stack_base: self.stack.len(),
625            saved_env: self.env.clone(),
626            initial_env,
627            initial_local_slots,
628            saved_iterator_depth: self.iterators.len(),
629            fn_name: String::new(),
630            argc: 0,
631            saved_source_dir: None,
632            module_functions: None,
633            module_state: None,
634            local_slots: Self::fresh_local_slots(chunk),
635            local_scope_base: self.env.scope_depth().saturating_sub(1),
636            local_scope_depth: 0,
637        });
638    }
639
640    /// Create a child VM that shares builtins and env but has fresh execution state.
641    /// Used for parallel/spawn to fork the VM for concurrent tasks.
642    pub(crate) fn child_vm(&self) -> Vm {
643        Vm {
644            stack: Vec::with_capacity(64),
645            env: self.env.clone(),
646            output: String::new(),
647            builtins: Rc::clone(&self.builtins),
648            async_builtins: Rc::clone(&self.async_builtins),
649            builtin_metadata: Rc::clone(&self.builtin_metadata),
650            builtins_by_id: Rc::clone(&self.builtins_by_id),
651            builtin_id_collisions: Rc::clone(&self.builtin_id_collisions),
652            iterators: Vec::new(),
653            frames: Vec::new(),
654            exception_handlers: Vec::new(),
655            spawned_tasks: BTreeMap::new(),
656            sync_runtime: self.sync_runtime.clone(),
657            shared_state_runtime: self.shared_state_runtime.clone(),
658            held_sync_guards: Vec::new(),
659            task_counter: 0,
660            runtime_context_counter: self.runtime_context_counter,
661            runtime_context: self.runtime_context.clone(),
662            deadlines: self.deadlines.clone(),
663            breakpoints: BTreeMap::new(),
664            function_breakpoints: std::collections::BTreeSet::new(),
665            pending_function_bp: None,
666            step_mode: false,
667            step_frame_depth: 0,
668            stopped: false,
669            last_line: 0,
670            source_dir: self.source_dir.clone(),
671            imported_paths: Vec::new(),
672            module_cache: Rc::clone(&self.module_cache),
673            source_cache: Rc::clone(&self.source_cache),
674            source_file: self.source_file.clone(),
675            source_text: self.source_text.clone(),
676            bridge: self.bridge.clone(),
677            denied_builtins: Rc::clone(&self.denied_builtins),
678            cancel_token: self.cancel_token.clone(),
679            interrupt_signal_token: self.interrupt_signal_token.clone(),
680            cancel_grace_instructions_remaining: None,
681            interrupt_handlers: Vec::new(),
682            next_interrupt_handle: 1,
683            pending_interrupt_signal: None,
684            interrupted: self.interrupted,
685            dispatching_interrupt: false,
686            interrupt_handler_deadline: None,
687            error_stack_trace: Vec::new(),
688            yield_sender: None,
689            project_root: self.project_root.clone(),
690            globals: Rc::clone(&self.globals),
691            debug_hook: None,
692        }
693    }
694
695    /// Create a child VM for external adapters that need to invoke Harn
696    /// closures while sharing the parent's builtins, globals, and module state.
697    pub(crate) fn child_vm_for_host(&self) -> Vm {
698        self.child_vm()
699    }
700
701    /// Request cancellation for every outstanding child task owned by this VM
702    /// and then abort the join handles. This prevents un-awaited spawned tasks
703    /// from outliving their parent execution scope.
704    pub(crate) fn cancel_spawned_tasks(&mut self) {
705        for (_, task) in std::mem::take(&mut self.spawned_tasks) {
706            task.cancel_token
707                .store(true, std::sync::atomic::Ordering::SeqCst);
708            task.handle.abort();
709        }
710    }
711
712    /// Set the source directory for import resolution and introspection.
713    /// Also auto-detects the project root if not already set.
714    pub fn set_source_dir(&mut self, dir: &std::path::Path) {
715        let dir = crate::stdlib::process::normalize_context_path(dir);
716        self.source_dir = Some(dir.clone());
717        crate::stdlib::set_thread_source_dir(&dir);
718        // Auto-detect project root if not explicitly set.
719        if self.project_root.is_none() {
720            self.project_root = crate::stdlib::process::find_project_root(&dir);
721        }
722    }
723
724    /// Explicitly set the project root directory.
725    /// Used by ACP/CLI to override auto-detection.
726    pub fn set_project_root(&mut self, root: &std::path::Path) {
727        self.project_root = Some(root.to_path_buf());
728    }
729
730    /// Get the project root directory, falling back to source_dir.
731    pub fn project_root(&self) -> Option<&std::path::Path> {
732        self.project_root.as_deref().or(self.source_dir.as_deref())
733    }
734
735    /// Return all registered builtin names (sync + async).
736    pub fn builtin_names(&self) -> Vec<String> {
737        let mut names: Vec<String> = self.builtins.keys().cloned().collect();
738        names.extend(self.async_builtins.keys().cloned());
739        names
740    }
741
742    /// Return discoverable metadata for registered builtins.
743    pub fn builtin_metadata(&self) -> Vec<VmBuiltinMetadata> {
744        self.builtin_metadata.values().cloned().collect()
745    }
746
747    /// Return discoverable metadata for a registered builtin name.
748    pub fn builtin_metadata_for(&self, name: &str) -> Option<&VmBuiltinMetadata> {
749        self.builtin_metadata.get(name)
750    }
751
752    /// Set a global constant (e.g. `pi`, `e`).
753    /// Stored separately from the environment so user-defined variables can shadow them.
754    pub fn set_global(&mut self, name: &str, value: VmValue) {
755        Rc::make_mut(&mut self.globals).insert(name.to_string(), value);
756    }
757
758    /// Install the script's `Harness` capability handle as the `harness`
759    /// global so the auto-call emitted by `Compiler::compile()` (for
760    /// `fn main(harness: Harness)` entrypoints) can read it. Hosts that
761    /// drive the VM directly (CLI, MCP server, composition runtime) call
762    /// this once before `execute()`.
763    pub fn set_harness(&mut self, harness: crate::harness::Harness) {
764        self.set_global("harness", harness.into_vm_value());
765    }
766
767    /// Get the captured output.
768    pub fn output(&self) -> &str {
769        &self.output
770    }
771
772    /// Drain and return the captured output, leaving the buffer empty.
773    /// Used by the async-builtin dispatch path to forward closure output
774    /// from a child VM back to its parent.
775    pub fn take_output(&mut self) -> String {
776        std::mem::take(&mut self.output)
777    }
778
779    /// Append text to this VM's captured output. Used to forward output
780    /// from child VMs (e.g. closures invoked via `call_closure_pub`)
781    /// back into the parent stream.
782    pub fn append_output(&mut self, text: &str) {
783        self.output.push_str(text);
784    }
785
786    pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
787        self.stack.pop().ok_or(VmError::StackUnderflow)
788    }
789
790    pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
791        self.stack.last().ok_or(VmError::StackUnderflow)
792    }
793
794    pub(crate) fn const_string(c: &Constant) -> Result<String, VmError> {
795        match c {
796            Constant::String(s) => Ok(s.clone()),
797            _ => Err(VmError::TypeError("expected string constant".into())),
798        }
799    }
800
801    pub(crate) fn const_str(c: &Constant) -> Result<&str, VmError> {
802        match c {
803            Constant::String(s) => Ok(s.as_str()),
804            _ => Err(VmError::TypeError("expected string constant".into())),
805        }
806    }
807
808    pub(crate) fn release_sync_guards_for_current_scope(&mut self) {
809        let depth = self.env.scope_depth();
810        self.held_sync_guards
811            .retain(|guard| guard.env_scope_depth < depth);
812    }
813
814    pub(crate) fn release_sync_guards_after_unwind(
815        &mut self,
816        frame_depth: usize,
817        env_scope_depth: usize,
818    ) {
819        self.held_sync_guards.retain(|guard| {
820            guard.frame_depth <= frame_depth && guard.env_scope_depth <= env_scope_depth
821        });
822    }
823
824    pub(crate) fn release_sync_guards_for_frame(&mut self, frame_depth: usize) {
825        self.held_sync_guards
826            .retain(|guard| guard.frame_depth != frame_depth);
827    }
828}
829
830impl Drop for Vm {
831    fn drop(&mut self) {
832        self.cancel_spawned_tasks();
833    }
834}
835
836impl Default for Vm {
837    fn default() -> Self {
838        Self::new()
839    }
840}
841
842#[cfg(test)]
843mod tests {
844    use std::rc::Rc;
845
846    use super::*;
847
848    fn baseline_with_stdlib(source: &str) -> VmBaseline {
849        let mut vm = Vm::new();
850        crate::register_vm_stdlib(&mut vm);
851        vm.set_source_info("baseline_test.harn", source);
852        vm.set_global("stable_global", VmValue::String(Rc::from("baseline")));
853        vm.baseline()
854    }
855
856    #[test]
857    fn vm_baseline_instantiates_clean_mutable_execution_state() {
858        let baseline = baseline_with_stdlib("pipeline main() { println(stable_global) }");
859
860        let mut dirty = baseline.instantiate();
861        dirty.stack.push(VmValue::Int(42));
862        dirty.output.push_str("dirty");
863        dirty.task_counter = 9;
864        dirty.runtime_context_counter = 7;
865        dirty
866            .error_stack_trace
867            .push(("main".to_string(), 1, 1, None));
868
869        let clean = baseline.instantiate();
870        assert!(clean.stack.is_empty());
871        assert!(clean.output.is_empty());
872        assert!(clean.frames.is_empty());
873        assert!(clean.exception_handlers.is_empty());
874        assert!(clean.spawned_tasks.is_empty());
875        assert!(clean.held_sync_guards.is_empty());
876        assert_eq!(clean.task_counter, 0);
877        assert_eq!(clean.runtime_context_counter, 0);
878        assert!(clean.deadlines.is_empty());
879        assert!(clean.cancel_token.is_none());
880        assert!(clean.interrupt_handlers.is_empty());
881        assert!(clean.error_stack_trace.is_empty());
882        assert!(clean.bridge.is_none());
883        assert!(clean
884            .globals
885            .get("stable_global")
886            .is_some_and(|value| value.display() == "baseline"));
887    }
888
889    #[tokio::test(flavor = "current_thread")]
890    async fn vm_baseline_rebinds_shared_state_builtins_per_instance() {
891        let local = tokio::task::LocalSet::new();
892        local
893            .run_until(async {
894                let source = r#"
895pipeline main() {
896  let cell = shared_cell({scope: "task_group", key: "turn", initial: 0})
897  println(shared_get(cell))
898  shared_set(cell, shared_get(cell) + 1)
899}"#;
900                let chunk = crate::compile_source(source).expect("compile");
901                let baseline = baseline_with_stdlib(source);
902
903                let mut first = baseline.instantiate();
904                first.execute(&chunk).await.expect("first execute");
905                assert_eq!(first.output(), "0\n");
906
907                let mut second = baseline.instantiate();
908                second.execute(&chunk).await.expect("second execute");
909                assert_eq!(
910                    second.output(),
911                    "0\n",
912                    "shared state created by the first VM must not leak into the next baseline instance"
913                );
914            })
915            .await;
916    }
917}