Skip to main content

harn_vm/
vm.rs

1mod format;
2mod imports;
3mod methods;
4mod ops;
5
6use std::cell::RefCell;
7use std::collections::{BTreeMap, HashSet};
8use std::future::Future;
9use std::pin::Pin;
10use std::rc::Rc;
11use std::time::Instant;
12
13use crate::chunk::{Chunk, CompiledFunction, Constant};
14use crate::value::{
15    ErrorCategory, ModuleFunctionRegistry, VmAsyncBuiltinFn, VmBuiltinFn, VmClosure, VmEnv,
16    VmError, VmTaskHandle, VmValue,
17};
18
19thread_local! {
20    static CURRENT_ASYNC_BUILTIN_CHILD_VM: RefCell<Vec<Vm>> = const { RefCell::new(Vec::new()) };
21}
22
23/// RAII guard that starts a tracing span on creation and ends it on drop.
24struct ScopeSpan(u64);
25
26impl ScopeSpan {
27    fn new(kind: crate::tracing::SpanKind, name: String) -> Self {
28        Self(crate::tracing::span_start(kind, name))
29    }
30}
31
32impl Drop for ScopeSpan {
33    fn drop(&mut self) {
34        crate::tracing::span_end(self.0);
35    }
36}
37
38/// Call frame for function execution.
39pub(crate) struct CallFrame {
40    pub(crate) chunk: Chunk,
41    pub(crate) ip: usize,
42    pub(crate) stack_base: usize,
43    pub(crate) saved_env: VmEnv,
44    /// Iterator stack depth to restore when this frame unwinds.
45    pub(crate) saved_iterator_depth: usize,
46    /// Function name for stack traces (empty for top-level pipeline).
47    pub(crate) fn_name: String,
48    /// Number of arguments actually passed by the caller (for default arg support).
49    pub(crate) argc: usize,
50    /// Saved VM_SOURCE_DIR to restore when this frame is popped.
51    /// Set when entering a closure that originated from an imported module.
52    pub(crate) saved_source_dir: Option<std::path::PathBuf>,
53    /// Module-local named functions available to symbolic calls within this frame.
54    pub(crate) module_functions: Option<ModuleFunctionRegistry>,
55    /// Shared module-level env for top-level `var` / `let` bindings of
56    /// this frame's originating module. Looked up after `self.env` and
57    /// before `self.globals` by `GetVar` / `SetVar`, giving each module
58    /// its own live static state that persists across calls. See the
59    /// `module_state` field on `VmClosure` for the full rationale.
60    pub(crate) module_state: Option<crate::value::ModuleState>,
61}
62
63/// Exception handler for try/catch.
64pub(crate) struct ExceptionHandler {
65    pub(crate) catch_ip: usize,
66    pub(crate) stack_depth: usize,
67    pub(crate) frame_depth: usize,
68    pub(crate) env_scope_depth: usize,
69    /// If non-empty, this catch only handles errors whose enum_name matches.
70    pub(crate) error_type: String,
71}
72
73/// Debug action returned by the debug hook.
74#[derive(Debug, Clone, PartialEq)]
75pub enum DebugAction {
76    /// Continue execution normally.
77    Continue,
78    /// Stop (breakpoint hit, step complete).
79    Stop,
80}
81
82/// Information about current execution state for the debugger.
83#[derive(Debug, Clone)]
84pub struct DebugState {
85    pub line: usize,
86    pub variables: BTreeMap<String, VmValue>,
87    pub frame_name: String,
88    pub frame_depth: usize,
89}
90
91/// Iterator state for for-in loops: either a pre-collected vec, an async channel, or a generator.
92pub(crate) enum IterState {
93    Vec {
94        items: Vec<VmValue>,
95        idx: usize,
96    },
97    Channel {
98        receiver: std::sync::Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
99        closed: std::sync::Arc<std::sync::atomic::AtomicBool>,
100    },
101    Generator {
102        gen: crate::value::VmGenerator,
103    },
104}
105
106#[derive(Clone)]
107pub(crate) struct LoadedModule {
108    pub(crate) functions: BTreeMap<String, Rc<VmClosure>>,
109    pub(crate) public_names: HashSet<String>,
110}
111
112/// The Harn bytecode virtual machine.
113pub struct Vm {
114    pub(crate) stack: Vec<VmValue>,
115    pub(crate) env: VmEnv,
116    pub(crate) output: String,
117    pub(crate) builtins: BTreeMap<String, VmBuiltinFn>,
118    pub(crate) async_builtins: BTreeMap<String, VmAsyncBuiltinFn>,
119    /// Iterator state for for-in loops.
120    pub(crate) iterators: Vec<IterState>,
121    /// Call frame stack.
122    pub(crate) frames: Vec<CallFrame>,
123    /// Exception handler stack.
124    pub(crate) exception_handlers: Vec<ExceptionHandler>,
125    /// Spawned async task handles.
126    pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
127    /// Counter for generating unique task IDs.
128    pub(crate) task_counter: u64,
129    /// Active deadline stack: (deadline_instant, frame_depth).
130    pub(crate) deadlines: Vec<(Instant, usize)>,
131    /// Breakpoints (source line numbers).
132    pub(crate) breakpoints: Vec<usize>,
133    /// Whether the VM is in step mode.
134    pub(crate) step_mode: bool,
135    /// The frame depth at which stepping started (for step-over).
136    pub(crate) step_frame_depth: usize,
137    /// Whether the VM is currently stopped at a debug point.
138    pub(crate) stopped: bool,
139    /// Last source line executed (to detect line changes).
140    pub(crate) last_line: usize,
141    /// Source directory for resolving imports.
142    pub(crate) source_dir: Option<std::path::PathBuf>,
143    /// Modules currently being imported (cycle prevention).
144    pub(crate) imported_paths: Vec<std::path::PathBuf>,
145    /// Loaded module cache keyed by canonical or synthetic module path.
146    pub(crate) module_cache: BTreeMap<std::path::PathBuf, LoadedModule>,
147    /// Source file path for error reporting.
148    pub(crate) source_file: Option<String>,
149    /// Source text for error reporting.
150    pub(crate) source_text: Option<String>,
151    /// Optional bridge for delegating unknown builtins in bridge mode.
152    pub(crate) bridge: Option<Rc<crate::bridge::HostBridge>>,
153    /// Builtins denied by sandbox mode (`--deny` / `--allow` flags).
154    pub(crate) denied_builtins: HashSet<String>,
155    /// Cancellation token for cooperative graceful shutdown (set by parent).
156    pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
157    /// Captured stack trace from the most recent error (fn_name, line, col).
158    pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
159    /// Yield channel sender for generator execution. When set, `Op::Yield`
160    /// sends values through this channel instead of being a no-op.
161    pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<VmValue>>,
162    /// Project root directory (detected via harn.toml).
163    /// Used as base directory for metadata, store, and checkpoint operations.
164    pub(crate) project_root: Option<std::path::PathBuf>,
165    /// Global constants (e.g. `pi`, `e`). Checked as a fallback in `GetVar`
166    /// after the environment, so user-defined variables can shadow them.
167    pub(crate) globals: BTreeMap<String, VmValue>,
168}
169
170impl Vm {
171    pub fn new() -> Self {
172        Self {
173            stack: Vec::with_capacity(256),
174            env: VmEnv::new(),
175            output: String::new(),
176            builtins: BTreeMap::new(),
177            async_builtins: BTreeMap::new(),
178            iterators: Vec::new(),
179            frames: Vec::new(),
180            exception_handlers: Vec::new(),
181            spawned_tasks: BTreeMap::new(),
182            task_counter: 0,
183            deadlines: Vec::new(),
184            breakpoints: Vec::new(),
185            step_mode: false,
186            step_frame_depth: 0,
187            stopped: false,
188            last_line: 0,
189            source_dir: None,
190            imported_paths: Vec::new(),
191            module_cache: BTreeMap::new(),
192            source_file: None,
193            source_text: None,
194            bridge: None,
195            denied_builtins: HashSet::new(),
196            cancel_token: None,
197            error_stack_trace: Vec::new(),
198            yield_sender: None,
199            project_root: None,
200            globals: BTreeMap::new(),
201        }
202    }
203
204    /// Set the bridge for delegating unknown builtins in bridge mode.
205    pub fn set_bridge(&mut self, bridge: Rc<crate::bridge::HostBridge>) {
206        self.bridge = Some(bridge);
207    }
208
209    /// Set builtins that are denied in sandbox mode.
210    /// When called, the given builtin names will produce a permission error.
211    pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
212        self.denied_builtins = denied;
213    }
214
215    /// Set source info for error reporting (file path and source text).
216    pub fn set_source_info(&mut self, file: &str, text: &str) {
217        self.source_file = Some(file.to_string());
218        self.source_text = Some(text.to_string());
219    }
220
221    /// Set breakpoints by source line number.
222    pub fn set_breakpoints(&mut self, lines: Vec<usize>) {
223        self.breakpoints = lines;
224    }
225
226    /// Enable step mode (stop at next line).
227    pub fn set_step_mode(&mut self, step: bool) {
228        self.step_mode = step;
229        self.step_frame_depth = self.frames.len();
230    }
231
232    /// Enable step-over mode (stop at next line at same or lower frame depth).
233    pub fn set_step_over(&mut self) {
234        self.step_mode = true;
235        self.step_frame_depth = self.frames.len();
236    }
237
238    /// Enable step-out mode (stop when returning from current frame).
239    pub fn set_step_out(&mut self) {
240        self.step_mode = true;
241        self.step_frame_depth = self.frames.len().saturating_sub(1);
242    }
243
244    /// Check if the VM is stopped at a debug point.
245    pub fn is_stopped(&self) -> bool {
246        self.stopped
247    }
248
249    /// Get the current debug state (variables, line, etc.).
250    pub fn debug_state(&self) -> DebugState {
251        let line = self.current_line();
252        let variables = self.env.all_variables();
253        let frame_name = if self.frames.len() > 1 {
254            format!("frame_{}", self.frames.len() - 1)
255        } else {
256            "pipeline".to_string()
257        };
258        DebugState {
259            line,
260            variables,
261            frame_name,
262            frame_depth: self.frames.len(),
263        }
264    }
265
266    /// Get all stack frames for the debugger.
267    pub fn debug_stack_frames(&self) -> Vec<(String, usize)> {
268        let mut frames = Vec::new();
269        for (i, frame) in self.frames.iter().enumerate() {
270            let line = if frame.ip > 0 && frame.ip - 1 < frame.chunk.lines.len() {
271                frame.chunk.lines[frame.ip - 1] as usize
272            } else {
273                0
274            };
275            let name = if frame.fn_name.is_empty() {
276                if i == 0 {
277                    "pipeline".to_string()
278                } else {
279                    format!("fn_{}", i)
280                }
281            } else {
282                frame.fn_name.clone()
283            };
284            frames.push((name, line));
285        }
286        frames
287    }
288
289    /// Get the current source line.
290    fn current_line(&self) -> usize {
291        if let Some(frame) = self.frames.last() {
292            let ip = if frame.ip > 0 { frame.ip - 1 } else { 0 };
293            if ip < frame.chunk.lines.len() {
294                return frame.chunk.lines[ip] as usize;
295            }
296        }
297        0
298    }
299
300    /// Execute one instruction, returning whether to stop (breakpoint/step).
301    /// Returns Ok(None) to continue, Ok(Some(val)) on program end, Err on error.
302    pub async fn step_execute(&mut self) -> Result<Option<(VmValue, bool)>, VmError> {
303        // Check if we need to stop at this line
304        let current_line = self.current_line();
305        let line_changed = current_line != self.last_line && current_line > 0;
306
307        if line_changed {
308            self.last_line = current_line;
309
310            // Check breakpoints
311            if self.breakpoints.contains(&current_line) {
312                self.stopped = true;
313                return Ok(Some((VmValue::Nil, true))); // true = stopped
314            }
315
316            // Check step mode
317            if self.step_mode && self.frames.len() <= self.step_frame_depth + 1 {
318                self.step_mode = false;
319                self.stopped = true;
320                return Ok(Some((VmValue::Nil, true))); // true = stopped
321            }
322        }
323
324        // Execute one instruction cycle
325        self.stopped = false;
326        self.execute_one_cycle().await
327    }
328
329    /// Execute a single instruction cycle.
330    async fn execute_one_cycle(&mut self) -> Result<Option<(VmValue, bool)>, VmError> {
331        // Check deadline
332        if let Some(&(deadline, _)) = self.deadlines.last() {
333            if Instant::now() > deadline {
334                self.deadlines.pop();
335                let err = VmError::Thrown(VmValue::String(Rc::from("Deadline exceeded")));
336                match self.handle_error(err) {
337                    Ok(None) => return Ok(None),
338                    Ok(Some(val)) => return Ok(Some((val, false))),
339                    Err(e) => return Err(e),
340                }
341            }
342        }
343
344        // Get current frame
345        let frame = match self.frames.last_mut() {
346            Some(f) => f,
347            None => {
348                let val = self.stack.pop().unwrap_or(VmValue::Nil);
349                return Ok(Some((val, false)));
350            }
351        };
352
353        // Check if we've reached end of chunk
354        if frame.ip >= frame.chunk.code.len() {
355            let val = self.stack.pop().unwrap_or(VmValue::Nil);
356            let popped_frame = self.frames.pop().unwrap();
357            if self.frames.is_empty() {
358                return Ok(Some((val, false)));
359            } else {
360                self.iterators.truncate(popped_frame.saved_iterator_depth);
361                self.env = popped_frame.saved_env;
362                self.stack.truncate(popped_frame.stack_base);
363                self.stack.push(val);
364                return Ok(None);
365            }
366        }
367
368        let op = frame.chunk.code[frame.ip];
369        frame.ip += 1;
370
371        match self.execute_op(op).await {
372            Ok(Some(val)) => Ok(Some((val, false))),
373            Ok(None) => Ok(None),
374            Err(VmError::Return(val)) => {
375                if let Some(popped_frame) = self.frames.pop() {
376                    if let Some(ref dir) = popped_frame.saved_source_dir {
377                        crate::stdlib::set_thread_source_dir(dir);
378                    }
379                    let current_depth = self.frames.len();
380                    self.exception_handlers
381                        .retain(|h| h.frame_depth <= current_depth);
382                    if self.frames.is_empty() {
383                        return Ok(Some((val, false)));
384                    }
385                    self.iterators.truncate(popped_frame.saved_iterator_depth);
386                    self.env = popped_frame.saved_env;
387                    self.stack.truncate(popped_frame.stack_base);
388                    self.stack.push(val);
389                    Ok(None)
390                } else {
391                    Ok(Some((val, false)))
392                }
393            }
394            Err(e) => {
395                if self.error_stack_trace.is_empty() {
396                    self.error_stack_trace = self.capture_stack_trace();
397                }
398                match self.handle_error(e) {
399                    Ok(None) => {
400                        self.error_stack_trace.clear();
401                        Ok(None)
402                    }
403                    Ok(Some(val)) => Ok(Some((val, false))),
404                    Err(e) => Err(self.enrich_error_with_line(e)),
405                }
406            }
407        }
408    }
409
410    /// Initialize execution (push the initial frame).
411    pub fn start(&mut self, chunk: &Chunk) {
412        self.frames.push(CallFrame {
413            chunk: chunk.clone(),
414            ip: 0,
415            stack_base: self.stack.len(),
416            saved_env: self.env.clone(),
417            saved_iterator_depth: self.iterators.len(),
418            fn_name: String::new(),
419            argc: 0,
420            saved_source_dir: None,
421            module_functions: None,
422            module_state: None,
423        });
424    }
425
426    /// Register a sync builtin function.
427    pub fn register_builtin<F>(&mut self, name: &str, f: F)
428    where
429        F: Fn(&[VmValue], &mut String) -> Result<VmValue, VmError> + 'static,
430    {
431        self.builtins.insert(name.to_string(), Rc::new(f));
432    }
433
434    /// Remove a sync builtin (so an async version can take precedence).
435    pub fn unregister_builtin(&mut self, name: &str) {
436        self.builtins.remove(name);
437    }
438
439    /// Register an async builtin function.
440    pub fn register_async_builtin<F, Fut>(&mut self, name: &str, f: F)
441    where
442        F: Fn(Vec<VmValue>) -> Fut + 'static,
443        Fut: Future<Output = Result<VmValue, VmError>> + 'static,
444    {
445        self.async_builtins
446            .insert(name.to_string(), Rc::new(move |args| Box::pin(f(args))));
447    }
448
449    /// Create a child VM that shares builtins and env but has fresh execution state.
450    /// Used for parallel/spawn to fork the VM for concurrent tasks.
451    fn child_vm(&self) -> Vm {
452        Vm {
453            stack: Vec::with_capacity(64),
454            env: self.env.clone(),
455            output: String::new(),
456            builtins: self.builtins.clone(),
457            async_builtins: self.async_builtins.clone(),
458            iterators: Vec::new(),
459            frames: Vec::new(),
460            exception_handlers: Vec::new(),
461            spawned_tasks: BTreeMap::new(),
462            task_counter: 0,
463            deadlines: self.deadlines.clone(),
464            breakpoints: Vec::new(),
465            step_mode: false,
466            step_frame_depth: 0,
467            stopped: false,
468            last_line: 0,
469            source_dir: self.source_dir.clone(),
470            imported_paths: Vec::new(),
471            module_cache: self.module_cache.clone(),
472            source_file: self.source_file.clone(),
473            source_text: self.source_text.clone(),
474            bridge: self.bridge.clone(),
475            denied_builtins: self.denied_builtins.clone(),
476            cancel_token: None,
477            error_stack_trace: Vec::new(),
478            yield_sender: None,
479            project_root: self.project_root.clone(),
480            globals: self.globals.clone(),
481        }
482    }
483
484    /// Set the source directory for import resolution and introspection.
485    /// Also auto-detects the project root if not already set.
486    pub fn set_source_dir(&mut self, dir: &std::path::Path) {
487        self.source_dir = Some(dir.to_path_buf());
488        crate::stdlib::set_thread_source_dir(dir);
489        // Auto-detect project root if not explicitly set.
490        if self.project_root.is_none() {
491            self.project_root = crate::stdlib::process::find_project_root(dir);
492        }
493    }
494
495    /// Explicitly set the project root directory.
496    /// Used by ACP/CLI to override auto-detection.
497    pub fn set_project_root(&mut self, root: &std::path::Path) {
498        self.project_root = Some(root.to_path_buf());
499    }
500
501    /// Get the project root directory, falling back to source_dir.
502    pub fn project_root(&self) -> Option<&std::path::Path> {
503        self.project_root.as_deref().or(self.source_dir.as_deref())
504    }
505
506    /// Return all registered builtin names (sync + async).
507    pub fn builtin_names(&self) -> Vec<String> {
508        let mut names: Vec<String> = self.builtins.keys().cloned().collect();
509        names.extend(self.async_builtins.keys().cloned());
510        names
511    }
512
513    /// Set a global constant (e.g. `pi`, `e`).
514    /// Stored separately from the environment so user-defined variables can shadow them.
515    pub fn set_global(&mut self, name: &str, value: VmValue) {
516        self.globals.insert(name.to_string(), value);
517    }
518
519    /// Get the captured output.
520    pub fn output(&self) -> &str {
521        &self.output
522    }
523
524    /// Execute a compiled chunk.
525    pub async fn execute(&mut self, chunk: &Chunk) -> Result<VmValue, VmError> {
526        let span_id = crate::tracing::span_start(crate::tracing::SpanKind::Pipeline, "main".into());
527        let result = self.run_chunk(chunk).await;
528        crate::tracing::span_end(span_id);
529        result
530    }
531
532    /// Convert a VmError into either a handled exception (returning Ok) or a propagated error.
533    fn handle_error(&mut self, error: VmError) -> Result<Option<VmValue>, VmError> {
534        // Extract the thrown value from the error
535        let thrown_value = match &error {
536            VmError::Thrown(v) => v.clone(),
537            other => VmValue::String(Rc::from(other.to_string())),
538        };
539
540        if let Some(handler) = self.exception_handlers.pop() {
541            // Check if this is a typed catch that doesn't match the thrown value
542            if !handler.error_type.is_empty() {
543                let matches = match &thrown_value {
544                    VmValue::EnumVariant { enum_name, .. } => *enum_name == handler.error_type,
545                    _ => false,
546                };
547                if !matches {
548                    // This handler doesn't match — try the next one
549                    return self.handle_error(error);
550                }
551            }
552
553            // Unwind call frames back to the handler's frame depth
554            while self.frames.len() > handler.frame_depth {
555                if let Some(frame) = self.frames.pop() {
556                    if let Some(ref dir) = frame.saved_source_dir {
557                        crate::stdlib::set_thread_source_dir(dir);
558                    }
559                    self.iterators.truncate(frame.saved_iterator_depth);
560                    self.env = frame.saved_env;
561                }
562            }
563
564            // Clean up deadlines from unwound frames
565            while self
566                .deadlines
567                .last()
568                .is_some_and(|d| d.1 > handler.frame_depth)
569            {
570                self.deadlines.pop();
571            }
572
573            self.env.truncate_scopes(handler.env_scope_depth);
574
575            // Restore stack to handler's depth
576            self.stack.truncate(handler.stack_depth);
577
578            // Push the error value onto the stack (catch body can access it)
579            self.stack.push(thrown_value);
580
581            // Set the IP in the current frame to the catch handler
582            if let Some(frame) = self.frames.last_mut() {
583                frame.ip = handler.catch_ip;
584            }
585
586            Ok(None) // Continue execution
587        } else {
588            Err(error) // No handler, propagate
589        }
590    }
591
592    async fn run_chunk(&mut self, chunk: &Chunk) -> Result<VmValue, VmError> {
593        self.run_chunk_entry(chunk, 0, None, None, None).await
594    }
595
596    async fn run_chunk_entry(
597        &mut self,
598        chunk: &Chunk,
599        argc: usize,
600        saved_source_dir: Option<std::path::PathBuf>,
601        module_functions: Option<ModuleFunctionRegistry>,
602        module_state: Option<crate::value::ModuleState>,
603    ) -> Result<VmValue, VmError> {
604        self.frames.push(CallFrame {
605            chunk: chunk.clone(),
606            ip: 0,
607            stack_base: self.stack.len(),
608            saved_env: self.env.clone(),
609            saved_iterator_depth: self.iterators.len(),
610            fn_name: String::new(),
611            argc,
612            saved_source_dir,
613            module_functions,
614            module_state,
615        });
616
617        loop {
618            // Check deadline before each instruction
619            if let Some(&(deadline, _)) = self.deadlines.last() {
620                if Instant::now() > deadline {
621                    self.deadlines.pop();
622                    let err = VmError::Thrown(VmValue::String(Rc::from("Deadline exceeded")));
623                    match self.handle_error(err) {
624                        Ok(None) => continue,
625                        Ok(Some(val)) => return Ok(val),
626                        Err(e) => return Err(e),
627                    }
628                }
629            }
630
631            // Get current frame
632            let frame = match self.frames.last_mut() {
633                Some(f) => f,
634                None => return Ok(self.stack.pop().unwrap_or(VmValue::Nil)),
635            };
636
637            // Check if we've reached end of chunk
638            if frame.ip >= frame.chunk.code.len() {
639                let val = self.stack.pop().unwrap_or(VmValue::Nil);
640                let popped_frame = self.frames.pop().unwrap();
641                if let Some(ref dir) = popped_frame.saved_source_dir {
642                    crate::stdlib::set_thread_source_dir(dir);
643                }
644
645                if self.frames.is_empty() {
646                    // We're done with the top-level chunk
647                    return Ok(val);
648                } else {
649                    // Returning from a function call
650                    self.iterators.truncate(popped_frame.saved_iterator_depth);
651                    self.env = popped_frame.saved_env;
652                    self.stack.truncate(popped_frame.stack_base);
653                    self.stack.push(val);
654                    continue;
655                }
656            }
657
658            let op = frame.chunk.code[frame.ip];
659            frame.ip += 1;
660
661            match self.execute_op(op).await {
662                Ok(Some(val)) => return Ok(val),
663                Ok(None) => continue,
664                Err(VmError::Return(val)) => {
665                    // Pop the current frame
666                    if let Some(popped_frame) = self.frames.pop() {
667                        if let Some(ref dir) = popped_frame.saved_source_dir {
668                            crate::stdlib::set_thread_source_dir(dir);
669                        }
670                        // Clean up exception handlers from the returned frame
671                        let current_depth = self.frames.len();
672                        self.exception_handlers
673                            .retain(|h| h.frame_depth <= current_depth);
674
675                        if self.frames.is_empty() {
676                            return Ok(val);
677                        }
678                        self.iterators.truncate(popped_frame.saved_iterator_depth);
679                        self.env = popped_frame.saved_env;
680                        self.stack.truncate(popped_frame.stack_base);
681                        self.stack.push(val);
682                    } else {
683                        return Ok(val);
684                    }
685                }
686                Err(e) => {
687                    // Capture stack trace before error handling unwinds frames
688                    if self.error_stack_trace.is_empty() {
689                        self.error_stack_trace = self.capture_stack_trace();
690                    }
691                    match self.handle_error(e) {
692                        Ok(None) => {
693                            self.error_stack_trace.clear();
694                            continue; // Handler found, continue
695                        }
696                        Ok(Some(val)) => return Ok(val),
697                        Err(e) => return Err(self.enrich_error_with_line(e)),
698                    }
699                }
700            }
701        }
702    }
703
704    /// Capture the current call stack as (fn_name, line, col, source_file) tuples.
705    fn capture_stack_trace(&self) -> Vec<(String, usize, usize, Option<String>)> {
706        self.frames
707            .iter()
708            .map(|f| {
709                let idx = if f.ip > 0 { f.ip - 1 } else { 0 };
710                let line = f.chunk.lines.get(idx).copied().unwrap_or(0) as usize;
711                let col = f.chunk.columns.get(idx).copied().unwrap_or(0) as usize;
712                (f.fn_name.clone(), line, col, f.chunk.source_file.clone())
713            })
714            .collect()
715    }
716
717    /// Enrich a VmError with source line information from the captured stack
718    /// trace. Appends ` (line N)` to error variants whose messages don't
719    /// already carry location context.
720    fn enrich_error_with_line(&self, error: VmError) -> VmError {
721        // Determine the line from the captured stack trace (innermost frame).
722        let line = self
723            .error_stack_trace
724            .last()
725            .map(|(_, l, _, _)| *l)
726            .unwrap_or_else(|| self.current_line());
727        if line == 0 {
728            return error;
729        }
730        let suffix = format!(" (line {line})");
731        match error {
732            VmError::Runtime(msg) => VmError::Runtime(format!("{msg}{suffix}")),
733            VmError::TypeError(msg) => VmError::TypeError(format!("{msg}{suffix}")),
734            VmError::DivisionByZero => VmError::Runtime(format!("Division by zero{suffix}")),
735            VmError::UndefinedVariable(name) => {
736                VmError::Runtime(format!("Undefined variable: {name}{suffix}"))
737            }
738            VmError::UndefinedBuiltin(name) => {
739                VmError::Runtime(format!("Undefined builtin: {name}{suffix}"))
740            }
741            VmError::ImmutableAssignment(name) => VmError::Runtime(format!(
742                "Cannot assign to immutable binding: {name}{suffix}"
743            )),
744            VmError::StackOverflow => {
745                VmError::Runtime(format!("Stack overflow: too many nested calls{suffix}"))
746            }
747            // Leave these untouched:
748            // - Thrown: user-thrown errors should not be silently modified
749            // - CategorizedError: structured errors for agent orchestration
750            // - Return: control flow, not a real error
751            // - StackUnderflow / InvalidInstruction: internal VM bugs
752            other => other,
753        }
754    }
755
756    const MAX_FRAMES: usize = 512;
757
758    /// Build the call-time env for a closure invocation.
759    ///
760    /// Harn is **lexically scoped for data**: a closure sees exactly the
761    /// data names it captured at creation time, plus its parameters,
762    /// plus names from its originating module's `module_state`, plus
763    /// the module-function registry. The caller's *data* locals are
764    /// intentionally not visible — that would be dynamic scoping, which
765    /// is neither what Harn's TS-flavored surface suggests to users nor
766    /// something real stdlib code relies on.
767    ///
768    /// **Exception: closure-typed bindings.** Function *names* are
769    /// late-bound, Python-`LOAD_GLOBAL`-style. When a local recursive
770    /// fn is declared in a pipeline body (or inside another function),
771    /// the closure is created BEFORE its own name is defined in the
772    /// enclosing scope, so `closure.env` captures a snapshot that is
773    /// missing the self-reference. To make `fn fact(n) { fact(n-1) }`
774    /// work without a letrec trick, we merge closure-typed entries
775    /// from the caller's scope stack — but only closure-typed ones.
776    /// Data locals are never leaked across call boundaries, so the
777    /// surprising "caller's variable magically visible in callee"
778    /// semantic is ruled out.
779    ///
780    /// Imported module closures have `module_state` set, at which
781    /// point the full lexical environment is already available via
782    /// `closure.env` + `module_state`, and we skip the closure merge
783    /// entirely as a fast path. This is the hot path for context-
784    /// builder workloads (~65% of VM CPU before this optimization).
785    fn closure_call_env(caller_env: &VmEnv, closure: &VmClosure) -> VmEnv {
786        if closure.module_state.is_some() {
787            return closure.env.clone();
788        }
789        let mut call_env = closure.env.clone();
790        // Late-bind only closure-typed names from the caller — enough
791        // for local recursive / mutually-recursive fns to self-reference
792        // without leaking caller-local data into the callee.
793        for scope in &caller_env.scopes {
794            for (name, (val, mutable)) in &scope.vars {
795                if matches!(val, VmValue::Closure(_)) && call_env.get(name).is_none() {
796                    let _ = call_env.define(name, val.clone(), *mutable);
797                }
798            }
799        }
800        call_env
801    }
802
803    fn resolve_named_closure(&self, name: &str) -> Option<Rc<VmClosure>> {
804        if let Some(VmValue::Closure(closure)) = self.env.get(name) {
805            return Some(closure);
806        }
807        self.frames
808            .last()
809            .and_then(|frame| frame.module_functions.as_ref())
810            .and_then(|registry| registry.borrow().get(name).cloned())
811    }
812
813    /// Push a new call frame for a closure invocation.
814    fn push_closure_frame(
815        &mut self,
816        closure: &VmClosure,
817        args: &[VmValue],
818        _parent_functions: &[CompiledFunction],
819    ) -> Result<(), VmError> {
820        if self.frames.len() >= Self::MAX_FRAMES {
821            return Err(VmError::StackOverflow);
822        }
823        let saved_env = self.env.clone();
824
825        // If this closure originated from an imported module, switch
826        // the thread-local source dir so that render() and other
827        // source-relative builtins resolve relative to the module.
828        let saved_source_dir = if let Some(ref dir) = closure.source_dir {
829            let prev = crate::stdlib::process::VM_SOURCE_DIR.with(|sd| sd.borrow().clone());
830            crate::stdlib::set_thread_source_dir(dir);
831            prev
832        } else {
833            None
834        };
835
836        let mut call_env = Self::closure_call_env(&saved_env, closure);
837        call_env.push_scope();
838
839        let default_start = closure
840            .func
841            .default_start
842            .unwrap_or(closure.func.params.len());
843        for (i, param) in closure.func.params.iter().enumerate() {
844            if i < args.len() {
845                let _ = call_env.define(param, args[i].clone(), false);
846            } else if i < default_start {
847                let _ = call_env.define(param, VmValue::Nil, false);
848            }
849        }
850
851        self.env = call_env;
852
853        self.frames.push(CallFrame {
854            chunk: closure.func.chunk.clone(),
855            ip: 0,
856            stack_base: self.stack.len(),
857            saved_env,
858            saved_iterator_depth: self.iterators.len(),
859            fn_name: closure.func.name.clone(),
860            argc: args.len(),
861            saved_source_dir,
862            module_functions: closure.module_functions.clone(),
863            module_state: closure.module_state.clone(),
864        });
865
866        Ok(())
867    }
868
869    /// Create a generator value by spawning the closure body as an async task.
870    /// The generator body communicates yielded values through an mpsc channel.
871    pub(crate) fn create_generator(&self, closure: &VmClosure, args: &[VmValue]) -> VmValue {
872        use crate::value::VmGenerator;
873
874        // Buffer size of 1: the generator produces one value at a time.
875        let (tx, rx) = tokio::sync::mpsc::channel::<VmValue>(1);
876
877        let mut child = self.child_vm();
878        child.yield_sender = Some(tx);
879
880        // Set up the environment for the generator body. The generator
881        // body runs in its own child VM; closure_call_env walks the
882        // current (parent) env so locally-defined generator closures
883        // can self-reference via the narrow closure-only merge. See
884        // `Vm::closure_call_env`.
885        let parent_env = self.env.clone();
886        let mut call_env = Self::closure_call_env(&parent_env, closure);
887        call_env.push_scope();
888
889        let default_start = closure
890            .func
891            .default_start
892            .unwrap_or(closure.func.params.len());
893        for (i, param) in closure.func.params.iter().enumerate() {
894            if i < args.len() {
895                let _ = call_env.define(param, args[i].clone(), false);
896            } else if i < default_start {
897                let _ = call_env.define(param, VmValue::Nil, false);
898            }
899        }
900        child.env = call_env;
901
902        let chunk = closure.func.chunk.clone();
903        let saved_source_dir = if let Some(ref dir) = closure.source_dir {
904            let prev = crate::stdlib::process::VM_SOURCE_DIR.with(|sd| sd.borrow().clone());
905            crate::stdlib::set_thread_source_dir(dir);
906            prev
907        } else {
908            None
909        };
910        let module_functions = closure.module_functions.clone();
911        let module_state = closure.module_state.clone();
912        let argc = args.len();
913        // Spawn the generator body as an async task.
914        // The task will execute until return, sending yielded values through the channel.
915        tokio::task::spawn_local(async move {
916            let _ = child
917                .run_chunk_entry(
918                    &chunk,
919                    argc,
920                    saved_source_dir,
921                    module_functions,
922                    module_state,
923                )
924                .await;
925            // When the generator body finishes (return or fall-through),
926            // the sender is dropped, signaling completion to the receiver.
927        });
928
929        VmValue::Generator(VmGenerator {
930            done: Rc::new(std::cell::Cell::new(false)),
931            receiver: Rc::new(tokio::sync::Mutex::new(rx)),
932        })
933    }
934
935    fn pop(&mut self) -> Result<VmValue, VmError> {
936        self.stack.pop().ok_or(VmError::StackUnderflow)
937    }
938
939    fn peek(&self) -> Result<&VmValue, VmError> {
940        self.stack.last().ok_or(VmError::StackUnderflow)
941    }
942
943    fn const_string(c: &Constant) -> Result<String, VmError> {
944        match c {
945            Constant::String(s) => Ok(s.clone()),
946            _ => Err(VmError::TypeError("expected string constant".into())),
947        }
948    }
949
950    /// Call a closure (used by method calls like .map/.filter etc.)
951    /// Uses recursive execution for simplicity in method dispatch.
952    fn call_closure<'a>(
953        &'a mut self,
954        closure: &'a VmClosure,
955        args: &'a [VmValue],
956        _parent_functions: &'a [CompiledFunction],
957    ) -> Pin<Box<dyn Future<Output = Result<VmValue, VmError>> + 'a>> {
958        Box::pin(async move {
959            let saved_env = self.env.clone();
960            let saved_frames = std::mem::take(&mut self.frames);
961            let saved_handlers = std::mem::take(&mut self.exception_handlers);
962            let saved_iterators = std::mem::take(&mut self.iterators);
963            let saved_deadlines = std::mem::take(&mut self.deadlines);
964
965            let mut call_env = Self::closure_call_env(&saved_env, closure);
966            call_env.push_scope();
967
968            let default_start = closure
969                .func
970                .default_start
971                .unwrap_or(closure.func.params.len());
972            for (i, param) in closure.func.params.iter().enumerate() {
973                if i < args.len() {
974                    let _ = call_env.define(param, args[i].clone(), false);
975                } else if i < default_start {
976                    let _ = call_env.define(param, VmValue::Nil, false);
977                }
978            }
979
980            self.env = call_env;
981            let argc = args.len();
982            let saved_source_dir = if let Some(ref dir) = closure.source_dir {
983                let prev = crate::stdlib::process::VM_SOURCE_DIR.with(|sd| sd.borrow().clone());
984                crate::stdlib::set_thread_source_dir(dir);
985                prev
986            } else {
987                None
988            };
989            let result = self
990                .run_chunk_entry(
991                    &closure.func.chunk,
992                    argc,
993                    saved_source_dir,
994                    closure.module_functions.clone(),
995                    closure.module_state.clone(),
996                )
997                .await;
998
999            self.env = saved_env;
1000            self.frames = saved_frames;
1001            self.exception_handlers = saved_handlers;
1002            self.iterators = saved_iterators;
1003            self.deadlines = saved_deadlines;
1004
1005            result
1006        })
1007    }
1008
1009    /// Invoke a value as a callable. Supports `VmValue::Closure` and
1010    /// `VmValue::BuiltinRef`, so builtin names passed by reference (e.g.
1011    /// `dict.rekey(snake_to_camel)`) dispatch through the same code path as
1012    /// user-defined closures.
1013    #[allow(clippy::manual_async_fn)]
1014    fn call_callable_value<'a>(
1015        &'a mut self,
1016        callable: &'a VmValue,
1017        args: &'a [VmValue],
1018        functions: &'a [CompiledFunction],
1019    ) -> Pin<Box<dyn Future<Output = Result<VmValue, VmError>> + 'a>> {
1020        Box::pin(async move {
1021            match callable {
1022                VmValue::Closure(closure) => self.call_closure(closure, args, functions).await,
1023                VmValue::BuiltinRef(name) => {
1024                    let name_owned = name.to_string();
1025                    self.call_named_builtin(&name_owned, args.to_vec()).await
1026                }
1027                other => Err(VmError::TypeError(format!(
1028                    "expected callable, got {}",
1029                    other.type_name()
1030                ))),
1031            }
1032        })
1033    }
1034
1035    /// Returns true if `v` is callable via `call_callable_value`.
1036    fn is_callable_value(v: &VmValue) -> bool {
1037        matches!(v, VmValue::Closure(_) | VmValue::BuiltinRef(_))
1038    }
1039
1040    /// Public wrapper for `call_closure`, used by the MCP server to invoke
1041    /// tool handler closures from outside the VM execution loop.
1042    pub async fn call_closure_pub(
1043        &mut self,
1044        closure: &VmClosure,
1045        args: &[VmValue],
1046        functions: &[CompiledFunction],
1047    ) -> Result<VmValue, VmError> {
1048        self.call_closure(closure, args, functions).await
1049    }
1050
1051    /// Resolve a named builtin: sync builtins → async builtins → bridge → error.
1052    /// Used by Call, TailCall, and Pipe handlers to avoid duplicating this lookup.
1053    async fn call_named_builtin(
1054        &mut self,
1055        name: &str,
1056        args: Vec<VmValue>,
1057    ) -> Result<VmValue, VmError> {
1058        // Auto-trace LLM calls and tool calls
1059        let span_kind = match name {
1060            "llm_call" | "llm_stream" | "agent_loop" => Some(crate::tracing::SpanKind::LlmCall),
1061            "mcp_call" => Some(crate::tracing::SpanKind::ToolCall),
1062            _ => None,
1063        };
1064        let _span = span_kind.map(|kind| ScopeSpan::new(kind, name.to_string()));
1065
1066        // Sandbox check: deny builtins blocked by --deny/--allow flags.
1067        if self.denied_builtins.contains(name) {
1068            return Err(VmError::CategorizedError {
1069                message: format!("Tool '{}' is not permitted.", name),
1070                category: ErrorCategory::ToolRejected,
1071            });
1072        }
1073        crate::orchestration::enforce_current_policy_for_builtin(name, &args)?;
1074        if let Some(builtin) = self.builtins.get(name).cloned() {
1075            builtin(&args, &mut self.output)
1076        } else if let Some(async_builtin) = self.async_builtins.get(name).cloned() {
1077            CURRENT_ASYNC_BUILTIN_CHILD_VM.with(|slot| {
1078                slot.borrow_mut().push(self.child_vm());
1079            });
1080            let result = async_builtin(args).await;
1081            CURRENT_ASYNC_BUILTIN_CHILD_VM.with(|slot| {
1082                slot.borrow_mut().pop();
1083            });
1084            result
1085        } else if let Some(bridge) = &self.bridge {
1086            crate::orchestration::enforce_current_policy_for_bridge_builtin(name)?;
1087            let args_json: Vec<serde_json::Value> =
1088                args.iter().map(crate::llm::vm_value_to_json).collect();
1089            let result = bridge
1090                .call(
1091                    "builtin_call",
1092                    serde_json::json!({"name": name, "args": args_json}),
1093                )
1094                .await?;
1095            Ok(crate::bridge::json_result_to_vm_value(&result))
1096        } else {
1097            let all_builtins = self
1098                .builtins
1099                .keys()
1100                .chain(self.async_builtins.keys())
1101                .map(|s| s.as_str());
1102            if let Some(suggestion) = crate::value::closest_match(name, all_builtins) {
1103                return Err(VmError::Runtime(format!(
1104                    "Undefined builtin: {name} (did you mean `{suggestion}`?)"
1105                )));
1106            }
1107            Err(VmError::UndefinedBuiltin(name.to_string()))
1108        }
1109    }
1110}
1111
1112/// Clone the VM at the top of the async-builtin child VM stack, returning a
1113/// fresh `Vm` instance that callers own and can use without coordinating
1114/// with other concurrent users of the stack. This replaces the legacy
1115/// `take/restore` pattern: that pattern serialized access because only one
1116/// consumer could hold the single stack entry at a time, which prevented
1117/// any form of concurrent tool-handler execution within a single
1118/// agent_loop iteration. Cloning is cheap — the VM struct shares its
1119/// heavy state (env, builtins, bridge, module_cache) via `Arc`/`Rc` — so
1120/// multiple concurrent handlers can each have their own execution context.
1121///
1122/// Returns `None` if no parent VM is currently pushed on the stack.
1123pub fn clone_async_builtin_child_vm() -> Option<Vm> {
1124    CURRENT_ASYNC_BUILTIN_CHILD_VM.with(|slot| slot.borrow().last().map(|vm| vm.child_vm()))
1125}
1126
1127/// Legacy API preserved for backward compatibility with any out-of-tree
1128/// callers. New code should use `clone_async_builtin_child_vm()` instead
1129/// — `take` serializes concurrent callers because only one can hold the
1130/// popped value at a time. Internally this now delegates to a clone so
1131/// even legacy callers don't deadlock each other, but the name is kept
1132/// until external callers migrate.
1133#[deprecated(
1134    note = "use clone_async_builtin_child_vm() — take/restore serialized concurrent callers"
1135)]
1136pub fn take_async_builtin_child_vm() -> Option<Vm> {
1137    clone_async_builtin_child_vm()
1138}
1139
1140/// Legacy API — now a no-op because `take_async_builtin_child_vm` returns
1141/// a clone rather than popping the stack, so there is nothing to restore.
1142/// Kept for backward compatibility.
1143#[deprecated(note = "clone_async_builtin_child_vm does not need a matching restore call")]
1144pub fn restore_async_builtin_child_vm(_vm: Vm) {
1145    // No-op: the new clone-based API doesn't require restoration since
1146    // the caller owns a fresh clone and the stack is never mutated.
1147    CURRENT_ASYNC_BUILTIN_CHILD_VM.with(|slot| {
1148        // Intentionally ignore — kept as a syntactic no-op block so the
1149        // function signature remains stable.
1150        let _ = slot;
1151    });
1152}
1153
1154impl Default for Vm {
1155    fn default() -> Self {
1156        Self::new()
1157    }
1158}
1159
1160#[cfg(test)]
1161mod tests {
1162    use super::*;
1163    use crate::compiler::Compiler;
1164    use crate::stdlib::register_vm_stdlib;
1165    use harn_lexer::Lexer;
1166    use harn_parser::Parser;
1167
1168    fn run_harn(source: &str) -> (String, VmValue) {
1169        let rt = tokio::runtime::Builder::new_current_thread()
1170            .enable_all()
1171            .build()
1172            .unwrap();
1173        rt.block_on(async {
1174            let local = tokio::task::LocalSet::new();
1175            local
1176                .run_until(async {
1177                    let mut lexer = Lexer::new(source);
1178                    let tokens = lexer.tokenize().unwrap();
1179                    let mut parser = Parser::new(tokens);
1180                    let program = parser.parse().unwrap();
1181                    let chunk = Compiler::new().compile(&program).unwrap();
1182
1183                    let mut vm = Vm::new();
1184                    register_vm_stdlib(&mut vm);
1185                    let result = vm.execute(&chunk).await.unwrap();
1186                    (vm.output().to_string(), result)
1187                })
1188                .await
1189        })
1190    }
1191
1192    fn run_output(source: &str) -> String {
1193        run_harn(source).0.trim_end().to_string()
1194    }
1195
1196    fn run_harn_result(source: &str) -> Result<(String, VmValue), VmError> {
1197        let rt = tokio::runtime::Builder::new_current_thread()
1198            .enable_all()
1199            .build()
1200            .unwrap();
1201        rt.block_on(async {
1202            let local = tokio::task::LocalSet::new();
1203            local
1204                .run_until(async {
1205                    let mut lexer = Lexer::new(source);
1206                    let tokens = lexer.tokenize().unwrap();
1207                    let mut parser = Parser::new(tokens);
1208                    let program = parser.parse().unwrap();
1209                    let chunk = Compiler::new().compile(&program).unwrap();
1210
1211                    let mut vm = Vm::new();
1212                    register_vm_stdlib(&mut vm);
1213                    let result = vm.execute(&chunk).await?;
1214                    Ok((vm.output().to_string(), result))
1215                })
1216                .await
1217        })
1218    }
1219
1220    #[test]
1221    fn test_arithmetic() {
1222        let out =
1223            run_output("pipeline t(task) { log(2 + 3)\nlog(10 - 4)\nlog(3 * 5)\nlog(10 / 3) }");
1224        assert_eq!(out, "[harn] 5\n[harn] 6\n[harn] 15\n[harn] 3");
1225    }
1226
1227    #[test]
1228    fn test_mixed_arithmetic() {
1229        let out = run_output("pipeline t(task) { log(3 + 1.5)\nlog(10 - 2.5) }");
1230        assert_eq!(out, "[harn] 4.5\n[harn] 7.5");
1231    }
1232
1233    #[test]
1234    fn test_comparisons() {
1235        let out =
1236            run_output("pipeline t(task) { log(1 < 2)\nlog(2 > 3)\nlog(1 == 1)\nlog(1 != 2) }");
1237        assert_eq!(out, "[harn] true\n[harn] false\n[harn] true\n[harn] true");
1238    }
1239
1240    #[test]
1241    fn test_let_var() {
1242        let out = run_output("pipeline t(task) { let x = 42\nlog(x)\nvar y = 1\ny = 2\nlog(y) }");
1243        assert_eq!(out, "[harn] 42\n[harn] 2");
1244    }
1245
1246    #[test]
1247    fn test_if_else() {
1248        let out = run_output(
1249            r#"pipeline t(task) { if true { log("yes") } if false { log("wrong") } else { log("no") } }"#,
1250        );
1251        assert_eq!(out, "[harn] yes\n[harn] no");
1252    }
1253
1254    #[test]
1255    fn test_while_loop() {
1256        let out = run_output("pipeline t(task) { var i = 0\n while i < 5 { i = i + 1 }\n log(i) }");
1257        assert_eq!(out, "[harn] 5");
1258    }
1259
1260    #[test]
1261    fn test_for_in() {
1262        let out = run_output("pipeline t(task) { for item in [1, 2, 3] { log(item) } }");
1263        assert_eq!(out, "[harn] 1\n[harn] 2\n[harn] 3");
1264    }
1265
1266    #[test]
1267    fn test_inner_for_return_does_not_leak_iterator_into_caller() {
1268        let out = run_output(
1269            r#"pipeline t(task) {
1270  fn first_match() {
1271    for pattern in ["a", "b"] {
1272      return pattern
1273    }
1274    return ""
1275  }
1276
1277  var seen = []
1278  for path in ["outer"] {
1279    seen = seen + [path + ":" + first_match()]
1280  }
1281  log(join(seen, ","))
1282}"#,
1283        );
1284        assert_eq!(out, "[harn] outer:a");
1285    }
1286
1287    #[test]
1288    fn test_fn_decl_and_call() {
1289        let out = run_output("pipeline t(task) { fn add(a, b) { return a + b }\nlog(add(3, 4)) }");
1290        assert_eq!(out, "[harn] 7");
1291    }
1292
1293    #[test]
1294    fn test_closure() {
1295        let out = run_output("pipeline t(task) { let double = { x -> x * 2 }\nlog(double(5)) }");
1296        assert_eq!(out, "[harn] 10");
1297    }
1298
1299    #[test]
1300    fn test_closure_capture() {
1301        let out = run_output(
1302            "pipeline t(task) { let base = 10\nfn offset(x) { return x + base }\nlog(offset(5)) }",
1303        );
1304        assert_eq!(out, "[harn] 15");
1305    }
1306
1307    #[test]
1308    fn test_string_concat() {
1309        let out = run_output(
1310            r#"pipeline t(task) { let a = "hello" + " " + "world"
1311log(a) }"#,
1312        );
1313        assert_eq!(out, "[harn] hello world");
1314    }
1315
1316    #[test]
1317    fn test_list_map() {
1318        let out = run_output(
1319            "pipeline t(task) { let doubled = [1, 2, 3].map({ x -> x * 2 })\nlog(doubled) }",
1320        );
1321        assert_eq!(out, "[harn] [2, 4, 6]");
1322    }
1323
1324    #[test]
1325    fn test_list_filter() {
1326        let out = run_output(
1327            "pipeline t(task) { let big = [1, 2, 3, 4, 5].filter({ x -> x > 3 })\nlog(big) }",
1328        );
1329        assert_eq!(out, "[harn] [4, 5]");
1330    }
1331
1332    #[test]
1333    fn test_list_reduce() {
1334        let out = run_output(
1335            "pipeline t(task) { let sum = [1, 2, 3, 4].reduce(0, { acc, x -> acc + x })\nlog(sum) }",
1336        );
1337        assert_eq!(out, "[harn] 10");
1338    }
1339
1340    #[test]
1341    fn test_dict_access() {
1342        let out = run_output(
1343            r#"pipeline t(task) { let d = {name: "test", value: 42}
1344log(d.name)
1345log(d.value) }"#,
1346        );
1347        assert_eq!(out, "[harn] test\n[harn] 42");
1348    }
1349
1350    #[test]
1351    fn test_dict_methods() {
1352        let out = run_output(
1353            r#"pipeline t(task) { let d = {a: 1, b: 2}
1354log(d.keys())
1355log(d.values())
1356log(d.has("a"))
1357log(d.has("z")) }"#,
1358        );
1359        assert_eq!(
1360            out,
1361            "[harn] [a, b]\n[harn] [1, 2]\n[harn] true\n[harn] false"
1362        );
1363    }
1364
1365    #[test]
1366    fn test_pipe_operator() {
1367        let out = run_output(
1368            "pipeline t(task) { fn double(x) { return x * 2 }\nlet r = 5 |> double\nlog(r) }",
1369        );
1370        assert_eq!(out, "[harn] 10");
1371    }
1372
1373    #[test]
1374    fn test_pipe_with_closure() {
1375        let out = run_output(
1376            r#"pipeline t(task) { let r = "hello world" |> { s -> s.split(" ") }
1377log(r) }"#,
1378        );
1379        assert_eq!(out, "[harn] [hello, world]");
1380    }
1381
1382    #[test]
1383    fn test_nil_coalescing() {
1384        let out = run_output(
1385            r#"pipeline t(task) { let a = nil ?? "fallback"
1386log(a)
1387let b = "present" ?? "fallback"
1388log(b) }"#,
1389        );
1390        assert_eq!(out, "[harn] fallback\n[harn] present");
1391    }
1392
1393    #[test]
1394    fn test_logical_operators() {
1395        let out =
1396            run_output("pipeline t(task) { log(true && false)\nlog(true || false)\nlog(!true) }");
1397        assert_eq!(out, "[harn] false\n[harn] true\n[harn] false");
1398    }
1399
1400    #[test]
1401    fn test_match() {
1402        let out = run_output(
1403            r#"pipeline t(task) { let x = "b"
1404match x { "a" -> { log("first") } "b" -> { log("second") } "c" -> { log("third") } } }"#,
1405        );
1406        assert_eq!(out, "[harn] second");
1407    }
1408
1409    #[test]
1410    fn test_subscript() {
1411        let out = run_output("pipeline t(task) { let arr = [10, 20, 30]\nlog(arr[1]) }");
1412        assert_eq!(out, "[harn] 20");
1413    }
1414
1415    #[test]
1416    fn test_string_methods() {
1417        let out = run_output(
1418            r#"pipeline t(task) { log("hello world".replace("world", "harn"))
1419log("a,b,c".split(","))
1420log("  hello  ".trim())
1421log("hello".starts_with("hel"))
1422log("hello".ends_with("lo"))
1423log("hello".substring(1, 3)) }"#,
1424        );
1425        assert_eq!(
1426            out,
1427            "[harn] hello harn\n[harn] [a, b, c]\n[harn] hello\n[harn] true\n[harn] true\n[harn] el"
1428        );
1429    }
1430
1431    #[test]
1432    fn test_list_properties() {
1433        let out = run_output(
1434            "pipeline t(task) { let list = [1, 2, 3]\nlog(list.count)\nlog(list.empty)\nlog(list.first)\nlog(list.last) }",
1435        );
1436        assert_eq!(out, "[harn] 3\n[harn] false\n[harn] 1\n[harn] 3");
1437    }
1438
1439    #[test]
1440    fn test_recursive_function() {
1441        let out = run_output(
1442            "pipeline t(task) { fn fib(n) { if n <= 1 { return n } return fib(n - 1) + fib(n - 2) }\nlog(fib(10)) }",
1443        );
1444        assert_eq!(out, "[harn] 55");
1445    }
1446
1447    #[test]
1448    fn test_ternary() {
1449        let out = run_output(
1450            r#"pipeline t(task) { let x = 5
1451let r = x > 0 ? "positive" : "non-positive"
1452log(r) }"#,
1453        );
1454        assert_eq!(out, "[harn] positive");
1455    }
1456
1457    #[test]
1458    fn test_for_in_dict() {
1459        let out = run_output(
1460            "pipeline t(task) { let d = {a: 1, b: 2}\nfor entry in d { log(entry.key) } }",
1461        );
1462        assert_eq!(out, "[harn] a\n[harn] b");
1463    }
1464
1465    #[test]
1466    fn test_list_any_all() {
1467        let out = run_output(
1468            "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 })) }",
1469        );
1470        assert_eq!(out, "[harn] true\n[harn] true\n[harn] false");
1471    }
1472
1473    #[test]
1474    fn test_disassembly() {
1475        let mut lexer = Lexer::new("pipeline t(task) { log(2 + 3) }");
1476        let tokens = lexer.tokenize().unwrap();
1477        let mut parser = Parser::new(tokens);
1478        let program = parser.parse().unwrap();
1479        let chunk = Compiler::new().compile(&program).unwrap();
1480        let disasm = chunk.disassemble("test");
1481        assert!(disasm.contains("CONSTANT"));
1482        assert!(disasm.contains("ADD"));
1483        assert!(disasm.contains("CALL"));
1484    }
1485
1486    // --- Error handling tests ---
1487
1488    #[test]
1489    fn test_try_catch_basic() {
1490        let out = run_output(
1491            r#"pipeline t(task) { try { throw "oops" } catch(e) { log("caught: " + e) } }"#,
1492        );
1493        assert_eq!(out, "[harn] caught: oops");
1494    }
1495
1496    #[test]
1497    fn test_try_no_error() {
1498        let out = run_output(
1499            r#"pipeline t(task) {
1500var result = 0
1501try { result = 42 } catch(e) { result = 0 }
1502log(result)
1503}"#,
1504        );
1505        assert_eq!(out, "[harn] 42");
1506    }
1507
1508    #[test]
1509    fn test_throw_uncaught() {
1510        let result = run_harn_result(r#"pipeline t(task) { throw "boom" }"#);
1511        assert!(result.is_err());
1512    }
1513
1514    // --- Additional test coverage ---
1515
1516    fn run_vm(source: &str) -> String {
1517        let rt = tokio::runtime::Builder::new_current_thread()
1518            .enable_all()
1519            .build()
1520            .unwrap();
1521        rt.block_on(async {
1522            let local = tokio::task::LocalSet::new();
1523            local
1524                .run_until(async {
1525                    let mut lexer = Lexer::new(source);
1526                    let tokens = lexer.tokenize().unwrap();
1527                    let mut parser = Parser::new(tokens);
1528                    let program = parser.parse().unwrap();
1529                    let chunk = Compiler::new().compile(&program).unwrap();
1530                    let mut vm = Vm::new();
1531                    register_vm_stdlib(&mut vm);
1532                    vm.execute(&chunk).await.unwrap();
1533                    vm.output().to_string()
1534                })
1535                .await
1536        })
1537    }
1538
1539    fn run_vm_err(source: &str) -> String {
1540        let rt = tokio::runtime::Builder::new_current_thread()
1541            .enable_all()
1542            .build()
1543            .unwrap();
1544        rt.block_on(async {
1545            let local = tokio::task::LocalSet::new();
1546            local
1547                .run_until(async {
1548                    let mut lexer = Lexer::new(source);
1549                    let tokens = lexer.tokenize().unwrap();
1550                    let mut parser = Parser::new(tokens);
1551                    let program = parser.parse().unwrap();
1552                    let chunk = Compiler::new().compile(&program).unwrap();
1553                    let mut vm = Vm::new();
1554                    register_vm_stdlib(&mut vm);
1555                    match vm.execute(&chunk).await {
1556                        Err(e) => format!("{}", e),
1557                        Ok(_) => panic!("Expected error"),
1558                    }
1559                })
1560                .await
1561        })
1562    }
1563
1564    #[test]
1565    fn test_hello_world() {
1566        let out = run_vm(r#"pipeline default(task) { log("hello") }"#);
1567        assert_eq!(out, "[harn] hello\n");
1568    }
1569
1570    #[test]
1571    fn test_arithmetic_new() {
1572        let out = run_vm("pipeline default(task) { log(2 + 3) }");
1573        assert_eq!(out, "[harn] 5\n");
1574    }
1575
1576    #[test]
1577    fn test_string_concat_new() {
1578        let out = run_vm(r#"pipeline default(task) { log("a" + "b") }"#);
1579        assert_eq!(out, "[harn] ab\n");
1580    }
1581
1582    #[test]
1583    fn test_if_else_new() {
1584        let out = run_vm("pipeline default(task) { if true { log(1) } else { log(2) } }");
1585        assert_eq!(out, "[harn] 1\n");
1586    }
1587
1588    #[test]
1589    fn test_for_loop_new() {
1590        let out = run_vm("pipeline default(task) { for i in [1, 2, 3] { log(i) } }");
1591        assert_eq!(out, "[harn] 1\n[harn] 2\n[harn] 3\n");
1592    }
1593
1594    #[test]
1595    fn test_while_loop_new() {
1596        let out = run_vm("pipeline default(task) { var i = 0\nwhile i < 3 { log(i)\ni = i + 1 } }");
1597        assert_eq!(out, "[harn] 0\n[harn] 1\n[harn] 2\n");
1598    }
1599
1600    #[test]
1601    fn test_function_call_new() {
1602        let out =
1603            run_vm("pipeline default(task) { fn add(a, b) { return a + b }\nlog(add(2, 3)) }");
1604        assert_eq!(out, "[harn] 5\n");
1605    }
1606
1607    #[test]
1608    fn test_closure_new() {
1609        let out = run_vm("pipeline default(task) { let f = { x -> x * 2 }\nlog(f(5)) }");
1610        assert_eq!(out, "[harn] 10\n");
1611    }
1612
1613    #[test]
1614    fn test_recursion() {
1615        let out = run_vm("pipeline default(task) { fn fact(n) { if n <= 1 { return 1 }\nreturn n * fact(n - 1) }\nlog(fact(5)) }");
1616        assert_eq!(out, "[harn] 120\n");
1617    }
1618
1619    #[test]
1620    fn test_try_catch_new() {
1621        let out = run_vm(r#"pipeline default(task) { try { throw "err" } catch (e) { log(e) } }"#);
1622        assert_eq!(out, "[harn] err\n");
1623    }
1624
1625    #[test]
1626    fn test_try_no_error_new() {
1627        let out = run_vm("pipeline default(task) { try { log(1) } catch (e) { log(2) } }");
1628        assert_eq!(out, "[harn] 1\n");
1629    }
1630
1631    #[test]
1632    fn test_list_map_new() {
1633        let out =
1634            run_vm("pipeline default(task) { let r = [1, 2, 3].map({ x -> x * 2 })\nlog(r) }");
1635        assert_eq!(out, "[harn] [2, 4, 6]\n");
1636    }
1637
1638    #[test]
1639    fn test_list_filter_new() {
1640        let out = run_vm(
1641            "pipeline default(task) { let r = [1, 2, 3, 4].filter({ x -> x > 2 })\nlog(r) }",
1642        );
1643        assert_eq!(out, "[harn] [3, 4]\n");
1644    }
1645
1646    #[test]
1647    fn test_dict_access_new() {
1648        let out = run_vm("pipeline default(task) { let d = {name: \"Alice\"}\nlog(d.name) }");
1649        assert_eq!(out, "[harn] Alice\n");
1650    }
1651
1652    #[test]
1653    fn test_string_interpolation() {
1654        let out = run_vm("pipeline default(task) { let x = 42\nlog(\"val=${x}\") }");
1655        assert_eq!(out, "[harn] val=42\n");
1656    }
1657
1658    #[test]
1659    fn test_match_new() {
1660        let out = run_vm(
1661            "pipeline default(task) { let x = \"b\"\nmatch x { \"a\" -> { log(1) } \"b\" -> { log(2) } } }",
1662        );
1663        assert_eq!(out, "[harn] 2\n");
1664    }
1665
1666    #[test]
1667    fn test_json_roundtrip() {
1668        let out = run_vm("pipeline default(task) { let s = json_stringify({a: 1})\nlog(s) }");
1669        assert!(out.contains("\"a\""));
1670        assert!(out.contains("1"));
1671    }
1672
1673    #[test]
1674    fn test_type_of() {
1675        let out = run_vm("pipeline default(task) { log(type_of(42))\nlog(type_of(\"hi\")) }");
1676        assert_eq!(out, "[harn] int\n[harn] string\n");
1677    }
1678
1679    #[test]
1680    fn test_stack_overflow() {
1681        let err = run_vm_err("pipeline default(task) { fn f() { f() }\nf() }");
1682        assert!(
1683            err.contains("stack") || err.contains("overflow") || err.contains("recursion"),
1684            "Expected stack overflow error, got: {}",
1685            err
1686        );
1687    }
1688
1689    #[test]
1690    fn test_division_by_zero() {
1691        let err = run_vm_err("pipeline default(task) { log(1 / 0) }");
1692        assert!(
1693            err.contains("Division by zero") || err.contains("division"),
1694            "Expected division by zero error, got: {}",
1695            err
1696        );
1697    }
1698
1699    #[test]
1700    fn test_float_division_by_zero_uses_ieee_values() {
1701        let out = run_vm(
1702            "pipeline default(task) { log(is_nan(0.0 / 0.0))\nlog(is_infinite(1.0 / 0.0))\nlog(is_infinite(-1.0 / 0.0)) }",
1703        );
1704        assert_eq!(out, "[harn] true\n[harn] true\n[harn] true\n");
1705    }
1706
1707    #[test]
1708    fn test_reusing_catch_binding_name_in_same_block() {
1709        let out = run_vm(
1710            r#"pipeline default(task) {
1711try {
1712    throw "a"
1713} catch e {
1714    log(e)
1715}
1716try {
1717    throw "b"
1718} catch e {
1719    log(e)
1720}
1721}"#,
1722        );
1723        assert_eq!(out, "[harn] a\n[harn] b\n");
1724    }
1725
1726    #[test]
1727    fn test_try_catch_nested() {
1728        let out = run_output(
1729            r#"pipeline t(task) {
1730try {
1731    try {
1732        throw "inner"
1733    } catch(e) {
1734        log("inner caught: " + e)
1735        throw "outer"
1736    }
1737} catch(e2) {
1738    log("outer caught: " + e2)
1739}
1740}"#,
1741        );
1742        assert_eq!(
1743            out,
1744            "[harn] inner caught: inner\n[harn] outer caught: outer"
1745        );
1746    }
1747
1748    // --- Concurrency tests ---
1749
1750    #[test]
1751    fn test_parallel_basic() {
1752        let out = run_output(
1753            "pipeline t(task) { let results = parallel(3) { i -> i * 10 }\nlog(results) }",
1754        );
1755        assert_eq!(out, "[harn] [0, 10, 20]");
1756    }
1757
1758    #[test]
1759    fn test_parallel_no_variable() {
1760        let out = run_output("pipeline t(task) { let results = parallel(3) { 42 }\nlog(results) }");
1761        assert_eq!(out, "[harn] [42, 42, 42]");
1762    }
1763
1764    #[test]
1765    fn test_parallel_map_basic() {
1766        let out = run_output(
1767            "pipeline t(task) { let results = parallel_map([1, 2, 3]) { x -> x * x }\nlog(results) }",
1768        );
1769        assert_eq!(out, "[harn] [1, 4, 9]");
1770    }
1771
1772    #[test]
1773    fn test_spawn_await() {
1774        let out = run_output(
1775            r#"pipeline t(task) {
1776let handle = spawn { log("spawned") }
1777let result = await(handle)
1778log("done")
1779}"#,
1780        );
1781        assert_eq!(out, "[harn] spawned\n[harn] done");
1782    }
1783
1784    #[test]
1785    fn test_spawn_cancel() {
1786        let out = run_output(
1787            r#"pipeline t(task) {
1788let handle = spawn { log("should be cancelled") }
1789cancel(handle)
1790log("cancelled")
1791}"#,
1792        );
1793        assert_eq!(out, "[harn] cancelled");
1794    }
1795
1796    #[test]
1797    fn test_spawn_returns_value() {
1798        let out = run_output("pipeline t(task) { let h = spawn { 42 }\nlet r = await(h)\nlog(r) }");
1799        assert_eq!(out, "[harn] 42");
1800    }
1801
1802    // --- Deadline tests ---
1803
1804    #[test]
1805    fn test_deadline_success() {
1806        let out = run_output(
1807            r#"pipeline t(task) {
1808let result = deadline 5s { log("within deadline")
180942 }
1810log(result)
1811}"#,
1812        );
1813        assert_eq!(out, "[harn] within deadline\n[harn] 42");
1814    }
1815
1816    #[test]
1817    fn test_deadline_exceeded() {
1818        let result = run_harn_result(
1819            r#"pipeline t(task) {
1820deadline 1ms {
1821  var i = 0
1822  while i < 1000000 { i = i + 1 }
1823}
1824}"#,
1825        );
1826        assert!(result.is_err());
1827    }
1828
1829    #[test]
1830    fn test_deadline_caught_by_try() {
1831        let out = run_output(
1832            r#"pipeline t(task) {
1833try {
1834  deadline 1ms {
1835    var i = 0
1836    while i < 1000000 { i = i + 1 }
1837  }
1838} catch(e) {
1839  log("caught")
1840}
1841}"#,
1842        );
1843        assert_eq!(out, "[harn] caught");
1844    }
1845
1846    /// Helper that runs Harn source with a set of denied builtins.
1847    fn run_harn_with_denied(
1848        source: &str,
1849        denied: HashSet<String>,
1850    ) -> Result<(String, VmValue), VmError> {
1851        let rt = tokio::runtime::Builder::new_current_thread()
1852            .enable_all()
1853            .build()
1854            .unwrap();
1855        rt.block_on(async {
1856            let local = tokio::task::LocalSet::new();
1857            local
1858                .run_until(async {
1859                    let mut lexer = Lexer::new(source);
1860                    let tokens = lexer.tokenize().unwrap();
1861                    let mut parser = Parser::new(tokens);
1862                    let program = parser.parse().unwrap();
1863                    let chunk = Compiler::new().compile(&program).unwrap();
1864
1865                    let mut vm = Vm::new();
1866                    register_vm_stdlib(&mut vm);
1867                    vm.set_denied_builtins(denied);
1868                    let result = vm.execute(&chunk).await?;
1869                    Ok((vm.output().to_string(), result))
1870                })
1871                .await
1872        })
1873    }
1874
1875    #[test]
1876    fn test_sandbox_deny_builtin() {
1877        let denied: HashSet<String> = ["push".to_string()].into_iter().collect();
1878        let result = run_harn_with_denied(
1879            r#"pipeline t(task) {
1880let xs = [1, 2]
1881push(xs, 3)
1882}"#,
1883            denied,
1884        );
1885        let err = result.unwrap_err();
1886        let msg = format!("{err}");
1887        assert!(
1888            msg.contains("not permitted"),
1889            "expected not permitted, got: {msg}"
1890        );
1891        assert!(
1892            msg.contains("push"),
1893            "expected builtin name in error, got: {msg}"
1894        );
1895    }
1896
1897    #[test]
1898    fn test_sandbox_allowed_builtin_works() {
1899        // Denying "push" should not block "log"
1900        let denied: HashSet<String> = ["push".to_string()].into_iter().collect();
1901        let result = run_harn_with_denied(r#"pipeline t(task) { log("hello") }"#, denied);
1902        let (output, _) = result.unwrap();
1903        assert_eq!(output.trim(), "[harn] hello");
1904    }
1905
1906    #[test]
1907    fn test_sandbox_empty_denied_set() {
1908        // With an empty denied set, everything should work.
1909        let result = run_harn_with_denied(r#"pipeline t(task) { log("ok") }"#, HashSet::new());
1910        let (output, _) = result.unwrap();
1911        assert_eq!(output.trim(), "[harn] ok");
1912    }
1913
1914    #[test]
1915    fn test_sandbox_propagates_to_spawn() {
1916        // Denied builtins should propagate to spawned VMs.
1917        let denied: HashSet<String> = ["push".to_string()].into_iter().collect();
1918        let result = run_harn_with_denied(
1919            r#"pipeline t(task) {
1920let handle = spawn {
1921  let xs = [1, 2]
1922  push(xs, 3)
1923}
1924await(handle)
1925}"#,
1926            denied,
1927        );
1928        let err = result.unwrap_err();
1929        let msg = format!("{err}");
1930        assert!(
1931            msg.contains("not permitted"),
1932            "expected not permitted in spawned VM, got: {msg}"
1933        );
1934    }
1935
1936    #[test]
1937    fn test_sandbox_propagates_to_parallel() {
1938        // Denied builtins should propagate to parallel VMs.
1939        let denied: HashSet<String> = ["push".to_string()].into_iter().collect();
1940        let result = run_harn_with_denied(
1941            r#"pipeline t(task) {
1942let results = parallel(2) { i ->
1943  let xs = [1, 2]
1944  push(xs, 3)
1945}
1946}"#,
1947            denied,
1948        );
1949        let err = result.unwrap_err();
1950        let msg = format!("{err}");
1951        assert!(
1952            msg.contains("not permitted"),
1953            "expected not permitted in parallel VM, got: {msg}"
1954        );
1955    }
1956
1957    #[test]
1958    fn test_if_else_has_lexical_block_scope() {
1959        let out = run_output(
1960            r#"pipeline t(task) {
1961let x = "outer"
1962if true {
1963  let x = "inner"
1964  log(x)
1965} else {
1966  let x = "other"
1967  log(x)
1968}
1969log(x)
1970}"#,
1971        );
1972        assert_eq!(out, "[harn] inner\n[harn] outer");
1973    }
1974
1975    #[test]
1976    fn test_loop_and_catch_bindings_are_block_scoped() {
1977        let out = run_output(
1978            r#"pipeline t(task) {
1979let label = "outer"
1980for item in [1, 2] {
1981  let label = "loop " + item
1982  log(label)
1983}
1984try {
1985  throw("boom")
1986} catch (label) {
1987  log(label)
1988}
1989log(label)
1990}"#,
1991        );
1992        assert_eq!(
1993            out,
1994            "[harn] loop 1\n[harn] loop 2\n[harn] boom\n[harn] outer"
1995        );
1996    }
1997}