Skip to main content

harn_vm/vm/
state.rs

1use std::collections::{BTreeMap, HashSet};
2use std::rc::Rc;
3use std::time::Instant;
4
5use crate::chunk::{Chunk, ChunkRef, Constant};
6use crate::value::{
7    ModuleFunctionRegistry, VmAsyncBuiltinFn, VmBuiltinFn, VmEnv, VmError, VmTaskHandle, VmValue,
8};
9use crate::BuiltinId;
10
11use super::debug::DebugHook;
12use super::modules::LoadedModule;
13
14/// RAII guard that starts a tracing span on creation and ends it on drop.
15pub(crate) struct ScopeSpan(u64);
16
17impl ScopeSpan {
18    pub(crate) fn new(kind: crate::tracing::SpanKind, name: String) -> Self {
19        Self(crate::tracing::span_start(kind, name))
20    }
21}
22
23impl Drop for ScopeSpan {
24    fn drop(&mut self) {
25        crate::tracing::span_end(self.0);
26    }
27}
28
29#[derive(Clone)]
30pub(crate) struct LocalSlot {
31    pub(crate) value: VmValue,
32    pub(crate) initialized: bool,
33    pub(crate) synced: bool,
34}
35
36/// Call frame for function execution.
37pub(crate) struct CallFrame {
38    pub(crate) chunk: ChunkRef,
39    pub(crate) ip: usize,
40    pub(crate) stack_base: usize,
41    pub(crate) saved_env: VmEnv,
42    /// Env snapshot captured at call-time, *after* argument binding. Used
43    /// by the debugger's `restartFrame` to rewind this frame to its
44    /// entry state (re-binding args from the original values) without
45    /// re-entering the call site. Cheap to clone because `VmEnv` is
46    /// already cloned into `saved_env` on every call. `None` for
47    /// scratch frames (evaluate, import init) where restart isn't
48    /// meaningful.
49    pub(crate) initial_env: Option<VmEnv>,
50    pub(crate) initial_local_slots: Option<Vec<LocalSlot>>,
51    /// Iterator stack depth to restore when this frame unwinds.
52    pub(crate) saved_iterator_depth: usize,
53    /// Function name for stack traces (empty for top-level pipeline).
54    pub(crate) fn_name: String,
55    /// Number of arguments actually passed by the caller (for default arg support).
56    pub(crate) argc: usize,
57    /// Saved VM_SOURCE_DIR to restore when this frame is popped.
58    /// Set when entering a closure that originated from an imported module.
59    pub(crate) saved_source_dir: Option<std::path::PathBuf>,
60    /// Module-local named functions available to symbolic calls within this frame.
61    pub(crate) module_functions: Option<ModuleFunctionRegistry>,
62    /// Shared module-level env for top-level `var` / `let` bindings of
63    /// this frame's originating module. Looked up after `self.env` and
64    /// before `self.globals` by `GetVar` / `SetVar`, giving each module
65    /// its own live static state that persists across calls. See the
66    /// `module_state` field on `VmClosure` for the full rationale.
67    pub(crate) module_state: Option<crate::value::ModuleState>,
68    /// Slot-indexed locals for compiler-resolved names in this frame.
69    pub(crate) local_slots: Vec<LocalSlot>,
70    /// Env scope index that corresponds to compiler local scope depth 0.
71    pub(crate) local_scope_base: usize,
72    /// Current compiler local scope depth, updated by PushScope/PopScope.
73    pub(crate) local_scope_depth: usize,
74}
75
76/// Exception handler for try/catch.
77pub(crate) struct ExceptionHandler {
78    pub(crate) catch_ip: usize,
79    pub(crate) stack_depth: usize,
80    pub(crate) frame_depth: usize,
81    pub(crate) env_scope_depth: usize,
82    /// If non-empty, this catch only handles errors whose enum_name matches.
83    pub(crate) error_type: String,
84}
85
86/// Iterator state for for-in loops.
87pub(crate) enum IterState {
88    Vec {
89        items: Rc<Vec<VmValue>>,
90        idx: usize,
91    },
92    Dict {
93        entries: Rc<BTreeMap<String, VmValue>>,
94        keys: Vec<String>,
95        idx: usize,
96    },
97    Channel {
98        receiver: std::sync::Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
99        closed: std::sync::Arc<std::sync::atomic::AtomicBool>,
100    },
101    Generator {
102        gen: crate::value::VmGenerator,
103    },
104    /// Step through a lazy range without materializing a Vec.
105    /// `next` holds the value to emit on the next IterNext; `stop` is
106    /// the first value that terminates the iteration (one past the end).
107    Range {
108        next: i64,
109        stop: i64,
110    },
111    VmIter {
112        handle: std::rc::Rc<std::cell::RefCell<crate::vm::iter::VmIter>>,
113    },
114}
115
116#[derive(Clone)]
117pub(crate) enum VmBuiltinDispatch {
118    Sync(VmBuiltinFn),
119    Async(VmAsyncBuiltinFn),
120}
121
122#[derive(Clone)]
123pub(crate) struct VmBuiltinEntry {
124    pub(crate) name: Rc<str>,
125    pub(crate) dispatch: VmBuiltinDispatch,
126}
127
128/// The Harn bytecode virtual machine.
129pub struct Vm {
130    pub(crate) stack: Vec<VmValue>,
131    pub(crate) env: VmEnv,
132    pub(crate) output: String,
133    pub(crate) builtins: BTreeMap<String, VmBuiltinFn>,
134    pub(crate) async_builtins: BTreeMap<String, VmAsyncBuiltinFn>,
135    /// Numeric side index for builtins. Name-keyed maps remain authoritative;
136    /// this index is the hot path for direct builtin bytecode and callback refs.
137    pub(crate) builtins_by_id: BTreeMap<BuiltinId, VmBuiltinEntry>,
138    /// IDs with detected name collisions. Collided names safely fall back to
139    /// the authoritative name-keyed lookup path.
140    pub(crate) builtin_id_collisions: HashSet<BuiltinId>,
141    /// Iterator state for for-in loops.
142    pub(crate) iterators: Vec<IterState>,
143    /// Call frame stack.
144    pub(crate) frames: Vec<CallFrame>,
145    /// Exception handler stack.
146    pub(crate) exception_handlers: Vec<ExceptionHandler>,
147    /// Spawned async task handles.
148    pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
149    /// Counter for generating unique task IDs.
150    pub(crate) task_counter: u64,
151    /// Active deadline stack: (deadline_instant, frame_depth).
152    pub(crate) deadlines: Vec<(Instant, usize)>,
153    /// Breakpoints, keyed by source-file path so a breakpoint at line N
154    /// in `auto.harn` doesn't also fire when execution hits line N in an
155    /// imported lib. The empty-string key is a wildcard used by callers
156    /// that don't track source paths (legacy `set_breakpoints` API).
157    pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
158    /// Function-name breakpoints. Any closure call whose
159    /// `CompiledFunction.name` matches an entry here raises a stop on
160    /// entry, regardless of the call site's file or line. Lets the IDE
161    /// break on `llm_call` / `host_run_pipeline` / any user pipeline
162    /// function without pinning down a source location first.
163    pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
164    /// Latched on `push_closure_frame` when the callee's name matches
165    /// `function_breakpoints`; consumed by the next step so the stop is
166    /// reported with reason="function breakpoint" and the breakpoint
167    /// name available for the DAP `stopped` event.
168    pub(crate) pending_function_bp: Option<String>,
169    /// Whether the VM is in step mode.
170    pub(crate) step_mode: bool,
171    /// The frame depth at which stepping started (for step-over).
172    pub(crate) step_frame_depth: usize,
173    /// Whether the VM is currently stopped at a debug point.
174    pub(crate) stopped: bool,
175    /// Last source line executed (to detect line changes).
176    pub(crate) last_line: usize,
177    /// Source directory for resolving imports.
178    pub(crate) source_dir: Option<std::path::PathBuf>,
179    /// Modules currently being imported (cycle prevention).
180    pub(crate) imported_paths: Vec<std::path::PathBuf>,
181    /// Loaded module cache keyed by canonical or synthetic module path.
182    pub(crate) module_cache: BTreeMap<std::path::PathBuf, LoadedModule>,
183    /// Source file path for error reporting.
184    pub(crate) source_file: Option<String>,
185    /// Source text for error reporting.
186    pub(crate) source_text: Option<String>,
187    /// Optional bridge for delegating unknown builtins in bridge mode.
188    pub(crate) bridge: Option<Rc<crate::bridge::HostBridge>>,
189    /// Builtins denied by sandbox mode (`--deny` / `--allow` flags).
190    pub(crate) denied_builtins: HashSet<String>,
191    /// Cancellation token for cooperative graceful shutdown (set by parent).
192    pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
193    /// Captured stack trace from the most recent error (fn_name, line, col).
194    pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
195    /// Yield channel sender for generator execution. When set, `Op::Yield`
196    /// sends values through this channel instead of being a no-op.
197    pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<VmValue>>,
198    /// Project root directory (detected via harn.toml).
199    /// Used as base directory for metadata, store, and checkpoint operations.
200    pub(crate) project_root: Option<std::path::PathBuf>,
201    /// Global constants (e.g. `pi`, `e`). Checked as a fallback in `GetVar`
202    /// after the environment, so user-defined variables can shadow them.
203    pub(crate) globals: BTreeMap<String, VmValue>,
204    /// Optional debugger hook invoked when execution advances to a new source line.
205    pub(crate) debug_hook: Option<Box<DebugHook>>,
206}
207
208impl Vm {
209    pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
210        chunk
211            .local_slots
212            .iter()
213            .map(|_| LocalSlot {
214                value: VmValue::Nil,
215                initialized: false,
216                synced: false,
217            })
218            .collect()
219    }
220
221    pub(crate) fn bind_param_slots(
222        slots: &mut [LocalSlot],
223        func: &crate::chunk::CompiledFunction,
224        args: &[VmValue],
225        synced: bool,
226    ) {
227        let default_start = func.default_start.unwrap_or(func.params.len());
228        let param_count = func.params.len();
229        for (i, _param) in func.params.iter().enumerate() {
230            if i >= slots.len() {
231                break;
232            }
233            if func.has_rest_param && i == param_count - 1 {
234                let rest_args = if i < args.len() {
235                    args[i..].to_vec()
236                } else {
237                    Vec::new()
238                };
239                slots[i].value = VmValue::List(Rc::new(rest_args));
240                slots[i].initialized = true;
241                slots[i].synced = synced;
242            } else if i < args.len() {
243                slots[i].value = args[i].clone();
244                slots[i].initialized = true;
245                slots[i].synced = synced;
246            } else if i < default_start {
247                slots[i].value = VmValue::Nil;
248                slots[i].initialized = true;
249                slots[i].synced = synced;
250            }
251        }
252    }
253
254    pub(crate) fn visible_variables(&self) -> BTreeMap<String, VmValue> {
255        let mut vars = self.env.all_variables();
256        let Some(frame) = self.frames.last() else {
257            return vars;
258        };
259        for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
260            if slot.initialized && info.scope_depth <= frame.local_scope_depth {
261                vars.insert(info.name.clone(), slot.value.clone());
262            }
263        }
264        vars
265    }
266
267    pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
268        let Some(frame) = self.frames.last_mut() else {
269            return;
270        };
271        let local_scope_base = frame.local_scope_base;
272        let local_scope_depth = frame.local_scope_depth;
273        let entries = frame
274            .local_slots
275            .iter_mut()
276            .zip(frame.chunk.local_slots.iter())
277            .filter_map(|(slot, info)| {
278                if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
279                    slot.synced = true;
280                    Some((
281                        local_scope_base + info.scope_depth,
282                        info.name.clone(),
283                        slot.value.clone(),
284                        info.mutable,
285                    ))
286                } else {
287                    None
288                }
289            })
290            .collect::<Vec<_>>();
291        for (scope_idx, name, value, mutable) in entries {
292            while self.env.scopes.len() <= scope_idx {
293                self.env.push_scope();
294            }
295            self.env.scopes[scope_idx]
296                .vars
297                .insert(name, (value, mutable));
298        }
299    }
300
301    pub(crate) fn closure_call_env_for_current_frame(
302        &self,
303        closure: &crate::value::VmClosure,
304    ) -> VmEnv {
305        if closure.module_state.is_some() {
306            return closure.env.clone();
307        }
308        let mut call_env = Self::closure_call_env(&self.env, closure);
309        let Some(frame) = self.frames.last() else {
310            return call_env;
311        };
312        for (slot, info) in frame
313            .local_slots
314            .iter()
315            .zip(frame.chunk.local_slots.iter())
316            .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
317        {
318            if matches!(slot.value, VmValue::Closure(_)) && call_env.get(&info.name).is_none() {
319                let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
320            }
321        }
322        call_env
323    }
324
325    pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
326        let frame = self.frames.last()?;
327        for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
328            if info.name == name && info.scope_depth <= frame.local_scope_depth {
329                let slot = frame.local_slots.get(idx)?;
330                if slot.initialized {
331                    return Some(slot.value.clone());
332                }
333            }
334        }
335        None
336    }
337
338    pub(crate) fn assign_active_local_slot(
339        &mut self,
340        name: &str,
341        value: VmValue,
342        debug: bool,
343    ) -> Result<bool, VmError> {
344        let Some(frame) = self.frames.last_mut() else {
345            return Ok(false);
346        };
347        for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
348            if info.name == name && info.scope_depth <= frame.local_scope_depth {
349                if !debug && !info.mutable {
350                    return Err(VmError::ImmutableAssignment(name.to_string()));
351                }
352                if let Some(slot) = frame.local_slots.get_mut(idx) {
353                    slot.value = value;
354                    slot.initialized = true;
355                    slot.synced = false;
356                    return Ok(true);
357                }
358            }
359        }
360        Ok(false)
361    }
362
363    pub fn new() -> Self {
364        Self {
365            stack: Vec::with_capacity(256),
366            env: VmEnv::new(),
367            output: String::new(),
368            builtins: BTreeMap::new(),
369            async_builtins: BTreeMap::new(),
370            builtins_by_id: BTreeMap::new(),
371            builtin_id_collisions: HashSet::new(),
372            iterators: Vec::new(),
373            frames: Vec::new(),
374            exception_handlers: Vec::new(),
375            spawned_tasks: BTreeMap::new(),
376            task_counter: 0,
377            deadlines: Vec::new(),
378            breakpoints: BTreeMap::new(),
379            function_breakpoints: std::collections::BTreeSet::new(),
380            pending_function_bp: None,
381            step_mode: false,
382            step_frame_depth: 0,
383            stopped: false,
384            last_line: 0,
385            source_dir: None,
386            imported_paths: Vec::new(),
387            module_cache: BTreeMap::new(),
388            source_file: None,
389            source_text: None,
390            bridge: None,
391            denied_builtins: HashSet::new(),
392            cancel_token: None,
393            error_stack_trace: Vec::new(),
394            yield_sender: None,
395            project_root: None,
396            globals: BTreeMap::new(),
397            debug_hook: None,
398        }
399    }
400
401    /// Set the bridge for delegating unknown builtins in bridge mode.
402    pub fn set_bridge(&mut self, bridge: Rc<crate::bridge::HostBridge>) {
403        self.bridge = Some(bridge);
404    }
405
406    /// Set builtins that are denied in sandbox mode.
407    /// When called, the given builtin names will produce a permission error.
408    pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
409        self.denied_builtins = denied;
410    }
411
412    /// Set source info for error reporting (file path and source text).
413    pub fn set_source_info(&mut self, file: &str, text: &str) {
414        self.source_file = Some(file.to_string());
415        self.source_text = Some(text.to_string());
416    }
417
418    /// Initialize execution (push the initial frame).
419    pub fn start(&mut self, chunk: &Chunk) {
420        let initial_env = self.env.clone();
421        self.frames.push(CallFrame {
422            chunk: Rc::new(chunk.clone()),
423            ip: 0,
424            stack_base: self.stack.len(),
425            saved_env: self.env.clone(),
426            // The top-level pipeline frame captures env at start so
427            // restartFrame on the outermost frame rewinds to the
428            // pre-pipeline state — basically "restart session" in
429            // debugger terms.
430            initial_env: Some(initial_env),
431            initial_local_slots: Some(Self::fresh_local_slots(chunk)),
432            saved_iterator_depth: self.iterators.len(),
433            fn_name: String::new(),
434            argc: 0,
435            saved_source_dir: None,
436            module_functions: None,
437            module_state: None,
438            local_slots: Self::fresh_local_slots(chunk),
439            local_scope_base: self.env.scope_depth().saturating_sub(1),
440            local_scope_depth: 0,
441        });
442    }
443
444    /// Create a child VM that shares builtins and env but has fresh execution state.
445    /// Used for parallel/spawn to fork the VM for concurrent tasks.
446    pub(crate) fn child_vm(&self) -> Vm {
447        Vm {
448            stack: Vec::with_capacity(64),
449            env: self.env.clone(),
450            output: String::new(),
451            builtins: self.builtins.clone(),
452            async_builtins: self.async_builtins.clone(),
453            builtins_by_id: self.builtins_by_id.clone(),
454            builtin_id_collisions: self.builtin_id_collisions.clone(),
455            iterators: Vec::new(),
456            frames: Vec::new(),
457            exception_handlers: Vec::new(),
458            spawned_tasks: BTreeMap::new(),
459            task_counter: 0,
460            deadlines: self.deadlines.clone(),
461            breakpoints: BTreeMap::new(),
462            function_breakpoints: std::collections::BTreeSet::new(),
463            pending_function_bp: None,
464            step_mode: false,
465            step_frame_depth: 0,
466            stopped: false,
467            last_line: 0,
468            source_dir: self.source_dir.clone(),
469            imported_paths: Vec::new(),
470            module_cache: self.module_cache.clone(),
471            source_file: self.source_file.clone(),
472            source_text: self.source_text.clone(),
473            bridge: self.bridge.clone(),
474            denied_builtins: self.denied_builtins.clone(),
475            cancel_token: self.cancel_token.clone(),
476            error_stack_trace: Vec::new(),
477            yield_sender: None,
478            project_root: self.project_root.clone(),
479            globals: self.globals.clone(),
480            debug_hook: None,
481        }
482    }
483
484    /// Create a child VM for external adapters that need to invoke Harn
485    /// closures while sharing the parent's builtins, globals, and module state.
486    pub(crate) fn child_vm_for_host(&self) -> Vm {
487        self.child_vm()
488    }
489
490    /// Set the source directory for import resolution and introspection.
491    /// Also auto-detects the project root if not already set.
492    pub fn set_source_dir(&mut self, dir: &std::path::Path) {
493        let dir = crate::stdlib::process::normalize_context_path(dir);
494        self.source_dir = Some(dir.clone());
495        crate::stdlib::set_thread_source_dir(&dir);
496        // Auto-detect project root if not explicitly set.
497        if self.project_root.is_none() {
498            self.project_root = crate::stdlib::process::find_project_root(&dir);
499        }
500    }
501
502    /// Explicitly set the project root directory.
503    /// Used by ACP/CLI to override auto-detection.
504    pub fn set_project_root(&mut self, root: &std::path::Path) {
505        self.project_root = Some(root.to_path_buf());
506    }
507
508    /// Get the project root directory, falling back to source_dir.
509    pub fn project_root(&self) -> Option<&std::path::Path> {
510        self.project_root.as_deref().or(self.source_dir.as_deref())
511    }
512
513    /// Return all registered builtin names (sync + async).
514    pub fn builtin_names(&self) -> Vec<String> {
515        let mut names: Vec<String> = self.builtins.keys().cloned().collect();
516        names.extend(self.async_builtins.keys().cloned());
517        names
518    }
519
520    /// Set a global constant (e.g. `pi`, `e`).
521    /// Stored separately from the environment so user-defined variables can shadow them.
522    pub fn set_global(&mut self, name: &str, value: VmValue) {
523        self.globals.insert(name.to_string(), value);
524    }
525
526    /// Get the captured output.
527    pub fn output(&self) -> &str {
528        &self.output
529    }
530
531    pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
532        self.stack.pop().ok_or(VmError::StackUnderflow)
533    }
534
535    pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
536        self.stack.last().ok_or(VmError::StackUnderflow)
537    }
538
539    pub(crate) fn const_string(c: &Constant) -> Result<String, VmError> {
540        match c {
541            Constant::String(s) => Ok(s.clone()),
542            _ => Err(VmError::TypeError("expected string constant".into())),
543        }
544    }
545}
546
547impl Default for Vm {
548    fn default() -> Self {
549        Self::new()
550    }
551}