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