Skip to main content

harn_vm/
vm.rs

1mod format;
2mod imports;
3pub mod iter;
4mod methods;
5mod ops;
6
7use std::cell::RefCell;
8use std::collections::{BTreeMap, HashSet};
9use std::future::Future;
10use std::pin::Pin;
11use std::rc::Rc;
12use std::time::Instant;
13
14use crate::chunk::{Chunk, CompiledFunction, Constant};
15use crate::value::{
16    ErrorCategory, ModuleFunctionRegistry, VmAsyncBuiltinFn, VmBuiltinFn, VmClosure, VmEnv,
17    VmError, VmTaskHandle, VmValue,
18};
19
20thread_local! {
21    static CURRENT_ASYNC_BUILTIN_CHILD_VM: RefCell<Vec<Vm>> = const { RefCell::new(Vec::new()) };
22}
23
24/// RAII guard that starts a tracing span on creation and ends it on drop.
25struct ScopeSpan(u64);
26
27impl ScopeSpan {
28    fn new(kind: crate::tracing::SpanKind, name: String) -> Self {
29        Self(crate::tracing::span_start(kind, name))
30    }
31}
32
33impl Drop for ScopeSpan {
34    fn drop(&mut self) {
35        crate::tracing::span_end(self.0);
36    }
37}
38
39/// Call frame for function execution.
40pub(crate) struct CallFrame {
41    pub(crate) chunk: Chunk,
42    pub(crate) ip: usize,
43    pub(crate) stack_base: usize,
44    pub(crate) saved_env: VmEnv,
45    /// Env snapshot captured at call-time, *after* argument binding. Used
46    /// by the debugger's `restartFrame` to rewind this frame to its
47    /// entry state (re-binding args from the original values) without
48    /// re-entering the call site. Cheap to clone because `VmEnv` is
49    /// already cloned into `saved_env` on every call. `None` for
50    /// scratch frames (evaluate, import init) where restart isn't
51    /// meaningful.
52    pub(crate) initial_env: Option<VmEnv>,
53    /// Iterator stack depth to restore when this frame unwinds.
54    pub(crate) saved_iterator_depth: usize,
55    /// Function name for stack traces (empty for top-level pipeline).
56    pub(crate) fn_name: String,
57    /// Number of arguments actually passed by the caller (for default arg support).
58    pub(crate) argc: usize,
59    /// Saved VM_SOURCE_DIR to restore when this frame is popped.
60    /// Set when entering a closure that originated from an imported module.
61    pub(crate) saved_source_dir: Option<std::path::PathBuf>,
62    /// Module-local named functions available to symbolic calls within this frame.
63    pub(crate) module_functions: Option<ModuleFunctionRegistry>,
64    /// Shared module-level env for top-level `var` / `let` bindings of
65    /// this frame's originating module. Looked up after `self.env` and
66    /// before `self.globals` by `GetVar` / `SetVar`, giving each module
67    /// its own live static state that persists across calls. See the
68    /// `module_state` field on `VmClosure` for the full rationale.
69    pub(crate) module_state: Option<crate::value::ModuleState>,
70}
71
72/// Exception handler for try/catch.
73pub(crate) struct ExceptionHandler {
74    pub(crate) catch_ip: usize,
75    pub(crate) stack_depth: usize,
76    pub(crate) frame_depth: usize,
77    pub(crate) env_scope_depth: usize,
78    /// If non-empty, this catch only handles errors whose enum_name matches.
79    pub(crate) error_type: String,
80}
81
82/// Debug action returned by the debug hook.
83#[derive(Debug, Clone, PartialEq)]
84pub enum DebugAction {
85    /// Continue execution normally.
86    Continue,
87    /// Stop (breakpoint hit, step complete).
88    Stop,
89}
90
91/// Information about current execution state for the debugger.
92#[derive(Debug, Clone)]
93pub struct DebugState {
94    pub line: usize,
95    pub variables: BTreeMap<String, VmValue>,
96    pub frame_name: String,
97    pub frame_depth: usize,
98}
99
100type DebugHook = dyn FnMut(&DebugState) -> DebugAction;
101
102/// Iterator state for for-in loops: either a pre-collected vec, an async channel, or a generator.
103pub(crate) enum IterState {
104    Vec {
105        items: Vec<VmValue>,
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    /// Step through a lazy range without materializing a Vec.
116    /// `next` holds the value to emit on the next IterNext; `stop` is
117    /// the first value that terminates the iteration (one past the end).
118    Range {
119        next: i64,
120        stop: i64,
121    },
122    VmIter {
123        handle: std::rc::Rc<std::cell::RefCell<crate::vm::iter::VmIter>>,
124    },
125}
126
127#[derive(Clone)]
128pub(crate) struct LoadedModule {
129    pub(crate) functions: BTreeMap<String, Rc<VmClosure>>,
130    pub(crate) public_names: HashSet<String>,
131}
132
133/// The Harn bytecode virtual machine.
134pub struct Vm {
135    pub(crate) stack: Vec<VmValue>,
136    pub(crate) env: VmEnv,
137    pub(crate) output: String,
138    pub(crate) builtins: BTreeMap<String, VmBuiltinFn>,
139    pub(crate) async_builtins: BTreeMap<String, VmAsyncBuiltinFn>,
140    /// Iterator state for for-in loops.
141    pub(crate) iterators: Vec<IterState>,
142    /// Call frame stack.
143    pub(crate) frames: Vec<CallFrame>,
144    /// Exception handler stack.
145    pub(crate) exception_handlers: Vec<ExceptionHandler>,
146    /// Spawned async task handles.
147    pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
148    /// Counter for generating unique task IDs.
149    pub(crate) task_counter: u64,
150    /// Active deadline stack: (deadline_instant, frame_depth).
151    pub(crate) deadlines: Vec<(Instant, usize)>,
152    /// Breakpoints, keyed by source-file path so a breakpoint at line N
153    /// in `auto.harn` doesn't also fire when execution hits line N in an
154    /// imported lib. The empty-string key is a wildcard used by callers
155    /// that don't track source paths (legacy `set_breakpoints` API).
156    pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
157    /// Function-name breakpoints. Any closure call whose
158    /// `CompiledFunction.name` matches an entry here raises a stop on
159    /// entry, regardless of the call site's file or line. Lets the IDE
160    /// break on `llm_call` / `host_run_pipeline` / any user pipeline
161    /// function without pinning down a source location first.
162    pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
163    /// Latched on `push_closure_frame` when the callee's name matches
164    /// `function_breakpoints`; consumed by the next step so the stop is
165    /// reported with reason="function breakpoint" and the breakpoint
166    /// name available for the DAP `stopped` event.
167    pub(crate) pending_function_bp: Option<String>,
168    /// Whether the VM is in step mode.
169    pub(crate) step_mode: bool,
170    /// The frame depth at which stepping started (for step-over).
171    pub(crate) step_frame_depth: usize,
172    /// Whether the VM is currently stopped at a debug point.
173    pub(crate) stopped: bool,
174    /// Last source line executed (to detect line changes).
175    pub(crate) last_line: usize,
176    /// Source directory for resolving imports.
177    pub(crate) source_dir: Option<std::path::PathBuf>,
178    /// Modules currently being imported (cycle prevention).
179    pub(crate) imported_paths: Vec<std::path::PathBuf>,
180    /// Loaded module cache keyed by canonical or synthetic module path.
181    pub(crate) module_cache: BTreeMap<std::path::PathBuf, LoadedModule>,
182    /// Source file path for error reporting.
183    pub(crate) source_file: Option<String>,
184    /// Source text for error reporting.
185    pub(crate) source_text: Option<String>,
186    /// Optional bridge for delegating unknown builtins in bridge mode.
187    pub(crate) bridge: Option<Rc<crate::bridge::HostBridge>>,
188    /// Builtins denied by sandbox mode (`--deny` / `--allow` flags).
189    pub(crate) denied_builtins: HashSet<String>,
190    /// Cancellation token for cooperative graceful shutdown (set by parent).
191    pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
192    /// Captured stack trace from the most recent error (fn_name, line, col).
193    pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
194    /// Yield channel sender for generator execution. When set, `Op::Yield`
195    /// sends values through this channel instead of being a no-op.
196    pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<VmValue>>,
197    /// Project root directory (detected via harn.toml).
198    /// Used as base directory for metadata, store, and checkpoint operations.
199    pub(crate) project_root: Option<std::path::PathBuf>,
200    /// Global constants (e.g. `pi`, `e`). Checked as a fallback in `GetVar`
201    /// after the environment, so user-defined variables can shadow them.
202    pub(crate) globals: BTreeMap<String, VmValue>,
203    /// Optional debugger hook invoked when execution advances to a new source line.
204    pub(crate) debug_hook: Option<Box<DebugHook>>,
205}
206
207impl Vm {
208    pub fn new() -> Self {
209        Self {
210            stack: Vec::with_capacity(256),
211            env: VmEnv::new(),
212            output: String::new(),
213            builtins: BTreeMap::new(),
214            async_builtins: BTreeMap::new(),
215            iterators: Vec::new(),
216            frames: Vec::new(),
217            exception_handlers: Vec::new(),
218            spawned_tasks: BTreeMap::new(),
219            task_counter: 0,
220            deadlines: Vec::new(),
221            breakpoints: BTreeMap::new(),
222            function_breakpoints: std::collections::BTreeSet::new(),
223            pending_function_bp: None,
224            step_mode: false,
225            step_frame_depth: 0,
226            stopped: false,
227            last_line: 0,
228            source_dir: None,
229            imported_paths: Vec::new(),
230            module_cache: BTreeMap::new(),
231            source_file: None,
232            source_text: None,
233            bridge: None,
234            denied_builtins: HashSet::new(),
235            cancel_token: None,
236            error_stack_trace: Vec::new(),
237            yield_sender: None,
238            project_root: None,
239            globals: BTreeMap::new(),
240            debug_hook: None,
241        }
242    }
243
244    /// Set the bridge for delegating unknown builtins in bridge mode.
245    pub fn set_bridge(&mut self, bridge: Rc<crate::bridge::HostBridge>) {
246        self.bridge = Some(bridge);
247    }
248
249    /// Set builtins that are denied in sandbox mode.
250    /// When called, the given builtin names will produce a permission error.
251    pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
252        self.denied_builtins = denied;
253    }
254
255    /// Set source info for error reporting (file path and source text).
256    pub fn set_source_info(&mut self, file: &str, text: &str) {
257        self.source_file = Some(file.to_string());
258        self.source_text = Some(text.to_string());
259    }
260
261    /// Replace breakpoints for a single source file. Pass an empty string
262    /// (or call `set_breakpoints` for the wildcard equivalent) to install
263    /// breakpoints that match every file — useful for ad-hoc CLI runs
264    /// where the embedder doesn't track per-file source paths.
265    pub fn set_breakpoints_for_file(&mut self, file: &str, lines: Vec<usize>) {
266        if lines.is_empty() {
267            self.breakpoints.remove(file);
268            return;
269        }
270        self.breakpoints
271            .insert(file.to_string(), lines.into_iter().collect());
272    }
273
274    /// Backwards-compatible wildcard form. Stores all lines under the
275    /// empty-string key, which matches *any* source file at the check
276    /// site. Existing embedders that don't track file scoping still work.
277    pub fn set_breakpoints(&mut self, lines: Vec<usize>) {
278        self.set_breakpoints_for_file("", lines);
279    }
280
281    /// Replace the function-breakpoint set. Every subsequent closure
282    /// call whose name matches one of the provided strings will pause
283    /// on entry. Empty vec clears the set.
284    pub fn set_function_breakpoints(&mut self, names: Vec<String>) {
285        self.function_breakpoints = names.into_iter().collect();
286        // Clear any pending latch so a stale entry from the previous
287        // configuration doesn't fire once.
288        self.pending_function_bp = None;
289    }
290
291    /// Returns the current function-breakpoint name set. Used by the
292    /// DAP adapter to build the `setFunctionBreakpoints` response with
293    /// verified=true per registered name.
294    pub fn function_breakpoint_names(&self) -> Vec<String> {
295        self.function_breakpoints.iter().cloned().collect()
296    }
297
298    /// Drain any pending function-breakpoint name latched by the most
299    /// recent closure entry. Returns `Some(name)` exactly once per hit
300    /// so the caller can emit a single `stopped` event.
301    pub fn take_pending_function_bp(&mut self) -> Option<String> {
302        self.pending_function_bp.take()
303    }
304
305    /// Source file path of the currently executing frame, if known.
306    pub(crate) fn current_source_file(&self) -> Option<&str> {
307        self.frames
308            .last()
309            .and_then(|f| f.chunk.source_file.as_deref())
310    }
311
312    /// True when a breakpoint at `line` is set for the current frame's
313    /// source file (or the wildcard set covers it).
314    pub(crate) fn breakpoint_matches(&self, line: usize) -> bool {
315        if let Some(wild) = self.breakpoints.get("") {
316            if wild.contains(&line) {
317                return true;
318            }
319        }
320        if let Some(file) = self.current_source_file() {
321            if let Some(set) = self.breakpoints.get(file) {
322                if set.contains(&line) {
323                    return true;
324                }
325            }
326            // Some callers send a relative or differently-prefixed path
327            // than the chunk records; fall back to suffix comparison so
328            // foo.harn matches /abs/path/foo.harn and vice-versa.
329            for (key, set) in &self.breakpoints {
330                if key.is_empty() {
331                    continue;
332                }
333                if (file.ends_with(key.as_str()) || key.ends_with(file)) && set.contains(&line) {
334                    return true;
335                }
336            }
337        }
338        false
339    }
340
341    /// Enable step mode (stop at the next source line regardless of
342    /// frame depth — i.e. step-in semantics, descending into calls).
343    pub fn set_step_mode(&mut self, step: bool) {
344        self.step_mode = step;
345        self.step_frame_depth = usize::MAX;
346    }
347
348    /// Enable step-over mode (stop at the next source line in the current
349    /// frame or a shallower one, skipping past any nested calls).
350    pub fn set_step_over(&mut self) {
351        self.step_mode = true;
352        self.step_frame_depth = self.frames.len();
353    }
354
355    /// Register a debug hook invoked whenever execution advances to a new source line.
356    pub fn set_debug_hook<F>(&mut self, hook: F)
357    where
358        F: FnMut(&DebugState) -> DebugAction + 'static,
359    {
360        self.debug_hook = Some(Box::new(hook));
361    }
362
363    /// Clear the current debug hook.
364    pub fn clear_debug_hook(&mut self) {
365        self.debug_hook = None;
366    }
367
368    /// Enable step-out mode (stop at the next source line *after* the
369    /// current frame has returned — strictly shallower than where the
370    /// user requested the step-out).
371    pub fn set_step_out(&mut self) {
372        self.step_mode = true;
373        // Condition site compares `frames.len() <= step_frame_depth`, so
374        // storing N-1 makes the stop fire only after the current frame
375        // pops (frames.len() drops from N to N-1 or less). Clamp to 0 for
376        // the top frame — caller handles that via the usize::MAX sentinel
377        // if they wanted step-in semantics.
378        self.step_frame_depth = self.frames.len().saturating_sub(1);
379    }
380
381    /// Check if the VM is stopped at a debug point.
382    pub fn is_stopped(&self) -> bool {
383        self.stopped
384    }
385
386    /// Get the current debug state (variables, line, etc.).
387    pub fn debug_state(&self) -> DebugState {
388        let line = self.current_line();
389        let variables = self.env.all_variables();
390        let frame_name = if self.frames.len() > 1 {
391            format!("frame_{}", self.frames.len() - 1)
392        } else {
393            "pipeline".to_string()
394        };
395        DebugState {
396            line,
397            variables,
398            frame_name,
399            frame_depth: self.frames.len(),
400        }
401    }
402
403    /// Call sites (name + ip) on `line` within the current frame's
404    /// chunk — drives DAP `stepInTargets` (#112). Walks the chunk's
405    /// parallel lines array, surfaces every Call / MethodCall /
406    /// CallSpread and pairs it with the name of the constant or
407    /// identifier preceding the call when we can derive it cheaply.
408    pub fn call_sites_on_line(&self, line: u32) -> Vec<(u32, String)> {
409        let Some(frame) = self.frames.last() else {
410            return Vec::new();
411        };
412        let chunk = &frame.chunk;
413        let mut out = Vec::new();
414        let code = &chunk.code;
415        let lines = &chunk.lines;
416        let mut ip: usize = 0;
417        while ip < code.len() {
418            let op = code[ip];
419            if ip < lines.len() && lines[ip] == line {
420                // 0x00 .. 0x99 covers the opcode space the compiler
421                // emits for calls. Rather than decode every op, we
422                // pattern-match on the Call-family opcodes via
423                // their numeric tag — stable because harn-vm locks
424                // opcodes with pin tests.
425                if matches!(op, 0x40..=0x44) {
426                    // Best-effort label: take the most recent
427                    // LoadConst / LoadGlobal constant value.
428                    let label = Self::label_preceding_call(chunk, ip);
429                    out.push((ip as u32, label));
430                }
431            }
432            ip += 1;
433        }
434        out
435    }
436
437    fn label_preceding_call(chunk: &crate::chunk::Chunk, call_ip: usize) -> String {
438        // Walk backwards a few instructions to find a LoadConst that
439        // resolves to a string (the callee name). Good enough for
440        // the IDE menu; deep callee resolution can land later if
441        // needed.
442        let mut back = call_ip.saturating_sub(6);
443        while back < call_ip {
444            let op = chunk.code[back];
445            // LoadConst opcodes (range covers the two-byte tag) —
446            // fall back to "call" when none found.
447            if (op == 0x01 || op == 0x02) && back + 2 < chunk.code.len() {
448                let idx = (u16::from(chunk.code[back + 1]) << 8) | u16::from(chunk.code[back + 2]);
449                if let Some(crate::chunk::Constant::String(s)) = chunk.constants.get(idx as usize) {
450                    return s.clone();
451                }
452            }
453            back += 1;
454        }
455        "call".to_string()
456    }
457
458    /// Install (or replace) the cooperative cancellation token on
459    /// this VM. Callers (DAP adapter, embedded host) flip the
460    /// wrapped AtomicBool to request graceful shutdown; the step
461    /// loop checks `is_cancel_requested()` at every instruction and
462    /// exits with `VmError::Cancelled` when set.
463    pub fn install_cancel_token(&mut self, token: std::sync::Arc<std::sync::atomic::AtomicBool>) {
464        self.cancel_token = Some(token);
465    }
466
467    /// Signal cooperative cancellation on this VM — the step loop
468    /// unwinds on its next instruction check. Lazily allocates a
469    /// fresh token when none is installed so hosts don't need to
470    /// pre-plumb it on every launch. Returns the Arc so the caller
471    /// can hold onto it and re-signal later if needed.
472    pub fn signal_cancel(&mut self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
473        let token = self.cancel_token.clone().unwrap_or_else(|| {
474            let t = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
475            self.cancel_token = Some(t.clone());
476            t
477        });
478        token.store(true, std::sync::atomic::Ordering::SeqCst);
479        token
480    }
481
482    /// True when cooperative cancellation has been requested.
483    pub fn is_cancel_requested(&self) -> bool {
484        self.cancel_token
485            .as_ref()
486            .map(|t| t.load(std::sync::atomic::Ordering::SeqCst))
487            .unwrap_or(false)
488    }
489
490    /// Identifiers visible at the given frame's scope — locals plus
491    /// every registered builtin + async builtin. Drives DAP
492    /// `completions` (#109) so the REPL autocomplete surfaces
493    /// everything the unified evaluator can reach.
494    pub fn identifiers_in_scope(&self, _frame_id: usize) -> Vec<String> {
495        let mut out: Vec<String> = self.env.all_variables().keys().cloned().collect();
496        out.extend(self.builtins.keys().cloned());
497        out.extend(self.async_builtins.keys().cloned());
498        out.sort();
499        out.dedup();
500        out
501    }
502
503    /// Get all stack frames for the debugger.
504    pub fn debug_stack_frames(&self) -> Vec<(String, usize)> {
505        let mut frames = Vec::new();
506        for (i, frame) in self.frames.iter().enumerate() {
507            let line = if frame.ip > 0 && frame.ip - 1 < frame.chunk.lines.len() {
508                frame.chunk.lines[frame.ip - 1] as usize
509            } else {
510                0
511            };
512            let name = if frame.fn_name.is_empty() {
513                if i == 0 {
514                    "pipeline".to_string()
515                } else {
516                    format!("fn_{}", i)
517                }
518            } else {
519                frame.fn_name.clone()
520            };
521            frames.push((name, line));
522        }
523        frames
524    }
525
526    /// Get the current source line.
527    fn current_line(&self) -> usize {
528        if let Some(frame) = self.frames.last() {
529            let ip = if frame.ip > 0 { frame.ip - 1 } else { 0 };
530            if ip < frame.chunk.lines.len() {
531                return frame.chunk.lines[ip] as usize;
532            }
533        }
534        0
535    }
536
537    /// Execute one instruction, returning whether to stop (breakpoint/step).
538    /// Returns Ok(None) to continue, Ok(Some(val)) on program end, Err on error.
539    ///
540    /// Line-change detection reads the line of the instruction we're
541    /// *about to execute* (`lines[ip]`) rather than the byte before
542    /// `ip`. After a jump, `ip-1` still points into the skipped region,
543    /// which previously reported phantom stops on the tail of a
544    /// not-taken branch (e.g. `host_metadata_save()` highlighted even
545    /// though `any_stale` was false). Using `lines[ip]` — combined with
546    /// cleanup ops emitted at line 0 after branch/loop exits — keeps
547    /// the debugger aligned with what's actually going to run.
548    pub async fn step_execute(&mut self) -> Result<Option<(VmValue, bool)>, VmError> {
549        // Cooperative cancellation (#108): the DAP adapter flips the
550        // shared flag when the IDE presses the Stop pill. Check here
551        // before any instruction work so the loop unwinds promptly
552        // on the next tick.
553        if self.is_cancel_requested() {
554            return Err(VmError::Thrown(VmValue::String(std::rc::Rc::from(
555                "kind:cancelled:VM cancelled by host",
556            ))));
557        }
558        let current_line = self.upcoming_line();
559        let line_changed = current_line != self.last_line && current_line > 0;
560
561        if line_changed {
562            self.last_line = current_line;
563
564            let state = self.debug_state();
565            if let Some(hook) = self.debug_hook.as_mut() {
566                if matches!(hook(&state), DebugAction::Stop) {
567                    self.stopped = true;
568                    return Ok(Some((VmValue::Nil, true)));
569                }
570            }
571
572            if self.breakpoint_matches(current_line) {
573                self.stopped = true;
574                return Ok(Some((VmValue::Nil, true)));
575            }
576
577            // Function-breakpoint latch: set by push_closure_frame when
578            // the callee's name is in `function_breakpoints`. Stop with
579            // the same shape as a line BP so the DAP adapter's
580            // classify_breakpoint_hit emits a standard stopped event.
581            if self.pending_function_bp.is_some() {
582                self.stopped = true;
583                return Ok(Some((VmValue::Nil, true)));
584            }
585
586            // step_frame_depth is the deepest frame count at which a stop
587            // is acceptable. set_step_mode uses usize::MAX (any depth,
588            // step-in), set_step_over uses N (same frame or shallower),
589            // set_step_out uses N-1 (strictly shallower than where the
590            // step-out was requested).
591            if self.step_mode && self.frames.len() <= self.step_frame_depth {
592                self.step_mode = false;
593                self.stopped = true;
594                return Ok(Some((VmValue::Nil, true)));
595            }
596        }
597
598        self.stopped = false;
599        self.execute_one_cycle().await
600    }
601
602    /// Line of the instruction *about to execute* — used by the
603    /// debugger for line-change detection so the first cycle after a
604    /// jump doesn't report a stale line from the skipped region.
605    fn upcoming_line(&self) -> usize {
606        if let Some(frame) = self.frames.last() {
607            if frame.ip < frame.chunk.lines.len() {
608                return frame.chunk.lines[frame.ip] as usize;
609            }
610        }
611        0
612    }
613
614    /// Number of live call frames. Used by the DAP adapter to
615    /// translate stackTrace ids (1-based, innermost first) back to
616    /// the VM's 0-based outermost-first index when processing
617    /// `restartFrame`.
618    pub fn frame_count(&self) -> usize {
619        self.frames.len()
620    }
621
622    /// Rewind the given frame to its entry state so stepping resumes
623    /// from the first instruction of the function with the original
624    /// arguments re-bound. Higher frames above `frame_id` are dropped.
625    /// Returns an error if the frame has no captured `initial_env`
626    /// (scratch / evaluator frames don't) or if the id is out of range.
627    ///
628    /// Side effects already performed by the restarted frame (tool
629    /// calls, file writes, host_call round-trips) are *not* rolled
630    /// back — DAP leaves that to the adapter's discretion. The IDE
631    /// should warn on frames whose source text contains obvious
632    /// side-effectful calls before invoking restartFrame.
633    pub fn restart_frame(&mut self, frame_id: usize) -> Result<(), VmError> {
634        if frame_id >= self.frames.len() {
635            return Err(VmError::Runtime(format!(
636                "restartFrame: frame id {frame_id} out of range (have {} frames)",
637                self.frames.len()
638            )));
639        }
640        let Some(initial_env) = self.frames[frame_id].initial_env.clone() else {
641            return Err(VmError::Runtime(
642                "restartFrame: target frame was not captured for restart (scratch / evaluator frame)".into(),
643            ));
644        };
645        // Drop every frame above the target. Each pop restores its
646        // saved_iterator_depth into `self.iterators` so iterator state
647        // unwinds consistently.
648        while self.frames.len() > frame_id + 1 {
649            let popped = self.frames.pop().expect("bounds checked above");
650            self.iterators.truncate(popped.saved_iterator_depth);
651        }
652        // Rewind the target frame.
653        let frame = self
654            .frames
655            .last_mut()
656            .expect("frame_id within bounds guarantees a frame");
657        frame.ip = 0;
658        let stack_base = frame.stack_base;
659        let saved_iter_depth = frame.saved_iterator_depth;
660        self.stack.truncate(stack_base);
661        self.iterators.truncate(saved_iter_depth);
662        self.env = initial_env;
663        self.last_line = 0;
664        self.stopped = false;
665        Ok(())
666    }
667
668    /// Assign a new value to a named binding in the paused VM's env.
669    /// Returns the value that was actually stored (after coercion, if
670    /// the VM performed any) so the caller can echo it back to the
671    /// DAP client. Fails if the name does not resolve to a mutable
672    /// binding in any live scope.
673    ///
674    /// The provided `value_expr` goes through the unified evaluator so
675    /// callers can type expressions like `plan.tasks.len() + 1` in the
676    /// Locals inline-edit field, not just literals.
677    pub async fn set_variable_in_frame(
678        &mut self,
679        name: &str,
680        value_expr: &str,
681        frame_id: usize,
682    ) -> Result<VmValue, VmError> {
683        let value = self.evaluate_in_frame(value_expr, frame_id).await?;
684        // Debug-specific assign: bypasses the `let` immutability gate
685        // because the user is explicitly editing in the IDE, and
686        // almost every pipeline binding is `let`. The underlying
687        // binding's mutability flag is preserved so runtime behavior
688        // after the override is unchanged.
689        self.env
690            .assign_debug(name, value.clone())
691            .map_err(|e| match e {
692                VmError::UndefinedVariable(n) => {
693                    VmError::Runtime(format!("setVariable: '{n}' is not in the current scope"))
694                }
695                other => other,
696            })?;
697        Ok(value)
698    }
699
700    /// Evaluate a Harn expression against the currently paused frame's
701    /// scope and return its value. This is the single evaluation path
702    /// used by hover tips, watch expressions, conditional breakpoints,
703    /// logpoint interpolation, and `setVariable` / `setExpression`
704    /// before we had a unified evaluator there were four separate
705    /// mini-parsers, each with its own rough edges (see burin-code #85).
706    ///
707    /// The expression is wrapped as `let __r = (<expr>)` so arbitrary
708    /// infix chains, ternaries, and access paths parse uniformly. A
709    /// scratch `CallFrame` runs the wrapped bytecode with `saved_env`
710    /// pointing at the caller's env, so the compiled expression sees
711    /// every local in scope. When the scratch frame pops, the caller's
712    /// env is automatically restored.
713    ///
714    /// A fixed instruction budget guards against runaway expressions
715    /// (infinite loops, accidental recursion) wedging the debugger.
716    /// Side effects — including `llm_call`, `host_*`, and file mutators
717    /// — are not blocked here; callers that invoke this for read-only
718    /// surfaces (hover, watch) should reject obviously-side-effectful
719    /// expressions before calling.
720    pub async fn evaluate_in_frame(
721        &mut self,
722        expr: &str,
723        _frame_id: usize,
724    ) -> Result<VmValue, VmError> {
725        let trimmed = expr.trim();
726        if trimmed.is_empty() {
727            return Err(VmError::Runtime("evaluate: empty expression".into()));
728        }
729
730        // Wrap as a pipeline whose body *returns* the expression. The
731        // explicit `return` compiles to `push value + Op::Return`, and
732        // Op::Return's frame-exit path pushes that value onto the
733        // caller's stack — which is where we read it from below.
734        // Avoids the script-mode compile path that trails a Pop+Nil
735        // sequence after every expression statement, which would
736        // clobber the result before we could capture it.
737        let wrapped = format!("pipeline default() {{\n  return ({trimmed})\n}}\n");
738        let program = harn_parser::check_source_strict(&wrapped)
739            .map_err(|e| VmError::Runtime(format!("evaluate: parse error: {e}")))?;
740        let mut chunk = crate::compiler::Compiler::new()
741            .compile(&program)
742            .map_err(|e| VmError::Runtime(format!("evaluate: compile error: {e}")))?;
743        // Inherit the current frame's source file so any runtime error
744        // enriched with `(line N)` attributes cleanly.
745        if let Some(current) = self.frames.last() {
746            chunk.source_file = current.chunk.source_file.clone();
747        }
748
749        // Snapshot every piece of VM state the scratch frame could
750        // perturb. Evaluation MUST be transparent: step state, scope
751        // depth, iterator depth, and the line-change baseline all
752        // restore on exit so the paused session continues exactly as
753        // before the user typed an expression into the REPL.
754        let saved_stack_len = self.stack.len();
755        let saved_frame_count = self.frames.len();
756        let saved_iter_depth = self.iterators.len();
757        let saved_scope_depth = self.env.scope_depth();
758        let saved_last_line = self.last_line;
759        let saved_step_mode = self.step_mode;
760        let saved_step_frame_depth = self.step_frame_depth;
761        let saved_stopped = self.stopped;
762        let saved_env = self.env.clone();
763
764        // Disable stepping during evaluation; otherwise the debug hook
765        // would fire on every synthetic line and block the pause UI.
766        self.step_mode = false;
767        self.stopped = false;
768
769        self.frames.push(CallFrame {
770            chunk,
771            ip: 0,
772            stack_base: saved_stack_len,
773            saved_env,
774            // Scratch evaluator frames never accept restartFrame — the
775            // REPL/watch user expects read-only inspection semantics,
776            // not replay — so skip the clone.
777            initial_env: None,
778            saved_iterator_depth: saved_iter_depth,
779            fn_name: "<eval>".to_string(),
780            argc: 0,
781            saved_source_dir: self.source_dir.clone(),
782            module_functions: None,
783            module_state: None,
784        });
785
786        // Drive one op at a time with a fixed budget. A pure expression
787        // is typically < 20 instructions; 10k gives plenty of headroom
788        // for e.g. a list comprehension without letting a bad loop
789        // hang the debugger forever.
790        const MAX_EVAL_STEPS: usize = 10_000;
791        let mut err: Option<VmError> = None;
792        for _ in 0..MAX_EVAL_STEPS {
793            if self.frames.len() <= saved_frame_count {
794                break;
795            }
796            match self.execute_one_cycle().await {
797                Ok(_) => {
798                    if self.frames.len() <= saved_frame_count {
799                        break;
800                    }
801                }
802                Err(e) => {
803                    err = Some(e);
804                    break;
805                }
806            }
807        }
808
809        // Read the result before restoring the stack — frame exit
810        // pushes the last-computed value onto the caller's stack, so
811        // it sits at `saved_stack_len` if execution completed cleanly.
812        let result = if self.stack.len() > saved_stack_len {
813            Some(self.stack[saved_stack_len].clone())
814        } else {
815            None
816        };
817
818        // Unconditional cleanup so a mid-execution error doesn't leak
819        // scratch state into the live session.
820        self.frames.truncate(saved_frame_count);
821        self.stack.truncate(saved_stack_len);
822        self.iterators.truncate(saved_iter_depth);
823        self.env.truncate_scopes(saved_scope_depth);
824        self.last_line = saved_last_line;
825        self.step_mode = saved_step_mode;
826        self.step_frame_depth = saved_step_frame_depth;
827        self.stopped = saved_stopped;
828
829        if let Some(e) = err {
830            return Err(e);
831        }
832        result.ok_or_else(|| {
833            VmError::Runtime(
834                "evaluate: step budget exceeded before the expression produced a value".into(),
835            )
836        })
837    }
838
839    async fn execute_one_cycle(&mut self) -> Result<Option<(VmValue, bool)>, VmError> {
840        if let Some(&(deadline, _)) = self.deadlines.last() {
841            if Instant::now() > deadline {
842                self.deadlines.pop();
843                let err = VmError::Thrown(VmValue::String(Rc::from("Deadline exceeded")));
844                match self.handle_error(err) {
845                    Ok(None) => return Ok(None),
846                    Ok(Some(val)) => return Ok(Some((val, false))),
847                    Err(e) => return Err(e),
848                }
849            }
850        }
851
852        let frame = match self.frames.last_mut() {
853            Some(f) => f,
854            None => {
855                let val = self.stack.pop().unwrap_or(VmValue::Nil);
856                return Ok(Some((val, false)));
857            }
858        };
859
860        if frame.ip >= frame.chunk.code.len() {
861            let val = self.stack.pop().unwrap_or(VmValue::Nil);
862            let popped_frame = self.frames.pop().unwrap();
863            if self.frames.is_empty() {
864                return Ok(Some((val, false)));
865            } else {
866                self.iterators.truncate(popped_frame.saved_iterator_depth);
867                self.env = popped_frame.saved_env;
868                self.stack.truncate(popped_frame.stack_base);
869                self.stack.push(val);
870                return Ok(None);
871            }
872        }
873
874        let op = frame.chunk.code[frame.ip];
875        frame.ip += 1;
876
877        match self.execute_op(op).await {
878            Ok(Some(val)) => Ok(Some((val, false))),
879            Ok(None) => Ok(None),
880            Err(VmError::Return(val)) => {
881                if let Some(popped_frame) = self.frames.pop() {
882                    if let Some(ref dir) = popped_frame.saved_source_dir {
883                        crate::stdlib::set_thread_source_dir(dir);
884                    }
885                    let current_depth = self.frames.len();
886                    self.exception_handlers
887                        .retain(|h| h.frame_depth <= current_depth);
888                    if self.frames.is_empty() {
889                        return Ok(Some((val, false)));
890                    }
891                    self.iterators.truncate(popped_frame.saved_iterator_depth);
892                    self.env = popped_frame.saved_env;
893                    self.stack.truncate(popped_frame.stack_base);
894                    self.stack.push(val);
895                    Ok(None)
896                } else {
897                    Ok(Some((val, false)))
898                }
899            }
900            Err(e) => {
901                if self.error_stack_trace.is_empty() {
902                    self.error_stack_trace = self.capture_stack_trace();
903                }
904                match self.handle_error(e) {
905                    Ok(None) => {
906                        self.error_stack_trace.clear();
907                        Ok(None)
908                    }
909                    Ok(Some(val)) => Ok(Some((val, false))),
910                    Err(e) => Err(self.enrich_error_with_line(e)),
911                }
912            }
913        }
914    }
915
916    /// Initialize execution (push the initial frame).
917    pub fn start(&mut self, chunk: &Chunk) {
918        let initial_env = self.env.clone();
919        self.frames.push(CallFrame {
920            chunk: chunk.clone(),
921            ip: 0,
922            stack_base: self.stack.len(),
923            saved_env: self.env.clone(),
924            // The top-level pipeline frame captures env at start so
925            // restartFrame on the outermost frame rewinds to the
926            // pre-pipeline state — basically "restart session" in
927            // debugger terms.
928            initial_env: Some(initial_env),
929            saved_iterator_depth: self.iterators.len(),
930            fn_name: String::new(),
931            argc: 0,
932            saved_source_dir: None,
933            module_functions: None,
934            module_state: None,
935        });
936    }
937
938    /// Register a sync builtin function.
939    pub fn register_builtin<F>(&mut self, name: &str, f: F)
940    where
941        F: Fn(&[VmValue], &mut String) -> Result<VmValue, VmError> + 'static,
942    {
943        self.builtins.insert(name.to_string(), Rc::new(f));
944    }
945
946    /// Remove a sync builtin (so an async version can take precedence).
947    pub fn unregister_builtin(&mut self, name: &str) {
948        self.builtins.remove(name);
949    }
950
951    /// Register an async builtin function.
952    pub fn register_async_builtin<F, Fut>(&mut self, name: &str, f: F)
953    where
954        F: Fn(Vec<VmValue>) -> Fut + 'static,
955        Fut: Future<Output = Result<VmValue, VmError>> + 'static,
956    {
957        self.async_builtins
958            .insert(name.to_string(), Rc::new(move |args| Box::pin(f(args))));
959    }
960
961    /// Create a child VM that shares builtins and env but has fresh execution state.
962    /// Used for parallel/spawn to fork the VM for concurrent tasks.
963    fn child_vm(&self) -> Vm {
964        Vm {
965            stack: Vec::with_capacity(64),
966            env: self.env.clone(),
967            output: String::new(),
968            builtins: self.builtins.clone(),
969            async_builtins: self.async_builtins.clone(),
970            iterators: Vec::new(),
971            frames: Vec::new(),
972            exception_handlers: Vec::new(),
973            spawned_tasks: BTreeMap::new(),
974            task_counter: 0,
975            deadlines: self.deadlines.clone(),
976            breakpoints: BTreeMap::new(),
977            function_breakpoints: std::collections::BTreeSet::new(),
978            pending_function_bp: None,
979            step_mode: false,
980            step_frame_depth: 0,
981            stopped: false,
982            last_line: 0,
983            source_dir: self.source_dir.clone(),
984            imported_paths: Vec::new(),
985            module_cache: self.module_cache.clone(),
986            source_file: self.source_file.clone(),
987            source_text: self.source_text.clone(),
988            bridge: self.bridge.clone(),
989            denied_builtins: self.denied_builtins.clone(),
990            cancel_token: None,
991            error_stack_trace: Vec::new(),
992            yield_sender: None,
993            project_root: self.project_root.clone(),
994            globals: self.globals.clone(),
995            debug_hook: None,
996        }
997    }
998
999    /// Set the source directory for import resolution and introspection.
1000    /// Also auto-detects the project root if not already set.
1001    pub fn set_source_dir(&mut self, dir: &std::path::Path) {
1002        self.source_dir = Some(dir.to_path_buf());
1003        crate::stdlib::set_thread_source_dir(dir);
1004        // Auto-detect project root if not explicitly set.
1005        if self.project_root.is_none() {
1006            self.project_root = crate::stdlib::process::find_project_root(dir);
1007        }
1008    }
1009
1010    /// Explicitly set the project root directory.
1011    /// Used by ACP/CLI to override auto-detection.
1012    pub fn set_project_root(&mut self, root: &std::path::Path) {
1013        self.project_root = Some(root.to_path_buf());
1014    }
1015
1016    /// Get the project root directory, falling back to source_dir.
1017    pub fn project_root(&self) -> Option<&std::path::Path> {
1018        self.project_root.as_deref().or(self.source_dir.as_deref())
1019    }
1020
1021    /// Return all registered builtin names (sync + async).
1022    pub fn builtin_names(&self) -> Vec<String> {
1023        let mut names: Vec<String> = self.builtins.keys().cloned().collect();
1024        names.extend(self.async_builtins.keys().cloned());
1025        names
1026    }
1027
1028    /// Set a global constant (e.g. `pi`, `e`).
1029    /// Stored separately from the environment so user-defined variables can shadow them.
1030    pub fn set_global(&mut self, name: &str, value: VmValue) {
1031        self.globals.insert(name.to_string(), value);
1032    }
1033
1034    /// Get the captured output.
1035    pub fn output(&self) -> &str {
1036        &self.output
1037    }
1038
1039    /// Execute a compiled chunk.
1040    pub async fn execute(&mut self, chunk: &Chunk) -> Result<VmValue, VmError> {
1041        let span_id = crate::tracing::span_start(crate::tracing::SpanKind::Pipeline, "main".into());
1042        let result = self.run_chunk(chunk).await;
1043        crate::tracing::span_end(span_id);
1044        result
1045    }
1046
1047    /// Convert a VmError into either a handled exception (returning Ok) or a propagated error.
1048    fn handle_error(&mut self, error: VmError) -> Result<Option<VmValue>, VmError> {
1049        let thrown_value = match &error {
1050            VmError::Thrown(v) => v.clone(),
1051            other => VmValue::String(Rc::from(other.to_string())),
1052        };
1053
1054        if let Some(handler) = self.exception_handlers.pop() {
1055            if !handler.error_type.is_empty() {
1056                // Typed catch: only match when the thrown enum's type equals the declared type.
1057                let matches = match &thrown_value {
1058                    VmValue::EnumVariant { enum_name, .. } => *enum_name == handler.error_type,
1059                    _ => false,
1060                };
1061                if !matches {
1062                    return self.handle_error(error);
1063                }
1064            }
1065
1066            while self.frames.len() > handler.frame_depth {
1067                if let Some(frame) = self.frames.pop() {
1068                    if let Some(ref dir) = frame.saved_source_dir {
1069                        crate::stdlib::set_thread_source_dir(dir);
1070                    }
1071                    self.iterators.truncate(frame.saved_iterator_depth);
1072                    self.env = frame.saved_env;
1073                }
1074            }
1075
1076            // Drop deadlines that belonged to unwound frames.
1077            while self
1078                .deadlines
1079                .last()
1080                .is_some_and(|d| d.1 > handler.frame_depth)
1081            {
1082                self.deadlines.pop();
1083            }
1084
1085            self.env.truncate_scopes(handler.env_scope_depth);
1086
1087            self.stack.truncate(handler.stack_depth);
1088            self.stack.push(thrown_value);
1089
1090            if let Some(frame) = self.frames.last_mut() {
1091                frame.ip = handler.catch_ip;
1092            }
1093
1094            Ok(None)
1095        } else {
1096            Err(error)
1097        }
1098    }
1099
1100    async fn run_chunk(&mut self, chunk: &Chunk) -> Result<VmValue, VmError> {
1101        self.run_chunk_entry(chunk, 0, None, None, None).await
1102    }
1103
1104    async fn run_chunk_entry(
1105        &mut self,
1106        chunk: &Chunk,
1107        argc: usize,
1108        saved_source_dir: Option<std::path::PathBuf>,
1109        module_functions: Option<ModuleFunctionRegistry>,
1110        module_state: Option<crate::value::ModuleState>,
1111    ) -> Result<VmValue, VmError> {
1112        let initial_env = self.env.clone();
1113        self.frames.push(CallFrame {
1114            chunk: chunk.clone(),
1115            ip: 0,
1116            stack_base: self.stack.len(),
1117            saved_env: self.env.clone(),
1118            initial_env: Some(initial_env),
1119            saved_iterator_depth: self.iterators.len(),
1120            fn_name: String::new(),
1121            argc,
1122            saved_source_dir,
1123            module_functions,
1124            module_state,
1125        });
1126
1127        loop {
1128            if let Some(&(deadline, _)) = self.deadlines.last() {
1129                if Instant::now() > deadline {
1130                    self.deadlines.pop();
1131                    let err = VmError::Thrown(VmValue::String(Rc::from("Deadline exceeded")));
1132                    match self.handle_error(err) {
1133                        Ok(None) => continue,
1134                        Ok(Some(val)) => return Ok(val),
1135                        Err(e) => return Err(e),
1136                    }
1137                }
1138            }
1139
1140            let frame = match self.frames.last_mut() {
1141                Some(f) => f,
1142                None => return Ok(self.stack.pop().unwrap_or(VmValue::Nil)),
1143            };
1144
1145            if frame.ip >= frame.chunk.code.len() {
1146                let val = self.stack.pop().unwrap_or(VmValue::Nil);
1147                let popped_frame = self.frames.pop().unwrap();
1148                if let Some(ref dir) = popped_frame.saved_source_dir {
1149                    crate::stdlib::set_thread_source_dir(dir);
1150                }
1151
1152                if self.frames.is_empty() {
1153                    return Ok(val);
1154                } else {
1155                    self.iterators.truncate(popped_frame.saved_iterator_depth);
1156                    self.env = popped_frame.saved_env;
1157                    self.stack.truncate(popped_frame.stack_base);
1158                    self.stack.push(val);
1159                    continue;
1160                }
1161            }
1162
1163            let op = frame.chunk.code[frame.ip];
1164            frame.ip += 1;
1165
1166            match self.execute_op(op).await {
1167                Ok(Some(val)) => return Ok(val),
1168                Ok(None) => continue,
1169                Err(VmError::Return(val)) => {
1170                    if let Some(popped_frame) = self.frames.pop() {
1171                        if let Some(ref dir) = popped_frame.saved_source_dir {
1172                            crate::stdlib::set_thread_source_dir(dir);
1173                        }
1174                        let current_depth = self.frames.len();
1175                        self.exception_handlers
1176                            .retain(|h| h.frame_depth <= current_depth);
1177
1178                        if self.frames.is_empty() {
1179                            return Ok(val);
1180                        }
1181                        self.iterators.truncate(popped_frame.saved_iterator_depth);
1182                        self.env = popped_frame.saved_env;
1183                        self.stack.truncate(popped_frame.stack_base);
1184                        self.stack.push(val);
1185                    } else {
1186                        return Ok(val);
1187                    }
1188                }
1189                Err(e) => {
1190                    // Capture stack trace before error handling unwinds frames.
1191                    if self.error_stack_trace.is_empty() {
1192                        self.error_stack_trace = self.capture_stack_trace();
1193                    }
1194                    match self.handle_error(e) {
1195                        Ok(None) => {
1196                            self.error_stack_trace.clear();
1197                            continue;
1198                        }
1199                        Ok(Some(val)) => return Ok(val),
1200                        Err(e) => return Err(self.enrich_error_with_line(e)),
1201                    }
1202                }
1203            }
1204        }
1205    }
1206
1207    /// Capture the current call stack as (fn_name, line, col, source_file) tuples.
1208    fn capture_stack_trace(&self) -> Vec<(String, usize, usize, Option<String>)> {
1209        self.frames
1210            .iter()
1211            .map(|f| {
1212                let idx = if f.ip > 0 { f.ip - 1 } else { 0 };
1213                let line = f.chunk.lines.get(idx).copied().unwrap_or(0) as usize;
1214                let col = f.chunk.columns.get(idx).copied().unwrap_or(0) as usize;
1215                (f.fn_name.clone(), line, col, f.chunk.source_file.clone())
1216            })
1217            .collect()
1218    }
1219
1220    /// Enrich a VmError with source line information from the captured stack
1221    /// trace. Appends ` (line N)` to error variants whose messages don't
1222    /// already carry location context.
1223    fn enrich_error_with_line(&self, error: VmError) -> VmError {
1224        // Determine the line from the captured stack trace (innermost frame).
1225        let line = self
1226            .error_stack_trace
1227            .last()
1228            .map(|(_, l, _, _)| *l)
1229            .unwrap_or_else(|| self.current_line());
1230        if line == 0 {
1231            return error;
1232        }
1233        let suffix = format!(" (line {line})");
1234        match error {
1235            VmError::Runtime(msg) => VmError::Runtime(format!("{msg}{suffix}")),
1236            VmError::TypeError(msg) => VmError::TypeError(format!("{msg}{suffix}")),
1237            VmError::DivisionByZero => VmError::Runtime(format!("Division by zero{suffix}")),
1238            VmError::UndefinedVariable(name) => {
1239                VmError::Runtime(format!("Undefined variable: {name}{suffix}"))
1240            }
1241            VmError::UndefinedBuiltin(name) => {
1242                VmError::Runtime(format!("Undefined builtin: {name}{suffix}"))
1243            }
1244            VmError::ImmutableAssignment(name) => VmError::Runtime(format!(
1245                "Cannot assign to immutable binding: {name}{suffix}"
1246            )),
1247            VmError::StackOverflow => {
1248                VmError::Runtime(format!("Stack overflow: too many nested calls{suffix}"))
1249            }
1250            // Leave these untouched:
1251            // - Thrown: user-thrown errors should not be silently modified
1252            // - CategorizedError: structured errors for agent orchestration
1253            // - Return: control flow, not a real error
1254            // - StackUnderflow / InvalidInstruction: internal VM bugs
1255            other => other,
1256        }
1257    }
1258
1259    const MAX_FRAMES: usize = 512;
1260
1261    /// Build the call-time env for a closure invocation.
1262    ///
1263    /// Harn is **lexically scoped for data**: a closure sees exactly the
1264    /// data names it captured at creation time, plus its parameters,
1265    /// plus names from its originating module's `module_state`, plus
1266    /// the module-function registry. The caller's *data* locals are
1267    /// intentionally not visible — that would be dynamic scoping, which
1268    /// is neither what Harn's TS-flavored surface suggests to users nor
1269    /// something real stdlib code relies on.
1270    ///
1271    /// **Exception: closure-typed bindings.** Function *names* are
1272    /// late-bound, Python-`LOAD_GLOBAL`-style. When a local recursive
1273    /// fn is declared in a pipeline body (or inside another function),
1274    /// the closure is created BEFORE its own name is defined in the
1275    /// enclosing scope, so `closure.env` captures a snapshot that is
1276    /// missing the self-reference. To make `fn fact(n) { fact(n-1) }`
1277    /// work without a letrec trick, we merge closure-typed entries
1278    /// from the caller's scope stack — but only closure-typed ones.
1279    /// Data locals are never leaked across call boundaries, so the
1280    /// surprising "caller's variable magically visible in callee"
1281    /// semantic is ruled out.
1282    ///
1283    /// Imported module closures have `module_state` set, at which
1284    /// point the full lexical environment is already available via
1285    /// `closure.env` + `module_state`, and we skip the closure merge
1286    /// entirely as a fast path. This is the hot path for context-
1287    /// builder workloads (~65% of VM CPU before this optimization).
1288    fn closure_call_env(caller_env: &VmEnv, closure: &VmClosure) -> VmEnv {
1289        if closure.module_state.is_some() {
1290            return closure.env.clone();
1291        }
1292        let mut call_env = closure.env.clone();
1293        // Late-bind only closure-typed names from the caller — enough
1294        // for local recursive / mutually-recursive fns to self-reference
1295        // without leaking caller-local data into the callee.
1296        for scope in &caller_env.scopes {
1297            for (name, (val, mutable)) in &scope.vars {
1298                if matches!(val, VmValue::Closure(_)) && call_env.get(name).is_none() {
1299                    let _ = call_env.define(name, val.clone(), *mutable);
1300                }
1301            }
1302        }
1303        call_env
1304    }
1305
1306    fn resolve_named_closure(&self, name: &str) -> Option<Rc<VmClosure>> {
1307        if let Some(VmValue::Closure(closure)) = self.env.get(name) {
1308            return Some(closure);
1309        }
1310        self.frames
1311            .last()
1312            .and_then(|frame| frame.module_functions.as_ref())
1313            .and_then(|registry| registry.borrow().get(name).cloned())
1314    }
1315
1316    /// Push a new call frame for a closure invocation.
1317    fn push_closure_frame(
1318        &mut self,
1319        closure: &VmClosure,
1320        args: &[VmValue],
1321        _parent_functions: &[CompiledFunction],
1322    ) -> Result<(), VmError> {
1323        if self.frames.len() >= Self::MAX_FRAMES {
1324            return Err(VmError::StackOverflow);
1325        }
1326        let saved_env = self.env.clone();
1327
1328        // If this closure originated from an imported module, switch
1329        // the thread-local source dir so that render() and other
1330        // source-relative builtins resolve relative to the module.
1331        let saved_source_dir = if let Some(ref dir) = closure.source_dir {
1332            let prev = crate::stdlib::process::VM_SOURCE_DIR.with(|sd| sd.borrow().clone());
1333            crate::stdlib::set_thread_source_dir(dir);
1334            prev
1335        } else {
1336            None
1337        };
1338
1339        let mut call_env = Self::closure_call_env(&saved_env, closure);
1340        call_env.push_scope();
1341
1342        let default_start = closure
1343            .func
1344            .default_start
1345            .unwrap_or(closure.func.params.len());
1346        let param_count = closure.func.params.len();
1347        for (i, param) in closure.func.params.iter().enumerate() {
1348            if closure.func.has_rest_param && i == param_count - 1 {
1349                // Rest parameter: collect remaining args into a list
1350                let rest_args = if i < args.len() {
1351                    args[i..].to_vec()
1352                } else {
1353                    Vec::new()
1354                };
1355                let _ = call_env.define(param, VmValue::List(std::rc::Rc::new(rest_args)), false);
1356            } else if i < args.len() {
1357                let _ = call_env.define(param, args[i].clone(), false);
1358            } else if i < default_start {
1359                let _ = call_env.define(param, VmValue::Nil, false);
1360            }
1361        }
1362
1363        // Snapshot the env *after* argument binding so restartFrame
1364        // can rewind this function to its entry state with the same
1365        // args re-applied. Cheap relative to the call itself.
1366        let initial_env = call_env.clone();
1367        self.env = call_env;
1368
1369        // Function-name breakpoint latch: record the name so the step
1370        // loop can raise a single "function breakpoint" stop on the
1371        // next cycle. We latch instead of stopping inline because
1372        // push_closure_frame is called from deep inside the call
1373        // dispatcher — the cleanest place for the debugger to observe
1374        // a consistent state is at the next line-change check.
1375        if self.function_breakpoints.contains(&closure.func.name) {
1376            self.pending_function_bp = Some(closure.func.name.clone());
1377        }
1378
1379        self.frames.push(CallFrame {
1380            chunk: closure.func.chunk.clone(),
1381            ip: 0,
1382            stack_base: self.stack.len(),
1383            saved_env,
1384            initial_env: Some(initial_env),
1385            saved_iterator_depth: self.iterators.len(),
1386            fn_name: closure.func.name.clone(),
1387            argc: args.len(),
1388            saved_source_dir,
1389            module_functions: closure.module_functions.clone(),
1390            module_state: closure.module_state.clone(),
1391        });
1392
1393        Ok(())
1394    }
1395
1396    /// Create a generator value by spawning the closure body as an async task.
1397    /// The generator body communicates yielded values through an mpsc channel.
1398    pub(crate) fn create_generator(&self, closure: &VmClosure, args: &[VmValue]) -> VmValue {
1399        use crate::value::VmGenerator;
1400
1401        // Buffer size of 1: the generator produces one value at a time.
1402        let (tx, rx) = tokio::sync::mpsc::channel::<VmValue>(1);
1403
1404        let mut child = self.child_vm();
1405        child.yield_sender = Some(tx);
1406
1407        // Set up the environment for the generator body. The generator
1408        // body runs in its own child VM; closure_call_env walks the
1409        // current (parent) env so locally-defined generator closures
1410        // can self-reference via the narrow closure-only merge. See
1411        // `Vm::closure_call_env`.
1412        let parent_env = self.env.clone();
1413        let mut call_env = Self::closure_call_env(&parent_env, closure);
1414        call_env.push_scope();
1415
1416        let default_start = closure
1417            .func
1418            .default_start
1419            .unwrap_or(closure.func.params.len());
1420        let param_count = closure.func.params.len();
1421        for (i, param) in closure.func.params.iter().enumerate() {
1422            if closure.func.has_rest_param && i == param_count - 1 {
1423                let rest_args = if i < args.len() {
1424                    args[i..].to_vec()
1425                } else {
1426                    Vec::new()
1427                };
1428                let _ = call_env.define(param, VmValue::List(std::rc::Rc::new(rest_args)), false);
1429            } else if i < args.len() {
1430                let _ = call_env.define(param, args[i].clone(), false);
1431            } else if i < default_start {
1432                let _ = call_env.define(param, VmValue::Nil, false);
1433            }
1434        }
1435        child.env = call_env;
1436
1437        let chunk = closure.func.chunk.clone();
1438        let saved_source_dir = if let Some(ref dir) = closure.source_dir {
1439            let prev = crate::stdlib::process::VM_SOURCE_DIR.with(|sd| sd.borrow().clone());
1440            crate::stdlib::set_thread_source_dir(dir);
1441            prev
1442        } else {
1443            None
1444        };
1445        let module_functions = closure.module_functions.clone();
1446        let module_state = closure.module_state.clone();
1447        let argc = args.len();
1448        // Spawn the generator body as an async task.
1449        // The task will execute until return, sending yielded values through the channel.
1450        tokio::task::spawn_local(async move {
1451            let _ = child
1452                .run_chunk_entry(
1453                    &chunk,
1454                    argc,
1455                    saved_source_dir,
1456                    module_functions,
1457                    module_state,
1458                )
1459                .await;
1460            // When the generator body finishes (return or fall-through),
1461            // the sender is dropped, signaling completion to the receiver.
1462        });
1463
1464        VmValue::Generator(VmGenerator {
1465            done: Rc::new(std::cell::Cell::new(false)),
1466            receiver: Rc::new(tokio::sync::Mutex::new(rx)),
1467        })
1468    }
1469
1470    fn pop(&mut self) -> Result<VmValue, VmError> {
1471        self.stack.pop().ok_or(VmError::StackUnderflow)
1472    }
1473
1474    fn peek(&self) -> Result<&VmValue, VmError> {
1475        self.stack.last().ok_or(VmError::StackUnderflow)
1476    }
1477
1478    fn const_string(c: &Constant) -> Result<String, VmError> {
1479        match c {
1480            Constant::String(s) => Ok(s.clone()),
1481            _ => Err(VmError::TypeError("expected string constant".into())),
1482        }
1483    }
1484
1485    /// Call a closure (used by method calls like .map/.filter etc.)
1486    /// Uses recursive execution for simplicity in method dispatch.
1487    fn call_closure<'a>(
1488        &'a mut self,
1489        closure: &'a VmClosure,
1490        args: &'a [VmValue],
1491        _parent_functions: &'a [CompiledFunction],
1492    ) -> Pin<Box<dyn Future<Output = Result<VmValue, VmError>> + 'a>> {
1493        Box::pin(async move {
1494            let saved_env = self.env.clone();
1495            let saved_frames = std::mem::take(&mut self.frames);
1496            let saved_handlers = std::mem::take(&mut self.exception_handlers);
1497            let saved_iterators = std::mem::take(&mut self.iterators);
1498            let saved_deadlines = std::mem::take(&mut self.deadlines);
1499
1500            let mut call_env = Self::closure_call_env(&saved_env, closure);
1501            call_env.push_scope();
1502
1503            let default_start = closure
1504                .func
1505                .default_start
1506                .unwrap_or(closure.func.params.len());
1507            let param_count = closure.func.params.len();
1508            for (i, param) in closure.func.params.iter().enumerate() {
1509                if closure.func.has_rest_param && i == param_count - 1 {
1510                    let rest_args = if i < args.len() {
1511                        args[i..].to_vec()
1512                    } else {
1513                        Vec::new()
1514                    };
1515                    let _ =
1516                        call_env.define(param, VmValue::List(std::rc::Rc::new(rest_args)), false);
1517                } else if i < args.len() {
1518                    let _ = call_env.define(param, args[i].clone(), false);
1519                } else if i < default_start {
1520                    let _ = call_env.define(param, VmValue::Nil, false);
1521                }
1522            }
1523
1524            self.env = call_env;
1525            let argc = args.len();
1526            let saved_source_dir = if let Some(ref dir) = closure.source_dir {
1527                let prev = crate::stdlib::process::VM_SOURCE_DIR.with(|sd| sd.borrow().clone());
1528                crate::stdlib::set_thread_source_dir(dir);
1529                prev
1530            } else {
1531                None
1532            };
1533            let result = self
1534                .run_chunk_entry(
1535                    &closure.func.chunk,
1536                    argc,
1537                    saved_source_dir,
1538                    closure.module_functions.clone(),
1539                    closure.module_state.clone(),
1540                )
1541                .await;
1542
1543            self.env = saved_env;
1544            self.frames = saved_frames;
1545            self.exception_handlers = saved_handlers;
1546            self.iterators = saved_iterators;
1547            self.deadlines = saved_deadlines;
1548
1549            result
1550        })
1551    }
1552
1553    /// Invoke a value as a callable. Supports `VmValue::Closure` and
1554    /// `VmValue::BuiltinRef`, so builtin names passed by reference (e.g.
1555    /// `dict.rekey(snake_to_camel)`) dispatch through the same code path as
1556    /// user-defined closures.
1557    #[allow(clippy::manual_async_fn)]
1558    fn call_callable_value<'a>(
1559        &'a mut self,
1560        callable: &'a VmValue,
1561        args: &'a [VmValue],
1562        functions: &'a [CompiledFunction],
1563    ) -> Pin<Box<dyn Future<Output = Result<VmValue, VmError>> + 'a>> {
1564        Box::pin(async move {
1565            match callable {
1566                VmValue::Closure(closure) => self.call_closure(closure, args, functions).await,
1567                VmValue::BuiltinRef(name) => {
1568                    let name_owned = name.to_string();
1569                    self.call_named_builtin(&name_owned, args.to_vec()).await
1570                }
1571                other => Err(VmError::TypeError(format!(
1572                    "expected callable, got {}",
1573                    other.type_name()
1574                ))),
1575            }
1576        })
1577    }
1578
1579    /// Returns true if `v` is callable via `call_callable_value`.
1580    fn is_callable_value(v: &VmValue) -> bool {
1581        matches!(v, VmValue::Closure(_) | VmValue::BuiltinRef(_))
1582    }
1583
1584    /// Public wrapper for `call_closure`, used by the MCP server to invoke
1585    /// tool handler closures from outside the VM execution loop.
1586    pub async fn call_closure_pub(
1587        &mut self,
1588        closure: &VmClosure,
1589        args: &[VmValue],
1590        functions: &[CompiledFunction],
1591    ) -> Result<VmValue, VmError> {
1592        self.call_closure(closure, args, functions).await
1593    }
1594
1595    /// Resolve a named builtin: sync builtins → async builtins → bridge → error.
1596    /// Used by Call, TailCall, and Pipe handlers to avoid duplicating this lookup.
1597    async fn call_named_builtin(
1598        &mut self,
1599        name: &str,
1600        args: Vec<VmValue>,
1601    ) -> Result<VmValue, VmError> {
1602        // Auto-trace LLM calls and tool calls.
1603        let span_kind = match name {
1604            "llm_call" | "llm_stream" | "agent_loop" => Some(crate::tracing::SpanKind::LlmCall),
1605            "mcp_call" => Some(crate::tracing::SpanKind::ToolCall),
1606            _ => None,
1607        };
1608        let _span = span_kind.map(|kind| ScopeSpan::new(kind, name.to_string()));
1609
1610        // Sandbox check: deny builtins blocked by --deny/--allow flags.
1611        if self.denied_builtins.contains(name) {
1612            return Err(VmError::CategorizedError {
1613                message: format!("Tool '{}' is not permitted.", name),
1614                category: ErrorCategory::ToolRejected,
1615            });
1616        }
1617        crate::orchestration::enforce_current_policy_for_builtin(name, &args)?;
1618        if let Some(builtin) = self.builtins.get(name).cloned() {
1619            builtin(&args, &mut self.output)
1620        } else if let Some(async_builtin) = self.async_builtins.get(name).cloned() {
1621            CURRENT_ASYNC_BUILTIN_CHILD_VM.with(|slot| {
1622                slot.borrow_mut().push(self.child_vm());
1623            });
1624            let result = async_builtin(args).await;
1625            CURRENT_ASYNC_BUILTIN_CHILD_VM.with(|slot| {
1626                slot.borrow_mut().pop();
1627            });
1628            result
1629        } else if let Some(bridge) = &self.bridge {
1630            crate::orchestration::enforce_current_policy_for_bridge_builtin(name)?;
1631            let args_json: Vec<serde_json::Value> =
1632                args.iter().map(crate::llm::vm_value_to_json).collect();
1633            let result = bridge
1634                .call(
1635                    "builtin_call",
1636                    serde_json::json!({"name": name, "args": args_json}),
1637                )
1638                .await?;
1639            Ok(crate::bridge::json_result_to_vm_value(&result))
1640        } else {
1641            let all_builtins = self
1642                .builtins
1643                .keys()
1644                .chain(self.async_builtins.keys())
1645                .map(|s| s.as_str());
1646            if let Some(suggestion) = crate::value::closest_match(name, all_builtins) {
1647                return Err(VmError::Runtime(format!(
1648                    "Undefined builtin: {name} (did you mean `{suggestion}`?)"
1649                )));
1650            }
1651            Err(VmError::UndefinedBuiltin(name.to_string()))
1652        }
1653    }
1654}
1655
1656/// Clone the VM at the top of the async-builtin child VM stack, returning a
1657/// fresh `Vm` instance the caller owns. Enables concurrent tool-handler
1658/// execution within a single agent_loop iteration — the VM shares its heavy
1659/// state (env, builtins, bridge, module_cache) via `Arc`/`Rc`, so cloning is
1660/// cheap and each handler gets its own execution context.
1661///
1662/// Returns `None` if no parent VM is currently pushed on the stack.
1663pub fn clone_async_builtin_child_vm() -> Option<Vm> {
1664    CURRENT_ASYNC_BUILTIN_CHILD_VM.with(|slot| slot.borrow().last().map(|vm| vm.child_vm()))
1665}
1666
1667/// Legacy API preserved for out-of-tree callers; new code should use
1668/// `clone_async_builtin_child_vm()`. `take/restore` serialized concurrent
1669/// callers because only one could hold the popped value at a time.
1670#[deprecated(
1671    note = "use clone_async_builtin_child_vm() — take/restore serialized concurrent callers"
1672)]
1673pub fn take_async_builtin_child_vm() -> Option<Vm> {
1674    clone_async_builtin_child_vm()
1675}
1676
1677/// Legacy no-op retained for backward compatibility.
1678#[deprecated(note = "clone_async_builtin_child_vm does not need a matching restore call")]
1679pub fn restore_async_builtin_child_vm(_vm: Vm) {
1680    CURRENT_ASYNC_BUILTIN_CHILD_VM.with(|slot| {
1681        let _ = slot;
1682    });
1683}
1684
1685impl Default for Vm {
1686    fn default() -> Self {
1687        Self::new()
1688    }
1689}
1690
1691#[cfg(test)]
1692mod tests {
1693    use super::*;
1694    use crate::compiler::Compiler;
1695    use crate::stdlib::register_vm_stdlib;
1696    use crate::values_equal;
1697    use harn_lexer::Lexer;
1698    use harn_parser::Parser;
1699
1700    fn run_harn(source: &str) -> (String, VmValue) {
1701        let rt = tokio::runtime::Builder::new_current_thread()
1702            .enable_all()
1703            .build()
1704            .unwrap();
1705        rt.block_on(async {
1706            let local = tokio::task::LocalSet::new();
1707            local
1708                .run_until(async {
1709                    let mut lexer = Lexer::new(source);
1710                    let tokens = lexer.tokenize().unwrap();
1711                    let mut parser = Parser::new(tokens);
1712                    let program = parser.parse().unwrap();
1713                    let chunk = Compiler::new().compile(&program).unwrap();
1714
1715                    let mut vm = Vm::new();
1716                    register_vm_stdlib(&mut vm);
1717                    let result = vm.execute(&chunk).await.unwrap();
1718                    (vm.output().to_string(), result)
1719                })
1720                .await
1721        })
1722    }
1723
1724    fn run_output(source: &str) -> String {
1725        run_harn(source).0.trim_end().to_string()
1726    }
1727
1728    fn run_harn_result(source: &str) -> Result<(String, VmValue), VmError> {
1729        let rt = tokio::runtime::Builder::new_current_thread()
1730            .enable_all()
1731            .build()
1732            .unwrap();
1733        rt.block_on(async {
1734            let local = tokio::task::LocalSet::new();
1735            local
1736                .run_until(async {
1737                    let mut lexer = Lexer::new(source);
1738                    let tokens = lexer.tokenize().unwrap();
1739                    let mut parser = Parser::new(tokens);
1740                    let program = parser.parse().unwrap();
1741                    let chunk = Compiler::new().compile(&program).unwrap();
1742
1743                    let mut vm = Vm::new();
1744                    register_vm_stdlib(&mut vm);
1745                    let result = vm.execute(&chunk).await?;
1746                    Ok((vm.output().to_string(), result))
1747                })
1748                .await
1749        })
1750    }
1751
1752    /// Drive the VM forward from a `start()`ed chunk until it reaches
1753    /// the first breakpoint (or exhausts the step budget). Returns the
1754    /// VM positioned in whatever frame the breakpoint lives in. Used
1755    /// by the `evaluate_in_frame` tests below so we can inspect a paused
1756    /// scope without wiring a full DAP session.
1757    fn run_until_paused(vm: &mut Vm, chunk: &Chunk) {
1758        vm.start(chunk);
1759        let rt = tokio::runtime::Builder::new_current_thread()
1760            .enable_all()
1761            .build()
1762            .unwrap();
1763        rt.block_on(async {
1764            let local = tokio::task::LocalSet::new();
1765            local
1766                .run_until(async {
1767                    for _ in 0..10_000 {
1768                        if vm.is_stopped() {
1769                            return;
1770                        }
1771                        match vm.step_execute().await {
1772                            Ok(Some((_, true))) => return,
1773                            Ok(_) => continue,
1774                            Err(e) => panic!("step_execute failed: {e}"),
1775                        }
1776                    }
1777                    panic!("run_until_paused: step budget exceeded");
1778                })
1779                .await
1780        })
1781    }
1782
1783    /// Synchronously evaluate an expression on an already-paused VM.
1784    /// Mirrors what harn-dap's `handle_evaluate` will do on the async
1785    /// runtime it already owns.
1786    fn eval(vm: &mut Vm, expr: &str) -> Result<VmValue, VmError> {
1787        let rt = tokio::runtime::Builder::new_current_thread()
1788            .enable_all()
1789            .build()
1790            .unwrap();
1791        rt.block_on(async {
1792            let local = tokio::task::LocalSet::new();
1793            local.run_until(vm.evaluate_in_frame(expr, 0)).await
1794        })
1795    }
1796
1797    #[test]
1798    fn test_evaluate_in_frame_literal() {
1799        // Need a live frame for evaluate_in_frame, even for a pure
1800        // expression, because the scratch chunk inherits source info
1801        // from the top frame. Seed one by compiling & starting an empty
1802        // pipeline that just waits on a breakpoint.
1803        let mut vm = Vm::new();
1804        register_vm_stdlib(&mut vm);
1805        vm.set_breakpoints(vec![2]);
1806        let chunk = crate::compile_source("let __seed__: int = 0\nlog(__seed__)\n").unwrap();
1807        run_until_paused(&mut vm, &chunk);
1808
1809        assert!(values_equal(
1810            &eval(&mut vm, "1 + 2").unwrap(),
1811            &VmValue::Int(3)
1812        ));
1813        assert!(values_equal(
1814            &eval(&mut vm, "\"hi\" + \" there\"").unwrap(),
1815            &VmValue::String(Rc::from("hi there"))
1816        ));
1817        assert!(values_equal(
1818            &eval(&mut vm, "5 > 3 && 2 < 4").unwrap(),
1819            &VmValue::Bool(true)
1820        ));
1821    }
1822
1823    #[test]
1824    fn test_evaluate_in_frame_sees_locals() {
1825        let mut vm = Vm::new();
1826        register_vm_stdlib(&mut vm);
1827        vm.set_breakpoints(vec![3]);
1828        let chunk = crate::compile_source(
1829            "let user: string = \"alice\"\nlet count: int = 42\nlog(count)\n",
1830        )
1831        .unwrap();
1832        run_until_paused(&mut vm, &chunk);
1833
1834        assert!(values_equal(
1835            &eval(&mut vm, "user").unwrap(),
1836            &VmValue::String(Rc::from("alice"))
1837        ));
1838        assert!(values_equal(
1839            &eval(&mut vm, "count * 2").unwrap(),
1840            &VmValue::Int(84)
1841        ));
1842        assert!(values_equal(
1843            &eval(&mut vm, "user + \" has \" + to_string(count)").unwrap(),
1844            &VmValue::String(Rc::from("alice has 42"))
1845        ));
1846    }
1847
1848    #[test]
1849    fn test_evaluate_in_frame_does_not_leak_state() {
1850        // Evaluation must be transparent to the live session — no
1851        // scope leftovers, no stack residue, no step-mode drift.
1852        let mut vm = Vm::new();
1853        register_vm_stdlib(&mut vm);
1854        vm.set_breakpoints(vec![2]);
1855        let chunk = crate::compile_source("let x: int = 7\nlog(x)\n").unwrap();
1856        run_until_paused(&mut vm, &chunk);
1857
1858        let pre_stack = vm.stack.len();
1859        let pre_frames = vm.frames.len();
1860        let pre_scope = vm.env.scope_depth();
1861        let _ = eval(&mut vm, "x + 100").unwrap();
1862        let _ = eval(&mut vm, "x * x").unwrap();
1863        assert_eq!(vm.stack.len(), pre_stack);
1864        assert_eq!(vm.frames.len(), pre_frames);
1865        assert_eq!(vm.env.scope_depth(), pre_scope);
1866        // The synthetic `__burin_eval_result__` binding must not linger
1867        // in the paused scope.
1868        assert!(vm.env.get("__burin_eval_result__").is_none());
1869    }
1870
1871    #[test]
1872    fn test_set_variable_in_frame_updates_let_binding() {
1873        // Pipeline authors overwhelmingly use `let`; the debug
1874        // setVariable path must bypass immutability or it's useless.
1875        let mut vm = Vm::new();
1876        register_vm_stdlib(&mut vm);
1877        vm.set_breakpoints(vec![3]);
1878        let chunk = crate::compile_source(
1879            "let count: int = 7\nlet label: string = \"before\"\nlog(count)\n",
1880        )
1881        .unwrap();
1882        run_until_paused(&mut vm, &chunk);
1883
1884        let rt = tokio::runtime::Builder::new_current_thread()
1885            .enable_all()
1886            .build()
1887            .unwrap();
1888        let stored = rt.block_on(async {
1889            let local = tokio::task::LocalSet::new();
1890            local
1891                .run_until(vm.set_variable_in_frame("count", "42", 0))
1892                .await
1893        });
1894        assert!(values_equal(&stored.unwrap(), &VmValue::Int(42)));
1895        assert!(values_equal(
1896            &eval(&mut vm, "count").unwrap(),
1897            &VmValue::Int(42)
1898        ));
1899
1900        // Expression RHS — not just literals.
1901        let rt = tokio::runtime::Builder::new_current_thread()
1902            .enable_all()
1903            .build()
1904            .unwrap();
1905        rt.block_on(async {
1906            let local = tokio::task::LocalSet::new();
1907            local
1908                .run_until(vm.set_variable_in_frame("label", "\"x\" + to_string(count)", 0))
1909                .await
1910                .unwrap()
1911        });
1912        assert!(values_equal(
1913            &eval(&mut vm, "label").unwrap(),
1914            &VmValue::String(Rc::from("x42"))
1915        ));
1916    }
1917
1918    #[test]
1919    fn test_set_variable_in_frame_rejects_undefined() {
1920        let mut vm = Vm::new();
1921        register_vm_stdlib(&mut vm);
1922        vm.set_breakpoints(vec![2]);
1923        let chunk = crate::compile_source("let x: int = 1\nlog(x)\n").unwrap();
1924        run_until_paused(&mut vm, &chunk);
1925
1926        let rt = tokio::runtime::Builder::new_current_thread()
1927            .enable_all()
1928            .build()
1929            .unwrap();
1930        let err = rt
1931            .block_on(async {
1932                let local = tokio::task::LocalSet::new();
1933                local
1934                    .run_until(vm.set_variable_in_frame("ghost", "0", 0))
1935                    .await
1936            })
1937            .unwrap_err();
1938        let msg = err.to_string();
1939        assert!(
1940            msg.contains("ghost"),
1941            "expected 'ghost' in error, got {msg}"
1942        );
1943    }
1944
1945    #[test]
1946    fn test_restart_frame_rewinds_ip_and_rebinds_args() {
1947        // Pause inside a function, mutate a local, restart the frame
1948        // — the mutation must vanish and execution must resume from
1949        // the top of the function with the original args.
1950        let mut vm = Vm::new();
1951        register_vm_stdlib(&mut vm);
1952        vm.set_breakpoints(vec![3]);
1953        let chunk = crate::compile_source(
1954            "fn inner(n: int) -> int { \n  let doubled: int = n * 2\n  log(doubled)\n  return doubled\n}\nlog(inner(21))\n",
1955        )
1956        .unwrap();
1957        run_until_paused(&mut vm, &chunk);
1958
1959        // We're paused at line 3 inside `inner`. Mutate the local so
1960        // we can assert the restart wiped it.
1961        let rt = tokio::runtime::Builder::new_current_thread()
1962            .enable_all()
1963            .build()
1964            .unwrap();
1965        rt.block_on(async {
1966            let local = tokio::task::LocalSet::new();
1967            local
1968                .run_until(vm.set_variable_in_frame("doubled", "999", 0))
1969                .await
1970                .unwrap()
1971        });
1972        assert!(values_equal(
1973            &eval(&mut vm, "doubled").unwrap(),
1974            &VmValue::Int(999)
1975        ));
1976
1977        // restart_frame(top_frame_index) rewinds `inner` to entry.
1978        let top = vm.frame_count() - 1;
1979        vm.restart_frame(top).unwrap();
1980
1981        // `doubled` no longer exists because the function's scope was
1982        // blown away, but `n` should still be bound from the re-applied
1983        // arg.
1984        assert!(values_equal(
1985            &eval(&mut vm, "n").unwrap(),
1986            &VmValue::Int(21)
1987        ));
1988    }
1989
1990    #[test]
1991    fn test_restart_frame_rejects_scratch_frames() {
1992        let mut vm = Vm::new();
1993        register_vm_stdlib(&mut vm);
1994        vm.set_breakpoints(vec![2]);
1995        let chunk = crate::compile_source("let x: int = 1\nlog(x)\n").unwrap();
1996        run_until_paused(&mut vm, &chunk);
1997        // The top-level pipeline frame has `initial_env: Some(_)` so
1998        // restartFrame *is* valid there — our script has no inner
1999        // function yet. Push a synthetic scratch frame via
2000        // evaluate_in_frame (which leaves no live frame when done),
2001        // then attempt restart on an out-of-range id.
2002        let err = vm.restart_frame(99).unwrap_err();
2003        assert!(err.to_string().contains("out of range"));
2004    }
2005
2006    #[test]
2007    fn test_signal_cancel_unwinds_step_loop() {
2008        let mut vm = Vm::new();
2009        register_vm_stdlib(&mut vm);
2010        // A busy-looping pipeline that would never terminate under a
2011        // normal run; signal cancel before stepping so the first
2012        // instruction check throws VmError::Thrown with the
2013        // cancelled kind.
2014        let chunk = crate::compile_source(
2015            "pipeline t(task) { var i = 0\n while i < 1000000 { i = i + 1 } }\n",
2016        )
2017        .unwrap();
2018        vm.start(&chunk);
2019        vm.signal_cancel();
2020        let rt = tokio::runtime::Builder::new_current_thread()
2021            .enable_all()
2022            .build()
2023            .unwrap();
2024        let result = rt.block_on(async {
2025            let local = tokio::task::LocalSet::new();
2026            local.run_until(vm.step_execute()).await
2027        });
2028        match result {
2029            Err(VmError::Thrown(VmValue::String(s))) => {
2030                assert!(
2031                    s.contains("kind:cancelled:"),
2032                    "cancellation must surface as a kind-tagged Thrown error"
2033                );
2034            }
2035            other => panic!("expected cancelled Thrown, got {other:?}"),
2036        }
2037    }
2038
2039    #[test]
2040    fn test_function_breakpoint_stops_on_entry() {
2041        let mut vm = Vm::new();
2042        register_vm_stdlib(&mut vm);
2043        vm.set_function_breakpoints(vec!["do_work".to_string()]);
2044        let chunk = crate::compile_source(
2045            "fn do_work(n: int) -> int { return n + 1 }\npipeline t(task) { let x = do_work(41)\nlog(x) }\n",
2046        )
2047        .unwrap();
2048        run_until_paused(&mut vm, &chunk);
2049        // The latch must identify the matching function and get
2050        // drained exactly once.
2051        let hit = vm.take_pending_function_bp().expect("must latch a hit");
2052        assert_eq!(hit, "do_work");
2053        assert!(vm.take_pending_function_bp().is_none(), "one-shot");
2054
2055        // The top frame should be `do_work` at entry.
2056        let frames = vm.debug_stack_frames();
2057        let top = frames.last().expect("callee frame on stack");
2058        assert_eq!(top.0, "do_work");
2059    }
2060
2061    #[test]
2062    fn test_function_breakpoint_unknown_name_does_not_fire() {
2063        let mut vm = Vm::new();
2064        register_vm_stdlib(&mut vm);
2065        vm.set_function_breakpoints(vec!["nonexistent".to_string()]);
2066        let chunk = crate::compile_source("pipeline t(task) { let x = 1\nlog(x) }\n").unwrap();
2067        // With no matching callee, the program runs to completion
2068        // without latching a hit; run_until_paused would have panicked
2069        // with "step budget exceeded" if the VM idled, so wrap with a
2070        // finite run of step_execute until a natural terminate.
2071        vm.start(&chunk);
2072        let rt = tokio::runtime::Builder::new_current_thread()
2073            .enable_all()
2074            .build()
2075            .unwrap();
2076        rt.block_on(async {
2077            let local = tokio::task::LocalSet::new();
2078            local
2079                .run_until(async {
2080                    for _ in 0..10_000 {
2081                        match vm.step_execute().await {
2082                            Ok(Some((_, false))) => return,
2083                            Ok(_) => continue,
2084                            Err(e) => panic!("step_execute failed: {e}"),
2085                        }
2086                    }
2087                    panic!("step budget exceeded");
2088                })
2089                .await
2090        });
2091        assert!(vm.take_pending_function_bp().is_none());
2092    }
2093
2094    #[test]
2095    fn test_evaluate_in_frame_parse_error_is_surfaced_standalone() {
2096        let mut vm = Vm::new();
2097        register_vm_stdlib(&mut vm);
2098        vm.set_breakpoints(vec![1]);
2099        let chunk = crate::compile_source("log(0)\n").unwrap();
2100        run_until_paused(&mut vm, &chunk);
2101
2102        let err = eval(&mut vm, "(\"unterminated").unwrap_err();
2103        let msg = err.to_string();
2104        assert!(
2105            msg.contains("evaluate:"),
2106            "expected evaluate error prefix, got: {msg}"
2107        );
2108    }
2109
2110    #[test]
2111    fn test_breakpoints_wildcard_matches_any_file() {
2112        let mut vm = Vm::new();
2113        vm.set_breakpoints(vec![3, 7]);
2114        assert!(vm.breakpoint_matches(3));
2115        assert!(vm.breakpoint_matches(7));
2116        assert!(!vm.breakpoint_matches(4));
2117    }
2118
2119    #[test]
2120    fn test_breakpoints_per_file_does_not_leak_to_wildcard() {
2121        let mut vm = Vm::new();
2122        vm.set_breakpoints_for_file("auto.harn", vec![10]);
2123        // Without an active frame, only the empty-string key matches; a
2124        // file-scoped breakpoint must NOT fire when no frame is active.
2125        assert!(!vm.breakpoint_matches(10));
2126    }
2127
2128    #[test]
2129    fn test_breakpoints_per_file_clear_on_empty() {
2130        let mut vm = Vm::new();
2131        vm.set_breakpoints_for_file("a.harn", vec![1, 2]);
2132        vm.set_breakpoints_for_file("a.harn", vec![]);
2133        assert!(!vm.breakpoints.contains_key("a.harn"));
2134    }
2135
2136    #[test]
2137    fn test_arithmetic() {
2138        let out =
2139            run_output("pipeline t(task) { log(2 + 3)\nlog(10 - 4)\nlog(3 * 5)\nlog(10 / 3) }");
2140        assert_eq!(out, "[harn] 5\n[harn] 6\n[harn] 15\n[harn] 3");
2141    }
2142
2143    #[test]
2144    fn test_mixed_arithmetic() {
2145        let out = run_output("pipeline t(task) { log(3 + 1.5)\nlog(10 - 2.5) }");
2146        assert_eq!(out, "[harn] 4.5\n[harn] 7.5");
2147    }
2148
2149    #[test]
2150    fn test_exponentiation() {
2151        let out = run_output(
2152            "pipeline t(task) { log(2 ** 8)\nlog(2 * 3 ** 2)\nlog(2 ** 3 ** 2)\nlog(2 ** -1) }",
2153        );
2154        assert_eq!(out, "[harn] 256\n[harn] 18\n[harn] 512\n[harn] 0.5");
2155    }
2156
2157    #[test]
2158    fn test_comparisons() {
2159        let out =
2160            run_output("pipeline t(task) { log(1 < 2)\nlog(2 > 3)\nlog(1 == 1)\nlog(1 != 2) }");
2161        assert_eq!(out, "[harn] true\n[harn] false\n[harn] true\n[harn] true");
2162    }
2163
2164    #[test]
2165    fn test_let_var() {
2166        let out = run_output("pipeline t(task) { let x = 42\nlog(x)\nvar y = 1\ny = 2\nlog(y) }");
2167        assert_eq!(out, "[harn] 42\n[harn] 2");
2168    }
2169
2170    #[test]
2171    fn test_if_else() {
2172        let out = run_output(
2173            r#"pipeline t(task) { if true { log("yes") } if false { log("wrong") } else { log("no") } }"#,
2174        );
2175        assert_eq!(out, "[harn] yes\n[harn] no");
2176    }
2177
2178    #[test]
2179    fn test_while_loop() {
2180        let out = run_output("pipeline t(task) { var i = 0\n while i < 5 { i = i + 1 }\n log(i) }");
2181        assert_eq!(out, "[harn] 5");
2182    }
2183
2184    #[test]
2185    fn test_for_in() {
2186        let out = run_output("pipeline t(task) { for item in [1, 2, 3] { log(item) } }");
2187        assert_eq!(out, "[harn] 1\n[harn] 2\n[harn] 3");
2188    }
2189
2190    #[test]
2191    fn test_inner_for_return_does_not_leak_iterator_into_caller() {
2192        let out = run_output(
2193            r#"pipeline t(task) {
2194  fn first_match() {
2195    for pattern in ["a", "b"] {
2196      return pattern
2197    }
2198    return ""
2199  }
2200
2201  var seen = []
2202  for path in ["outer"] {
2203    seen = seen + [path + ":" + first_match()]
2204  }
2205  log(join(seen, ","))
2206}"#,
2207        );
2208        assert_eq!(out, "[harn] outer:a");
2209    }
2210
2211    #[test]
2212    fn test_fn_decl_and_call() {
2213        let out = run_output("pipeline t(task) { fn add(a, b) { return a + b }\nlog(add(3, 4)) }");
2214        assert_eq!(out, "[harn] 7");
2215    }
2216
2217    #[test]
2218    fn test_closure() {
2219        let out = run_output("pipeline t(task) { let double = { x -> x * 2 }\nlog(double(5)) }");
2220        assert_eq!(out, "[harn] 10");
2221    }
2222
2223    #[test]
2224    fn test_closure_capture() {
2225        let out = run_output(
2226            "pipeline t(task) { let base = 10\nfn offset(x) { return x + base }\nlog(offset(5)) }",
2227        );
2228        assert_eq!(out, "[harn] 15");
2229    }
2230
2231    #[test]
2232    fn test_string_concat() {
2233        let out = run_output(
2234            r#"pipeline t(task) { let a = "hello" + " " + "world"
2235log(a) }"#,
2236        );
2237        assert_eq!(out, "[harn] hello world");
2238    }
2239
2240    #[test]
2241    fn test_list_map() {
2242        let out = run_output(
2243            "pipeline t(task) { let doubled = [1, 2, 3].map({ x -> x * 2 })\nlog(doubled) }",
2244        );
2245        assert_eq!(out, "[harn] [2, 4, 6]");
2246    }
2247
2248    #[test]
2249    fn test_list_filter() {
2250        let out = run_output(
2251            "pipeline t(task) { let big = [1, 2, 3, 4, 5].filter({ x -> x > 3 })\nlog(big) }",
2252        );
2253        assert_eq!(out, "[harn] [4, 5]");
2254    }
2255
2256    #[test]
2257    fn test_list_reduce() {
2258        let out = run_output(
2259            "pipeline t(task) { let sum = [1, 2, 3, 4].reduce(0, { acc, x -> acc + x })\nlog(sum) }",
2260        );
2261        assert_eq!(out, "[harn] 10");
2262    }
2263
2264    #[test]
2265    fn test_dict_access() {
2266        let out = run_output(
2267            r#"pipeline t(task) { let d = {name: "test", value: 42}
2268log(d.name)
2269log(d.value) }"#,
2270        );
2271        assert_eq!(out, "[harn] test\n[harn] 42");
2272    }
2273
2274    #[test]
2275    fn test_dict_methods() {
2276        let out = run_output(
2277            r#"pipeline t(task) { let d = {a: 1, b: 2}
2278log(d.keys())
2279log(d.values())
2280log(d.has("a"))
2281log(d.has("z")) }"#,
2282        );
2283        assert_eq!(
2284            out,
2285            "[harn] [a, b]\n[harn] [1, 2]\n[harn] true\n[harn] false"
2286        );
2287    }
2288
2289    #[test]
2290    fn test_pipe_operator() {
2291        let out = run_output(
2292            "pipeline t(task) { fn double(x) { return x * 2 }\nlet r = 5 |> double\nlog(r) }",
2293        );
2294        assert_eq!(out, "[harn] 10");
2295    }
2296
2297    #[test]
2298    fn test_pipe_with_closure() {
2299        let out = run_output(
2300            r#"pipeline t(task) { let r = "hello world" |> { s -> s.split(" ") }
2301log(r) }"#,
2302        );
2303        assert_eq!(out, "[harn] [hello, world]");
2304    }
2305
2306    #[test]
2307    fn test_nil_coalescing() {
2308        let out = run_output(
2309            r#"pipeline t(task) { let a = nil ?? "fallback"
2310log(a)
2311let b = "present" ?? "fallback"
2312log(b) }"#,
2313        );
2314        assert_eq!(out, "[harn] fallback\n[harn] present");
2315    }
2316
2317    #[test]
2318    fn test_logical_operators() {
2319        let out =
2320            run_output("pipeline t(task) { log(true && false)\nlog(true || false)\nlog(!true) }");
2321        assert_eq!(out, "[harn] false\n[harn] true\n[harn] false");
2322    }
2323
2324    #[test]
2325    fn test_match() {
2326        let out = run_output(
2327            r#"pipeline t(task) { let x = "b"
2328match x { "a" -> { log("first") } "b" -> { log("second") } "c" -> { log("third") } } }"#,
2329        );
2330        assert_eq!(out, "[harn] second");
2331    }
2332
2333    #[test]
2334    fn test_subscript() {
2335        let out = run_output("pipeline t(task) { let arr = [10, 20, 30]\nlog(arr[1]) }");
2336        assert_eq!(out, "[harn] 20");
2337    }
2338
2339    #[test]
2340    fn test_string_methods() {
2341        let out = run_output(
2342            r#"pipeline t(task) { log("hello world".replace("world", "harn"))
2343log("a,b,c".split(","))
2344log("  hello  ".trim())
2345log("hello".starts_with("hel"))
2346log("hello".ends_with("lo"))
2347log("hello".substring(1, 3)) }"#,
2348        );
2349        assert_eq!(
2350            out,
2351            "[harn] hello harn\n[harn] [a, b, c]\n[harn] hello\n[harn] true\n[harn] true\n[harn] el"
2352        );
2353    }
2354
2355    #[test]
2356    fn test_list_properties() {
2357        let out = run_output(
2358            "pipeline t(task) { let list = [1, 2, 3]\nlog(list.count)\nlog(list.empty)\nlog(list.first)\nlog(list.last) }",
2359        );
2360        assert_eq!(out, "[harn] 3\n[harn] false\n[harn] 1\n[harn] 3");
2361    }
2362
2363    #[test]
2364    fn test_recursive_function() {
2365        let out = run_output(
2366            "pipeline t(task) { fn fib(n) { if n <= 1 { return n } return fib(n - 1) + fib(n - 2) }\nlog(fib(10)) }",
2367        );
2368        assert_eq!(out, "[harn] 55");
2369    }
2370
2371    #[test]
2372    fn test_ternary() {
2373        let out = run_output(
2374            r#"pipeline t(task) { let x = 5
2375let r = x > 0 ? "positive" : "non-positive"
2376log(r) }"#,
2377        );
2378        assert_eq!(out, "[harn] positive");
2379    }
2380
2381    #[test]
2382    fn test_for_in_dict() {
2383        let out = run_output(
2384            "pipeline t(task) { let d = {a: 1, b: 2}\nfor entry in d { log(entry.key) } }",
2385        );
2386        assert_eq!(out, "[harn] a\n[harn] b");
2387    }
2388
2389    #[test]
2390    fn test_list_any_all() {
2391        let out = run_output(
2392            "pipeline t(task) { let nums = [2, 4, 6]\nlog(nums.any({ x -> x > 5 }))\nlog(nums.all({ x -> x > 0 }))\nlog(nums.all({ x -> x > 3 })) }",
2393        );
2394        assert_eq!(out, "[harn] true\n[harn] true\n[harn] false");
2395    }
2396
2397    #[test]
2398    fn test_disassembly() {
2399        let mut lexer = Lexer::new("pipeline t(task) { log(2 + 3) }");
2400        let tokens = lexer.tokenize().unwrap();
2401        let mut parser = Parser::new(tokens);
2402        let program = parser.parse().unwrap();
2403        let chunk = Compiler::new().compile(&program).unwrap();
2404        let disasm = chunk.disassemble("test");
2405        assert!(disasm.contains("CONSTANT"));
2406        assert!(disasm.contains("ADD"));
2407        assert!(disasm.contains("CALL"));
2408    }
2409
2410    // --- Error handling tests ---
2411
2412    #[test]
2413    fn test_try_catch_basic() {
2414        let out = run_output(
2415            r#"pipeline t(task) { try { throw "oops" } catch(e) { log("caught: " + e) } }"#,
2416        );
2417        assert_eq!(out, "[harn] caught: oops");
2418    }
2419
2420    #[test]
2421    fn test_try_no_error() {
2422        let out = run_output(
2423            r#"pipeline t(task) {
2424var result = 0
2425try { result = 42 } catch(e) { result = 0 }
2426log(result)
2427}"#,
2428        );
2429        assert_eq!(out, "[harn] 42");
2430    }
2431
2432    #[test]
2433    fn test_throw_uncaught() {
2434        let result = run_harn_result(r#"pipeline t(task) { throw "boom" }"#);
2435        assert!(result.is_err());
2436    }
2437
2438    // --- Additional test coverage ---
2439
2440    fn run_vm(source: &str) -> String {
2441        let rt = tokio::runtime::Builder::new_current_thread()
2442            .enable_all()
2443            .build()
2444            .unwrap();
2445        rt.block_on(async {
2446            let local = tokio::task::LocalSet::new();
2447            local
2448                .run_until(async {
2449                    let mut lexer = Lexer::new(source);
2450                    let tokens = lexer.tokenize().unwrap();
2451                    let mut parser = Parser::new(tokens);
2452                    let program = parser.parse().unwrap();
2453                    let chunk = Compiler::new().compile(&program).unwrap();
2454                    let mut vm = Vm::new();
2455                    register_vm_stdlib(&mut vm);
2456                    vm.execute(&chunk).await.unwrap();
2457                    vm.output().to_string()
2458                })
2459                .await
2460        })
2461    }
2462
2463    fn run_vm_err(source: &str) -> String {
2464        let rt = tokio::runtime::Builder::new_current_thread()
2465            .enable_all()
2466            .build()
2467            .unwrap();
2468        rt.block_on(async {
2469            let local = tokio::task::LocalSet::new();
2470            local
2471                .run_until(async {
2472                    let mut lexer = Lexer::new(source);
2473                    let tokens = lexer.tokenize().unwrap();
2474                    let mut parser = Parser::new(tokens);
2475                    let program = parser.parse().unwrap();
2476                    let chunk = Compiler::new().compile(&program).unwrap();
2477                    let mut vm = Vm::new();
2478                    register_vm_stdlib(&mut vm);
2479                    match vm.execute(&chunk).await {
2480                        Err(e) => format!("{}", e),
2481                        Ok(_) => panic!("Expected error"),
2482                    }
2483                })
2484                .await
2485        })
2486    }
2487
2488    #[test]
2489    fn test_hello_world() {
2490        let out = run_vm(r#"pipeline default(task) { log("hello") }"#);
2491        assert_eq!(out, "[harn] hello\n");
2492    }
2493
2494    #[test]
2495    fn test_arithmetic_new() {
2496        let out = run_vm("pipeline default(task) { log(2 + 3) }");
2497        assert_eq!(out, "[harn] 5\n");
2498    }
2499
2500    #[test]
2501    fn test_string_concat_new() {
2502        let out = run_vm(r#"pipeline default(task) { log("a" + "b") }"#);
2503        assert_eq!(out, "[harn] ab\n");
2504    }
2505
2506    #[test]
2507    fn test_if_else_new() {
2508        let out = run_vm("pipeline default(task) { if true { log(1) } else { log(2) } }");
2509        assert_eq!(out, "[harn] 1\n");
2510    }
2511
2512    #[test]
2513    fn test_for_loop_new() {
2514        let out = run_vm("pipeline default(task) { for i in [1, 2, 3] { log(i) } }");
2515        assert_eq!(out, "[harn] 1\n[harn] 2\n[harn] 3\n");
2516    }
2517
2518    #[test]
2519    fn test_while_loop_new() {
2520        let out = run_vm("pipeline default(task) { var i = 0\nwhile i < 3 { log(i)\ni = i + 1 } }");
2521        assert_eq!(out, "[harn] 0\n[harn] 1\n[harn] 2\n");
2522    }
2523
2524    #[test]
2525    fn test_function_call_new() {
2526        let out =
2527            run_vm("pipeline default(task) { fn add(a, b) { return a + b }\nlog(add(2, 3)) }");
2528        assert_eq!(out, "[harn] 5\n");
2529    }
2530
2531    #[test]
2532    fn test_closure_new() {
2533        let out = run_vm("pipeline default(task) { let f = { x -> x * 2 }\nlog(f(5)) }");
2534        assert_eq!(out, "[harn] 10\n");
2535    }
2536
2537    #[test]
2538    fn test_recursion() {
2539        let out = run_vm("pipeline default(task) { fn fact(n) { if n <= 1 { return 1 }\nreturn n * fact(n - 1) }\nlog(fact(5)) }");
2540        assert_eq!(out, "[harn] 120\n");
2541    }
2542
2543    #[test]
2544    fn test_try_catch_new() {
2545        let out = run_vm(r#"pipeline default(task) { try { throw "err" } catch (e) { log(e) } }"#);
2546        assert_eq!(out, "[harn] err\n");
2547    }
2548
2549    #[test]
2550    fn test_try_no_error_new() {
2551        let out = run_vm("pipeline default(task) { try { log(1) } catch (e) { log(2) } }");
2552        assert_eq!(out, "[harn] 1\n");
2553    }
2554
2555    #[test]
2556    fn test_list_map_new() {
2557        let out =
2558            run_vm("pipeline default(task) { let r = [1, 2, 3].map({ x -> x * 2 })\nlog(r) }");
2559        assert_eq!(out, "[harn] [2, 4, 6]\n");
2560    }
2561
2562    #[test]
2563    fn test_list_filter_new() {
2564        let out = run_vm(
2565            "pipeline default(task) { let r = [1, 2, 3, 4].filter({ x -> x > 2 })\nlog(r) }",
2566        );
2567        assert_eq!(out, "[harn] [3, 4]\n");
2568    }
2569
2570    #[test]
2571    fn test_dict_access_new() {
2572        let out = run_vm("pipeline default(task) { let d = {name: \"Alice\"}\nlog(d.name) }");
2573        assert_eq!(out, "[harn] Alice\n");
2574    }
2575
2576    #[test]
2577    fn test_string_interpolation() {
2578        let out = run_vm("pipeline default(task) { let x = 42\nlog(\"val=${x}\") }");
2579        assert_eq!(out, "[harn] val=42\n");
2580    }
2581
2582    #[test]
2583    fn test_match_new() {
2584        let out = run_vm(
2585            "pipeline default(task) { let x = \"b\"\nmatch x { \"a\" -> { log(1) } \"b\" -> { log(2) } } }",
2586        );
2587        assert_eq!(out, "[harn] 2\n");
2588    }
2589
2590    #[test]
2591    fn test_json_roundtrip() {
2592        let out = run_vm("pipeline default(task) { let s = json_stringify({a: 1})\nlog(s) }");
2593        assert!(out.contains("\"a\""));
2594        assert!(out.contains("1"));
2595    }
2596
2597    #[test]
2598    fn test_type_of() {
2599        let out = run_vm("pipeline default(task) { log(type_of(42))\nlog(type_of(\"hi\")) }");
2600        assert_eq!(out, "[harn] int\n[harn] string\n");
2601    }
2602
2603    #[test]
2604    fn test_stack_overflow() {
2605        let err = run_vm_err("pipeline default(task) { fn f() { f() }\nf() }");
2606        assert!(
2607            err.contains("stack") || err.contains("overflow") || err.contains("recursion"),
2608            "Expected stack overflow error, got: {}",
2609            err
2610        );
2611    }
2612
2613    #[test]
2614    fn test_division_by_zero() {
2615        let err = run_vm_err("pipeline default(task) { log(1 / 0) }");
2616        assert!(
2617            err.contains("Division by zero") || err.contains("division"),
2618            "Expected division by zero error, got: {}",
2619            err
2620        );
2621    }
2622
2623    #[test]
2624    fn test_float_division_by_zero_uses_ieee_values() {
2625        let out = run_vm(
2626            "pipeline default(task) { log(is_nan(0.0 / 0.0))\nlog(is_infinite(1.0 / 0.0))\nlog(is_infinite(-1.0 / 0.0)) }",
2627        );
2628        assert_eq!(out, "[harn] true\n[harn] true\n[harn] true\n");
2629    }
2630
2631    #[test]
2632    fn test_reusing_catch_binding_name_in_same_block() {
2633        let out = run_vm(
2634            r#"pipeline default(task) {
2635try {
2636    throw "a"
2637} catch e {
2638    log(e)
2639}
2640try {
2641    throw "b"
2642} catch e {
2643    log(e)
2644}
2645}"#,
2646        );
2647        assert_eq!(out, "[harn] a\n[harn] b\n");
2648    }
2649
2650    #[test]
2651    fn test_try_catch_nested() {
2652        let out = run_output(
2653            r#"pipeline t(task) {
2654try {
2655    try {
2656        throw "inner"
2657    } catch(e) {
2658        log("inner caught: " + e)
2659        throw "outer"
2660    }
2661} catch(e2) {
2662    log("outer caught: " + e2)
2663}
2664}"#,
2665        );
2666        assert_eq!(
2667            out,
2668            "[harn] inner caught: inner\n[harn] outer caught: outer"
2669        );
2670    }
2671
2672    // --- Concurrency tests ---
2673
2674    #[test]
2675    fn test_parallel_basic() {
2676        let out = run_output(
2677            "pipeline t(task) { let results = parallel(3) { i -> i * 10 }\nlog(results) }",
2678        );
2679        assert_eq!(out, "[harn] [0, 10, 20]");
2680    }
2681
2682    #[test]
2683    fn test_parallel_no_variable() {
2684        let out = run_output("pipeline t(task) { let results = parallel(3) { 42 }\nlog(results) }");
2685        assert_eq!(out, "[harn] [42, 42, 42]");
2686    }
2687
2688    #[test]
2689    fn test_parallel_each_basic() {
2690        let out = run_output(
2691            "pipeline t(task) { let results = parallel each [1, 2, 3] { x -> x * x }\nlog(results) }",
2692        );
2693        assert_eq!(out, "[harn] [1, 4, 9]");
2694    }
2695
2696    #[test]
2697    fn test_spawn_await() {
2698        let out = run_output(
2699            r#"pipeline t(task) {
2700let handle = spawn { log("spawned") }
2701let result = await(handle)
2702log("done")
2703}"#,
2704        );
2705        assert_eq!(out, "[harn] spawned\n[harn] done");
2706    }
2707
2708    #[test]
2709    fn test_spawn_cancel() {
2710        let out = run_output(
2711            r#"pipeline t(task) {
2712let handle = spawn { log("should be cancelled") }
2713cancel(handle)
2714log("cancelled")
2715}"#,
2716        );
2717        assert_eq!(out, "[harn] cancelled");
2718    }
2719
2720    #[test]
2721    fn test_spawn_returns_value() {
2722        let out = run_output("pipeline t(task) { let h = spawn { 42 }\nlet r = await(h)\nlog(r) }");
2723        assert_eq!(out, "[harn] 42");
2724    }
2725
2726    // --- Deadline tests ---
2727
2728    #[test]
2729    fn test_deadline_success() {
2730        let out = run_output(
2731            r#"pipeline t(task) {
2732let result = deadline 5s { log("within deadline")
273342 }
2734log(result)
2735}"#,
2736        );
2737        assert_eq!(out, "[harn] within deadline\n[harn] 42");
2738    }
2739
2740    #[test]
2741    fn test_deadline_exceeded() {
2742        let result = run_harn_result(
2743            r#"pipeline t(task) {
2744deadline 1ms {
2745  var i = 0
2746  while i < 1000000 { i = i + 1 }
2747}
2748}"#,
2749        );
2750        assert!(result.is_err());
2751    }
2752
2753    #[test]
2754    fn test_deadline_caught_by_try() {
2755        let out = run_output(
2756            r#"pipeline t(task) {
2757try {
2758  deadline 1ms {
2759    var i = 0
2760    while i < 1000000 { i = i + 1 }
2761  }
2762} catch(e) {
2763  log("caught")
2764}
2765}"#,
2766        );
2767        assert_eq!(out, "[harn] caught");
2768    }
2769
2770    /// Helper that runs Harn source with a set of denied builtins.
2771    fn run_harn_with_denied(
2772        source: &str,
2773        denied: HashSet<String>,
2774    ) -> Result<(String, VmValue), VmError> {
2775        let rt = tokio::runtime::Builder::new_current_thread()
2776            .enable_all()
2777            .build()
2778            .unwrap();
2779        rt.block_on(async {
2780            let local = tokio::task::LocalSet::new();
2781            local
2782                .run_until(async {
2783                    let mut lexer = Lexer::new(source);
2784                    let tokens = lexer.tokenize().unwrap();
2785                    let mut parser = Parser::new(tokens);
2786                    let program = parser.parse().unwrap();
2787                    let chunk = Compiler::new().compile(&program).unwrap();
2788
2789                    let mut vm = Vm::new();
2790                    register_vm_stdlib(&mut vm);
2791                    vm.set_denied_builtins(denied);
2792                    let result = vm.execute(&chunk).await?;
2793                    Ok((vm.output().to_string(), result))
2794                })
2795                .await
2796        })
2797    }
2798
2799    #[test]
2800    fn test_sandbox_deny_builtin() {
2801        let denied: HashSet<String> = ["push".to_string()].into_iter().collect();
2802        let result = run_harn_with_denied(
2803            r#"pipeline t(task) {
2804let xs = [1, 2]
2805push(xs, 3)
2806}"#,
2807            denied,
2808        );
2809        let err = result.unwrap_err();
2810        let msg = format!("{err}");
2811        assert!(
2812            msg.contains("not permitted"),
2813            "expected not permitted, got: {msg}"
2814        );
2815        assert!(
2816            msg.contains("push"),
2817            "expected builtin name in error, got: {msg}"
2818        );
2819    }
2820
2821    #[test]
2822    fn test_sandbox_allowed_builtin_works() {
2823        // Denying "push" should not block "log"
2824        let denied: HashSet<String> = ["push".to_string()].into_iter().collect();
2825        let result = run_harn_with_denied(r#"pipeline t(task) { log("hello") }"#, denied);
2826        let (output, _) = result.unwrap();
2827        assert_eq!(output.trim(), "[harn] hello");
2828    }
2829
2830    #[test]
2831    fn test_sandbox_empty_denied_set() {
2832        // With an empty denied set, everything should work.
2833        let result = run_harn_with_denied(r#"pipeline t(task) { log("ok") }"#, HashSet::new());
2834        let (output, _) = result.unwrap();
2835        assert_eq!(output.trim(), "[harn] ok");
2836    }
2837
2838    #[test]
2839    fn test_sandbox_propagates_to_spawn() {
2840        // Denied builtins should propagate to spawned VMs.
2841        let denied: HashSet<String> = ["push".to_string()].into_iter().collect();
2842        let result = run_harn_with_denied(
2843            r#"pipeline t(task) {
2844let handle = spawn {
2845  let xs = [1, 2]
2846  push(xs, 3)
2847}
2848await(handle)
2849}"#,
2850            denied,
2851        );
2852        let err = result.unwrap_err();
2853        let msg = format!("{err}");
2854        assert!(
2855            msg.contains("not permitted"),
2856            "expected not permitted in spawned VM, got: {msg}"
2857        );
2858    }
2859
2860    #[test]
2861    fn test_sandbox_propagates_to_parallel() {
2862        // Denied builtins should propagate to parallel VMs.
2863        let denied: HashSet<String> = ["push".to_string()].into_iter().collect();
2864        let result = run_harn_with_denied(
2865            r#"pipeline t(task) {
2866let results = parallel(2) { i ->
2867  let xs = [1, 2]
2868  push(xs, 3)
2869}
2870}"#,
2871            denied,
2872        );
2873        let err = result.unwrap_err();
2874        let msg = format!("{err}");
2875        assert!(
2876            msg.contains("not permitted"),
2877            "expected not permitted in parallel VM, got: {msg}"
2878        );
2879    }
2880
2881    #[test]
2882    fn test_if_else_has_lexical_block_scope() {
2883        let out = run_output(
2884            r#"pipeline t(task) {
2885let x = "outer"
2886if true {
2887  let x = "inner"
2888  log(x)
2889} else {
2890  let x = "other"
2891  log(x)
2892}
2893log(x)
2894}"#,
2895        );
2896        assert_eq!(out, "[harn] inner\n[harn] outer");
2897    }
2898
2899    #[test]
2900    fn test_loop_and_catch_bindings_are_block_scoped() {
2901        let out = run_output(
2902            r#"pipeline t(task) {
2903let label = "outer"
2904for item in [1, 2] {
2905  let label = "loop ${item}"
2906  log(label)
2907}
2908try {
2909  throw("boom")
2910} catch (label) {
2911  log(label)
2912}
2913log(label)
2914}"#,
2915        );
2916        assert_eq!(
2917            out,
2918            "[harn] loop 1\n[harn] loop 2\n[harn] boom\n[harn] outer"
2919        );
2920    }
2921}