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